You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1083 lines
46 KiB
PHP
1083 lines
46 KiB
PHP
<?php
|
|
namespace App\Services\Cloud;
|
|
|
|
use App\Models\CloudInstance;
|
|
use App\Models\CloudInstanceFirewall;
|
|
use App\Models\CloudInstanceFirewallRule;
|
|
use App\Models\CloudInstanceFirewallVersion;
|
|
use App\Models\CloudInstanceMigration;
|
|
use App\Models\CloudJob;
|
|
|
|
/**
|
|
* PHP-owned desired/applied state for the host-enforced instance firewall.
|
|
*
|
|
* Reads are database-only. Writes lock the parent instance before checking the
|
|
* active job lane, so firewall, network, rescue, reinstall and delete
|
|
* mutations have one consistent per-instance serialization boundary. Only a
|
|
* typed rule DTO is persisted or sent to the Agent; libvirt XML and host rule
|
|
* syntax never cross this boundary.
|
|
*/
|
|
final class CloudFirewallService
|
|
{
|
|
public const MAX_RULES = 50;
|
|
|
|
private const BUSY_STATES = ['pending', 'applying', 'uncertain'];
|
|
private const PROTOCOLS = ['tcp', 'udp', 'icmp'];
|
|
|
|
/** A migration may only snapshot a firewall generation that is settled. */
|
|
public static function assertMaintenanceMigrationReady(
|
|
CloudInstance $instance
|
|
): void {
|
|
if (!self::catalogAvailable()) {
|
|
return;
|
|
}
|
|
$policy = CloudInstanceFirewall::where(
|
|
'instance_id', (int) $instance->id
|
|
)->first();
|
|
if ($policy === null) {
|
|
return;
|
|
}
|
|
if ((int) $policy->host_id !== (int) $instance->host_id
|
|
|| !in_array((string) $policy->sync_state,
|
|
['active', 'disabled'], true)
|
|
|| (int) $policy->desired_revision
|
|
!== (int) $policy->applied_revision
|
|
|| !is_string($policy->desired_digest)
|
|
|| !is_string($policy->applied_digest)
|
|
|| !hash_equals((string) $policy->desired_digest,
|
|
(string) $policy->applied_digest)) {
|
|
throw new CloudError(
|
|
'实例防火墙尚未收敛,暂不能开始维护迁移',
|
|
409
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Re-apply the settled desired firewall generation on a migrated target.
|
|
* The caller already holds the instance and migration orchestration locks.
|
|
*/
|
|
public static function queueMaintenanceMigrationReapplyLocked(
|
|
CloudInstance $instance,
|
|
CloudInstanceMigration $migration,
|
|
int $actorUserId,
|
|
int $retryGeneration = 0
|
|
): ?CloudJob {
|
|
if (!self::catalogAvailable()) {
|
|
return null;
|
|
}
|
|
$policy = CloudInstanceFirewall::where(
|
|
'instance_id', (int) $instance->id
|
|
)->lockForUpdate()->first();
|
|
if ($policy === null) {
|
|
return null;
|
|
}
|
|
$retry = $retryGeneration > 0;
|
|
$initialReady = !$retry
|
|
&& (int) $policy->host_id === (int) $migration->source_host_id
|
|
&& in_array((string) $policy->sync_state,
|
|
['active', 'disabled'], true)
|
|
&& (int) $policy->desired_revision
|
|
=== (int) $policy->applied_revision
|
|
&& is_string($policy->applied_digest)
|
|
&& hash_equals((string) $policy->desired_digest,
|
|
(string) $policy->applied_digest);
|
|
$retryReady = $retry
|
|
&& (int) $policy->host_id === (int) $migration->target_host_id
|
|
&& (string) $policy->sync_state === 'failed'
|
|
&& (int) $policy->desired_revision
|
|
> (int) $policy->applied_revision;
|
|
if ((int) $policy->user_id !== (int) $instance->user_id
|
|
|| (int) $instance->host_id !== (int) $migration->target_host_id
|
|
|| !is_string($policy->desired_digest)
|
|
|| (!$initialReady && !$retryReady)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移防火墙账本尚未收敛',
|
|
409
|
|
);
|
|
}
|
|
$now = time();
|
|
$policy->host_id = (int) $instance->host_id;
|
|
if (!(bool) $policy->enabled) {
|
|
// Restore creates the platform baseline filter. A disabled user
|
|
// policy has no additional host rules to apply.
|
|
$policy->updated_at = $now;
|
|
$policy->save();
|
|
return null;
|
|
}
|
|
|
|
$rules = self::rulesForRevision(
|
|
(int) $instance->id,
|
|
(int) $policy->desired_revision
|
|
);
|
|
$revision = (int) $policy->desired_revision + 1;
|
|
$policyDigest = self::policyDigest(true, $rules);
|
|
if (!hash_equals((string) $policy->desired_digest, $policyDigest)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移防火墙规则与策略摘要不一致',
|
|
409
|
|
);
|
|
}
|
|
$agentPolicy = self::agentPolicy($revision, true, $rules);
|
|
$agentPolicyDigest = self::agentPolicyDigest($agentPolicy);
|
|
$agentPolicy['policy_digest'] = $agentPolicyDigest;
|
|
$requestHash = hash('sha256', json_encode([
|
|
'maintenance_migration_id' => (int) $migration->id,
|
|
'retry_generation' => $retryGeneration,
|
|
'revision' => $revision,
|
|
'enabled' => true,
|
|
'rules' => $rules,
|
|
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
|
| JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS));
|
|
$idempotencyKey = 'maintenance-migration-'
|
|
. (string) $migration->migration_key . '-' . $retryGeneration;
|
|
|
|
$version = new CloudInstanceFirewallVersion();
|
|
$version->instance_id = (int) $instance->id;
|
|
$version->revision = $revision;
|
|
$version->enabled = true;
|
|
$version->policy_digest = $policyDigest;
|
|
$version->request_hash = $requestHash;
|
|
$version->idempotency_key = $idempotencyKey;
|
|
$version->state = 'pending';
|
|
$version->job_id = null;
|
|
$version->operation_id = null;
|
|
$version->error_code = null;
|
|
$version->applied_at = null;
|
|
$version->created_at = $version->updated_at = $now;
|
|
$version->save();
|
|
|
|
foreach ($rules as $sequence => $rule) {
|
|
$row = new CloudInstanceFirewallRule();
|
|
$row->version_id = (int) $version->id;
|
|
$row->sequence = $sequence;
|
|
$row->direction = 'ingress';
|
|
$row->protocol = $rule['protocol'];
|
|
$row->source_cidr = $rule['source_cidr'];
|
|
$row->port_from = $rule['port_from'];
|
|
$row->port_to = $rule['port_to'];
|
|
$row->description = $rule['description'];
|
|
$row->created_at = $now;
|
|
$row->save();
|
|
}
|
|
|
|
$job = new CloudJob();
|
|
$job->operation_id = bin2hex(random_bytes(16));
|
|
$job->request_idempotency_key = 'migration-firewall-'
|
|
. (string) $migration->migration_key . '-' . $retryGeneration;
|
|
$job->request_fingerprint = $requestHash;
|
|
$job->instance_id = (int) $instance->id;
|
|
$job->user_id = $actorUserId;
|
|
$job->host_id = (int) $instance->host_id;
|
|
$job->kind = 'firewall_apply';
|
|
$job->execution_mode = 'agent';
|
|
$job->status = 'queued';
|
|
$job->sealed_payload = CloudSecrets::encrypt([
|
|
'method' => 'PUT',
|
|
'request_target' => '/v1/vms/'
|
|
. rawurlencode((string) $instance->uuid) . '/firewall',
|
|
'body' => $agentPolicy,
|
|
'owner_id' => (int) $instance->user_id,
|
|
'can_manage' => true,
|
|
'firewall_version_id' => (int) $version->id,
|
|
'firewall_revision' => $revision,
|
|
'firewall_policy_digest' => $policyDigest,
|
|
'agent_firewall_policy_digest' => $agentPolicyDigest,
|
|
'maintenance_migration_id' => (int) $migration->id,
|
|
], 'job-payload');
|
|
$job->available_at = $job->created_at = $job->updated_at = $now;
|
|
$job->save();
|
|
|
|
$version->job_id = (int) $job->id;
|
|
$version->operation_id = (string) $job->operation_id;
|
|
$version->updated_at = $now;
|
|
$version->save();
|
|
$policy->desired_revision = $revision;
|
|
$policy->desired_digest = $policyDigest;
|
|
$policy->sync_state = 'pending';
|
|
$policy->last_operation_id = (string) $job->operation_id;
|
|
$policy->last_error_code = null;
|
|
$policy->updated_at = $now;
|
|
$policy->save();
|
|
return $job;
|
|
}
|
|
|
|
public static function listing(CloudInstance $instance, array $actor): array
|
|
{
|
|
self::assertOwnerAndTemplate($instance, $actor);
|
|
$policy = CloudInstanceFirewall::where(
|
|
'instance_id', (int) $instance->id
|
|
)->where('user_id', (int) $instance->user_id)
|
|
->where('host_id', (int) $instance->host_id)->first();
|
|
|
|
$rules = $policy === null ? [] : self::rulesForRevision(
|
|
(int) $instance->id, (int) $policy->desired_revision
|
|
);
|
|
$active = CloudJobService::blockingQueryForInstance(
|
|
(int) $instance->id
|
|
)->orderBy('id')->first();
|
|
$state = $policy === null ? 'disabled'
|
|
: self::publicState((string) $policy->sync_state);
|
|
$canMutate = $active === null
|
|
&& (string) $instance->status === 'active'
|
|
&& $instance->serviceAvailable()
|
|
&& !in_array($state, self::BUSY_STATES, true);
|
|
|
|
return [
|
|
'enabled' => $policy !== null && (bool) $policy->enabled,
|
|
'desired_revision' => $policy === null ? 0
|
|
: max(0, (int) $policy->desired_revision),
|
|
'applied_revision' => $policy === null ? 0
|
|
: max(0, (int) $policy->applied_revision),
|
|
'sync_state' => $state,
|
|
'last_success_at' => $policy === null
|
|
|| (int) $policy->last_success_at < 1
|
|
? null : (int) $policy->last_success_at,
|
|
'last_failure_at' => $policy === null
|
|
|| (int) $policy->last_failure_at < 1
|
|
? null : (int) $policy->last_failure_at,
|
|
'last_error_code' => $policy === null
|
|
? null : CloudOperationErrorCatalog::publicCode(
|
|
$policy->last_error_code
|
|
),
|
|
'can_mutate' => $canMutate,
|
|
'rules' => $rules,
|
|
];
|
|
}
|
|
|
|
/** Replace the complete desired policy and enqueue exactly one apply job. */
|
|
public static function apply(CloudInstance $instance, array $actor,
|
|
array $input): array
|
|
{
|
|
CloudInput::only($input, [
|
|
'enabled', 'expected_revision', 'idempotency_key', 'rules',
|
|
]);
|
|
if (!is_bool($input['enabled'] ?? null)) {
|
|
throw new CloudError('请选择是否启用防火墙');
|
|
}
|
|
$expected = filter_var($input['expected_revision'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]);
|
|
if ($expected === false) {
|
|
throw new CloudError('防火墙策略版本无效');
|
|
}
|
|
$key = self::idempotencyKey($input['idempotency_key'] ?? null);
|
|
$rules = self::rules($input['rules'] ?? null);
|
|
$enabled = (bool) $input['enabled'];
|
|
$policyDigest = self::policyDigest($enabled, $rules);
|
|
$jobRequestKey = self::jobRequestKey((int) $instance->id, $key);
|
|
$requestHash = hash('sha256', json_encode([
|
|
'expected_revision' => (int) $expected,
|
|
'enabled' => $enabled,
|
|
'rules' => $rules,
|
|
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
|
| JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS));
|
|
|
|
return $instance->getConnection()->transaction(function () use (
|
|
$instance, $actor, $expected, $key, $rules, $enabled,
|
|
$policyDigest, $requestHash, $jobRequestKey
|
|
): array {
|
|
$locked = CloudInstance::where('id', (int) $instance->id)
|
|
->lockForUpdate()->first();
|
|
if ($locked === null || (string) $locked->status === 'deleted') {
|
|
throw new CloudError('虚拟机不存在', 404);
|
|
}
|
|
self::assertOwnerAndTemplate($locked, $actor);
|
|
if ((string) $locked->status !== 'active') {
|
|
throw new CloudError('实例正在执行到期销毁流程,不能修改防火墙', 409);
|
|
}
|
|
if (!$locked->serviceAvailable()) {
|
|
throw new CloudError('实例服务已到期或正在恢复,不能修改防火墙', 409);
|
|
}
|
|
|
|
$priorJob = CloudJob::where('user_id', (int) $locked->user_id)
|
|
->where('request_idempotency_key', $jobRequestKey)
|
|
->lockForUpdate()->first();
|
|
if ($priorJob !== null) {
|
|
if ((int) $priorJob->instance_id !== (int) $locked->id
|
|
|| (string) $priorJob->kind !== 'firewall_apply'
|
|
|| !hash_equals((string) $priorJob->request_fingerprint,
|
|
$requestHash)) {
|
|
throw new CloudError('幂等键已用于其他防火墙请求', 409);
|
|
}
|
|
return [
|
|
'policy' => self::listing($locked, $actor),
|
|
'job' => $priorJob,
|
|
'unchanged' => self::jobWasUndispatchedNoop($priorJob),
|
|
];
|
|
}
|
|
|
|
$existing = CloudInstanceFirewallVersion::where(
|
|
'instance_id', (int) $locked->id
|
|
)->where('idempotency_key', $key)->lockForUpdate()->first();
|
|
if ($existing !== null) {
|
|
if (!is_string($existing->request_hash)
|
|
|| !hash_equals((string) $existing->request_hash,
|
|
$requestHash)) {
|
|
throw new CloudError('幂等键已用于其他防火墙请求', 409);
|
|
}
|
|
$job = $existing->job_id === null ? null
|
|
: CloudJob::where('id', (int) $existing->job_id)
|
|
->where('instance_id', (int) $locked->id)->first();
|
|
if ($job === null || !hash_equals(
|
|
(string) ($existing->operation_id ?? ''),
|
|
(string) ($job->operation_id ?? '')
|
|
)) {
|
|
throw new CloudError('防火墙幂等记录缺少对应任务,请联系管理员', 409);
|
|
}
|
|
return [
|
|
'policy' => self::listing($locked, $actor),
|
|
'job' => $job,
|
|
'unchanged' => false,
|
|
];
|
|
}
|
|
|
|
$policy = CloudInstanceFirewall::where(
|
|
'instance_id', (int) $locked->id
|
|
)->lockForUpdate()->first();
|
|
$revision = $policy === null ? 0 : (int) $policy->desired_revision;
|
|
if ((int) $expected !== $revision) {
|
|
throw new CloudError('防火墙策略已变化,请刷新后重试', 409);
|
|
}
|
|
if ($policy !== null
|
|
&& (int) $policy->applied_revision === $revision
|
|
&& is_string($policy->applied_digest)
|
|
&& hash_equals((string) $policy->desired_digest, $policyDigest)
|
|
&& hash_equals((string) $policy->applied_digest, $policyDigest)
|
|
&& (bool) $policy->enabled === $enabled
|
|
&& in_array((string) $policy->sync_state,
|
|
['active', 'disabled'], true)) {
|
|
$appliedVersion = CloudInstanceFirewallVersion::where(
|
|
'instance_id', (int) $locked->id
|
|
)->where('revision', $revision)
|
|
->where('state', 'applied')->first();
|
|
if ($appliedVersion !== null
|
|
&& hash_equals((string) $appliedVersion->policy_digest,
|
|
$policyDigest)) {
|
|
// Preserve the original applied version and rules, but
|
|
// give this accepted mutation its own immediately terminal
|
|
// receipt. Nothing enters the worker queue or reaches the
|
|
// Agent because durable host evidence already matches.
|
|
$job = new CloudJob();
|
|
$job->operation_id = bin2hex(random_bytes(16));
|
|
$job->request_idempotency_key = $jobRequestKey;
|
|
$job->request_fingerprint = $requestHash;
|
|
$job->instance_id = $locked->id;
|
|
$job->user_id = (int) $locked->user_id;
|
|
$job->host_id = $locked->host_id;
|
|
$job->kind = 'firewall_apply';
|
|
$job->execution_mode = 'agent';
|
|
$job->sealed_payload = CloudSecrets::encrypt(
|
|
[], 'job-payload'
|
|
);
|
|
$job->available_at = $job->created_at =
|
|
$job->updated_at = time();
|
|
$job->save();
|
|
CloudJobService::completeWithoutDispatchLocked($job, [
|
|
'unchanged' => true,
|
|
'policy_digest' => $policyDigest,
|
|
'revision' => $revision,
|
|
]);
|
|
return [
|
|
'policy' => self::listing($locked, $actor),
|
|
'job' => $job,
|
|
'unchanged' => true,
|
|
];
|
|
}
|
|
}
|
|
$now = time();
|
|
$activeJobs = CloudJobService::blockingQueryForInstance(
|
|
(int) $locked->id
|
|
)->orderBy('id')
|
|
->lockForUpdate()->get();
|
|
if (!$activeJobs->isEmpty()) {
|
|
// The browser already freezes editing while a target is
|
|
// pending. Reject direct-API replacements as well: otherwise
|
|
// a tenant could generate unbounded cancelled jobs, immutable
|
|
// versions and rule rows before one worker lease is acquired.
|
|
throw new CloudError('虚拟机已有任务,请等待完成', 409);
|
|
}
|
|
|
|
$revision++;
|
|
$agentPolicy = self::agentPolicy($revision, $enabled, $rules);
|
|
$agentPolicyDigest = self::agentPolicyDigest($agentPolicy);
|
|
$agentPolicy['policy_digest'] = $agentPolicyDigest;
|
|
$version = new CloudInstanceFirewallVersion();
|
|
$version->instance_id = $locked->id;
|
|
$version->revision = $revision;
|
|
$version->enabled = $enabled;
|
|
$version->policy_digest = $policyDigest;
|
|
$version->request_hash = $requestHash;
|
|
$version->idempotency_key = $key;
|
|
$version->state = 'pending';
|
|
$version->job_id = null;
|
|
$version->operation_id = null;
|
|
$version->error_code = null;
|
|
$version->applied_at = null;
|
|
$version->created_at = $version->updated_at = $now;
|
|
$version->save();
|
|
|
|
foreach ($rules as $sequence => $rule) {
|
|
$row = new CloudInstanceFirewallRule();
|
|
$row->version_id = $version->id;
|
|
$row->sequence = $sequence;
|
|
$row->direction = 'ingress';
|
|
$row->protocol = $rule['protocol'];
|
|
$row->source_cidr = $rule['source_cidr'];
|
|
$row->port_from = $rule['port_from'];
|
|
$row->port_to = $rule['port_to'];
|
|
$row->description = $rule['description'];
|
|
$row->created_at = $now;
|
|
$row->save();
|
|
}
|
|
|
|
$job = new CloudJob();
|
|
$job->operation_id = bin2hex(random_bytes(16));
|
|
$job->request_idempotency_key = $jobRequestKey;
|
|
$job->request_fingerprint = $requestHash;
|
|
$job->instance_id = $locked->id;
|
|
$job->user_id = (int) $locked->user_id;
|
|
$job->host_id = $locked->host_id;
|
|
$job->kind = 'firewall_apply';
|
|
$job->execution_mode = 'agent';
|
|
$job->status = 'queued';
|
|
$job->sealed_payload = CloudSecrets::encrypt([
|
|
'method' => 'PUT',
|
|
'request_target' => '/v1/vms/'
|
|
. rawurlencode((string) $locked->uuid) . '/firewall',
|
|
'body' => $agentPolicy,
|
|
'owner_id' => (int) $locked->user_id,
|
|
'can_manage' => true,
|
|
'firewall_version_id' => (int) $version->id,
|
|
'firewall_revision' => $revision,
|
|
'firewall_policy_digest' => $policyDigest,
|
|
'agent_firewall_policy_digest' => $agentPolicyDigest,
|
|
], 'job-payload');
|
|
$job->available_at = $job->created_at = $job->updated_at = $now;
|
|
$job->save();
|
|
|
|
$version->job_id = $job->id;
|
|
$version->operation_id = $job->operation_id;
|
|
$version->updated_at = $now;
|
|
$version->save();
|
|
|
|
if ($policy === null) {
|
|
$policy = new CloudInstanceFirewall();
|
|
$policy->instance_id = $locked->id;
|
|
$policy->user_id = $locked->user_id;
|
|
$policy->host_id = $locked->host_id;
|
|
$policy->applied_revision = 0;
|
|
$policy->applied_digest = null;
|
|
$policy->last_success_at = 0;
|
|
$policy->last_failure_at = 0;
|
|
$policy->created_at = $now;
|
|
}
|
|
$policy->enabled = $enabled;
|
|
$policy->desired_revision = $revision;
|
|
$policy->desired_digest = $policyDigest;
|
|
$policy->sync_state = 'pending';
|
|
$policy->last_operation_id = $job->operation_id;
|
|
$policy->last_error_code = null;
|
|
$policy->updated_at = $now;
|
|
$policy->save();
|
|
|
|
return [
|
|
'policy' => self::listing($locked, $actor),
|
|
'job' => $job,
|
|
'unchanged' => false,
|
|
];
|
|
}, 3);
|
|
}
|
|
|
|
/** Reject stale jobs, or return false when confirmed deletion supersedes one. */
|
|
public static function assertJobRunnable(CloudJob $job, array $payload): bool
|
|
{
|
|
if ((string) $job->kind !== 'firewall_apply') {
|
|
return true;
|
|
}
|
|
$versionId = filter_var($payload['firewall_version_id'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
|
$revision = filter_var($payload['firewall_revision'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
|
$digest = $payload['firewall_policy_digest'] ?? null;
|
|
$agentDigest = $payload['agent_firewall_policy_digest'] ?? null;
|
|
$body = $payload['body'] ?? null;
|
|
$policy = $job->instance_id === null ? null
|
|
: CloudInstanceFirewall::where('instance_id', (int) $job->instance_id)
|
|
->first();
|
|
$version = $versionId === false ? null
|
|
: CloudInstanceFirewallVersion::find((int) $versionId);
|
|
if ($policy === null || $version === null || $revision === false
|
|
|| !is_string($digest)
|
|
|| preg_match('/^[a-f0-9]{64}$/D', $digest) !== 1
|
|
|| !is_string($agentDigest)
|
|
|| preg_match('/^[a-f0-9]{64}$/D', $agentDigest) !== 1
|
|
|| !is_array($body) || array_is_list($body)
|
|
|| (int) $policy->host_id !== (int) $job->host_id
|
|
|| (int) $policy->user_id !== (int) ($payload['owner_id'] ?? 0)
|
|
|| (int) $version->instance_id !== (int) $job->instance_id
|
|
|| (int) $version->revision !== (int) $revision
|
|
|| !hash_equals((string) $version->policy_digest, $digest)
|
|
|| !hash_equals((string) $version->operation_id,
|
|
(string) $job->operation_id)
|
|
|| (int) ($version->job_id ?? 0) !== (int) $job->id
|
|
|| (int) ($body['revision'] ?? 0) !== (int) $revision
|
|
|| !is_string($body['policy_digest'] ?? null)
|
|
|| !hash_equals($agentDigest,
|
|
(string) $body['policy_digest'])) {
|
|
throw new CloudError('防火墙任务与面板目标策略不一致', 409);
|
|
}
|
|
if ((string) $policy->sync_state === 'deleted') {
|
|
return false;
|
|
}
|
|
if (!hash_equals((string) $policy->desired_digest, $digest)
|
|
|| !hash_equals((string) $policy->last_operation_id,
|
|
(string) $job->operation_id)) {
|
|
throw new CloudError('防火墙任务与面板目标策略不一致', 409);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public static function markJobRunning(CloudJob $job): void
|
|
{
|
|
if ((string) $job->kind !== 'firewall_apply') {
|
|
return;
|
|
}
|
|
$now = time();
|
|
CloudInstanceFirewall::where('instance_id', (int) $job->instance_id)
|
|
->where('last_operation_id', (string) $job->operation_id)
|
|
->where('sync_state', 'pending')
|
|
->update(['sync_state' => 'applying', 'updated_at' => $now]);
|
|
CloudInstanceFirewallVersion::where('job_id', (int) $job->id)
|
|
->where('operation_id', (string) $job->operation_id)
|
|
->where('state', 'pending')
|
|
->update(['state' => 'applying', 'updated_at' => $now]);
|
|
}
|
|
|
|
/** Apply a worker disposition while its cloud_jobs row is locked. */
|
|
public static function finishJobLocked(CloudJob $job, string $status,
|
|
$result, array $payload, array $operation): void
|
|
{
|
|
if ((string) $job->kind !== 'firewall_apply') {
|
|
return;
|
|
}
|
|
$confirmedOperationId = $operation['operation_id'] ?? null;
|
|
if ($job->dispatched_at !== null
|
|
&& (!is_string($confirmedOperationId)
|
|
|| !hash_equals((string) $job->operation_id,
|
|
$confirmedOperationId))) {
|
|
throw new CloudError(
|
|
'Agent 防火墙结果与任务操作编号不一致,必须人工核查', 502
|
|
);
|
|
}
|
|
$versionId = filter_var($payload['firewall_version_id'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
|
$revision = filter_var($payload['firewall_revision'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
|
$digest = $payload['firewall_policy_digest'] ?? null;
|
|
$agentDigest = $payload['agent_firewall_policy_digest'] ?? null;
|
|
$policy = $job->instance_id === null ? null
|
|
: CloudInstanceFirewall::where('instance_id', (int) $job->instance_id)
|
|
->lockForUpdate()->first();
|
|
$version = $versionId === false ? null
|
|
: CloudInstanceFirewallVersion::where('id', (int) $versionId)
|
|
->lockForUpdate()->first();
|
|
if ($policy === null || $version === null || $revision === false
|
|
|| !is_string($digest)
|
|
|| preg_match('/^[a-f0-9]{64}$/D', $digest) !== 1
|
|
|| !is_string($agentDigest)
|
|
|| preg_match('/^[a-f0-9]{64}$/D', $agentDigest) !== 1
|
|
|| (int) $policy->host_id !== (int) $job->host_id
|
|
|| (int) $policy->user_id !== (int) ($payload['owner_id'] ?? 0)
|
|
|| (int) $version->instance_id !== (int) $job->instance_id
|
|
|| (int) $version->revision !== (int) $revision
|
|
|| !hash_equals((string) $version->policy_digest, $digest)
|
|
|| !hash_equals((string) $version->operation_id,
|
|
(string) $job->operation_id)
|
|
|| (int) ($version->job_id ?? 0) !== (int) $job->id) {
|
|
throw new CloudError('防火墙任务与面板记录不一致,必须人工核查', 409);
|
|
}
|
|
|
|
$now = time();
|
|
if ((string) $policy->sync_state === 'deleted') {
|
|
// The destructive operation is the final state. Preserve its
|
|
// operation ID and policy marker while closing this now-obsolete
|
|
// version so the worker never retries it forever.
|
|
$version->state = 'superseded';
|
|
$version->error_code = 'firewall_apply_superseded';
|
|
$version->updated_at = $now;
|
|
$version->save();
|
|
return;
|
|
}
|
|
if ((int) $policy->desired_revision !== (int) $revision
|
|
|| !hash_equals((string) $policy->desired_digest, $digest)
|
|
|| !hash_equals((string) $policy->last_operation_id,
|
|
(string) $job->operation_id)) {
|
|
throw new CloudError('防火墙任务与面板记录不一致,必须人工核查', 409);
|
|
}
|
|
if ($status === 'running') {
|
|
$policy->sync_state = 'applying';
|
|
$version->state = 'applying';
|
|
} elseif ($status === 'uncertain') {
|
|
$policy->sync_state = 'uncertain';
|
|
$policy->last_failure_at = $now;
|
|
$policy->last_error_code = 'firewall_result_uncertain';
|
|
$version->state = 'uncertain';
|
|
$version->error_code = 'firewall_result_uncertain';
|
|
} elseif ($status === 'failed') {
|
|
$errorCode = CloudOperationErrorCatalog::workerSummary(
|
|
'firewall_apply', 'failed', $operation
|
|
) ?? 'firewall_apply_failed';
|
|
$policy->sync_state = 'failed';
|
|
$policy->last_failure_at = $now;
|
|
$policy->last_error_code = $errorCode;
|
|
$version->state = 'failed';
|
|
$version->error_code = $errorCode;
|
|
} elseif ($status === 'succeeded') {
|
|
$confirmedRevision = is_array($result)
|
|
? filter_var($result['revision'] ?? null, FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]) : false;
|
|
$confirmedDigest = is_array($result)
|
|
? ($result['policy_digest'] ?? null) : null;
|
|
if ($confirmedRevision === false
|
|
|| (int) $confirmedRevision !== (int) $revision
|
|
|| !is_string($confirmedDigest)
|
|
|| !hash_equals($agentDigest, $confirmedDigest)) {
|
|
throw new CloudError('Agent 成功结果缺少已确认的防火墙策略', 502);
|
|
}
|
|
$policy->applied_revision = (int) $revision;
|
|
$policy->applied_digest = $digest;
|
|
$policy->sync_state = (bool) $version->enabled
|
|
? 'active' : 'disabled';
|
|
$policy->last_success_at = $now;
|
|
$policy->last_error_code = null;
|
|
$version->state = 'applied';
|
|
$version->error_code = null;
|
|
$version->applied_at = $now;
|
|
}
|
|
$policy->updated_at = $version->updated_at = $now;
|
|
$version->save();
|
|
$policy->save();
|
|
}
|
|
|
|
/** Preserve a visible uncertain state after a dispatched HTTP failure. */
|
|
public static function markJobUncertain(CloudJob $job): void
|
|
{
|
|
if (!in_array((string) $job->kind,
|
|
['firewall_apply', 'delete', 'expiry_delete', 'delete_force'], true)) {
|
|
return;
|
|
}
|
|
if ((string) $job->kind !== 'firewall_apply'
|
|
&& !self::catalogAvailable()) {
|
|
return;
|
|
}
|
|
(new CloudInstanceFirewall())->getConnection()->transaction(
|
|
function () use ($job): void {
|
|
$now = time();
|
|
if (in_array((string) $job->kind,
|
|
['delete', 'expiry_delete', 'delete_force'], true)) {
|
|
CloudInstanceFirewall::where(
|
|
'instance_id', (int) $job->instance_id
|
|
)->update([
|
|
'sync_state' => 'cleanup_pending',
|
|
'last_operation_id' => (string) $job->operation_id,
|
|
'last_failure_at' => $now,
|
|
'last_error_code' => 'firewall_cleanup_pending',
|
|
'updated_at' => $now,
|
|
]);
|
|
return;
|
|
}
|
|
CloudInstanceFirewall::where(
|
|
'instance_id', (int) $job->instance_id
|
|
)->where('last_operation_id', (string) $job->operation_id)
|
|
->update([
|
|
'sync_state' => 'uncertain',
|
|
'last_failure_at' => $now,
|
|
'last_error_code' => 'firewall_result_uncertain',
|
|
'updated_at' => $now,
|
|
]);
|
|
CloudInstanceFirewallVersion::where('job_id', (int) $job->id)
|
|
->where('operation_id', (string) $job->operation_id)
|
|
->update([
|
|
'state' => 'uncertain',
|
|
'error_code' => 'firewall_result_uncertain',
|
|
'updated_at' => $now,
|
|
]);
|
|
}, 3
|
|
);
|
|
}
|
|
|
|
/** Reflect VM-delete cleanup without erasing the firewall audit history. */
|
|
public static function finishInstanceDeleteLocked(CloudJob $job,
|
|
string $status): void
|
|
{
|
|
if (!in_array((string) $job->kind,
|
|
['delete', 'expiry_delete', 'delete_force'], true)
|
|
|| $job->instance_id === null
|
|
|| !in_array($status, ['succeeded', 'failed', 'uncertain'], true)
|
|
|| !self::catalogAvailable()) {
|
|
return;
|
|
}
|
|
$policy = CloudInstanceFirewall::where(
|
|
'instance_id', (int) $job->instance_id
|
|
)->lockForUpdate()->first();
|
|
if ($policy === null) {
|
|
return;
|
|
}
|
|
$now = time();
|
|
if ($status === 'succeeded') {
|
|
$policy->enabled = false;
|
|
$policy->sync_state = 'deleted';
|
|
$policy->last_operation_id = (string) $job->operation_id;
|
|
$policy->last_error_code = null;
|
|
} elseif ($status === 'uncertain') {
|
|
$policy->sync_state = 'cleanup_pending';
|
|
$policy->last_operation_id = (string) $job->operation_id;
|
|
$policy->last_failure_at = $now;
|
|
$policy->last_error_code = 'firewall_cleanup_pending';
|
|
} elseif ((string) $policy->sync_state === 'cleanup_pending'
|
|
&& hash_equals((string) $policy->last_operation_id,
|
|
(string) $job->operation_id)) {
|
|
$converged = (int) $policy->desired_revision
|
|
=== (int) $policy->applied_revision;
|
|
$policy->sync_state = $converged
|
|
? ((bool) $policy->enabled ? 'active' : 'disabled')
|
|
: 'failed';
|
|
$policy->last_error_code = $converged
|
|
? null : 'firewall_apply_failed';
|
|
}
|
|
$policy->updated_at = $now;
|
|
$policy->save();
|
|
}
|
|
|
|
private static function assertOwnerAndTemplate(CloudInstance $instance,
|
|
array $actor): void
|
|
{
|
|
if ((int) $instance->user_id !== (int) ($actor['user_id'] ?? 0)) {
|
|
throw new CloudError('虚拟机不存在或无权访问', 404);
|
|
}
|
|
$spec = json_decode((string) $instance->spec_json, true);
|
|
if (!is_array($spec) || array_is_list($spec)
|
|
|| ($spec['os_source'] ?? null) !== 'cloud_template') {
|
|
throw new CloudError('当前实例不支持面板防火墙', 409);
|
|
}
|
|
}
|
|
|
|
private static function idempotencyKey($value): string
|
|
{
|
|
if (!is_string($value)) {
|
|
throw new CloudError('请提供有效的防火墙请求幂等键');
|
|
}
|
|
$value = trim($value);
|
|
if (strlen($value) < 16 || strlen($value) > 128
|
|
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9._:-]*$/D', $value) !== 1) {
|
|
throw new CloudError('防火墙请求幂等键需为 16 至 128 位安全字符');
|
|
}
|
|
return $value;
|
|
}
|
|
|
|
private static function jobRequestKey(int $instanceId, string $key): string
|
|
{
|
|
return 'fw-' . $instanceId . '-' . hash('sha256', $key);
|
|
}
|
|
|
|
private static function jobWasUndispatchedNoop(CloudJob $job): bool
|
|
{
|
|
if ((string) $job->phase !== 'terminal'
|
|
|| (string) $job->outcome !== 'succeeded'
|
|
|| (int) $job->dispatch_attempts !== 0
|
|
|| !is_string($job->result_json)) {
|
|
return false;
|
|
}
|
|
$result = json_decode($job->result_json, true);
|
|
return is_array($result) && !array_is_list($result)
|
|
&& ($result['unchanged'] ?? null) === true;
|
|
}
|
|
|
|
private static function rules($value): array
|
|
{
|
|
if (!is_array($value) || !array_is_list($value)) {
|
|
throw new CloudError('防火墙规则必须是数组');
|
|
}
|
|
if (count($value) > self::MAX_RULES) {
|
|
throw new CloudError('每台实例最多允许 50 条防火墙规则');
|
|
}
|
|
$rules = [];
|
|
$duplicates = [];
|
|
foreach ($value as $item) {
|
|
if (!is_array($item) || array_is_list($item)) {
|
|
throw new CloudError('防火墙规则格式无效');
|
|
}
|
|
CloudInput::only($item, [
|
|
'protocol', 'source_cidr', 'port_from', 'port_to',
|
|
'description',
|
|
]);
|
|
$protocol = is_string($item['protocol'] ?? null)
|
|
? strtolower(trim($item['protocol'])) : '';
|
|
if (!in_array($protocol, self::PROTOCOLS, true)) {
|
|
throw new CloudError('防火墙协议仅支持 TCP、UDP 或 ICMP');
|
|
}
|
|
$source = self::cidr($item['source_cidr'] ?? null);
|
|
$from = $item['port_from'] ?? null;
|
|
$to = $item['port_to'] ?? null;
|
|
if ($protocol === 'icmp') {
|
|
if ($from !== null || $to !== null) {
|
|
throw new CloudError('ICMP 规则不能设置端口');
|
|
}
|
|
$from = $to = null;
|
|
} else {
|
|
$from = filter_var($from, FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1, 'max_range' => 65535]]);
|
|
$to = filter_var($to, FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1, 'max_range' => 65535]]);
|
|
if ($from === false || $to === false || (int) $from > (int) $to) {
|
|
throw new CloudError('防火墙端口需为 1 至 65535 的有效范围');
|
|
}
|
|
$from = (int) $from;
|
|
$to = (int) $to;
|
|
}
|
|
$description = $item['description'] ?? '';
|
|
if (!is_string($description)) {
|
|
throw new CloudError('防火墙规则说明格式无效');
|
|
}
|
|
$description = trim($description);
|
|
if (mb_strlen($description, 'UTF-8') > 100
|
|
|| preg_match('//u', $description) !== 1
|
|
|| preg_match('/[\x00-\x1F\x7F]/u', $description) === 1) {
|
|
throw new CloudError('防火墙规则说明最多 100 个字符,不能包含控制字符');
|
|
}
|
|
$identity = implode('|', [
|
|
$protocol, $source, $from ?? '', $to ?? '',
|
|
]);
|
|
if (isset($duplicates[$identity])) {
|
|
throw new CloudError('防火墙规则存在重复项');
|
|
}
|
|
$duplicates[$identity] = true;
|
|
$rules[] = [
|
|
'protocol' => $protocol,
|
|
'source_cidr' => $source,
|
|
'port_from' => $from,
|
|
'port_to' => $to,
|
|
'description' => $description,
|
|
];
|
|
}
|
|
usort($rules, static function (array $left, array $right): int {
|
|
foreach (['protocol', 'source_cidr'] as $field) {
|
|
$comparison = strcmp($left[$field], $right[$field]);
|
|
if ($comparison !== 0) {
|
|
return $comparison;
|
|
}
|
|
}
|
|
foreach (['port_from', 'port_to'] as $field) {
|
|
$comparison = ($left[$field] ?? -1) <=> ($right[$field] ?? -1);
|
|
if ($comparison !== 0) {
|
|
return $comparison;
|
|
}
|
|
}
|
|
return strcmp($left['description'], $right['description']);
|
|
});
|
|
return $rules;
|
|
}
|
|
|
|
/**
|
|
* Normalize one IPv4 or IPv6 host/network into its canonical network
|
|
* prefix. Accepting host bits preserves the original API contract while
|
|
* ensuring the Agent only receives one stable representation.
|
|
*/
|
|
private static function cidr($value): string
|
|
{
|
|
if (!is_string($value)) {
|
|
throw new CloudError('防火墙来源必须是 IPv4、IPv6 地址或 CIDR');
|
|
}
|
|
$value = trim($value);
|
|
$parts = explode('/', $value);
|
|
if (count($parts) > 2 || str_contains($value, '%')) {
|
|
throw new CloudError('防火墙来源必须是有效的 IPv4、IPv6 地址或 CIDR');
|
|
}
|
|
$address = $parts[0] ?? '';
|
|
$family = filter_var($address, FILTER_VALIDATE_IP,
|
|
FILTER_FLAG_IPV4) !== false ? 4 : (filter_var(
|
|
$address,
|
|
FILTER_VALIDATE_IP,
|
|
FILTER_FLAG_IPV6
|
|
) !== false ? 6 : 0);
|
|
$maximum = $family === 4 ? 32 : 128;
|
|
$prefix = count($parts) === 1 ? (string) $maximum : $parts[1];
|
|
if ($family === 0 || !is_string($prefix)
|
|
|| preg_match('/^(?:0|[1-9][0-9]{0,2})$/D', $prefix) !== 1
|
|
|| (int) $prefix > $maximum) {
|
|
throw new CloudError('防火墙来源必须是有效的 IPv4、IPv6 地址或 CIDR');
|
|
}
|
|
$prefix = (int) $prefix;
|
|
$packed = inet_pton($address);
|
|
if (!is_string($packed) || strlen($packed) !== ($family === 4 ? 4 : 16)) {
|
|
throw new CloudError('防火墙来源无法规范化');
|
|
}
|
|
$bytes = array_values(unpack('C*', $packed));
|
|
$whole = intdiv($prefix, 8);
|
|
$remaining = $prefix % 8;
|
|
foreach ($bytes as $index => $byte) {
|
|
if ($index < $whole) {
|
|
continue;
|
|
}
|
|
if ($index === $whole && $remaining > 0) {
|
|
$bytes[$index] = $byte
|
|
& ((0xff << (8 - $remaining)) & 0xff);
|
|
continue;
|
|
}
|
|
$bytes[$index] = 0;
|
|
}
|
|
$network = $family === 4
|
|
? implode('.', $bytes) : self::ipv6Text($bytes);
|
|
return $network . '/' . $prefix;
|
|
}
|
|
|
|
/**
|
|
* Format masked IPv6 bytes like Go net/netip and RFC 5952. Only an actual
|
|
* IPv4-mapped address keeps a dotted-decimal tail; compatible, translated,
|
|
* and NAT64 forms stay hexadecimal.
|
|
*/
|
|
private static function ipv6Text(array $bytes): string
|
|
{
|
|
if (count($bytes) !== 16) {
|
|
throw new CloudError('防火墙来源无法规范化');
|
|
}
|
|
$mapped = true;
|
|
for ($index = 0; $index < 10; $index++) {
|
|
if (($bytes[$index] ?? null) !== 0) {
|
|
$mapped = false;
|
|
break;
|
|
}
|
|
}
|
|
$mapped = $mapped
|
|
&& ($bytes[10] ?? null) === 0xff
|
|
&& ($bytes[11] ?? null) === 0xff;
|
|
if ($mapped) {
|
|
return '::ffff:' . implode('.', array_slice($bytes, 12, 4));
|
|
}
|
|
|
|
$words = [];
|
|
for ($index = 0; $index < 16; $index += 2) {
|
|
$words[] = ($bytes[$index] << 8) | $bytes[$index + 1];
|
|
}
|
|
$bestStart = -1;
|
|
$bestLength = 0;
|
|
for ($index = 0; $index < 8;) {
|
|
if ($words[$index] !== 0) {
|
|
$index++;
|
|
continue;
|
|
}
|
|
$start = $index;
|
|
while ($index < 8 && $words[$index] === 0) {
|
|
$index++;
|
|
}
|
|
$length = $index - $start;
|
|
if ($length >= 2 && $length > $bestLength) {
|
|
$bestStart = $start;
|
|
$bestLength = $length;
|
|
}
|
|
}
|
|
$hex = array_map(static fn (int $word): string => dechex($word), $words);
|
|
if ($bestStart < 0) {
|
|
return implode(':', $hex);
|
|
}
|
|
$left = implode(':', array_slice($hex, 0, $bestStart));
|
|
$right = implode(':', array_slice(
|
|
$hex,
|
|
$bestStart + $bestLength
|
|
));
|
|
if ($left === '') {
|
|
return $right === '' ? '::' : '::' . $right;
|
|
}
|
|
return $right === '' ? $left . '::' : $left . '::' . $right;
|
|
}
|
|
|
|
private static function policyDigest(bool $enabled, array $rules): string
|
|
{
|
|
return hash('sha256', json_encode([
|
|
'version' => 1,
|
|
'enabled' => $enabled,
|
|
'rules' => $rules,
|
|
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
|
| JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS));
|
|
}
|
|
|
|
/** Translate the PHP-owned ingress allow-list into the Agent DTO. */
|
|
private static function agentPolicy(int $revision, bool $enabled,
|
|
array $rules): array
|
|
{
|
|
$agentRules = [];
|
|
if ($enabled) {
|
|
foreach ($rules as $rule) {
|
|
$agentRule = [
|
|
'direction' => 'ingress',
|
|
'action' => 'accept',
|
|
'protocol' => $rule['protocol'],
|
|
'cidr' => $rule['source_cidr'],
|
|
];
|
|
if ($rule['port_from'] !== null) {
|
|
$agentRule['port_from'] = (int) $rule['port_from'];
|
|
$agentRule['port_to'] = (int) $rule['port_to'];
|
|
}
|
|
$agentRules[] = $agentRule;
|
|
}
|
|
}
|
|
return [
|
|
'revision' => $revision,
|
|
'default_in' => $enabled ? 'drop' : 'accept',
|
|
'default_out' => 'accept',
|
|
'rules' => $agentRules,
|
|
];
|
|
}
|
|
|
|
/** Match Go's json.Marshal field order for FirewallPolicy validation. */
|
|
private static function agentPolicyDigest(array $policy): string
|
|
{
|
|
return hash('sha256', json_encode($policy,
|
|
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
|
| JSON_UNESCAPED_UNICODE));
|
|
}
|
|
|
|
private static function rulesForRevision(int $instanceId,
|
|
int $revision): array
|
|
{
|
|
if ($revision < 1) {
|
|
return [];
|
|
}
|
|
$version = CloudInstanceFirewallVersion::where(
|
|
'instance_id', $instanceId
|
|
)->where('revision', $revision)->first();
|
|
if ($version === null) {
|
|
return [];
|
|
}
|
|
$rules = [];
|
|
foreach (CloudInstanceFirewallRule::where(
|
|
'version_id', (int) $version->id
|
|
)->orderBy('sequence')->get() as $rule) {
|
|
$rules[] = [
|
|
'protocol' => (string) $rule->protocol,
|
|
'source_cidr' => (string) $rule->source_cidr,
|
|
'port_from' => $rule->port_from === null
|
|
? null : (int) $rule->port_from,
|
|
'port_to' => $rule->port_to === null
|
|
? null : (int) $rule->port_to,
|
|
'description' => (string) $rule->description,
|
|
];
|
|
}
|
|
return $rules;
|
|
}
|
|
|
|
private static function publicState(string $value): string
|
|
{
|
|
return in_array($value, [
|
|
'disabled', 'pending', 'applying', 'active', 'failed',
|
|
'uncertain', 'cleanup_pending', 'deleted',
|
|
], true) ? $value : 'uncertain';
|
|
}
|
|
|
|
private static function catalogAvailable(): bool
|
|
{
|
|
return (new CloudInstanceFirewall())->getConnection()
|
|
->getSchemaBuilder()->hasTable('cloud_instance_firewalls');
|
|
}
|
|
}
|