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 = CloudJob::where('instance_id', (int) $instance->id) ->whereIn('status', self::ACTIVE_JOB_STATES)->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); $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 ): 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); } $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)) { // A new idempotency key must not turn an already-converged // policy into another permanent version/job/rule set. // The original applied version remains the audit record. return [ 'policy' => self::listing($locked, $actor), 'job' => null, 'unchanged' => true, ]; } } $now = time(); $activeJobs = CloudJob::where('instance_id', (int) $locked->id) ->whereIn('status', self::ACTIVE_JOB_STATES)->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++; $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->instance_id = $locked->id; $job->user_id = (int) $locked->user_id; $job->host_id = $locked->host_id; $job->kind = 'firewall_apply'; $job->status = 'queued'; $job->payload_cipher = CloudSecrets::encrypt([ 'method' => 'PUT', 'resource' => 'vms/' . rawurlencode((string) $locked->uuid) . '/firewall', 'body' => [ 'enabled' => $enabled, 'revision' => $revision, 'policy_digest' => $policyDigest, 'rules' => $rules, ], 'owner_id' => (int) $locked->user_id, 'can_manage' => true, 'firewall_version_id' => (int) $version->id, 'firewall_revision' => $revision, 'firewall_policy_digest' => $policyDigest, ]); $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; $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_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($digest, (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( '引擎防火墙结果与任务操作编号不一致,必须人工核查', 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; $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 || (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($digest, $confirmedDigest)) { throw new CloudError('引擎成功结果缺少已确认的防火墙策略', 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'], 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'], 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'], 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 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::ipv4Cidr($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; } private static function ipv4Cidr($value): string { if (!is_string($value)) { throw new CloudError('防火墙来源必须是 IPv4 地址或 CIDR'); } $value = trim($value); $parts = explode('/', $value, 2); $address = $parts[0] ?? ''; $prefix = count($parts) === 1 ? '32' : $parts[1]; if (filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false || !is_string($prefix) || preg_match('/^(?:[0-9]|[12][0-9]|3[0-2])$/D', $prefix) !== 1) { throw new CloudError('防火墙来源必须是有效的 IPv4 地址或 CIDR'); } $prefix = (int) $prefix; $number = (int) sprintf('%u', ip2long($address)); $mask = $prefix === 0 ? 0 : ((0xffffffff << (32 - $prefix)) & 0xffffffff); return long2ip($number & $mask) . '/' . $prefix; } 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)); } 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'); } }