transaction(function (): array { $state = self::state(true); $rows = self::activeQuery('share')->get(); $dynamic = self::dynamicRulesFromRows($rows); $rules = []; foreach ($rows as $row) { $rules[] = self::displayRow($row); } return [ 'revision' => (int) $state->revision, 'rules' => $rules, 'maximum_expanded_rules' => self::MAX_EXPANDED_RULES, 'base_expanded_rules' => self::baseExpandedCount(), 'available_expanded_rules' => self::MAX_EXPANDED_RULES - self::expandedCount($dynamic), ]; }, 3); } public static function create(array $input, array $actor): array { self::requireManager($actor); CloudInput::only($input, [ 'expected_revision', 'service', 'protocol', 'port', 'direction', 'reason', ]); $expected = self::revision($input['expected_revision'] ?? null); $normalized = self::inputRule($input); self::connection()->transaction(function () use ( $actor, $expected, $normalized ): void { $state = self::lockedState($expected); $rows = self::activeQuery('update')->get(); if ($rows->count() >= self::MAX_TEST_RULES) { throw new CloudError('手动测试规则数量已达上限', 409); } $candidate = self::dynamicRulesFromRows($rows); $ruleKey = bin2hex(random_bytes(16)); $candidate[] = self::canonicalDynamicRule($ruleKey, $normalized); self::validateCombined($candidate); // Reject an oversized catalog before it can be committed. Without // this exact serialization check the administrator could save a // valid-looking directory that makes every later payment fail // while freezing its provisioning snapshot. self::snapshot($expected + 1, $candidate); $now = time(); $row = new CloudPlatformTestPolicyRule(); $row->rule_key = $ruleKey; self::fillRow($row, $normalized); $row->created_by = $row->updated_by = (int) $actor['user_id']; $row->created_at = $row->updated_at = $now; $row->save(); self::advance($state, $actor, $now); }, 3); return self::page(); } public static function update(string $ruleKey, array $input, array $actor): array { self::requireManager($actor); self::assertRuleKey($ruleKey); CloudInput::only($input, [ 'expected_revision', 'service', 'protocol', 'port', 'direction', 'reason', ]); $expected = self::revision($input['expected_revision'] ?? null); $normalized = self::inputRule($input); self::connection()->transaction(function () use ( $actor, $expected, $normalized, $ruleKey ): void { $state = self::lockedState($expected); $rows = self::activeQuery('update')->get(); $target = $rows->first(static fn ($row): bool => hash_equals((string) $row->rule_key, $ruleKey)); if ($target === null) { throw new CloudError('手动测试规则不存在', 404); } $candidate = []; foreach ($rows as $row) { $candidate[] = (string) $row->rule_key === $ruleKey ? self::canonicalDynamicRule($ruleKey, $normalized) : self::canonicalDynamicRuleFromRow($row); } self::validateCombined($candidate); self::snapshot($expected + 1, $candidate); $now = time(); self::fillRow($target, $normalized); $target->updated_by = (int) $actor['user_id']; $target->updated_at = $now; $target->save(); self::advance($state, $actor, $now); }, 3); return self::page(); } public static function delete(string $ruleKey, array $input, array $actor): array { self::requireManager($actor); self::assertRuleKey($ruleKey); CloudInput::only($input, ['expected_revision']); $expected = self::revision($input['expected_revision'] ?? null); self::connection()->transaction(function () use ( $actor, $expected, $ruleKey ): void { $state = self::lockedState($expected); $row = self::activeQuery('update') ->where('rule_key', $ruleKey)->first(); if ($row === null) { throw new CloudError('手动测试规则不存在', 404); } $now = time(); $row->deleted_by = $row->updated_by = (int) $actor['user_id']; $row->deleted_at = $row->updated_at = $now; $row->save(); self::advance($state, $actor, $now); }, 3); return self::page(); } /** Freeze the complete effective policy inside an existing DB transaction. */ public static function snapshotForProvisioning(): array { return self::connection()->transaction(function (): array { $state = self::state(true); $dynamic = self::dynamicRulesFromRows( self::activeQuery('share')->get() ); self::validateCombined($dynamic); return self::snapshot((int) $state->revision, $dynamic); }, 3); } /** Strictly validate a historical snapshot without consulting live rows. */ public static function assertSnapshot($value): array { if (!is_array($value) || array_is_list($value)) { throw new CloudError('平台网络策略快照无效', 409); } self::assertExactKeys($value, self::SNAPSHOT_KEYS, '平台网络策略快照'); $manifest = CloudPlatformDefaultNetworkPolicy::manifest(); $revision = $value['catalog_revision'] ?? null; if (($value['schema_version'] ?? null) !== self::SNAPSHOT_SCHEMA_VERSION || ($value['base_policy_version'] ?? null) !== $manifest['policy_version'] || is_bool($revision) || !is_int($revision) || $revision < 0 || !is_string($value['digest'] ?? null) || preg_match('/^[a-f0-9]{64}$/D', $value['digest']) !== 1 || !is_array($value['rules'] ?? null) || !array_is_list($value['rules'])) { throw new CloudError('平台网络策略快照无效', 409); } $base = array_map([self::class, 'canonicalRule'], $manifest['rules']); if (count($value['rules']) < count($base) || array_slice($value['rules'], 0, count($base)) !== $base) { throw new CloudError('平台网络策略基础版本不匹配', 409); } $dynamic = array_slice($value['rules'], count($base)); $canonicalDynamic = []; foreach ($dynamic as $rule) { if (!is_array($rule) || array_is_list($rule)) { throw new CloudError('平台网络策略测试规则无效', 409); } self::assertExactKeys($rule, self::RULE_KEYS, '平台网络策略测试规则'); if (($rule['category'] ?? null) !== 'test' || !is_string($rule['id'] ?? null) || preg_match('/^test-[a-f0-9]{32}$/D', $rule['id']) !== 1) { throw new CloudError('平台网络策略测试规则无效', 409); } $canonicalDynamic[] = self::canonicalValidatedRule($rule); } usort($canonicalDynamic, static fn (array $left, array $right): int => strcmp($left['id'], $right['id'])); if ($dynamic !== $canonicalDynamic) { throw new CloudError('平台网络策略测试规则顺序无效', 409); } self::validateCombined($canonicalDynamic); $expected = self::snapshot($revision, $canonicalDynamic); if (!hash_equals($expected['digest'], $value['digest']) || $expected !== $value) { throw new CloudError('平台网络策略快照摘要不匹配', 409); } return $expected; } private static function snapshot(int $revision, array $dynamic): array { $manifest = CloudPlatformDefaultNetworkPolicy::manifest(); $rules = array_map([self::class, 'canonicalRule'], $manifest['rules']); foreach ($dynamic as $rule) { $rules[] = self::canonicalRule($rule); } $document = [ 'schema_version' => self::SNAPSHOT_SCHEMA_VERSION, 'base_policy_version' => (int) $manifest['policy_version'], 'catalog_revision' => $revision, 'rules' => $rules, ]; $encoded = json_encode($document, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS); $snapshot = $document + ['digest' => hash('sha256', $encoded)]; $snapshotBytes = json_encode($snapshot, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS); if (strlen($snapshotBytes) > 32768) { throw new CloudError( '平台网络策略快照超过 32 KiB,请缩短服务或原因说明', 422 ); } return $snapshot; } private static function validateCombined(array $dynamic): void { $manifest = CloudPlatformDefaultNetworkPolicy::manifest(); $expanded = []; foreach ($manifest['rules'] as $rule) { self::addExpanded($expanded, $rule, false); } $ids = []; foreach ($dynamic as $rule) { $rule = self::canonicalValidatedRule($rule); if (isset($ids[$rule['id']])) { throw new CloudError('手动测试规则标识重复', 422); } $ids[$rule['id']] = true; foreach ($rule['protocols'] as $protocol) { foreach ($manifest['explicitly_unrestricted'] as $entry) { if ($entry['protocol'] === $protocol && $entry['port'] >= $rule['port_from'] && $entry['port'] <= $rule['port_to']) { throw new CloudError( '该端口已明确保持不限制,不能加入测试封禁', 422 ); } } } self::addExpanded($expanded, $rule, true); } if (count($expanded) > self::MAX_EXPANDED_RULES) { throw new CloudError( '平台规则展开后超过 70 条,请减少协议或方向组合', 422 ); } } private static function addExpanded(array &$expanded, array $rule, bool $rejectOverlap): void { foreach ($rule['protocols'] as $protocol) { foreach ($rule['directions'] as $direction) { foreach ($expanded as $existing) { if ($rejectOverlap && $existing['protocol'] === $protocol && $existing['direction'] === $direction && $rule['port_from'] <= $existing['port_to'] && $rule['port_to'] >= $existing['port_from']) { throw new CloudError( '手动测试规则与现有平台规则重复或重叠', 422 ); } } $expanded[] = [ 'protocol' => $protocol, 'direction' => $direction, 'port_from' => $rule['port_from'], 'port_to' => $rule['port_to'], ]; } } } private static function canonicalValidatedRule(array $rule): array { $label = self::text($rule['label'] ?? null, 120, '服务'); $reason = self::text($rule['reason'] ?? null, 500, '原因'); $protocols = self::enumList($rule['protocols'] ?? null, ['tcp', 'udp'], '协议'); $directions = self::enumList($rule['directions'] ?? null, ['ingress', 'egress'], '方向'); $from = $rule['port_from'] ?? null; $to = $rule['port_to'] ?? null; if (is_bool($from) || !is_int($from) || is_bool($to) || !is_int($to) || $from < 1 || $to > 65535 || $from > $to) { throw new CloudError('端口范围无效', 422); } return self::canonicalRule([ 'id' => $rule['id'], 'label' => $label, 'category' => 'test', 'protocols' => $protocols, 'port_from' => $from, 'port_to' => $to, 'directions' => $directions, 'reason' => $reason, ]); } private static function inputRule(array $input): array { $protocol = $input['protocol'] ?? null; $direction = $input['direction'] ?? null; if (!is_string($protocol) || !in_array($protocol, ['tcp', 'udp', 'tcp_udp'], true)) { throw new CloudError('协议只能选择 TCP、UDP 或 TCP/UDP', 422); } if (!is_string($direction) || !in_array($direction, ['ingress', 'egress', 'both'], true)) { throw new CloudError('方向只能选择入站、出站或双向', 422); } [$from, $to] = self::port($input['port'] ?? null); return [ 'service' => self::text($input['service'] ?? null, 120, '服务'), 'protocol' => $protocol, 'port_from' => $from, 'port_to' => $to, 'direction' => $direction, 'reason' => self::text($input['reason'] ?? null, 500, '原因'), ]; } private static function canonicalDynamicRule(string $ruleKey, array $rule): array { return self::canonicalRule([ 'id' => 'test-' . $ruleKey, 'label' => $rule['service'], 'category' => 'test', 'protocols' => match ($rule['protocol']) { 'tcp' => ['tcp'], 'udp' => ['udp'], default => ['tcp', 'udp'], }, 'port_from' => $rule['port_from'], 'port_to' => $rule['port_to'], 'directions' => match ($rule['direction']) { 'ingress' => ['ingress'], 'egress' => ['egress'], default => ['ingress', 'egress'], }, 'reason' => $rule['reason'], ]); } private static function canonicalDynamicRuleFromRow($row): array { return self::canonicalDynamicRule((string) $row->rule_key, [ 'service' => (string) $row->service, 'protocol' => (string) $row->protocol, 'port_from' => (int) $row->port_from, 'port_to' => (int) $row->port_to, 'direction' => (string) $row->direction, 'reason' => (string) $row->reason, ]); } private static function dynamicRulesFromRows($rows): array { $rules = []; foreach ($rows as $row) { $rules[] = self::canonicalDynamicRuleFromRow($row); } usort($rules, static fn (array $left, array $right): int => strcmp($left['id'], $right['id'])); return $rules; } private static function canonicalRule(array $rule): array { return [ 'id' => $rule['id'], 'label' => $rule['label'], 'category' => $rule['category'], 'protocols' => array_values($rule['protocols']), 'port_from' => (int) $rule['port_from'], 'port_to' => (int) $rule['port_to'], 'directions' => array_values($rule['directions']), 'reason' => $rule['reason'], ]; } private static function displayRow($row): array { $port = (int) $row->port_from === (int) $row->port_to ? (string) $row->port_from : $row->port_from . '–' . $row->port_to; return [ 'id' => (string) $row->rule_key, 'service' => (string) $row->service, 'protocol' => (string) $row->protocol, 'protocol_label' => match ((string) $row->protocol) { 'tcp' => 'TCP', 'udp' => 'UDP', default => 'TCP/UDP', }, 'port' => $port, 'direction' => (string) $row->direction, 'direction_label' => match ((string) $row->direction) { 'ingress' => '仅公网入站', 'egress' => '仅公网出站', default => '公网入站、出站', }, 'reason' => (string) $row->reason, 'created_at' => (int) $row->created_at, 'updated_at' => (int) $row->updated_at, ]; } private static function fillRow($row, array $rule): void { $row->service = $rule['service']; $row->protocol = $rule['protocol']; $row->port_from = $rule['port_from']; $row->port_to = $rule['port_to']; $row->direction = $rule['direction']; $row->reason = $rule['reason']; } private static function activeQuery(string $lock = '') { $query = CloudPlatformTestPolicyRule::whereNull('deleted_at') ->orderBy('rule_key'); return match ($lock) { 'share' => $query->sharedLock(), 'update' => $query->lockForUpdate(), default => $query, }; } private static function state(bool $lock) { $query = CloudPlatformTestPolicyState::where('id', self::STATE_ID); if ($lock) { $query->sharedLock(); } $state = $query->first(); if ($state === null) { throw new CloudError('手动测试策略尚未初始化,请先执行 cloudInit', 503); } return $state; } private static function lockedState(int $expected) { $state = CloudPlatformTestPolicyState::where('id', self::STATE_ID) ->lockForUpdate()->first(); if ($state === null) { throw new CloudError('手动测试策略尚未初始化,请先执行 cloudInit', 503); } if ((int) $state->revision !== $expected) { throw new CloudError('测试策略已被其他管理员更新,请刷新后重试', 409); } return $state; } private static function advance($state, array $actor, int $now): void { $state->revision = (int) $state->revision + 1; $state->updated_by = (int) $actor['user_id']; $state->updated_at = $now; $state->save(); } private static function requireManager(array $actor): void { CloudAccess::manage($actor); } private static function revision($value): int { $revision = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => PHP_INT_MAX]]); if ($revision === false) { throw new CloudError('测试策略版本无效', 422); } return (int) $revision; } private static function port($value): array { if (is_int($value)) { $value = (string) $value; } if (!is_string($value) || preg_match('/^([0-9]{1,5})(?:-([0-9]{1,5}))?$/D', trim($value), $matches) !== 1) { throw new CloudError('端口需为单个端口或起止范围', 422); } $from = (int) $matches[1]; $to = isset($matches[2]) && $matches[2] !== '' ? (int) $matches[2] : $from; if ($from < 1 || $to > 65535 || $from > $to) { throw new CloudError('端口需在 1 至 65535 范围内', 422); } return [$from, $to]; } private static function text($value, int $maximum, string $name): string { if (!is_string($value)) { throw new CloudError($name . '不能为空', 422); } $value = trim($value); if ($value === '' || strlen($value) > $maximum || preg_match('//u', $value) !== 1 || preg_match('/[\x00-\x1F\x7F]/u', $value) === 1) { throw new CloudError($name . '格式无效或长度超限', 422); } return $value; } private static function enumList($value, array $allowed, string $name): array { if (!is_array($value) || !array_is_list($value) || $value === []) { throw new CloudError($name . '无效', 422); } $seen = []; foreach ($value as $item) { if (!is_string($item) || !in_array($item, $allowed, true) || isset($seen[$item])) { throw new CloudError($name . '无效', 422); } $seen[$item] = true; } return array_values(array_filter($allowed, static fn (string $item): bool => isset($seen[$item]))); } private static function assertRuleKey(string $value): void { if (preg_match('/^[a-f0-9]{32}$/D', $value) !== 1) { throw new CloudError('手动测试规则不存在', 404); } } private static function assertExactKeys(array $value, array $expected, string $name): void { $actual = array_keys($value); sort($actual, SORT_STRING); $wanted = $expected; sort($wanted, SORT_STRING); if ($actual !== $wanted) { throw new CloudError($name . '字段无效', 409); } } private static function expandedCount(array $dynamic): int { $count = self::baseExpandedCount(); foreach ($dynamic as $rule) { $count += count($rule['protocols']) * count($rule['directions']); } return $count; } private static function baseExpandedCount(): int { $count = 0; foreach (CloudPlatformDefaultNetworkPolicy::manifest()['rules'] as $rule) { $count += count($rule['protocols']) * count($rule['directions']); } return $count; } private static function connection() { return (new CloudPlatformTestPolicyState())->getConnection(); } }