From bccb75a2ae1cdd0ee958367e886dd96c90f84b68 Mon Sep 17 00:00:00 2001 From: admin Date: Thu, 8 Oct 2026 13:04:24 +0800 Subject: [PATCH] Harden tenant VPC creation policy --- docs/VALIDATION.md | 30 + .../Cloud/CloudPrivateCidrAllocator.php | 33 + web/app/Services/Cloud/CloudVpcService.php | 300 +++++----- web/config/.config.php.example | 2 + web/public/cloud/vpc.js | 6 +- .../views/venix/cloud/pages/vpcs.tpl | 8 +- web/resources/views/venix/layout_assets.tpl | 2 +- web/sql/cloud.sql | 5 +- .../CloudVpcControlPlaneContractTest.php | 31 + web/tests/CloudVpcCreatePolicyTest.php | 564 ++++++++++++++++++ web/tests/CloudVpcMemberReuseTest.php | 26 + web/tests/CloudVpcUserPageContractTest.php | 19 +- web/tests/VirtualizationConfigTest.php | 3 + 13 files changed, 872 insertions(+), 157 deletions(-) create mode 100644 web/tests/CloudVpcCreatePolicyTest.php diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 8babd3bd..f7041d5c 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,5 +1,35 @@ # 本版验证记录 +## 2026-10-08:租户 VPC 创建策略、账户配额与幂等加固 + +- 租户创建 API 现在只接收 `name`、`region_id` 和 `request_key`;CIDR、前缀、首个 + 子网、成员容量和 Fabric 身份全部改为平台策略。新 VPC 固定自动分配独立 `/24`,首个 + 子网覆盖该 `/24`,成员上限为 200;历史大 VPC 的 4096 协议/观测上界不变。 +- 默认每账户最多保留 5 个非 `deleted` VPC,可用 + `cloud_max_vpcs_per_account` 在 1 至 100 内调整。创建事务先锁账户行,再核对根、配额、 + Region/Fabric 和 CIDR 分配;`deleting` 根仍占账户配额,`deleting` 成员仍占成员容量, + 只有精确收敛为 `deleted` 才释放。 +- 同一创建键的回放先于当前配额、Region/Fabric 状态和分配器策略;请求摘要只包含稳定的 + 名称与地区。历史创建摘要继续按确定性 root、owner/name/region、operation 和 allocator + 链接兼容,但缺 operation、network/subnet 或精确 CIDR claim 闭集时 fail-closed。已删除 + root 只返回原 tombstone,不复活 CIDR;released allocation 出现残留 claim 同样拒绝回放。 +- CIDR 分配、root、首个 subnet 和 operation 位于同一默认数据库事务。删除了失败后的 + 二次 `release()` 补偿,避免事务回滚后与同 request key 重试竞态、误释放胜者 CIDR。 + 租户创建表单同步移除高级网络字段并提升资产版本,旧缓存不会继续提交已禁字段。 +- PHP 8.5/WASM + SQLite 下 `CloudVpcCreatePolicyTest`、 + `CloudVpcControlPlaneContractTest`、`CloudPrivateCidrAllocatorTest`、 + `CloudVpcMemberReuseTest`、`CloudVpcRootDeletionTest`、 + `CloudVpcTombstoneConvergenceTest`、`CloudVpcUserPageContractTest` 和 + `VirtualizationConfigTest` 通过;覆盖强制 post-allocation 失败零泄漏、满配额回放、历史 + hash、平台状态变化、deleted tombstone、live/released claim 损坏和 deleting 容量。 + 另通过 105 个 Smarty 模板编译、274 条路由目标、52 个前端资产契约、schema 契约、 + 修改 PHP 语法、`vpc.js` Node 语法和 `git diff --check`。 +- SQLite 不实现 MariaDB 的 `SELECT ... FOR UPDATE` 并发语义;上线前仍须在隔离 MariaDB + 上并发争抢账户最后一个名额、并发同 key 丢响应重试,并核对最终仅有一条 root、network、 + claim 和 create operation。当前未连接真实数据库、PHP-FPM、浏览器或宿主机,也未改变 + WireGuard/libvirt/firewalld 数据面。额外全仓 `SourceSyntaxTest` 仍被未修改的 + `AdminSystemLogsContractTest.php:108` 既有解析错误阻断,不归因于本轮 VPC 修改。 + ## 2026-10-08:VPC 来宾网络启动代次门禁 - 私网 MAC、`/32` 地址和唯一的 VPC CIDR scope-link 路由共同生成独立 diff --git a/web/app/Services/Cloud/CloudPrivateCidrAllocator.php b/web/app/Services/Cloud/CloudPrivateCidrAllocator.php index 15e107d7..b2b4edfa 100644 --- a/web/app/Services/Cloud/CloudPrivateCidrAllocator.php +++ b/web/app/Services/Cloud/CloudPrivateCidrAllocator.php @@ -215,6 +215,39 @@ final class CloudPrivateCidrAllocator }); } + /** Prove the claim closure used by a committed VPC-create replay. */ + public static function assertAllocationLedger(CloudPrivateNetwork $network): void + { + $state = (string) $network->state; + if (in_array($state, self::LIVE_STATES, true)) { + self::assertClaimLedger($network); + return; + } + if ($state !== 'released' || $network->active_cidr !== null + || (int) $network->released_at < 1) { + throw new CloudError('私网 CIDR 声明账本不一致,已停止回放', 503); + } + $prefix = (int) $network->prefix_length; + if ($prefix < self::DEFAULT_MIN_PREFIX_LENGTH + || $prefix > self::QUANTUM_PREFIX_LENGTH) { + throw new CloudError('私网 CIDR 声明账本不一致,已停止回放', 503); + } + try { + $canonical = self::normalizeCidr((string) $network->cidr, $prefix); + } catch (\Throwable) { + throw new CloudError('私网 CIDR 声明账本不一致,已停止回放', 503); + } + if ((string) $network->cidr !== $canonical['cidr'] + || (int) $network->network_address !== $canonical['network'] + || (int) $network->broadcast_address !== $canonical['broadcast'] + || !self::isRfc1918($canonical['network'], $canonical['broadcast']) + || CloudPrivateCidrClaim::where( + 'allocation_key', (string) $network->allocation_key + )->lockForUpdate()->get(['id'])->isNotEmpty()) { + throw new CloudError('私网 CIDR 声明账本不一致,已停止回放', 503); + } + } + /** Return a canonical RFC1918 IPv4 network description without the DB. */ public static function normalize(string $cidr, ?int $expectedPrefix = null): array { diff --git a/web/app/Services/Cloud/CloudVpcService.php b/web/app/Services/Cloud/CloudVpcService.php index f68f85b8..ad89ac2c 100644 --- a/web/app/Services/Cloud/CloudVpcService.php +++ b/web/app/Services/Cloud/CloudVpcService.php @@ -16,6 +16,7 @@ use App\Models\CloudVpcPrivateIp; use App\Models\CloudVpcRoute; use App\Models\CloudVpcSubnet; use App\Models\User; +use App\Services\Config; /** * PHP-owned VPC control plane. @@ -31,10 +32,17 @@ use App\Models\User; final class CloudVpcService { public const MAX_SUBNETS = 64; + /** Protocol/readback ceiling retained for existing large VPCs. */ public const MAX_MEMBERS = 4096; + /** Tenant creation policy for newly allocated /24 VPCs. */ + public const DEFAULT_MAX_MEMBERS = 200; + public const DEFAULT_MAX_VPCS_PER_ACCOUNT = 5; + public const MAX_VPCS_PER_ACCOUNT = 100; public const MAX_ROUTES = 256; public const MAX_ACL_RULES = 256; + private const DEFAULT_PREFIX_LENGTH = 24; + /** * Version of the engine observation contract that proves guest-visible * private addressing and routes, rather than only host/libvirt state. @@ -110,157 +118,90 @@ final class CloudVpcService */ public static function create(array $actor, array $input): array { - CloudInput::only($input, [ - 'name', 'region_id', 'cidr', 'prefix_length', 'max_members', - 'request_key', 'fabric_id', 'fabric_revision', 'subnet_cidr', - 'subnet_gateway', - ]); + // Tenant intent is deliberately small. CIDR, subnet shape, member + // capacity and Fabric identity are platform policy and must never be + // accepted merely because a caller guessed the current values. + CloudInput::only($input, ['name', 'region_id', 'request_key']); $name = CloudInput::name($input['name'] ?? null); $regionId = self::positiveInt($input['region_id'] ?? null, 1, 1000000000, '地区无效'); $requestKey = self::requestKey($input['request_key'] ?? null); - $maxMembers = self::positiveInt($input['max_members'] ?? 256, 1, - self::MAX_MEMBERS, 'VPC 成员上限无效'); - $region = CloudRegion::where('id', $regionId)->where('status', 'active')->first(); - if ($region === null) { - throw new CloudError('地区不存在或暂不可用', 409); - } - - $requestedCidr = isset($input['cidr']) ? self::cidr( - $input['cidr'], 16, 24, 'VPC CIDR') : null; - $prefix = $requestedCidr === null - ? (int) ($input['prefix_length'] ?? 24) - : $requestedCidr['prefix']; - if ($requestedCidr === null && !array_key_exists('prefix_length', $input)) { - $prefix = 24; - } - if ($prefix < 16 || $prefix > 24) { - throw new CloudError('VPC CIDR 前缀必须为 /16 至 /24'); - } - if ($requestedCidr !== null && isset($input['prefix_length']) - && (int) $input['prefix_length'] !== $requestedCidr['prefix']) { - throw new CloudError('VPC CIDR 与前缀长度不一致'); - } - // Fabric identity and revision are platform-owned. Do not derive - // them from the mutable numeric region ID or accept a tenant-supplied - // value: a Fabric may use any stable ID and may advance its revision - // after a host/key change. Missing mappings fail before CIDR reserve. - $fabricConnection = (new CloudRegionFabric())->getConnection(); - if (!$fabricConnection->getSchemaBuilder()->hasTable('cloud_region_fabrics')) { - throw new CloudError('VPC Fabric 映射表尚未安装', 503); - } - $fabric = CloudRegionFabric::where('region_id', $regionId) - ->where('state', 'active')->first(); - if ($fabric === null) { - throw new CloudError('该地区尚未配置可用的 WireGuard Fabric', 409); - } - $fabricId = self::fabricId((string) $fabric->fabric_id); - $fabricRegion = self::fabricId((string) $fabric->fabric_region); - $fabricRevision = self::positiveInt($fabric->fabric_revision, 1, - 9000000000000000, 'Fabric 版本无效'); - if (array_key_exists('fabric_id', $input) - && (string) $input['fabric_id'] !== $fabricId) { - throw new CloudError('Fabric 由平台按地区分配,不能由请求选择', 403); - } - if (array_key_exists('fabric_revision', $input) - && (int) $input['fabric_revision'] !== $fabricRevision) { - throw new CloudError('Fabric 版本已由平台更新,请刷新后重试', 409); - } - $subnet = isset($input['subnet_cidr']) - ? self::cidr($input['subnet_cidr'], $prefix, 30, '子网 CIDR') - : null; - $gateway = $input['subnet_gateway'] ?? null; - if ($gateway !== null) { - // Phase 3 deliberately has no guest default gateway. Keeping - // the nullable column makes a later data-plane migration - // explicit, but tenant input cannot enable route injection now. - throw new CloudError('当前 VPC 控制面不支持子网网关'); - } - $userId = (int) ($actor['user_id'] ?? 0); if ($userId < 1) { throw new CloudError('账户无效', 401); } $allocationKey = substr(hash('sha256', 'vpc-allocation:' . $userId . ':' . $requestKey), 0, 32); $vpcKey = substr(hash('sha256', 'vpc:' . $userId . ':' . $requestKey), 0, 32); + // Only immutable tenant intent belongs in the idempotency hash. A + // lost response must remain replayable after Fabric or policy changes. $requestHash = self::requestHash('vpc_create', [ - 'name' => $name, 'region_id' => $regionId, 'cidr' => $requestedCidr['cidr'] ?? null, - 'prefix_length' => $prefix, 'max_members' => $maxMembers, - 'fabric_id' => $fabricId, 'fabric_region' => $fabricRegion, - 'fabric_revision' => $fabricRevision, - 'subnet_cidr' => $subnet['cidr'] ?? null, 'subnet_gateway' => $gateway, + 'name' => $name, + 'region_id' => $regionId, ]); - $network = null; + $maxMembers = self::DEFAULT_MAX_MEMBERS; + $prefix = self::DEFAULT_PREFIX_LENGTH; $connection = (new CloudVpc())->getConnection(); try { return $connection->transaction(function () use ( - $actor, $name, $region, $requestKey, $requestHash, $maxMembers, - $fabricId, $fabricRegion, $fabricRevision, $subnet, $gateway, $vpcKey, - $allocationKey, $userId, $regionId, $requestedCidr, $prefix, - &$network, $connection + $actor, $name, $requestKey, $requestHash, $maxMembers, + $vpcKey, $allocationKey, $userId, $regionId, $prefix, + $connection ): array { - // Serialize region/Fabric mapping changes with VPC creation. - // The mapping is checked again after the transaction starts; - // a concurrent administrator update cannot pin an obsolete - // Fabric revision into a new desired document. - $lockedRegion = CloudRegion::where('id', $regionId) + // Account deletion locks the owner row before checking VPCs. + // The same row also serializes quota checks for this account. + if (!$connection->getSchemaBuilder()->hasTable('user')) { + throw new CloudError('账户表尚未安装', 503); + } + $owner = User::where('id', $userId)->lockForUpdate()->first(); + if ($owner === null) { + throw new CloudError('账户不存在', 401); + } + + // Replay committed intent before consulting mutable platform + // state, quota or the allocator. This also prevents a deleted + // tombstone from being resurrected under its old request key. + $existing = CloudVpc::where('vpc_key', $vpcKey) + ->lockForUpdate()->first(); + if ($existing !== null) { + return self::replayCreateLocked( + $existing, $actor, $userId, $regionId, $name, + $requestKey, $allocationKey + ); + } + + $accountLimit = self::accountVpcLimit(); + $accountVpcCount = CloudVpc::where('user_id', $userId) + ->where('state', '<>', 'deleted')->count(); + if ($accountVpcCount >= $accountLimit) { + throw new CloudError( + '账户 VPC 数量已达到上限(' . $accountLimit . ' 个)', 409 + ); + } + + // Only a genuinely new intent consults the current region and + // Fabric mapping. Lock both rows so an administrator cannot + // change the mapping while this root is being committed. + if (!$connection->getSchemaBuilder()->hasTable('cloud_region_fabrics')) { + throw new CloudError('VPC Fabric 映射表尚未安装', 503); + } + $region = CloudRegion::where('id', $regionId) ->where('status', 'active')->lockForUpdate()->first(); - $lockedFabric = CloudRegionFabric::where('region_id', $regionId) + $fabric = CloudRegionFabric::where('region_id', $regionId) ->where('state', 'active')->lockForUpdate()->first(); - if ($lockedRegion === null || $lockedFabric === null - || (string) $lockedFabric->fabric_id !== $fabricId - || (string) $lockedFabric->fabric_region !== $fabricRegion - || (int) $lockedFabric->fabric_revision !== $fabricRevision) { - throw new CloudError('地区 Fabric 配置已变化,请刷新后重试', 409); + if ($region === null) { + throw new CloudError('地区不存在或暂不可用', 409); } - $region = $lockedRegion; - // Account deletion locks the owner row before checking VPCs. - // Hold that same lock across allocation and root creation so - // a concurrent create cannot appear after the final account - // deletion check and become an orphaned private network. - if ($connection->getSchemaBuilder()->hasTable('user')) { - $owner = User::where('id', $userId)->lockForUpdate()->first(); - if ($owner === null) { - throw new CloudError('账户不存在', 401); - } + if ($fabric === null) { + throw new CloudError('该地区尚未配置可用的 WireGuard Fabric', 409); } + $fabricId = self::fabricId((string) $fabric->fabric_id); + $fabricRegion = self::fabricId((string) $fabric->fabric_region); + $fabricRevision = self::positiveInt($fabric->fabric_revision, 1, + 9000000000000000, 'Fabric 版本无效'); + $network = CloudPrivateCidrAllocator::allocate( - $allocationKey, $userId, $regionId, - $requestedCidr['cidr'] ?? null, $prefix, $vpcKey + $allocationKey, $userId, $regionId, null, $prefix, $vpcKey ); - return $connection->transaction(function () use ( - $actor, $name, $region, $requestKey, $requestHash, $maxMembers, - $fabricId, $fabricRegion, $fabricRevision, $subnet, $gateway, $network, $vpcKey, - $allocationKey - ): array { - $existing = CloudVpc::where('vpc_key', $vpcKey)->lockForUpdate()->first(); - if ($existing !== null) { - $operation = CloudVpcOperation::where('vpc_id', $existing->id) - ->where('idempotency_key', $requestKey)->lockForUpdate()->first(); - if ($operation !== null && ((string) $operation->kind !== 'vpc_create' - || !hash_equals((string) $operation->request_hash, $requestHash))) { - throw new CloudError('同一请求幂等键的参数不一致', 409); - } - if ((string) $existing->name !== $name - || (int) $existing->region_id !== (int) $region->id - || (int) $existing->max_members !== $maxMembers - || (string) $existing->fabric_id !== $fabricId - || (string) $existing->fabric_region !== $fabricRegion - || (int) $existing->fabric_revision !== $fabricRevision) { - throw new CloudError('同一请求幂等键的参数不一致', 409); - } - $existingSubnet = CloudVpcSubnet::where('vpc_id', $existing->id) - ->orderBy('id')->first(); - $expectedSubnet = $subnet['cidr'] ?? self::cidr( - (string) $network->cidr, 16, 30, '子网 CIDR' - )['cidr']; - if ($existingSubnet === null - || (string) $existingSubnet->cidr !== (string) $expectedSubnet - || ($existingSubnet->gateway_ip ?? null) !== $gateway) { - throw new CloudError('同一请求幂等键的参数不一致', 409); - } - return self::documentView($existing, $actor); - } $now = time(); $vpc = new CloudVpc(); $vpc->vpc_key = $vpcKey; @@ -287,7 +228,7 @@ final class CloudVpcService $vpc->updated_at = $now; $vpc->save(); - $subnetValue = $subnet ?? self::cidr((string) $network->cidr, 16, 30, '子网 CIDR'); + $subnetValue = self::cidr((string) $network->cidr, 24, 24, '子网 CIDR'); if ($subnetValue['network'] < (int) $network->network_address || $subnetValue['broadcast'] > (int) $network->broadcast_address) { throw new CloudError('子网必须完全位于 VPC CIDR 内'); @@ -300,7 +241,7 @@ final class CloudVpcService $row->network_address = $subnetValue['network']; $row->broadcast_address = $subnetValue['broadcast']; $row->prefix_length = $subnetValue['prefix']; - $row->gateway_ip = $gateway; + $row->gateway_ip = null; $row->state = 'applying'; $row->desired_revision = 0; $row->observed_revision = 0; @@ -313,20 +254,12 @@ final class CloudVpcService $result = self::touchDesiredLocked($vpc, 'vpc_create', $requestKey, $requestHash); return self::documentView($result['vpc'], $actor); - }, 3); }, 3); } catch (\Throwable $error) { - // If root creation failed after the allocator committed, release - // only this request's reservation. A successful root is never - // silently released by a later retry. - if ($network !== null && !CloudVpc::where('vpc_key', $vpcKey)->exists()) { - try { - CloudPrivateCidrAllocator::release($allocationKey, (int) $network->revision); - } catch (\Throwable) { - // Keep the reservation fail-closed; reconciliation can - // inspect it rather than risking reuse of an unknown CIDR. - } - } + // CIDR allocation and root creation use the same default + // connection and outer transaction, so failure rolls both back. + // A post-rollback release would race a same-key retry and could + // release the retry's newly committed allocation. if ($error instanceof CloudError) { throw $error; } @@ -633,8 +566,10 @@ final class CloudVpcService } self::assertInstanceRegion($instance, (int) $vpc->region_id); $members = CloudVpcMember::where('vpc_id', $vpc->id)->lockForUpdate()->get(); - $liveCount = $members->filter(static fn ($row): bool => !in_array( - (string) $row->state, ['deleted', 'deleting'], true))->count(); + // A deleting member still owns its address and host-side state + // until exact tombstone convergence. Only deleted frees capacity. + $liveCount = $members->filter(static fn ($row): bool => + (string) $row->state !== 'deleted')->count(); if ($liveCount >= (int) $vpc->max_members) { throw new CloudError('VPC 成员数量已达到上限', 409); } @@ -4494,6 +4429,81 @@ final class CloudVpcService return true; } + /** + * Return a previously committed create without consulting current policy. + * + * Historical create-operation hashes included platform-owned Fabric and + * CIDR defaults, so they cannot be compared with the stable tenant-intent + * hash introduced later. The deterministic root identity, immutable + * owner/name/region tuple, create operation and allocator linkage are the + * durable compatibility proof. Missing ledger rows fail closed. + */ + private static function replayCreateLocked( + CloudVpc $vpc, + array $actor, + int $userId, + int $regionId, + string $name, + string $requestKey, + string $allocationKey + ): array { + if ((int) $vpc->user_id !== $userId + || (int) ($actor['user_id'] ?? 0) !== $userId + || (int) $vpc->region_id !== $regionId + || !hash_equals((string) $vpc->name, $name)) { + throw new CloudError('同一请求幂等键的参数不一致', 409); + } + $operation = CloudVpcOperation::where('vpc_id', $vpc->id) + ->where('idempotency_key', $requestKey) + ->lockForUpdate()->first(); + if ($operation === null + || (string) $operation->kind !== 'vpc_create' + || (int) $operation->user_id !== $userId) { + throw new CloudError('VPC 创建操作账本不完整,请联系管理员', 503); + } + $network = CloudPrivateNetwork::where( + 'id', (int) $vpc->private_network_id + )->lockForUpdate()->first(); + $deleted = (string) $vpc->state === 'deleted'; + $networkStateValid = $network !== null && ($deleted + ? ((string) $network->state === 'released' + && $network->active_cidr === null) + : (in_array((string) $network->state, + ['active', 'applying', 'degraded', 'uncertain'], true) + && (string) $network->active_cidr === (string) $vpc->cidr)); + if ($network === null + || !$networkStateValid + || (string) $network->allocation_key !== $allocationKey + || (string) $network->vpc_key !== (string) $vpc->vpc_key + || (int) $network->user_id !== $userId + || (int) $network->region_id !== $regionId + || (string) $network->cidr !== (string) $vpc->cidr + || (!$deleted && CloudVpcSubnet::where('vpc_id', $vpc->id) + ->orderBy('id')->lockForUpdate()->first() === null)) { + throw new CloudError('VPC 创建资源账本不完整,请联系管理员', 503); + } + CloudPrivateCidrAllocator::assertAllocationLedger($network); + return self::documentView($vpc, $actor); + } + + /** Resolve the bounded deployment setting used by the account row lock. */ + private static function accountVpcLimit(): int + { + $value = Config::get( + 'cloud_max_vpcs_per_account', self::DEFAULT_MAX_VPCS_PER_ACCOUNT + ); + $parsed = filter_var($value, FILTER_VALIDATE_INT, [ + 'options' => [ + 'min_range' => 1, + 'max_range' => self::MAX_VPCS_PER_ACCOUNT, + ], + ]); + if ($parsed === false) { + throw new CloudError('账户 VPC 配额配置无效', 503); + } + return (int) $parsed; + } + private static function requestHash(string $kind, array $value): string { return hash('sha256', self::canonicalJson(['kind' => $kind, 'input' => $value])); diff --git a/web/config/.config.php.example b/web/config/.config.php.example index 30eb7c40..14f05834 100644 --- a/web/config/.config.php.example +++ b/web/config/.config.php.example @@ -52,6 +52,8 @@ $System_Config['cloud_introspection_url'] = 'http://127.0.0.1/api/internal/cloud $System_Config['cloud_introspection_host'] = ''; # 单台实例最多排队的未来续费账期,防止免费套餐或自动化请求无限写入数据库。 $System_Config['cloud_max_renewal_periods_ahead'] = 24; +# 每个账户最多保留的未删除 VPC 数量;创建请求按账户行锁串行核对。 +$System_Config['cloud_max_vpcs_per_account'] = 5; # redis $System_Config['redis_scheme'] = 'tcp'; $System_Config['redis_host'] = '127.0.0.1'; diff --git a/web/public/cloud/vpc.js b/web/public/cloud/vpc.js index 4fbe5739..84306517 100644 --- a/web/public/cloud/vpc.js +++ b/web/public/cloud/vpc.js @@ -684,9 +684,7 @@ async function createVpc(event) { const form = event.currentTarget; const body = { name: form.name.value.trim(), region_id: Number(form.region_id.value), - cidr: form.cidr.value.trim(), max_members: Number(form.max_members.value || 256), }; - if (form.subnet_cidr.value.trim()) body.subnet_cidr = form.subnet_cidr.value.trim(); // Keep one idempotency key for the same form values until the server has // acknowledged the create. A lost 202 response must be retryable without // allocating a second VPC/CIDR; changing the values starts a new intent. @@ -701,7 +699,7 @@ async function createVpc(event) { try { const payload = await api('/api/v1/vpcs', { method: 'POST', body }); delete form.dataset.requestKey; delete form.dataset.requestFingerprint; - form.reset(); form.max_members.value = '256'; + form.reset(); byId('vpc-create-panel').hidden = true; await applyDocument(payload, 'VPC 已创建,正在等待宿主机回读。'); } catch (error) { setFormError('vpc-create-error', error.message); } @@ -879,7 +877,7 @@ function readBootstrap() { function bind() { byId('vpc-create-open').addEventListener('click', () => { const form = byId('vpc-create-form'); - form.reset(); form.max_members.value = '256'; + form.reset(); delete form.dataset.requestKey; delete form.dataset.requestFingerprint; byId('vpc-create-panel').hidden = false; byId('vpc-create-name').focus(); }); diff --git a/web/resources/views/venix/cloud/pages/vpcs.tpl b/web/resources/views/venix/cloud/pages/vpcs.tpl index e55ba68b..11d86d0d 100644 --- a/web/resources/views/venix/cloud/pages/vpcs.tpl +++ b/web/resources/views/venix/cloud/pages/vpcs.tpl @@ -43,14 +43,12 @@

创建 VPC

平台会按地区绑定已激活的 WireGuard Fabric;浏览器不会接触宿主机密钥或地址。

-
只用于面板识别。
+
使用英文、数字、点、下划线或连字符。
只列出已完成 Fabric 映射的地区。
-
必须是 RFC1918 的 /16 至 /24 网段。
-
子网必须完全位于 VPC CIDR 内;当前不提供网关。
-
每台虚拟机只允许加入一个 VPC。
+
平台将自动分配独立 /24 私网和首个子网,成员地址自动分配。
-
+
diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index d7e6eab8..4de62050 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026100802' scope='global'} +{assign var=venix_asset_version value='2026100803' scope='global'} diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql index 272342c6..3f950873 100644 --- a/web/sql/cloud.sql +++ b/web/sql/cloud.sql @@ -291,7 +291,7 @@ CREATE TABLE IF NOT EXISTS cloud_vpcs ( fabric_id VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, fabric_region VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '', fabric_revision BIGINT UNSIGNED NOT NULL DEFAULT 0, - max_members INT UNSIGNED NOT NULL DEFAULT 256, + max_members INT UNSIGNED NOT NULL DEFAULT 200, state VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'applying', desired_revision BIGINT UNSIGNED NOT NULL DEFAULT 1, observed_revision BIGINT UNSIGNED NOT NULL DEFAULT 0, @@ -319,6 +319,9 @@ ALTER TABLE cloud_vpcs ADD COLUMN IF NOT EXISTS fabric_region VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '' AFTER fabric_id; ALTER TABLE cloud_vpcs ADD INDEX IF NOT EXISTS cloud_vpc_fabric (fabric_id, fabric_revision, region_id); +-- Existing rows keep their recorded capacity; only the default for newly +-- inserted platform-owned /24 VPCs is corrected. +ALTER TABLE cloud_vpcs ALTER COLUMN max_members SET DEFAULT 200; -- Subnets are typed L3 ranges inside a VPC. No guest gateway, DHCP or RA is -- implied; members receive exact /32 addresses in this ledger. diff --git a/web/tests/CloudVpcControlPlaneContractTest.php b/web/tests/CloudVpcControlPlaneContractTest.php index b712f84d..391e04c5 100644 --- a/web/tests/CloudVpcControlPlaneContractTest.php +++ b/web/tests/CloudVpcControlPlaneContractTest.php @@ -13,6 +13,7 @@ $assert = static function ($condition, string $message): void { $schema = $read('sql/cloud.sql'); $service = $read('app/Services/Cloud/CloudVpcService.php'); +$allocator = $read('app/Services/Cloud/CloudPrivateCidrAllocator.php'); $regionFabricModel = $read('app/Models/CloudRegionFabric.php'); $adminResource = $read('app/Services/Cloud/CloudAdminResourceService.php'); $adminResourceController = $read('app/Controllers/CloudAdminResourceController.php'); @@ -90,6 +91,36 @@ $assert(str_contains($service, 'CloudRegionFabric') && str_contains($adminResourceController, 'regionFabric') && str_contains($regionFabricModel, 'cloud_region_fabrics'), 'VPC creation must pin an explicit platform-owned region/Fabric mapping and verify its active engine gate.'); +$createStart = strpos($service, 'public static function create('); +$createEnd = strpos($service, 'public static function delete(', $createStart ?: 0); +$createBlock = $createStart !== false && $createEnd !== false + ? substr($service, $createStart, $createEnd - $createStart) : ''; +$replayPosition = strpos($createBlock, 'replayCreateLocked('); +$quotaPosition = strpos($createBlock, 'accountVpcLimit()'); +$fabricPosition = strpos($createBlock, "CloudRegionFabric::where('region_id', \$regionId)"); +$assert($createBlock !== '' + && str_contains($createBlock, + "CloudInput::only(\$input, ['name', 'region_id', 'request_key'])") + && str_contains($createBlock, '$maxMembers = self::DEFAULT_MAX_MEMBERS') + && str_contains($createBlock, '$prefix = self::DEFAULT_PREFIX_LENGTH') + && str_contains($createBlock, "'name' => \$name") + && str_contains($createBlock, "'region_id' => \$regionId") + && !str_contains($createBlock, "'cidr' => \$requestedCidr") + && $replayPosition !== false && $quotaPosition !== false + && $fabricPosition !== false + && $replayPosition < $quotaPosition && $quotaPosition < $fabricPosition + && str_contains($service, 'public const DEFAULT_MAX_MEMBERS = 200;') + && str_contains($service, 'public const DEFAULT_MAX_VPCS_PER_ACCOUNT = 5;') + && str_contains($service, "where('state', '<>', 'deleted')->count()") + && str_contains($service, 'VPC 创建操作账本不完整') + && str_contains($service, 'VPC 创建资源账本不完整') + && str_contains($service, 'CloudPrivateCidrAllocator::assertAllocationLedger') + && str_contains($allocator, 'public static function assertAllocationLedger') + && !str_contains($createBlock, 'CloudPrivateCidrAllocator::release') + && str_contains($service, "(string) \$row->state !== 'deleted'") + && str_contains($schema, 'max_members INT UNSIGNED NOT NULL DEFAULT 200') + && str_contains($schema, 'ALTER COLUMN max_members SET DEFAULT 200'), + 'Tenant VPC creation lost its strict intent contract, bounded policy, quota lock or stable replay ordering.'); $assert(str_contains($service, "'status' => 'superseded'") && str_contains($service, 'where(\'lease_token\', $leaseToken)') && str_contains($service, "where('status', 'running')"), diff --git a/web/tests/CloudVpcCreatePolicyTest.php b/web/tests/CloudVpcCreatePolicyTest.php new file mode 100644 index 00000000..faaee4b4 --- /dev/null +++ b/web/tests/CloudVpcCreatePolicyTest.php @@ -0,0 +1,564 @@ + 5]; + +$capsule = new Capsule(); +$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); + +$schema->create('user', static function (Blueprint $table): void { + $table->increments('id'); +}); +$schema->create('cloud_regions', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('code', 32)->unique(); + $table->string('name', 80); + $table->string('country_code', 2)->nullable(); + $table->string('status', 16); + $table->integer('sort')->default(0); + $table->unsignedBigInteger('created_at')->default(0); + $table->unsignedBigInteger('updated_at')->default(0); +}); +$schema->create('cloud_region_fabrics', static function (Blueprint $table): void { + $table->increments('id'); + $table->unsignedInteger('region_id')->unique(); + $table->string('fabric_id', 64); + $table->string('fabric_region', 64); + $table->unsignedBigInteger('fabric_revision'); + $table->string('state', 16); + $table->unsignedBigInteger('created_at')->default(0); + $table->unsignedBigInteger('updated_at')->default(0); +}); +$schema->create('cloud_private_cidr_allocator_configs', static function (Blueprint $table): void { + $table->unsignedTinyInteger('id')->primary(); + $table->string('pool_cidr', 18); + $table->unsignedTinyInteger('quantum_prefix_length'); + $table->unsignedTinyInteger('min_prefix_length'); + $table->unsignedTinyInteger('max_prefix_length'); + $table->unsignedBigInteger('revision'); + $table->unsignedBigInteger('updated_at'); +}); +$schema->create('cloud_private_cidr_claims', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('block_cidr', 18)->unique(); + $table->string('allocation_key', 32); + $table->unsignedBigInteger('created_at'); + $table->index(['allocation_key', 'block_cidr']); +}); +$schema->create('cloud_private_networks', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('vpc_key', 32)->unique(); + $table->string('allocation_key', 32)->unique(); + $table->unsignedInteger('user_id'); + $table->unsignedInteger('region_id'); + $table->string('cidr', 18); + $table->string('requested_cidr', 18)->nullable(); + $table->string('active_cidr', 18)->nullable()->unique(); + $table->unsignedBigInteger('network_address'); + $table->unsignedBigInteger('broadcast_address'); + $table->unsignedTinyInteger('prefix_length'); + $table->string('state', 16); + $table->unsignedBigInteger('revision'); + $table->unsignedBigInteger('created_at'); + $table->unsignedBigInteger('updated_at'); + $table->unsignedBigInteger('released_at')->nullable(); +}); +$schema->create('cloud_vpcs', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('vpc_key', 32)->unique(); + $table->unsignedInteger('user_id'); + $table->unsignedInteger('region_id'); + $table->unsignedInteger('private_network_id')->unique(); + $table->string('name', 63); + $table->string('cidr', 18); + $table->string('fabric_id', 64); + $table->string('fabric_region', 64); + $table->unsignedBigInteger('fabric_revision'); + $table->unsignedInteger('max_members'); + $table->string('state', 16); + $table->unsignedBigInteger('desired_revision'); + $table->unsignedBigInteger('observed_revision'); + $table->string('desired_digest', 64); + $table->string('observed_digest', 64)->nullable(); + $table->string('sync_state', 16); + $table->string('last_operation_id', 32)->nullable(); + $table->string('last_error_code', 64)->nullable(); + $table->unsignedBigInteger('last_success_at')->default(0); + $table->unsignedBigInteger('last_failure_at')->default(0); + $table->unsignedBigInteger('created_at'); + $table->unsignedBigInteger('updated_at'); + $table->index(['user_id', 'state', 'id']); +}); +$schema->create('cloud_vpc_subnets', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('subnet_key', 32); + $table->unsignedInteger('vpc_id'); + $table->string('cidr', 18); + $table->unsignedBigInteger('network_address'); + $table->unsignedBigInteger('broadcast_address'); + $table->unsignedTinyInteger('prefix_length'); + $table->string('gateway_ip', 15)->nullable(); + $table->string('state', 16); + $table->unsignedBigInteger('desired_revision'); + $table->unsignedBigInteger('observed_revision'); + $table->string('desired_digest', 64)->nullable(); + $table->string('observed_digest', 64)->nullable(); + $table->string('last_error_code', 64)->nullable(); + $table->unsignedBigInteger('created_at'); + $table->unsignedBigInteger('updated_at'); + $table->unique(['vpc_id', 'subnet_key']); + $table->unique(['vpc_id', 'cidr']); +}); +$schema->create('cloud_vpc_private_ips', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('ip_key', 32); + $table->unsignedInteger('vpc_id'); + $table->unsignedInteger('subnet_id'); + $table->unsignedInteger('member_id')->nullable(); + $table->unsignedInteger('instance_id')->nullable(); + $table->string('private_ip', 15); + $table->unsignedBigInteger('private_ip_int'); + $table->string('state', 16); + $table->unsignedBigInteger('desired_revision'); + $table->unsignedBigInteger('observed_revision'); + $table->string('desired_digest', 64)->nullable(); + $table->string('observed_digest', 64)->nullable(); + $table->string('last_error_code', 64)->nullable(); + $table->unsignedBigInteger('created_at'); + $table->unsignedBigInteger('updated_at'); +}); +$schema->create('cloud_vpc_members', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('member_key', 32); + $table->unsignedInteger('vpc_id'); + $table->unsignedInteger('subnet_id'); + $table->unsignedInteger('private_ip_id')->nullable(); + $table->unsignedInteger('instance_id'); + $table->unsignedInteger('host_id'); + $table->string('private_ip', 15); + $table->unsignedBigInteger('private_ip_int'); + $table->string('state', 16); + $table->unsignedBigInteger('desired_revision'); + $table->unsignedBigInteger('observed_revision'); + $table->string('desired_digest', 64)->nullable(); + $table->string('observed_digest', 64)->nullable(); + $table->string('last_operation_id', 32)->nullable(); + $table->string('last_error_code', 64)->nullable(); + $table->unsignedBigInteger('created_at'); + $table->unsignedBigInteger('updated_at'); +}); +$schema->create('cloud_vpc_routes', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('route_key', 32); + $table->unsignedInteger('vpc_id'); + $table->unsignedInteger('member_id'); + $table->string('destination_cidr', 18); + $table->unsignedBigInteger('destination_int'); + $table->unsignedBigInteger('broadcast_int'); + $table->unsignedTinyInteger('prefix_length'); + $table->string('next_hop_ip', 15); + $table->unsignedSmallInteger('metric'); + $table->string('state', 16); + $table->unsignedBigInteger('desired_revision'); + $table->unsignedBigInteger('observed_revision'); + $table->string('desired_digest', 64)->nullable(); + $table->string('observed_digest', 64)->nullable(); + $table->string('last_error_code', 64)->nullable(); + $table->unsignedBigInteger('created_at'); + $table->unsignedBigInteger('updated_at'); +}); +$schema->create('cloud_vpc_acl_rules', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('rule_key', 32); + $table->unsignedInteger('vpc_id'); + $table->unsignedInteger('priority'); + $table->string('direction', 8); + $table->string('action', 8); + $table->string('protocol', 8); + $table->string('source_cidr', 18); + $table->unsignedBigInteger('source_int'); + $table->unsignedBigInteger('source_broadcast_int'); + $table->unsignedTinyInteger('source_prefix_length'); + $table->string('destination_cidr', 18); + $table->unsignedBigInteger('destination_int'); + $table->unsignedBigInteger('destination_broadcast_int'); + $table->unsignedTinyInteger('destination_prefix_length'); + $table->unsignedSmallInteger('port_from')->nullable(); + $table->unsignedSmallInteger('port_to')->nullable(); + $table->string('state', 16); + $table->unsignedBigInteger('desired_revision'); + $table->unsignedBigInteger('observed_revision'); + $table->string('desired_digest', 64)->nullable(); + $table->string('observed_digest', 64)->nullable(); + $table->string('last_error_code', 64)->nullable(); + $table->unsignedBigInteger('created_at'); + $table->unsignedBigInteger('updated_at'); +}); +$schema->create('cloud_vpc_host_deployments', static function (Blueprint $table): void { + $table->increments('id'); + $table->unsignedInteger('vpc_id'); + $table->unsignedInteger('host_id'); + $table->unsignedBigInteger('fabric_revision')->default(0); + $table->string('state', 16); + $table->unsignedBigInteger('desired_revision'); + $table->unsignedBigInteger('observed_revision'); + $table->string('desired_digest', 64)->nullable(); + $table->string('observed_digest', 64)->nullable(); + $table->string('last_operation_id', 32)->nullable(); + $table->string('last_error_code', 64)->nullable(); + $table->unsignedBigInteger('last_success_at')->default(0); + $table->unsignedBigInteger('last_failure_at')->default(0); + $table->unsignedBigInteger('created_at'); + $table->unsignedBigInteger('updated_at'); + $table->unique(['vpc_id', 'host_id']); +}); +$schema->create('cloud_vpc_operations', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('operation_id', 32)->unique(); + $table->unsignedInteger('vpc_id'); + $table->unsignedInteger('user_id'); + $table->string('kind', 24); + $table->unsignedBigInteger('desired_revision'); + $table->string('idempotency_key', 128); + $table->string('request_hash', 64); + $table->string('status', 24); + $table->text('payload_json'); + $table->text('observed_json')->nullable(); + $table->unsignedSmallInteger('evidence_version')->default(0); + $table->string('error_code', 64)->nullable(); + $table->unsignedBigInteger('created_at'); + $table->unsignedBigInteger('updated_at'); + $table->unsignedBigInteger('finished_at')->nullable(); + $table->string('lease_token', 32)->nullable(); + $table->unsignedBigInteger('lease_until')->default(0); + $table->unsignedInteger('attempts')->default(0); + $table->unique(['vpc_id', 'idempotency_key']); + $table->unique(['vpc_id', 'desired_revision']); +}); + +$now = time(); +Capsule::table('user')->insert(['id' => 7]); +Capsule::table('cloud_regions')->insert([ + ['id' => 1, 'code' => 'region-one', 'name' => 'Region One', + 'status' => 'active', 'sort' => 1, 'created_at' => $now, 'updated_at' => $now], +]); +Capsule::table('cloud_region_fabrics')->insert([ + 'id' => 1, 'region_id' => 1, 'fabric_id' => 'fabric-one', + 'fabric_region' => 'region-one', 'fabric_revision' => 7, + 'state' => 'active', 'created_at' => $now, 'updated_at' => $now, +]); +Capsule::table('cloud_private_cidr_allocator_configs')->insert([ + 'id' => 1, 'pool_cidr' => '10.0.0.0/8', 'quantum_prefix_length' => 24, + 'min_prefix_length' => 16, 'max_prefix_length' => 24, + 'revision' => 1, 'updated_at' => $now, +]); + +$actor = [ + 'user_id' => 7, + 'is_admin' => false, + 'is_super_admin' => false, + 'can_manage' => false, +]; +$create = static fn (string $name, int $regionId, string $requestKey): array => + CloudVpcService::create($actor, [ + 'name' => $name, + 'region_id' => $regionId, + 'request_key' => $requestKey, + ]); +$expectError = static function ( + int $status, + callable $operation, + string $message +) use ($assert): CloudError { + try { + $operation(); + } catch (CloudError $error) { + $assert($error->httpStatus === $status, + $message . ' returned HTTP ' . $error->httpStatus . ' instead of ' . $status . '.'); + return $error; + } + throw new RuntimeException($message . ' did not fail.'); +}; + +// The public create contract contains only stable tenant intent. Supplying a +// value equal to platform policy is still forbidden so callers cannot depend +// on or later widen an implementation detail. +$forbidden = [ + 'cidr' => '10.20.0.0/24', + 'prefix_length' => 24, + 'max_members' => 200, + 'fabric_id' => 'fabric-one', + 'fabric_revision' => 7, + 'subnet_cidr' => '10.20.0.0/24', + 'subnet_gateway' => null, +]; +foreach ($forbidden as $field => $value) { + $input = [ + 'name' => 'strict-' . str_replace('_', '-', $field), + 'region_id' => 1, + 'request_key' => 'strict-' . str_replace('_', '-', $field), + $field => $value, + ]; + $expectError(422, static fn () => CloudVpcService::create($actor, $input), + 'Tenant create accepted platform-owned field ' . $field); +} +$assert(Capsule::table('cloud_vpcs')->count() === 0 + && Capsule::table('cloud_private_networks')->count() === 0 + && Capsule::table('cloud_private_cidr_claims')->count() === 0, + 'Rejected platform-owned fields changed durable VPC or CIDR state.'); + +$System_Config['cloud_max_vpcs_per_account'] = 0; +$expectError(503, static fn () => $create( + 'invalid-quota', 1, 'invalid-quota-0001' +), 'An invalid account quota configuration was accepted'); +$assert(Capsule::table('cloud_vpcs')->count() === 0 + && Capsule::table('cloud_private_networks')->count() === 0 + && Capsule::table('cloud_private_cidr_claims')->count() === 0, + 'Invalid account quota configuration changed durable VPC or CIDR state.'); +$System_Config['cloud_max_vpcs_per_account'] = 5; + +$alphaInput = ['name' => 'alpha', 'region_id' => 1, 'request_key' => 'create-alpha-0001']; +Capsule::statement( + "CREATE TRIGGER cloud_vpc_create_failure_probe " + . "BEFORE INSERT ON cloud_vpc_subnets BEGIN " + . "SELECT RAISE(ABORT, 'forced subnet failure'); END" +); +$expectError(503, static fn () => CloudVpcService::create($actor, $alphaInput), + 'A forced post-allocation create failure escaped as success'); +$assert(Capsule::table('cloud_vpcs')->count() === 0 + && Capsule::table('cloud_private_networks')->count() === 0 + && Capsule::table('cloud_private_cidr_claims')->count() === 0 + && Capsule::table('cloud_vpc_operations')->count() === 0, + 'A failed root transaction leaked its allocation, claim or operation.'); +Capsule::statement('DROP TRIGGER cloud_vpc_create_failure_probe'); +$alpha = CloudVpcService::create($actor, $alphaInput); +$alphaRoot = Capsule::table('cloud_vpcs')->where('vpc_key', $alpha['vpc']['vpc_key'])->first(); +$alphaNetwork = $alphaRoot === null ? null : Capsule::table('cloud_private_networks') + ->where('id', (int) $alphaRoot->private_network_id)->first(); +$alphaSubnet = $alphaRoot === null ? null : Capsule::table('cloud_vpc_subnets') + ->where('vpc_id', (int) $alphaRoot->id)->first(); +$assert($alphaRoot !== null && $alphaNetwork !== null && $alphaSubnet !== null + && (string) $alphaRoot->cidr === '10.0.0.0/24' + && (int) $alphaRoot->max_members === CloudVpcService::DEFAULT_MAX_MEMBERS + && (int) $alphaRoot->max_members === 200 + && (string) $alphaNetwork->cidr === (string) $alphaRoot->cidr + && $alphaNetwork->requested_cidr === null + && (int) $alphaNetwork->prefix_length === 24 + && (string) $alphaSubnet->cidr === (string) $alphaRoot->cidr + && (int) $alphaSubnet->prefix_length === 24 + && $alphaSubnet->gateway_ip === null + && Capsule::table('cloud_private_cidr_claims') + ->where('allocation_key', (string) $alphaNetwork->allocation_key)->count() === 1, + 'Automatic create did not persist one /24, the 200-member policy and a whole-CIDR subnet.'); + +$countsAfterAlpha = [ + 'vpcs' => Capsule::table('cloud_vpcs')->count(), + 'networks' => Capsule::table('cloud_private_networks')->count(), + 'claims' => Capsule::table('cloud_private_cidr_claims')->count(), + 'operations' => Capsule::table('cloud_vpc_operations')->count(), +]; +$alphaReplay = CloudVpcService::create($actor, $alphaInput); +$assert($alphaReplay['vpc']['vpc_key'] === $alpha['vpc']['vpc_key'] + && Capsule::table('cloud_vpcs')->count() === $countsAfterAlpha['vpcs'] + && Capsule::table('cloud_private_networks')->count() === $countsAfterAlpha['networks'] + && Capsule::table('cloud_private_cidr_claims')->count() === $countsAfterAlpha['claims'] + && Capsule::table('cloud_vpc_operations')->count() === $countsAfterAlpha['operations'], + 'An identical create replay duplicated its root, allocation, claim or operation.'); + +// Historical create hashes contained mutable platform policy. The committed +// root tuple and operation identity remain the compatibility proof. +$historicalHash = hash('sha256', 'historical-create-policy'); +Capsule::table('cloud_vpc_operations')->where('vpc_id', (int) $alphaRoot->id) + ->where('kind', 'vpc_create')->update(['request_hash' => $historicalHash]); +$historicalReplay = CloudVpcService::create($actor, $alphaInput); +$assert($historicalReplay['vpc']['vpc_key'] === $alpha['vpc']['vpc_key'], + 'A historical create-operation hash stopped an otherwise exact replay.'); + +// Early replay must retain the allocator's exact claim-ledger proof even +// though it intentionally does not consult mutable allocator policy. +$alphaClaim = Capsule::table('cloud_private_cidr_claims') + ->where('allocation_key', (string) $alphaNetwork->allocation_key)->first(); +$assert($alphaClaim !== null, 'The initial /24 claim fixture is missing.'); +Capsule::table('cloud_private_cidr_claims')->where('id', (int) $alphaClaim->id)->delete(); +$expectError(503, static fn () => CloudVpcService::create($actor, $alphaInput), + 'A create replay accepted a missing live CIDR claim'); +Capsule::table('cloud_private_cidr_claims')->insert([ + 'block_cidr' => (string) $alphaClaim->block_cidr, + 'allocation_key' => (string) $alphaNetwork->allocation_key, + 'created_at' => (int) $alphaClaim->created_at, +]); + +// Replay must resolve from durable tenant intent before mutable platform +// readiness. A lost successful response stays recoverable during maintenance. +Capsule::table('cloud_region_fabrics')->where('region_id', 1)->update([ + 'fabric_revision' => 8, 'updated_at' => $now + 1, +]); +$revisionReplay = CloudVpcService::create($actor, $alphaInput); +Capsule::table('cloud_region_fabrics')->where('region_id', 1)->update([ + 'state' => 'inactive', 'updated_at' => $now + 2, +]); +$inactiveFabricReplay = CloudVpcService::create($actor, $alphaInput); +Capsule::table('cloud_regions')->where('id', 1)->update([ + 'status' => 'inactive', 'updated_at' => $now + 3, +]); +$inactiveRegionReplay = CloudVpcService::create($actor, $alphaInput); +$assert($revisionReplay['vpc']['vpc_key'] === $alpha['vpc']['vpc_key'] + && $inactiveFabricReplay['vpc']['vpc_key'] === $alpha['vpc']['vpc_key'] + && $inactiveRegionReplay['vpc']['vpc_key'] === $alpha['vpc']['vpc_key'] + && (int) Capsule::table('cloud_vpcs')->where('id', $alphaRoot->id) + ->value('fabric_revision') === 7, + 'A mutable Fabric/region change broke replay or rewrote the committed root.'); + +$expectError(409, static fn () => CloudVpcService::create($actor, [ + 'name' => 'alpha-renamed', 'region_id' => 1, + 'request_key' => $alphaInput['request_key'], +]), 'A create replay accepted name drift'); +$expectError(409, static fn () => CloudVpcService::create($actor, [ + 'name' => 'alpha', 'region_id' => 2, + 'request_key' => $alphaInput['request_key'], +]), 'A create replay accepted region drift'); + +Capsule::table('cloud_regions')->where('id', 1)->update([ + 'status' => 'active', 'updated_at' => $now + 4, +]); +Capsule::table('cloud_region_fabrics')->where('region_id', 1)->update([ + 'fabric_revision' => 8, 'state' => 'active', 'updated_at' => $now + 4, +]); + +$quotaRoots = []; +foreach ([ + ['beta', 'create-beta-0001'], + ['gamma', 'create-gamma-0001'], + ['delta', 'create-delta-0001'], + ['epsilon', 'create-epsilon-0001'], +] as [$name, $requestKey]) { + $quotaRoots[$name] = $create($name, 1, $requestKey); +} +Capsule::table('cloud_vpcs') + ->where('vpc_key', $quotaRoots['epsilon']['vpc']['vpc_key']) + ->update(['state' => 'deleting', 'updated_at' => $now + 5]); +$assert(Capsule::table('cloud_vpcs')->where('user_id', 7) + ->where('state', '<>', 'deleted')->count() === 5, + 'Quota fixture did not retain five non-deleted roots including deleting.'); +$fullQuotaCounts = [ + 'vpcs' => Capsule::table('cloud_vpcs')->count(), + 'networks' => Capsule::table('cloud_private_networks')->count(), + 'claims' => Capsule::table('cloud_private_cidr_claims')->count(), + 'operations' => Capsule::table('cloud_vpc_operations')->count(), +]; +$fullQuotaReplay = CloudVpcService::create($actor, $alphaInput); +$assert($fullQuotaReplay['vpc']['vpc_key'] === $alpha['vpc']['vpc_key'] + && Capsule::table('cloud_vpcs')->count() === $fullQuotaCounts['vpcs'] + && Capsule::table('cloud_private_networks')->count() === $fullQuotaCounts['networks'] + && Capsule::table('cloud_private_cidr_claims')->count() === $fullQuotaCounts['claims'] + && Capsule::table('cloud_vpc_operations')->count() === $fullQuotaCounts['operations'], + 'A committed create stopped being replayable after the account became full.'); + +$beforeQuotaFailure = [ + 'vpcs' => Capsule::table('cloud_vpcs')->count(), + 'networks' => Capsule::table('cloud_private_networks')->count(), + 'claims' => Capsule::table('cloud_private_cidr_claims')->count(), + 'operations' => Capsule::table('cloud_vpc_operations')->count(), +]; +$quotaError = $expectError(409, static fn () => $create( + 'zeta', 1, 'create-zeta-0001' +), 'A sixth non-deleted VPC bypassed the account quota'); +$assert(str_contains($quotaError->getMessage(), '5') + && Capsule::table('cloud_vpcs')->count() === $beforeQuotaFailure['vpcs'] + && Capsule::table('cloud_private_networks')->count() === $beforeQuotaFailure['networks'] + && Capsule::table('cloud_private_cidr_claims')->count() === $beforeQuotaFailure['claims'] + && Capsule::table('cloud_vpc_operations')->count() === $beforeQuotaFailure['operations'], + 'Quota rejection leaked a VPC, allocation, CIDR claim or operation.'); + +// Model a fully converged delete: the root tombstone remains for audit, while +// the allocator row and exact /24 claim have been safely released. +$betaRoot = CloudVpc::where('vpc_key', $quotaRoots['beta']['vpc']['vpc_key'])->firstOrFail(); +$betaNetwork = CloudPrivateNetwork::where('id', (int) $betaRoot->private_network_id)->firstOrFail(); +CloudPrivateCidrAllocator::release( + (string) $betaNetwork->allocation_key, + (int) $betaNetwork->revision +); +Capsule::table('cloud_vpc_subnets')->where('vpc_id', (int) $betaRoot->id)->delete(); +$betaRoot->state = 'deleted'; +$betaRoot->updated_at = $now + 6; +$betaRoot->save(); + +Capsule::table('cloud_private_cidr_claims')->insert([ + 'block_cidr' => (string) $betaNetwork->cidr, + 'allocation_key' => (string) $betaNetwork->allocation_key, + 'created_at' => $now + 6, +]); +$expectError(503, static fn () => $create( + 'beta', 1, 'create-beta-0001' +), 'A deleted create replay accepted a residual released CIDR claim'); +Capsule::table('cloud_private_cidr_claims') + ->where('allocation_key', (string) $betaNetwork->allocation_key)->delete(); + +$beforeDeletedReplay = [ + 'vpcs' => Capsule::table('cloud_vpcs')->count(), + 'networks' => Capsule::table('cloud_private_networks')->count(), + 'claims' => Capsule::table('cloud_private_cidr_claims')->count(), + 'operations' => Capsule::table('cloud_vpc_operations')->count(), +]; +$betaReplay = $create('beta', 1, 'create-beta-0001'); +$assert(($betaReplay['vpc']['state'] ?? null) === 'deleted' + && $betaReplay['vpc']['vpc_key'] === $quotaRoots['beta']['vpc']['vpc_key'] + && Capsule::table('cloud_vpcs')->count() === $beforeDeletedReplay['vpcs'] + && Capsule::table('cloud_private_networks')->count() === $beforeDeletedReplay['networks'] + && Capsule::table('cloud_private_cidr_claims')->count() === $beforeDeletedReplay['claims'] + && Capsule::table('cloud_vpc_operations')->count() === $beforeDeletedReplay['operations'], + 'A deleted create replay resurrected the root, allocation, claim or operation.'); + +$zeta = $create('zeta', 1, 'create-zeta-0001'); +$assert($zeta['vpc']['vpc_key'] !== '' + && Capsule::table('cloud_vpcs')->where('user_id', 7) + ->where('state', '<>', 'deleted')->count() === 5 + && Capsule::table('cloud_private_networks')->where('state', 'released')->count() === 1 + && Capsule::table('cloud_private_cidr_claims')->count() === 5, + 'A deleted root did not release one account slot and its exact CIDR claim.'); + +// A deterministic root without its create operation is not safe to replay: +// returning it would hide a partial commit or damaged audit trail. +$zetaRoot = Capsule::table('cloud_vpcs')->where('vpc_key', $zeta['vpc']['vpc_key'])->first(); +$assert($zetaRoot !== null, 'The post-release quota create did not persist its root.'); +Capsule::table('cloud_vpc_operations')->where('vpc_id', (int) $zetaRoot->id) + ->where('kind', 'vpc_create')->delete(); +$beforeBrokenReplay = [ + 'vpcs' => Capsule::table('cloud_vpcs')->count(), + 'networks' => Capsule::table('cloud_private_networks')->count(), + 'claims' => Capsule::table('cloud_private_cidr_claims')->count(), +]; +$expectError(503, static fn () => $create( + 'zeta', 1, 'create-zeta-0001' +), 'A create replay returned a root with a missing create-operation ledger'); +$assert(Capsule::table('cloud_vpcs')->count() === $beforeBrokenReplay['vpcs'] + && Capsule::table('cloud_private_networks')->count() === $beforeBrokenReplay['networks'] + && Capsule::table('cloud_private_cidr_claims')->count() === $beforeBrokenReplay['claims'], + 'A failed damaged-ledger replay changed VPC or CIDR state.'); + +echo "VPC create policy, quota and idempotency tests passed.\n"; diff --git a/web/tests/CloudVpcMemberReuseTest.php b/web/tests/CloudVpcMemberReuseTest.php index 5bdba2ec..ffea7284 100644 --- a/web/tests/CloudVpcMemberReuseTest.php +++ b/web/tests/CloudVpcMemberReuseTest.php @@ -1509,4 +1509,30 @@ foreach ([ 'A later global proof did not combine with the exact partial owner receipt.'); } +// A deleting member still owns its address and possible host-side device. +// It must consume capacity until exact tombstone convergence removes it. +$deletingCapacity = $seedVpc( + 21, '10.61.0.0/24', '10.61.0.0/29', 150, + 'active', 'active' +); +Capsule::table('cloud_vpcs')->where('id', 21)->update(['max_members' => 1]); +$seedInstance(21001, 150); +$seedInstance(21002, 150); +$seedPair( + 210001, 210101, $deletingCapacity, + 21001, 150, '10.61.0.1', 'deleting' +); +$expectCloudError(static fn () => CloudVpcService::attachMember( + $deletingCapacity['vpc_key'], $actor, [ + 'subnet_key' => $deletingCapacity['subnet_key'], + 'instance_id' => 21002, + 'request_key' => 'deleting-capacity-0001', + ] +), 409); +$assert(Capsule::table('cloud_vpc_members')->where('vpc_id', 21)->count() === 1 + && Capsule::table('cloud_vpc_members')->where('instance_id', 21002)->count() === 0 + && (int) Capsule::table('cloud_vpcs')->where('id', 21) + ->value('desired_revision') === 1, + 'A deleting member stopped consuming capacity before tombstone convergence.'); + echo "VPC member and private-IP reuse contracts passed.\n"; diff --git a/web/tests/CloudVpcUserPageContractTest.php b/web/tests/CloudVpcUserPageContractTest.php index 7030bd73..daf102a1 100644 --- a/web/tests/CloudVpcUserPageContractTest.php +++ b/web/tests/CloudVpcUserPageContractTest.php @@ -70,12 +70,29 @@ $assert(str_contains($app, "vpcs: '/cloud/vpc.js'"), 'Cloud page module routing must load the VPC module.'); foreach ([ - 'vpc-create-form', 'vpc-create-region', 'vpc-create-cidr', 'vpc-create-subnet', + 'vpc-create-form', 'vpc-create-name', 'vpc-create-region', 'vpc-list', 'vpc-detail', 'vpc-list-reconcile', 'vpc-bootstrap', ] as $id) { $assert(str_contains($template, 'id="' . $id . '"'), 'VPC view is missing required control ' . $id . '.'); } +$assert(!str_contains($template, 'id="vpc-create-cidr"') + && !str_contains($template, 'id="vpc-create-subnet"') + && !str_contains($template, 'id="vpc-create-max-members"') + && str_contains($template, '平台将自动分配独立 /24 私网和首个子网'), + 'Tenant VPC create form must leave CIDR, subnet and member capacity to platform policy.'); +$createStart = strpos($script, 'async function createVpc('); +$createEnd = strpos($script, 'async function submitSubnet(', $createStart ?: 0); +$createSection = $createStart !== false && $createEnd !== false + ? substr($script, $createStart, $createEnd - $createStart) : ''; +$assert($createSection !== '' + && str_contains($createSection, 'name: form.name.value.trim()') + && str_contains($createSection, 'region_id: Number(form.region_id.value)') + && str_contains($createSection, 'body.request_key = form.dataset.requestKey') + && !str_contains($createSection, 'form.cidr') + && !str_contains($createSection, 'form.subnet_cidr') + && !str_contains($createSection, 'form.max_members'), + 'Tenant create JavaScript must submit only name, region and the idempotency key.'); foreach (['子网与 CIDR', '成员与私网 IP', 'Route', 'VPC ACL', '最近操作'] as $label) { $assert(str_contains($script, $label), 'VPC module is missing section ' . $label . '.'); diff --git a/web/tests/VirtualizationConfigTest.php b/web/tests/VirtualizationConfigTest.php index 0b2d88db..5d3d3109 100644 --- a/web/tests/VirtualizationConfigTest.php +++ b/web/tests/VirtualizationConfigTest.php @@ -36,5 +36,8 @@ try { $root = dirname(__DIR__); $assert(str_contains(file_get_contents($root . '/bootstrap.php'), "'/config/config.php'"), 'Canonical config.php missing'); $assert(str_contains(file_get_contents($root . '/config/.config.php.example'), "['cloud_engine_data_dir']"), 'Private engine configuration missing'); +$assert(str_contains(file_get_contents($root . '/config/.config.php.example'), + "['cloud_max_vpcs_per_account'] = 5"), + 'Default account VPC quota configuration missing'); $assert(str_contains(file_get_contents($root . '/config/routes.php'), "'/config/routes_cloud.php'"), 'Cloud API routes not registered'); echo "Virtualization configuration and separate log database contracts passed.\n";