From 63591583a4bd5026f786226df8e2bcbd24992934 Mon Sep 17 00:00:00 2001 From: codex Date: Tue, 3 Nov 2026 16:57:52 +0800 Subject: [PATCH] refactor: make active dual-stack claims authoritative --- docs/DEPLOYMENT.md | 2 + web/app/Command/CloudSetup.php | 4 +- web/app/Models/CloudResourceReservationIp.php | 5 + .../CloudActivePublicNetworkClaimSet.php | 147 ++++++ .../Cloud/CloudAdminInstanceService.php | 5 +- .../Cloud/CloudAdminResourceService.php | 91 +++- web/app/Services/Cloud/CloudBackupService.php | 28 ++ .../Cloud/CloudInstanceMigrationService.php | 4 + web/app/Services/Cloud/CloudJobService.php | 20 + .../CloudNetworkChangeOptionsService.php | 1 + .../Services/Cloud/CloudPlacementService.php | 109 +---- ...oudPublicIpPoolReplacementBatchService.php | 42 +- .../CloudPublicNetworkAllocationService.php | 441 ++++++++++++++--- .../CloudPublicNetworkTransitionGate.php | 51 ++ web/app/Services/Cloud/CloudWorkerService.php | 22 + web/sql/cloud.sql | 48 +- ...vePublicNetworkClaimSchemaBehaviorTest.php | 153 ++++++ ...AdminResourceActiveClaimProjectionTest.php | 363 ++++++++++++++ web/tests/CloudFinancialWorkflowTest.php | 200 ++++---- web/tests/CloudFreshSchemaContractTest.php | 2 +- .../CloudNetworkIpLedgerContractTest.php | 45 +- ...oudProvisioningPublicNetworkLedgerTest.php | 6 +- ...ublicIpPoolReplacementBatchServiceTest.php | 46 ++ ...licIpPoolReplacementSchemaContractTest.php | 2 +- ...loudPublicNetworkAllocationServiceTest.php | 444 ++++++++++++++++-- ...licNetworkLegacyWriterGateContractTest.php | 196 ++++++++ ...licNetworkTransitionSchemaContractTest.php | 17 +- .../CloudRescueCatalogSchemaContractTest.php | 2 +- .../CloudTemplateImportIntentContractTest.php | 2 +- .../CloudTrafficPoolSchemaContractTest.php | 2 +- ...CloudUndispatchedFinalizerRecoveryTest.php | 9 + web/tests/CloudVpcSchemaContractTest.php | 2 +- 32 files changed, 2170 insertions(+), 341 deletions(-) create mode 100644 web/app/Services/Cloud/CloudActivePublicNetworkClaimSet.php create mode 100644 web/app/Services/Cloud/CloudPublicNetworkTransitionGate.php create mode 100644 web/tests/CloudActivePublicNetworkClaimSchemaBehaviorTest.php create mode 100644 web/tests/CloudAdminResourceActiveClaimProjectionTest.php create mode 100644 web/tests/CloudPublicNetworkLegacyWriterGateContractTest.php diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index e5be8948..2cd56130 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -160,6 +160,8 @@ libvirt 的持久 pool 定义就是 Agent 后续使用的映射,不另写存 公网网络接入在宿主机的“网络接入”中按资源池线路独立配置,可使用 `bridge:br0`、其他 Linux 网桥或 `network:default` 这样的 libvirt network。名称以字母或数字开头,后续只能包含字母、数字、点、下划线和短横线,bridge 名称为 1~15 字符,libvirt network 名称为 1~64 字符。宿主机上的公网网桥或 libvirt network 必须由运维预先准备。Agent 只发现、验证和使用现有公网网络,不创建公网网桥、不启动 libvirt network,也不修改公网地址、上游网关或挂载。`cloud_hosts.default_network` 仅保留为兼容展示值,不参与 Agent 就绪、调度、恢复、迁移或换 IP 决策;真正的运行时权威是资源池线路、当前 Agent 代次已验证的网络接入,以及绑定该接入的公网地址池。VPC 使用下述独立的 Agent 受管 bridge 和 L3 路由,不改变这一公网边界。 +全新公网账本 schema 版本为 `go-agent-wss-v29-active-public-network-claims`。每个资源预留的当前公网权威只来自 `cloud_resource_reservation_ips.active_claim = 1` 的一组 IPv4+IPv6 精确声明;两族允许具有各自的 generation 和 operation ID,但必须绑定同一资源预留和网络接入,并各自与具体 IP、地址池、宿主机、实例状态双向一致。`cloud_resource_reservations` 中旧的单地址列只保留审计形态,不参与当前地址读取、释放或管理员投影。释放时历史声明保留并把 `active_claim` 置空,具体 IP 同时清空 claim、operation、reservation 和 instance 归属。尚未迁移到双栈 transition ledger 的换 IP、地址池批量替换、独立恢复和维护迁移入口会在创建任务、账单或目标资源前拒绝,并在 Worker 派发前再次防守;不能通过恢复旧单地址写入路径绕过该门禁。 + Agent 的 capabilities 响应仍使用 `network_selectors` 字段,但它是自动发现的当前可用 `bridge:<名称>` / `network:<名称>` 列表,排序去重且最多 64 项,不再来自配置文件。Linux 网桥必须有 sysfs bridge 目录且接口为 UP;libvirt network 必须处于 active 状态。完整 Agent 测试保存当前代次的候选列表,但不要求某个宿主机全局默认值必须存在。管理员只能从该代次已测试列表创建网络接入,并必须对每个接入执行精确验证;创建、恢复、迁移、重装和换 IP 会在锁内再次核对本次资源池线路、接入、公网池与 Agent 代次。修改兼容 `default_network` 不会撤销 Agent 就绪结果,修改或失效真实网络接入则由接入自身的验证状态阻止运行时使用。 公网 IPv6 防伪还依赖宿主机启动门禁。Agent 每次成功重算公网 TAP 身份时,会先把完整、排序后的 v1 投影原子写入 `journal_path + ".public-guard-v1.json"`,完成文件 `fsync`、`rename` 和目录 `fsync` 后才允许替换 `bridge virt_cloud_public_guard` nftables 表。该文件必须是 root 所有的普通 `0600` 文件,父目录必须由 root 所有且不可被 group/other 写入;版本、严格 JSON、SHA-256、规范化 MAC、全局 IPv6 和 MAC 派生 link-local IPv6 任一不一致都会拒绝读取。它与 `journal_path + ".public-guard.lock"`、实时 Agent 变更和启动预检共用同一把跨进程 `flock`,不得手工编辑、复制半成品或用空文件代替。明确的零实例投影也是一份带摘要的合法 JSON;文件缺失或损坏绝不会被解释成“当前没有实例”。该状态文件必须与 Journal 一起纳入宿主机状态备份。 diff --git a/web/app/Command/CloudSetup.php b/web/app/Command/CloudSetup.php index 08c35172..585ff5e9 100644 --- a/web/app/Command/CloudSetup.php +++ b/web/app/Command/CloudSetup.php @@ -8,7 +8,7 @@ use App\Services\Config; /** Initializes only the clean-break PHP business and Agent log schemas. */ final class CloudSetup { - private const SCHEMA_VERSION = 'go-agent-wss-v28-public-network-transition'; + private const SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'; private const MAIN_TABLES = [ 'cloud_regions', 'cloud_traffic_pool_groups', 'cloud_network_lines', 'cloud_resource_pools', @@ -442,6 +442,8 @@ final class CloudSetup ], 'cloud_public_ips' => [ 'chk_cloud_public_ip_family', 'chk_cloud_public_ip_prefix', + 'chk_cloud_public_ip_state', + 'chk_cloud_public_ip_owner_shape', ], 'cloud_traffic_pool_groups' => [ 'chk_cloud_traffic_pool_group_mode', diff --git a/web/app/Models/CloudResourceReservationIp.php b/web/app/Models/CloudResourceReservationIp.php index 4d0375cb..66a89b7c 100644 --- a/web/app/Models/CloudResourceReservationIp.php +++ b/web/app/Models/CloudResourceReservationIp.php @@ -20,4 +20,9 @@ final class CloudResourceReservationIp extends Model 'created_at' => 'int', 'updated_at' => 'int', ]; + + public function publicIp() + { + return $this->belongsTo(CloudPublicIp::class, 'public_ip_id'); + } } diff --git a/web/app/Services/Cloud/CloudActivePublicNetworkClaimSet.php b/web/app/Services/Cloud/CloudActivePublicNetworkClaimSet.php new file mode 100644 index 00000000..773ce2a7 --- /dev/null +++ b/web/app/Services/Cloud/CloudActivePublicNetworkClaimSet.php @@ -0,0 +1,147 @@ + $claims + * @param array $addresses keyed by public IP id + */ + public static function fromLedger(int $reservationId, array $claims, + array $addresses, CloudPublicNetworkSnapshot $publicNetwork): self + { + if ($reservationId < 1 || count($claims) !== 2) { + throw new CloudError('活动双栈公网地址账本不完整', 409); + } + $canonical = []; + $attachmentId = null; + foreach ($claims as $claim) { + $family = (int) ($claim->address_family ?? 0); + $claimId = (int) ($claim->id ?? 0); + $generation = (int) ($claim->claim_generation ?? 0); + $publicIpId = (int) ($claim->public_ip_id ?? 0); + $ip = $addresses[$publicIpId] ?? null; + $operationId = (string) ($claim->operation_id ?? ''); + $currentAttachmentId = (int) ( + $claim->network_attachment_id ?? 0 + ); + $addressCidr = is_object($ip) + ? (string) ($ip->address ?? '') . '/' + . (int) ($ip->prefix_length ?? 0) + : ''; + if (!in_array($family, [4, 6], true) + || isset($canonical[$family]) + || $claimId < 1 || $generation < 1 || $publicIpId < 1 + || (int) ($claim->reservation_id ?? 0) !== $reservationId + || (int) ($claim->active_claim ?? 0) !== 1 + || $currentAttachmentId < 1 + || (int) ($claim->public_ip_pool_id ?? 0) < 1 + || preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1 + || !is_object($ip) + || (int) ($ip->id ?? 0) !== $publicIpId + || (int) ($ip->address_family ?? 0) !== $family + || (int) ($ip->reservation_id ?? 0) !== $reservationId + || (int) ($ip->reservation_ip_claim_id ?? 0) !== $claimId + || (int) ($ip->public_ip_pool_id ?? 0) + !== (int) $claim->public_ip_pool_id + || !hash_equals( + $addressCidr, + $publicNetwork->address($family) + ) + || !hash_equals( + $operationId, + (string) ($ip->operation_id ?? '') + )) { + throw new CloudError('活动双栈公网地址账本不一致', 409); + } + if ($attachmentId === null) { + $attachmentId = $currentAttachmentId; + } elseif ($attachmentId !== $currentAttachmentId) { + throw new CloudError('活动双栈公网地址不属于同一网络接入', 409); + } + $canonical[$family] = [ + 'family' => $family, + 'claim_id' => $claimId, + 'claim_generation' => $generation, + 'claim_operation_id' => $operationId, + 'public_ip_id' => $publicIpId, + 'network_attachment_id' => $currentAttachmentId, + 'public_ip_pool_id' => (int) $claim->public_ip_pool_id, + ]; + } + if (!isset($canonical[4], $canonical[6])) { + throw new CloudError('活动双栈公网地址账本不完整', 409); + } + ksort($canonical, SORT_NUMERIC); + $identity = [ + 'reservation_id' => $reservationId, + 'claims' => array_values($canonical), + 'public_network_sha256' => $publicNetwork->fingerprint(), + ]; + $digest = hash('sha256', json_encode( + $identity, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + )); + return new self($reservationId, $canonical, $publicNetwork, $digest); + } + + public function reservationId(): int + { + return $this->reservationId; + } + + public function claimId(int $family): int + { + if (!isset($this->claims[$family])) { + throw new \InvalidArgumentException('Address family is invalid.'); + } + return $this->claims[$family]['claim_id']; + } + + public function generation(int $family): int + { + if (!isset($this->claims[$family])) { + throw new \InvalidArgumentException('Address family is invalid.'); + } + return $this->claims[$family]['claim_generation']; + } + + public function publicIpId(int $family): int + { + if (!isset($this->claims[$family])) { + throw new \InvalidArgumentException('Address family is invalid.'); + } + return $this->claims[$family]['public_ip_id']; + } + + public function networkAttachmentId(): int + { + return $this->claims[4]['network_attachment_id']; + } + + public function publicNetwork(): CloudPublicNetworkSnapshot + { + return $this->publicNetwork; + } + + public function digest(): string + { + return $this->digest; + } +} diff --git a/web/app/Services/Cloud/CloudAdminInstanceService.php b/web/app/Services/Cloud/CloudAdminInstanceService.php index 26a47f47..399ee5c2 100644 --- a/web/app/Services/Cloud/CloudAdminInstanceService.php +++ b/web/app/Services/Cloud/CloudAdminInstanceService.php @@ -189,8 +189,9 @@ final class CloudAdminInstanceService 'bandwidth_mbps' => self::positiveOrNull($spec['bandwidth_mbps'] ?? null), 'os_source' => self::text($spec['os_source'] ?? null, 32), 'login_name' => self::text($spec['login_name'] ?? null, 32), - 'network_change_supported' => $canMutate && $managedCloudTemplate - && $networkValid && $publicIpCidr !== null, + // Re-enabled only when every address-changing writer uses the + // dual-stack transition ledger. + 'network_change_supported' => false, 'instance_settings_supported' => $canMutate && $managedCloudTemplate && $networkValid, // The Agent can extend its UUID-derived name on collisions. Do diff --git a/web/app/Services/Cloud/CloudAdminResourceService.php b/web/app/Services/Cloud/CloudAdminResourceService.php index ae6fee18..02d081dd 100644 --- a/web/app/Services/Cloud/CloudAdminResourceService.php +++ b/web/app/Services/Cloud/CloudAdminResourceService.php @@ -13,6 +13,7 @@ use App\Models\CloudPublicIp; use App\Models\CloudRegion; use App\Models\CloudResourcePool; use App\Models\CloudResourceReservation; +use App\Models\CloudResourceReservationIp; /** Database-only administrator projections for regions, lines, pools and reservations. */ final class CloudAdminResourceService @@ -436,9 +437,16 @@ final class CloudAdminResourceService $inner->where('reservation_key', 'like', '%' . $q . '%'); if (ctype_digit($q)) { foreach (['id', 'order_id', 'offer_id', 'host_id', 'user_id', - 'instance_id', 'public_ip_id'] as $column) { + 'instance_id'] as $column) { $inner->orWhere($column, (int) $q); } + $inner->orWhereHas( + 'activePublicIpClaims', + static fn ($claims) => $claims->where( + 'public_ip_id', + (int) $q + ) + ); } }); } @@ -1306,7 +1314,6 @@ final class CloudAdminResourceService $poolIds = $rows->pluck('resource_pool_id')->filter()->unique()->all(); $offerIds = $rows->pluck('offer_id')->filter()->unique()->all(); $hostIds = $rows->pluck('host_id')->filter()->unique()->all(); - $ipIds = $rows->pluck('public_ip_id')->filter()->unique()->all(); $pools = $poolIds === [] ? collect() : CloudResourcePool::whereIn('id', $poolIds)->get(); $lines = $pools->isEmpty() ? collect() : CloudNetworkLine::whereIn('id', $pools->pluck('line_id')->unique()->all())->get(); @@ -1318,7 +1325,6 @@ final class CloudAdminResourceService 'regions' => self::keyById($regions), 'offers' => self::keyById($offerIds === [] ? collect() : CloudOffer::whereIn('id', $offerIds)->get()), 'hosts' => self::keyById($hostIds === [] ? collect() : CloudHost::whereIn('id', $hostIds)->get()), - 'ips' => self::keyById($ipIds === [] ? collect() : CloudPublicIp::whereIn('id', $ipIds)->get()), ]; } @@ -1329,7 +1335,7 @@ final class CloudAdminResourceService $region = $line === null ? null : ($lookups['regions'][(int) $line->region_id] ?? null); $offer = $lookups['offers'][(int) $row->offer_id] ?? null; $host = $lookups['hosts'][(int) $row->host_id] ?? null; - $ip = $lookups['ips'][(int) $row->public_ip_id] ?? null; + $publicNetwork = self::reservationPublicNetwork($row); return [ 'id' => (int) $row->id, 'reservation_key' => (string) $row->reservation_key, @@ -1344,8 +1350,14 @@ final class CloudAdminResourceService 'host_name' => (string) ($host->name ?? ''), 'user_id' => (int) $row->user_id, 'instance_id' => $row->instance_id === null ? null : (int) $row->instance_id, - 'public_ip_id' => $row->public_ip_id === null ? null : (int) $row->public_ip_id, - 'public_ip' => (string) ($ip->address ?? ''), + // These two names remain response compatibility only. Their + // values are derived from the active IPv4 claim, never from the + // retired singular reservation columns. + 'public_ip_id' => $publicNetwork['ipv4']['public_ip_id'] ?? null, + 'public_ip' => $publicNetwork['ipv4']['address'] ?? '', + 'public_ipv4' => $publicNetwork['ipv4']['address'] ?? '', + 'public_ipv6' => $publicNetwork['ipv6']['address'] ?? '', + 'public_ips' => array_values($publicNetwork), 'operation_id' => (string) ($row->operation_id ?? ''), 'cpu_cores' => (int) $row->cpu_cores, 'memory_mib' => (int) $row->memory_mib, @@ -1359,6 +1371,73 @@ final class CloudAdminResourceService ]; } + /** @return array> */ + private static function reservationPublicNetwork( + CloudResourceReservation $reservation + ): array { + if ((string) $reservation->state === 'released') { + $claims = CloudResourceReservationIp::where( + 'reservation_id', + (int) $reservation->id + ); + $claimIds = (clone $claims)->pluck('id')->map( + static fn ($id): int => (int) $id + )->all(); + $ipLeak = CloudPublicIp::where(function ($query) use ( + $reservation, + $claimIds + ): void { + $query->where( + 'reservation_id', + (int) $reservation->id + ); + if ($claimIds !== []) { + $query->orWhereIn( + 'reservation_ip_claim_id', + $claimIds + ); + } + })->exists(); + if ((clone $claims)->where('active_claim', 1)->exists() + || $ipLeak) { + throw new CloudError( + '已释放资源预留仍占用活动公网地址', + 409 + ); + } + return []; + } + $expectedInstanceId = null; + if ((string) $reservation->state === 'committed') { + $expectedInstanceId = (int) ($reservation->instance_id ?? 0); + if ($expectedInstanceId < 1) { + throw new CloudError('已提交资源预留缺少实例归属', 409); + } + } + $claimSet = CloudPublicNetworkAllocationService::currentClaimSet( + (int) $reservation->id, + (string) $reservation->state, + $expectedInstanceId + ); + $result = []; + foreach ([4 => 'ipv4', 6 => 'ipv6'] as $family => $key) { + $cidr = $claimSet->publicNetwork()->address($family); + $separator = strrpos($cidr, '/'); + if ($separator === false) { + throw new CloudError('活动公网地址快照格式损坏', 409); + } + $result[$key] = [ + 'address_family' => $family, + 'claim_id' => $claimSet->claimId($family), + 'claim_generation' => $claimSet->generation($family), + 'public_ip_id' => $claimSet->publicIpId($family), + 'address' => substr($cidr, 0, $separator), + 'address_cidr' => $cidr, + ]; + } + return $result; + } + private static function emptyReservationPage(): array { return [ diff --git a/web/app/Services/Cloud/CloudBackupService.php b/web/app/Services/Cloud/CloudBackupService.php index 36c7824c..ac9812a8 100644 --- a/web/app/Services/Cloud/CloudBackupService.php +++ b/web/app/Services/Cloud/CloudBackupService.php @@ -920,6 +920,7 @@ final class CloudBackupService array $input): array { CloudAccess::manage($actor); + CloudPublicNetworkTransitionGate::assertPortableRestoreReady(); CloudInput::only($input, ['target_host_id', 'target_resource_pool_id', 'name', 'confirm_new_instance']); @@ -1255,6 +1256,33 @@ final class CloudBackupService CloudOriginalBackupRestorePolicy::assertEligible( $lockedInstance, $lockedBackup ); + $claimSet = CloudPublicNetworkAllocationService::currentClaimSet( + (int) ($lockedInstance->reservation_id ?? 0), + 'committed', + (int) $lockedInstance->id + ); + $instanceSpec = self::decodeSpec( + (string) $lockedInstance->spec_json + ); + try { + $frozenNetwork = CloudPublicNetworkSnapshot::fromArray( + $instanceSpec['public_network'] ?? null + ); + } catch (\Throwable) { + throw new CloudError( + '实例缺少有效的双栈公网网络快照,不能恢复', + 409 + ); + } + if (!hash_equals( + $claimSet->publicNetwork()->fingerprint(), + $frozenNetwork->fingerprint() + )) { + throw new CloudError( + '实例公网网络快照与活动地址声明不一致', + 409 + ); + } self::assertNoActiveJob($lockedInstance); if (CloudBackupRecovery::where( 'instance_id', (int) $lockedInstance->id diff --git a/web/app/Services/Cloud/CloudInstanceMigrationService.php b/web/app/Services/Cloud/CloudInstanceMigrationService.php index e6d56736..c50e7e9c 100644 --- a/web/app/Services/Cloud/CloudInstanceMigrationService.php +++ b/web/app/Services/Cloud/CloudInstanceMigrationService.php @@ -28,6 +28,7 @@ final class CloudInstanceMigrationService CloudJob $receiveJob, array $inspection ): bool { + CloudPublicNetworkTransitionGate::assertMigrationReady(); $cleanup = $inspection['cleanup'] ?? null; $planId = is_array($cleanup) ? ($cleanup['plan_id'] ?? null) : null; $steps = is_array($cleanup) ? ($cleanup['steps'] ?? null) : null; @@ -174,6 +175,7 @@ final class CloudInstanceMigrationService array $input ): array { CloudAccess::manage($actor); + CloudPublicNetworkTransitionGate::assertMigrationReady(); CloudInput::only($input, [ 'target_host_id', 'target_resource_pool_id', 'cleanup_mode', 'confirm_maintenance_migration', @@ -870,6 +872,7 @@ final class CloudInstanceMigrationService array $input ): CloudJob { CloudAccess::manage($actor); + CloudPublicNetworkTransitionGate::assertMigrationReady(); CloudInput::only($input, ['action', 'confirm_recovery']); $action = $input['action'] ?? null; if (!is_string($action) @@ -1025,6 +1028,7 @@ final class CloudInstanceMigrationService array $input ): CloudJob { CloudAccess::manage($actor); + CloudPublicNetworkTransitionGate::assertMigrationReady(); CloudInput::only($input, ['confirm_source_cleanup']); if (($input['confirm_source_cleanup'] ?? false) !== true) { throw new CloudError('请确认删除源宿主机上的旧副本'); diff --git a/web/app/Services/Cloud/CloudJobService.php b/web/app/Services/Cloud/CloudJobService.php index 51fbc9fa..6426ff55 100644 --- a/web/app/Services/Cloud/CloudJobService.php +++ b/web/app/Services/Cloud/CloudJobService.php @@ -2531,6 +2531,14 @@ final class CloudJobService ?string $paidNetworkChangeExpectedAmount = null): CloudJob { CloudAccess::vmActor($instance, $actor); + if ($kind === 'network_change') { + CloudPublicNetworkTransitionGate::assertWriterReady(); + } + if (in_array($kind, ['delete', 'expiry_delete'], true)) { + CloudPublicNetworkTransitionGate::assertInstanceDeleteReady( + $instance + ); + } $requestKey = self::requestKey($actor); $paidNetworkChange = $paidNetworkChangeExpectedAmount !== null; if ($paidNetworkChange && ($kind !== 'network_change' @@ -2631,6 +2639,11 @@ final class CloudJobService if ($locked === null || (string) $locked->status === 'deleted') { throw new CloudError('虚拟机不存在', 404); } + if (in_array($kind, ['delete', 'expiry_delete'], true)) { + CloudPublicNetworkTransitionGate::assertInstanceDeleteReady( + $locked + ); + } if ($requestKey !== null) { $prior = CloudJob::where('user_id', (int) $actor['user_id']) ->where('request_idempotency_key', $requestKey) @@ -2967,6 +2980,7 @@ final class CloudJobService int $actorUserId, string $batchKey ): CloudJob { + CloudPublicNetworkTransitionGate::assertWriterReady(); if ($actorUserId < 1 || preg_match('/^[a-f0-9]{32}$/D', $batchKey) !== 1 || (string) $parent->kind @@ -3108,6 +3122,9 @@ final class CloudJobService || (string) $locked->service_status !== 'purge_deleting') { throw new CloudError('实例尚未完成销毁前停机,不能删除磁盘', 409); } + CloudPublicNetworkTransitionGate::assertInstanceDeleteReady( + $locked + ); CloudInstanceMigrationService::assertInstanceMutationAvailable( $locked, 'expiry_delete' @@ -3199,6 +3216,9 @@ final class CloudJobService (string) $instance->uuid) !== 1) { throw new CloudError('关联实例已不存在或与原删除任务不一致', 409); } + CloudPublicNetworkTransitionGate::assertInstanceDeleteReady( + $instance + ); $priorPayload = CloudSecrets::decrypt( (string) $lockedPrior->sealed_payload, diff --git a/web/app/Services/Cloud/CloudNetworkChangeOptionsService.php b/web/app/Services/Cloud/CloudNetworkChangeOptionsService.php index b05afa2d..5e1939ae 100644 --- a/web/app/Services/Cloud/CloudNetworkChangeOptionsService.php +++ b/web/app/Services/Cloud/CloudNetworkChangeOptionsService.php @@ -20,6 +20,7 @@ final class CloudNetworkChangeOptionsService public static function forInstance(CloudInstance $instance): array { + CloudPublicNetworkTransitionGate::assertWriterReady(); $spec = json_decode((string) $instance->spec_json, true); if (!is_array($spec) || array_is_list($spec) || ($spec['managed'] ?? false) !== true diff --git a/web/app/Services/Cloud/CloudPlacementService.php b/web/app/Services/Cloud/CloudPlacementService.php index d8a8f474..296e3c7f 100644 --- a/web/app/Services/Cloud/CloudPlacementService.php +++ b/web/app/Services/Cloud/CloudPlacementService.php @@ -503,6 +503,7 @@ final class CloudPlacementService int $userId, array $resources, int $requiredResourcePoolId, int $additionalDiskGib = 0): array { + self::assertBackupRestoreTransitionReady($restore); $resources = self::upgradeResources($resources); $capacityResources = $resources; $capacityResources['disk_gib'] += max(0, $additionalDiskGib); @@ -647,6 +648,7 @@ final class CloudPlacementService CloudBackupRestore $restore, int $instanceId ): array { + self::assertBackupRestoreTransitionReady($restore); $reservation = CloudResourceReservation::where( 'backup_restore_id', (int) $restore->id @@ -729,6 +731,7 @@ final class CloudPlacementService public static function finishBackupRestore(CloudBackupRestore $restore, int $instanceId, string $publicIpCidr, string $status): void { + self::assertBackupRestoreTransitionReady($restore); $host = CloudHost::where('id', (int) $restore->target_host_id) ->lockForUpdate()->first(); $reservation = CloudResourceReservation::where( @@ -991,103 +994,26 @@ final class CloudPlacementService return; } - // Backup restores retain their pre-C11 single-address ledger. + // Clean break: restored-instance deletion cannot consult the + // retired singular reservation/IP columns. C11 reconnects + // this branch only after portable restores own active pairs. if ($orderId !== 0 || $restoreId < 1 || (int) ($hint->offer_id ?? 0) !== 0) { throw new CloudError('已删除实例的资源来源无效', 409); } - $host = CloudHost::where('id', (int) $instance->host_id) - ->lockForUpdate()->first(); - $reservation = CloudResourceReservation::where( - 'id', - $reservationId - )->lockForUpdate()->first(); - $restore = CloudBackupRestore::where('id', $restoreId) - ->lockForUpdate()->first(); - if ($host === null || $reservation === null - || (int) $reservation->host_id !== (int) $host->id - || (int) $reservation->instance_id !== (int) $instance->id - || (int) $reservation->resource_pool_id - !== (int) ($instance->resource_pool_id ?? 0) - || $restore === null || $instance->order_id !== null - || (int) $restore->target_host_id - !== (int) $instance->host_id - || (int) $restore->target_instance_id - !== (int) $instance->id - || (int) $restore->reservation_id - !== (int) $reservation->id - || (string) $restore->state !== 'ready' - || !hash_equals( - (string) $restore->operation_id, - (string) $reservation->operation_id - )) { - throw new CloudError( - '已删除恢复实例的资源账本不一致', - 409 - ); - } - self::releaseLockedReservation($reservation, $reason, true); + CloudPublicNetworkTransitionGate::assertPortableRestoreReady(); }, 3 ); } - private static function releaseLockedReservation( - CloudResourceReservation $reservation, - string $reason, - bool $includeCommitted - ): void { - if ((string) $reservation->state === 'released') { - return; - } - if ((string) $reservation->state === 'committed' && !$includeCommitted) { - throw new CloudError('已交付实例的资源不能按失败任务释放', 409); - } - $ip = CloudPublicIp::where('id', (int) $reservation->public_ip_id) - ->lockForUpdate()->first(); - if ($ip === null || (int) $ip->host_id !== (int) $reservation->host_id - || !self::reservationNetworkMatches($reservation, $ip) - || (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id - || !hash_equals((string) $reservation->operation_id, - (string) ($ip->operation_id ?? '')) - || !in_array((string) $reservation->state, - ['held', 'uncertain', 'committed'], true) - || ((string) $reservation->state === 'held' - && (string) $ip->state !== 'reserved') - || ((string) $reservation->state === 'uncertain' - && (string) $ip->state !== 'uncertain') - || ((string) $reservation->state === 'committed' - && (string) $ip->state !== 'assigned')) { - throw new CloudError('待释放资源的公网 IP 账本不一致', 409); - } - if ((string) $reservation->state === 'committed' - && ((string) $ip->state !== 'assigned' - || (int) ($ip->instance_id ?? 0) !== (int) ($reservation->instance_id ?? 0))) { - throw new CloudError('已交付实例的公网 IP 账本不一致', 409); - } - $reason = preg_replace('/[^a-z0-9_.-]/', '', strtolower($reason)) ?? ''; - $reason = substr($reason === '' ? 'released' : $reason, 0, 64); - $now = time(); - $reservation->state = 'released'; - $reservation->released_at = $now; - $reservation->release_reason = $reason; - $reservation->expires_at = null; - $reservation->updated_at = $now; - $reservation->save(); - $ip->state = 'available'; - $ip->reservation_id = null; - $ip->instance_id = null; - $ip->operation_id = null; - $ip->updated_at = $now; - $ip->save(); - } - /** Atomically settle the PHP-side address ledger for a network-change job. */ public static function finishNetworkChange(CloudInstance $instance, string $operationId, int $sourceIpId, int $targetIpId, int $sourceAttachmentId, int $targetAttachmentId, int $sourcePoolId, int $targetPoolId, string $outcome): void { + CloudPublicNetworkTransitionGate::assertWriterReady(); if (!in_array($outcome, ['succeeded', 'failed', 'uncertain'], true) || preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1 || min($sourceIpId, $targetIpId, $sourceAttachmentId, @@ -1458,6 +1384,15 @@ final class CloudPlacementService return substr($reason, 0, 64); } + private static function assertBackupRestoreTransitionReady( + CloudBackupRestore $restore + ): void { + if ($restore->backup_id === null) { + CloudPublicNetworkTransitionGate::assertMigrationReady(); + } + CloudPublicNetworkTransitionGate::assertPortableRestoreReady(); + } + private static function markReservationReleased( CloudResourceReservation $reservation, string $reason @@ -1798,16 +1733,6 @@ final class CloudPlacementService ->whereNull('operation_id')->orderBy('id'); } - /** Require the complete immutable network identity of a reservation. */ - private static function reservationNetworkMatches( - CloudResourceReservation $reservation, CloudPublicIp $ip): bool - { - return (int) ($reservation->network_attachment_id ?? 0) > 0 - && (int) ($reservation->public_ip_pool_id ?? 0) > 0 - && (int) ($ip->public_ip_pool_id ?? 0) - === (int) $reservation->public_ip_pool_id; - } - private static function publicIpBelongsToPool(CloudPublicIp $ip, CloudPublicIpPool $pool): bool { diff --git a/web/app/Services/Cloud/CloudPublicIpPoolReplacementBatchService.php b/web/app/Services/Cloud/CloudPublicIpPoolReplacementBatchService.php index 241e52af..fca4d9a7 100644 --- a/web/app/Services/Cloud/CloudPublicIpPoolReplacementBatchService.php +++ b/web/app/Services/Cloud/CloudPublicIpPoolReplacementBatchService.php @@ -13,6 +13,7 @@ use App\Models\CloudPublicIpPoolReplacementBatch; use App\Models\CloudPublicIpPoolReplacementBatchItem; use App\Models\CloudResourcePool; use App\Models\CloudResourceReservation; +use App\Models\CloudResourceReservationIp; /** * Durable same-host replacement of every assigned address in one public pool. @@ -49,11 +50,20 @@ final class CloudPublicIpPoolReplacementBatchService || (int) $sourceAttachment->host_id !== $hostId) { throw new CloudError('源公网地址池不存在', 404); } - $assignedCount = CloudResourceReservation::where( - 'host_id', $hostId - )->where('public_ip_pool_id', (int) $source->id) - ->where('state', 'committed')->whereNotNull('instance_id') - ->count(); + $assignedCount = CloudResourceReservationIp::query() + ->join( + 'cloud_resource_reservations as reservation', + 'reservation.id', + '=', + 'cloud_resource_reservation_ips.reservation_id' + )->where('reservation.host_id', $hostId) + ->where( + 'cloud_resource_reservation_ips.public_ip_pool_id', + (int) $source->id + )->where('cloud_resource_reservation_ips.active_claim', 1) + ->where('cloud_resource_reservation_ips.state', 'committed') + ->where('reservation.state', 'committed') + ->whereNotNull('reservation.instance_id')->count(); $activeBatches = CloudPublicIpPoolReplacementBatch::where( 'host_id', $hostId )->where('active_claim', 1)->where(function ($query) use ( @@ -205,6 +215,7 @@ final class CloudPublicIpPoolReplacementBatchService array $actor, array $input): array { CloudAccess::manage($actor); + CloudPublicNetworkTransitionGate::assertWriterReady(); CloudInput::only($input, [ 'target_pool_key', 'expected_source_revision', 'expected_target_revision', 'confirm_replacement', 'request_key', @@ -270,11 +281,22 @@ final class CloudPublicIpPoolReplacementBatchService if ($sourceRef === null || $targetRef === null) { throw new CloudError('源或目标公网地址池不存在', 404); } - $instanceIds = CloudResourceReservation::query() - ->where('host_id', $hostId) - ->where('public_ip_pool_id', (int) $sourceRef->id) - ->where('state', 'committed')->whereNotNull('instance_id') - ->orderBy('instance_id')->pluck('instance_id')->map( + $instanceIds = CloudResourceReservationIp::query() + ->join( + 'cloud_resource_reservations as reservation', + 'reservation.id', + '=', + 'cloud_resource_reservation_ips.reservation_id' + )->where('reservation.host_id', $hostId) + ->where( + 'cloud_resource_reservation_ips.public_ip_pool_id', + (int) $sourceRef->id + )->where('cloud_resource_reservation_ips.active_claim', 1) + ->where('cloud_resource_reservation_ips.state', 'committed') + ->where('reservation.state', 'committed') + ->whereNotNull('reservation.instance_id') + ->orderBy('reservation.instance_id') + ->pluck('reservation.instance_id')->map( static fn ($id): int => (int) $id )->unique()->values()->all(); if ($instanceIds === []) { diff --git a/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php b/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php index b3f15a83..6991c0ac 100644 --- a/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php +++ b/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php @@ -16,6 +16,83 @@ final class CloudPublicNetworkAllocationService { private const FAMILIES = [4, 6]; + /** Read-only projection of the exact active dual-stack authority. */ + public static function currentClaimSet( + int $reservationId, + string $expectedState = 'committed', + ?int $expectedInstanceId = null + ): CloudActivePublicNetworkClaimSet { + if ($reservationId < 1 + || !in_array($expectedState, + ['held', 'committed', 'uncertain'], true) + || ($expectedInstanceId !== null && $expectedInstanceId < 1)) { + throw new CloudError('公网网络资源预留无效', 409); + } + // This interface is projection-only. A repeatable-read transaction + // prevents its several exact-ledger reads from accepting a torn pair; + // mutation callers use the private locking path instead. + return self::connection()->transaction(static function () use ( + $reservationId, + $expectedState, + $expectedInstanceId + ): CloudActivePublicNetworkClaimSet { + $reservation = self::unlockedReservation($reservationId); + $hostId = (int) ($reservation->host_id ?? 0); + $resourcePoolId = (int) ($reservation->resource_pool_id ?? 0); + $reservationUserId = (int) ($reservation->user_id ?? 0); + $resourcePoolLineId = $resourcePoolId > 0 + ? DB::table('cloud_resource_pools') + ->where('id', $resourcePoolId)->value('line_id') + : null; + $reservationInstanceId = $reservation?->instance_id === null + ? null : (int) $reservation->instance_id; + $instance = $expectedState === 'committed' + && $reservationInstanceId !== null + && $reservationInstanceId > 0 + ? DB::table('cloud_instances') + ->where('id', $reservationInstanceId)->first() + : null; + if ($reservation === null || $hostId < 1 + || $resourcePoolId < 1 + || $reservationUserId < 1 + || $resourcePoolLineId === null + || (int) $resourcePoolLineId < 1 + || (string) $reservation->state !== $expectedState + || ($expectedState === 'committed' + && ($reservationInstanceId === null + || $reservationInstanceId < 1 + || $instance === null + || (int) ($instance->reservation_id ?? 0) + !== $reservationId + || (int) ($instance->host_id ?? 0) !== $hostId + || (int) ($instance->resource_pool_id ?? 0) + !== $resourcePoolId + || (int) ($instance->user_id ?? 0) + !== $reservationUserId)) + || ($expectedState !== 'committed' + && $reservationInstanceId !== null) + || ($expectedInstanceId !== null + && $reservationInstanceId !== $expectedInstanceId) + || DB::table('cloud_hosts')->where('id', $hostId) + ->value('id') === null) { + throw new CloudError('公网网络资源预留权威链不一致', 409); + } + $claims = self::unlockedClaims($reservationId); + $set = self::claimSet( + $claims, + $expectedState === 'held' ? 'reserved' : $expectedState, + $expectedState === 'committed' + ? $reservationInstanceId : null, + $hostId, + (int) $resourcePoolLineId + ); + if ($set->reservationId() !== $reservationId) { + throw new CloudError('公网网络活动声明归属不一致', 409); + } + return $set; + }); + } + public static function reserveBundle(int $hostId, int $lineId, int $reservationId, string $operationId): CloudPublicNetworkSnapshot { @@ -47,9 +124,8 @@ final class CloudPublicNetworkAllocationService ['held', 'committed', 'uncertain']); $existing = self::lockedClaims($reservationId); if ($existing !== []) { - self::assertClaimSet($existing, $operationId, [ - 'reserved', 'committed', 'uncertain', - ]); + $claimState = self::claimStateForReservation($reservation); + self::assertClaimSet($existing, $operationId, [$claimState]); if ($selection === null) { throw new CloudError('公网网络资源预留状态不明确', 409); } @@ -60,9 +136,16 @@ final class CloudPublicNetworkAllocationService 'reserved' => ['reserved'], 'committed' => ['assigned'], 'uncertain' => ['uncertain'], - ]); + ], $claimState === 'committed' + ? (int) ($reservation->instance_id ?? 0) : null); return self::snapshot($existing); } + if (self::lockedHistoricalClaims($reservationId) !== []) { + throw new CloudError( + '初始公网网络预留不能复用历史地址声明', + 409 + ); + } if ($claimHints !== [] || (string) $reservation->state !== 'held') { throw new CloudError('公网网络资源预留状态不明确', 409); } @@ -74,13 +157,14 @@ final class CloudPublicNetworkAllocationService $claims = []; foreach (self::FAMILIES as $family) { $pool = $selection['pools'][$family]; - $ip = self::reserveAddress($pool, $reservationId, - $operationId, $now, + $ip = self::reserveAddress($pool, $now, $selection['address_candidates'][$family] ?? null); $claimId = DB::table('cloud_resource_reservation_ips') ->insertGetId([ 'reservation_id' => $reservationId, 'address_family' => $family, + 'claim_generation' => 1, + 'active_claim' => 1, 'network_attachment_id' => (int) $selection['attachment']->id, 'public_ip_pool_id' => (int) $pool->id, @@ -92,6 +176,13 @@ final class CloudPublicNetworkAllocationService 'released_at' => null, 'release_reason' => '', ]); + self::bindAddressToClaim( + $ip, + $reservationId, + $operationId, + $claimId, + $now + ); $claims[] = DB::table('cloud_resource_reservation_ips') ->where('id', $claimId)->first(); } @@ -126,8 +217,16 @@ final class CloudPublicNetworkAllocationService self::assertReservation($reservation, $hostId, $operationId, ['held', 'committed', 'uncertain']); $claims = self::lockedClaims($reservationId); - self::assertClaimSet($claims, $operationId, - ['reserved', 'uncertain', 'committed']); + $claimState = self::claimStateForReservation($reservation); + self::assertClaimSet( + $claims, + $operationId, + [$claimState] + ); + if ($claimState === 'committed' + && (int) ($reservation->instance_id ?? 0) !== $instanceId) { + throw new CloudError('实例网络归属与资源预留不一致', 409); + } self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); self::assertClaimAddresses($claims, $addresses, $selection, @@ -136,22 +235,32 @@ final class CloudPublicNetworkAllocationService 'uncertain' => ['uncertain'], 'committed' => ['assigned'], ], $instanceId); + if ($claimState === 'committed') { + return self::snapshot($claims); + } $now = time(); foreach ($claims as $claim) { $ip = $addresses[(int) $claim->public_ip_id]; - DB::table('cloud_public_ips')->where('id', (int) $ip->id) - ->update([ + $ipUpdated = DB::table('cloud_public_ips') + ->where('id', (int) $ip->id) + ->where('reservation_ip_claim_id', (int) $claim->id) + ->where('operation_id', $operationId)->update([ 'state' => 'assigned', 'reservation_id' => $reservationId, + 'reservation_ip_claim_id' => (int) $claim->id, 'instance_id' => $instanceId, 'operation_id' => $operationId, 'updated_at' => $now, ]); - DB::table('cloud_resource_reservation_ips') - ->where('id', (int) $claim->id)->update([ + $claimUpdated = DB::table('cloud_resource_reservation_ips') + ->where('id', (int) $claim->id) + ->where('active_claim', 1)->update([ 'state' => 'committed', 'updated_at' => $now, ]); + if ($ipUpdated !== 1 || $claimUpdated !== 1) { + throw new CloudError('双栈公网地址提交账本未精确更新', 409); + } } return self::snapshot(self::lockedClaims($reservationId)); }); @@ -180,8 +289,12 @@ final class CloudPublicNetworkAllocationService self::assertReservation($reservation, $hostId, $operationId, ['held', 'uncertain']); $claims = self::lockedClaims($reservationId); - self::assertClaimSet($claims, $operationId, - ['reserved', 'uncertain']); + $claimState = self::claimStateForReservation($reservation); + self::assertClaimSet( + $claims, + $operationId, + [$claimState] + ); self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); self::assertClaimAddresses($claims, $addresses, $selection, @@ -189,19 +302,27 @@ final class CloudPublicNetworkAllocationService 'reserved' => ['reserved'], 'uncertain' => ['uncertain'], ]); + if ($claimState === 'uncertain') { + return; + } $now = time(); foreach ($claims as $claim) { - DB::table('cloud_public_ips') + $ipUpdated = DB::table('cloud_public_ips') ->where('id', (int) $claim->public_ip_id) + ->where('reservation_ip_claim_id', (int) $claim->id) ->where('operation_id', $operationId)->update([ 'state' => 'uncertain', 'updated_at' => $now, ]); - DB::table('cloud_resource_reservation_ips') - ->where('id', (int) $claim->id)->update([ + $claimUpdated = DB::table('cloud_resource_reservation_ips') + ->where('id', (int) $claim->id) + ->where('active_claim', 1)->update([ 'state' => 'uncertain', 'updated_at' => $now, ]); + if ($ipUpdated !== 1 || $claimUpdated !== 1) { + throw new CloudError('双栈公网地址隔离账本未精确更新', 409); + } } }); } @@ -234,8 +355,11 @@ final class CloudPublicNetworkAllocationService self::assertReservation($reservation, $hostId, $operationId, ['held', 'uncertain']); $claims = self::lockedClaims($reservationId); - self::assertClaimSet($claims, $operationId, - ['reserved', 'uncertain']); + self::assertClaimSet( + $claims, + $operationId, + [self::claimStateForReservation($reservation)] + ); self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); self::assertClaimAddresses($claims, $addresses, $selection, @@ -243,7 +367,7 @@ final class CloudPublicNetworkAllocationService 'reserved' => ['reserved'], 'uncertain' => ['uncertain'], ]); - self::releaseLockedClaims($claims, $operationId, $reason); + self::releaseLockedClaims($claims, $reason); }); } @@ -280,16 +404,19 @@ final class CloudPublicNetworkAllocationService $selection = self::lockClaimNetworkContext($claimHints, $hostId); $reservation = self::lockReservation($reservationId); self::assertReservation($reservation, $hostId, $operationId, - ['held', 'committed', 'uncertain']); + ['committed']); + if ((int) ($reservation->instance_id ?? 0) !== $instanceId) { + throw new CloudError('实例网络归属与资源预留不一致', 409); + } $claims = self::lockedClaims($reservationId); - self::assertClaimSet($claims, $operationId, ['committed']); + self::assertActiveClaimSet($claims, ['committed']); self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); self::assertClaimAddresses($claims, $addresses, $selection, - $operationId, [ + null, [ 'committed' => ['assigned'], ], $instanceId); - self::releaseLockedClaims($claims, $operationId, $reason); + self::releaseLockedClaims($claims, $reason); }); } @@ -303,6 +430,7 @@ final class CloudPublicNetworkAllocationService { return DB::table('cloud_resource_reservation_ips') ->where('reservation_id', $reservationId) + ->where('active_claim', 1) ->orderBy('address_family')->orderBy('id')->get()->all(); } @@ -333,6 +461,31 @@ final class CloudPublicNetworkAllocationService } } + private static function claimStateForReservation(object $reservation): string + { + $state = (string) ($reservation->state ?? ''); + $instanceId = $reservation->instance_id === null + ? null : (int) $reservation->instance_id; + if (($state === 'committed' + && ($instanceId === null || $instanceId < 1)) + || (in_array($state, ['held', 'uncertain'], true) + && $instanceId !== null)) { + throw new CloudError( + '公网网络资源预留生命周期不一致', + 409 + ); + } + return match ($state) { + 'held' => 'reserved', + 'committed' => 'committed', + 'uncertain' => 'uncertain', + default => throw new CloudError( + '公网网络资源预留生命周期不一致', + 409 + ), + }; + } + /** Locks the exact historical attachment and pools before the reservation. */ private static function lockClaimNetworkContext(array $claimHints, int $hostId, ?int $lineId = null): array @@ -434,18 +587,8 @@ final class CloudPublicNetworkAllocationService object $pool): CloudIpAddress { try { - $address = CloudIpAddress::parse((string) $row->address); - if ((int) $row->host_id !== (int) $pool->host_id - || (int) $row->public_ip_pool_id !== (int) $pool->id - || (int) $row->address_family - !== (int) $pool->address_family - || (int) $row->prefix_length - !== (int) $pool->guest_prefix_length - || !hash_equals($address->text(), (string) $row->address) - || !is_string($row->address_binary) - || !hash_equals($address->binary(), $row->address_binary) - || !self::rawAddressBelongsToPool($address, $pool) - || ((string) $row->state !== 'disabled' + $address = self::assertConcreteAddressIdentity($row, $pool); + if (((string) $row->state !== 'disabled' && !self::rawAddressAllowedByPool($address, $pool))) { throw new \InvalidArgumentException(); } @@ -464,6 +607,30 @@ final class CloudPublicNetworkAllocationService } } + /** Validate immutable identity without reapplying mutable allowlists. */ + private static function assertConcreteAddressIdentity(object $row, + object $pool): CloudIpAddress + { + try { + $address = CloudIpAddress::parse((string) $row->address); + if ((int) $row->host_id !== (int) $pool->host_id + || (int) $row->public_ip_pool_id !== (int) $pool->id + || (int) $row->address_family + !== (int) $pool->address_family + || (int) $row->prefix_length + !== (int) $pool->guest_prefix_length + || !hash_equals($address->text(), (string) $row->address) + || !is_string($row->address_binary) + || !hash_equals($address->binary(), $row->address_binary) + || !self::rawAddressBelongsToPool($address, $pool)) { + throw new \InvalidArgumentException(); + } + return $address; + } catch (\Throwable) { + throw new CloudError('公网地址具体身份与地址池不一致', 409); + } + } + private static function assertAddressOwnership(object $row, ?object $pool = null, array $retainedSourceEvidence = []): void { @@ -471,17 +638,21 @@ final class CloudPublicNetworkAllocationService ? null : (int) $row->reservation_id; $instanceId = $row->instance_id === null ? null : (int) $row->instance_id; + $claimId = $row->reservation_ip_claim_id === null + ? null : (int) $row->reservation_ip_claim_id; $operationId = $row->operation_id; $validOperation = is_string($operationId) && preg_match('/^[a-f0-9]{32}$/D', $operationId) === 1; $state = (string) $row->state; $valid = match ($state) { 'available', 'disabled' => $reservationId === null - && $instanceId === null && $operationId === null, + && $claimId === null && $instanceId === null + && $operationId === null, 'reserved' => $reservationId !== null && $reservationId > 0 + && $claimId !== null && $claimId > 0 && $instanceId === null && $validOperation, 'assigned' => $reservationId !== null && $reservationId > 0 - && $validOperation && ( + && $claimId !== null && $claimId > 0 && $validOperation && ( ($instanceId !== null && $instanceId > 0) || self::matchesRetainedSourceEvidence( $row, @@ -489,15 +660,10 @@ final class CloudPublicNetworkAllocationService $retainedSourceEvidence ) ), - 'changing' => $reservationId === null - && $instanceId !== null && $instanceId > 0 + 'changing', 'uncertain' => $reservationId !== null + && $reservationId > 0 && $claimId !== null && $claimId > 0 + && ($instanceId === null || $instanceId > 0) && $validOperation, - 'uncertain' => $validOperation && ( - ($reservationId !== null && $reservationId > 0 - && $instanceId === null) - || ($reservationId === null - && $instanceId !== null && $instanceId > 0) - ), default => false, }; if (!$valid) { @@ -537,22 +703,29 @@ final class CloudPublicNetworkAllocationService } private static function assertClaimAddresses(array $claims, - array $addresses, array $selection, string $operationId, + array $addresses, array $selection, ?string $operationId, array $allowedPairs, ?int $instanceId = null): void { foreach ($claims as $claim) { $ip = $addresses[(int) $claim->public_ip_id] ?? null; $claimState = (string) $claim->state; + $claimOperationId = (string) ($claim->operation_id ?? ''); + $expectedOperationId = $operationId ?? $claimOperationId; $allowedIpStates = $allowedPairs[$claimState] ?? []; $family = (int) $claim->address_family; $pool = $selection['pools'][$family] ?? null; if ($ip === null || $pool === null || $allowedIpStates === [] || !in_array((string) $ip->state, $allowedIpStates, true) || (int) $ip->reservation_id !== (int) $claim->reservation_id + || (int) ($ip->reservation_ip_claim_id ?? 0) + !== (int) $claim->id || (int) $ip->address_family !== (int) $claim->address_family || (int) $ip->public_ip_pool_id !== (int) $claim->public_ip_pool_id - || !hash_equals($operationId, + || preg_match('/^[a-f0-9]{32}$/D', $claimOperationId) !== 1 + || !hash_equals($claimOperationId, + (string) ($ip->operation_id ?? '')) + || !hash_equals($expectedOperationId, (string) ($ip->operation_id ?? ''))) { throw new CloudError('公网地址与预留账本不一致', 409); } @@ -572,26 +745,34 @@ final class CloudPublicNetworkAllocationService } private static function releaseLockedClaims(array $claims, - string $operationId, string $reason): void + string $reason): void { $now = time(); foreach ($claims as $claim) { - DB::table('cloud_public_ips') + $ipUpdated = DB::table('cloud_public_ips') ->where('id', (int) $claim->public_ip_id) - ->where('operation_id', $operationId)->update([ + ->where('reservation_ip_claim_id', (int) $claim->id) + ->where('operation_id', (string) $claim->operation_id) + ->update([ 'state' => 'available', 'reservation_id' => null, + 'reservation_ip_claim_id' => null, 'instance_id' => null, 'operation_id' => null, 'updated_at' => $now, ]); - DB::table('cloud_resource_reservation_ips') - ->where('id', (int) $claim->id)->update([ + $claimUpdated = DB::table('cloud_resource_reservation_ips') + ->where('id', (int) $claim->id) + ->where('active_claim', 1)->update([ 'state' => 'released', + 'active_claim' => null, 'released_at' => $now, 'release_reason' => $reason, 'updated_at' => $now, ]); + if ($ipUpdated !== 1 || $claimUpdated !== 1) { + throw new CloudError('双栈公网地址释放账本未精确更新', 409); + } } } @@ -843,8 +1024,8 @@ final class CloudPublicNetworkAllocationService return null; } - private static function reserveAddress(object $pool, int $reservationId, - string $operationId, int $now, ?array $selection): object + private static function reserveAddress(object $pool, int $now, + ?array $selection): object { $family = (int) $pool->address_family; if ($selection === null) { @@ -856,12 +1037,15 @@ final class CloudPublicNetworkAllocationService ); } if ($selection['row'] !== null) { - return self::claimAddress( - $selection['row'], - $reservationId, - $operationId, - $now - ); + $row = $selection['row']; + if ((string) $row->state !== 'available' + || $row->reservation_id !== null + || $row->reservation_ip_claim_id !== null + || $row->instance_id !== null + || $row->operation_id !== null) { + throw new CloudError('公网地址候选已被占用', 409); + } + return $row; } $candidate = $selection['candidate']; $rangeStart = $selection['range_start']; @@ -878,10 +1062,11 @@ final class CloudPublicNetworkAllocationService 'address' => $candidate->text(), 'address_binary' => $candidate->binary(), 'prefix_length' => (int) $pool->guest_prefix_length, - 'state' => 'reserved', - 'reservation_id' => $reservationId, + 'state' => 'available', + 'reservation_id' => null, + 'reservation_ip_claim_id' => null, 'instance_id' => null, - 'operation_id' => $operationId, + 'operation_id' => null, 'created_at' => $now, 'updated_at' => $now, ]); @@ -894,18 +1079,26 @@ final class CloudPublicNetworkAllocationService return DB::table('cloud_public_ips')->where('id', $id)->first(); } - private static function claimAddress(object $row, int $reservationId, - string $operationId, int $now): object + private static function bindAddressToClaim(object $row, int $reservationId, + string $operationId, int $claimId, int $now): void { - DB::table('cloud_public_ips')->where('id', (int) $row->id)->update([ + $updated = DB::table('cloud_public_ips') + ->where('id', (int) $row->id) + ->where('state', 'available') + ->whereNull('reservation_id') + ->whereNull('reservation_ip_claim_id') + ->whereNull('instance_id') + ->whereNull('operation_id')->update([ 'state' => 'reserved', 'reservation_id' => $reservationId, + 'reservation_ip_claim_id' => $claimId, 'instance_id' => null, 'operation_id' => $operationId, 'updated_at' => $now, ]); - return DB::table('cloud_public_ips')->where('id', (int) $row->id) - ->first(); + if ($updated !== 1) { + throw new CloudError('公网地址声明绑定失败', 409); + } } private static function validatePool(object $pool, int $family): void @@ -1026,12 +1219,32 @@ final class CloudPublicNetworkAllocationService { return DB::table('cloud_resource_reservation_ips') ->where('reservation_id', $reservationId) + ->where('active_claim', 1) ->orderBy('address_family')->orderBy('id')->lockForUpdate()->get() ->all(); } + private static function lockedHistoricalClaims(int $reservationId): array + { + return DB::table('cloud_resource_reservation_ips') + ->where('reservation_id', $reservationId) + ->whereNull('active_claim')->orderBy('id')->lockForUpdate()->get() + ->all(); + } + private static function assertClaimSet(array $claims, string $operationId, array $allowedStates): void + { + self::assertActiveClaimSet($claims, $allowedStates); + foreach ($claims as $claim) { + if (!hash_equals($operationId, (string) $claim->operation_id)) { + throw new CloudError('双栈公网地址操作身份不一致', 409); + } + } + } + + private static function assertActiveClaimSet(array $claims, + array $allowedStates): void { if (count($claims) !== 2) { throw new CloudError('双栈公网地址账本不完整', 409); @@ -1041,7 +1254,10 @@ final class CloudPublicNetworkAllocationService $family = (int) $claim->address_family; if (!in_array($family, self::FAMILIES, true) || isset($families[$family]) - || !hash_equals($operationId, (string) $claim->operation_id) + || (int) ($claim->claim_generation ?? 0) < 1 + || (int) ($claim->active_claim ?? 0) !== 1 + || preg_match('/^[a-f0-9]{32}$/D', + (string) ($claim->operation_id ?? '')) !== 1 || !in_array((string) $claim->state, $allowedStates, true)) { throw new CloudError('双栈公网地址账本不一致', 409); } @@ -1053,6 +1269,17 @@ final class CloudPublicNetworkAllocationService } private static function snapshot(array $claims): CloudPublicNetworkSnapshot + { + return self::claimSet($claims)->publicNetwork(); + } + + private static function claimSet( + array $claims, + ?string $expectedState = null, + ?int $expectedInstanceId = null, + ?int $expectedHostId = null, + ?int $expectedLineId = null + ): CloudActivePublicNetworkClaimSet { if (count($claims) !== 2) { throw new CloudError('双栈公网地址账本不完整', 409); @@ -1066,11 +1293,17 @@ final class CloudPublicNetworkAllocationService } $attachment = DB::table('cloud_host_network_attachments') ->where('id', $attachmentIds[0])->first(); - if ($attachment === null) { + if ($attachment === null + || ($expectedHostId !== null + && (int) $attachment->host_id !== $expectedHostId) + || ($expectedLineId !== null + && (int) $attachment->line_id !== $expectedLineId)) { throw new CloudError('公网网络接入不存在', 409); } $legs = []; $dns = []; + $addresses = []; + $reservationIds = []; foreach ($claims as $claim) { $family = (int) $claim->address_family; $pool = DB::table('cloud_public_ip_pools') @@ -1080,10 +1313,16 @@ final class CloudPublicNetworkAllocationService if ($pool === null || $ip === null || (int) $pool->address_family !== $family || (int) $ip->address_family !== $family + || ($expectedHostId !== null + && ((int) $pool->host_id !== $expectedHostId + || (int) $ip->host_id !== $expectedHostId)) || (int) $pool->network_attachment_id !== $attachmentIds[0] || (int) $ip->public_ip_pool_id !== (int) $pool->id) { throw new CloudError('双栈公网地址引用损坏', 409); } + self::assertConcreteAddressIdentity($ip, $pool); + $addresses[(int) $ip->id] = $ip; + $reservationIds[(int) $claim->reservation_id] = true; $legs[$family] = [ 'pool_key' => (string) $pool->pool_key, 'pool_cidr' => (string) $pool->cidr, @@ -1099,13 +1338,71 @@ final class CloudPublicNetworkAllocationService $dns[$text] = $text; } } - return CloudPublicNetworkSnapshot::fromArray([ + if (count($reservationIds) !== 1) { + throw new CloudError('双栈公网地址不属于同一资源预留', 409); + } + self::assertCurrentClaimSetStates( + $claims, + $addresses, + $expectedState, + $expectedInstanceId + ); + $snapshot = CloudPublicNetworkSnapshot::fromArray([ 'contract' => 1, 'network_selector' => (string) $attachment->network_selector, 'ipv4' => $legs[4] ?? null, 'ipv6' => $legs[6] ?? null, 'dns_servers' => array_values($dns), ]); + return CloudActivePublicNetworkClaimSet::fromLedger( + (int) array_key_first($reservationIds), + $claims, + $addresses, + $snapshot + ); + } + + /** + * @param array $claims + * @param array $addresses + */ + private static function assertCurrentClaimSetStates(array $claims, + array $addresses, ?string $expectedState, + ?int $expectedInstanceId): void + { + $claimStates = []; + $instanceIds = []; + foreach ($claims as $claim) { + $claimState = (string) ($claim->state ?? ''); + $ip = $addresses[(int) ($claim->public_ip_id ?? 0)] ?? null; + $ipState = is_object($ip) ? (string) ($ip->state ?? '') : ''; + $expectedIpState = match ($claimState) { + 'reserved' => 'reserved', + 'committed' => 'assigned', + 'uncertain' => 'uncertain', + default => '', + }; + $instanceId = is_object($ip) && $ip->instance_id !== null + ? (int) $ip->instance_id : null; + if ($expectedIpState === '' || $ipState !== $expectedIpState + || ($claimState !== 'committed' && $instanceId !== null) + || ($claimState === 'committed' + && ($instanceId === null || $instanceId < 1))) { + throw new CloudError('活动双栈公网地址状态不一致', 409); + } + $claimStates[$claimState] = true; + if ($instanceId !== null) { + $instanceIds[$instanceId] = true; + } + } + if (count($claimStates) !== 1 + || ($expectedState !== null && !isset($claimStates[$expectedState])) + || (isset($claimStates['committed']) && count($instanceIds) !== 1) + || (!isset($claimStates['committed']) && $instanceIds !== []) + || ($expectedInstanceId !== null + && !isset($instanceIds[$expectedInstanceId]))) { + throw new CloudError('活动双栈公网地址集合状态不一致', 409); + } } private static function assertIdentity(int $reservationId, diff --git a/web/app/Services/Cloud/CloudPublicNetworkTransitionGate.php b/web/app/Services/Cloud/CloudPublicNetworkTransitionGate.php new file mode 100644 index 00000000..7d17002e --- /dev/null +++ b/web/app/Services/Cloud/CloudPublicNetworkTransitionGate.php @@ -0,0 +1,51 @@ +reservation_id ?? 0); + if ($reservationId < 1) { + return; + } + $restoreId = CloudResourceReservation::where( + 'id', + $reservationId + )->value('backup_restore_id'); + if ($restoreId !== null && (int) $restoreId > 0) { + self::assertPortableRestoreReady(); + } + } +} diff --git a/web/app/Services/Cloud/CloudWorkerService.php b/web/app/Services/Cloud/CloudWorkerService.php index 48c2e764..d1308b2d 100644 --- a/web/app/Services/Cloud/CloudWorkerService.php +++ b/web/app/Services/Cloud/CloudWorkerService.php @@ -428,6 +428,28 @@ final class CloudWorkerService return true; } } + if ((string) $job->kind === 'network_change') { + CloudPublicNetworkTransitionGate::assertWriterReady(); + } elseif ((string) $job->kind === 'backup_restore') { + CloudPublicNetworkTransitionGate::assertPortableRestoreReady(); + } elseif (str_starts_with( + (string) $job->kind, + 'instance_migration_' + )) { + CloudPublicNetworkTransitionGate::assertMigrationReady(); + } elseif (in_array( + (string) $job->kind, + ['delete', 'delete_force', 'expiry_delete'], + true + ) && $job->instance_id !== null) { + $deleteInstance = CloudInstance::find( + (int) $job->instance_id + ); + if ($deleteInstance !== null) { + CloudPublicNetworkTransitionGate:: + assertInstanceDeleteReady($deleteInstance); + } + } $now = time(); $dispatchClaim = self::dispatchableBeforeDeadline( CloudJob::where('id', $job->id) diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql index 8bf08489..c16c8ea9 100644 --- a/web/sql/cloud.sql +++ b/web/sql/cloud.sql @@ -365,6 +365,40 @@ CREATE TABLE cloud_public_ips ( CONSTRAINT chk_cloud_public_ip_prefix CHECK ( (address_family = 4 AND prefix_length BETWEEN 1 AND 30) OR (address_family = 6 AND prefix_length BETWEEN 1 AND 120) + ), + CONSTRAINT chk_cloud_public_ip_state CHECK ( + state IN ( + 'available','disabled','reserved','assigned','changing','uncertain' + ) + ), + CONSTRAINT chk_cloud_public_ip_owner_shape CHECK ( + ( + state IN ('available','disabled') + AND reservation_id IS NULL + AND reservation_ip_claim_id IS NULL + AND instance_id IS NULL + AND operation_id IS NULL + ) + OR ( + state = 'reserved' + AND reservation_id IS NOT NULL + AND reservation_ip_claim_id IS NOT NULL + AND instance_id IS NULL + AND operation_id IS NOT NULL + ) + OR ( + state IN ('changing','uncertain') + AND reservation_id IS NOT NULL + AND reservation_ip_claim_id IS NOT NULL + AND operation_id IS NOT NULL + ) + OR ( + state = 'assigned' + AND reservation_id IS NOT NULL + AND reservation_ip_claim_id IS NOT NULL + AND instance_id IS NOT NULL + AND operation_id IS NOT NULL + ) ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; @@ -1466,7 +1500,19 @@ CREATE TABLE cloud_resource_reservation_ips ( claim_generation >= 1 ), CONSTRAINT chk_cloud_reservation_ip_active CHECK ( - active_claim IS NULL OR active_claim = 1 + ( + state = 'released' + AND active_claim IS NULL + ) + OR ( + state = 'committed' + AND active_claim IS NOT NULL + AND active_claim = 1 + ) + OR ( + state IN ('reserved','uncertain') + AND (active_claim IS NULL OR active_claim = 1) + ) ), CONSTRAINT chk_cloud_reservation_ip_state CHECK ( state IN ('reserved','committed','uncertain','released') diff --git a/web/tests/CloudActivePublicNetworkClaimSchemaBehaviorTest.php b/web/tests/CloudActivePublicNetworkClaimSchemaBehaviorTest.php new file mode 100644 index 00000000..91252774 --- /dev/null +++ b/web/tests/CloudActivePublicNetworkClaimSchemaBehaviorTest.php @@ -0,0 +1,153 @@ +setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); +$pdo->exec(<<<'SQL' +CREATE TABLE claims ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + reservation_id INTEGER NOT NULL, + address_family INTEGER NOT NULL, + claim_generation INTEGER NOT NULL, + active_claim INTEGER DEFAULT 1, + operation_id TEXT NOT NULL, + state TEXT NOT NULL, + released_at INTEGER DEFAULT NULL, + release_reason TEXT NOT NULL DEFAULT '', + UNIQUE (reservation_id, address_family, active_claim), + UNIQUE (reservation_id, claim_generation, address_family), + CHECK (address_family IN (4,6)), + CHECK (claim_generation >= 1), + CHECK ( + (state = 'released' AND active_claim IS NULL) + OR ( + state = 'committed' + AND active_claim IS NOT NULL + AND active_claim = 1 + ) + OR ( + state IN ('reserved','uncertain') + AND (active_claim IS NULL OR active_claim = 1) + ) + ), + CHECK ( + (state = 'released' AND released_at IS NOT NULL AND release_reason <> '') + OR (state <> 'released' AND released_at IS NULL AND release_reason = '') + ) +); +CREATE TABLE addresses ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + state TEXT NOT NULL, + reservation_id INTEGER DEFAULT NULL, + reservation_ip_claim_id INTEGER DEFAULT NULL, + instance_id INTEGER DEFAULT NULL, + operation_id TEXT DEFAULT NULL, + CHECK ( + state IN ('available','disabled','reserved','assigned','changing','uncertain') + ), + CHECK ( + ( + state IN ('available','disabled') + AND reservation_id IS NULL + AND reservation_ip_claim_id IS NULL + AND instance_id IS NULL + AND operation_id IS NULL + ) + OR ( + state = 'reserved' + AND reservation_id IS NOT NULL + AND reservation_ip_claim_id IS NOT NULL + AND instance_id IS NULL + AND operation_id IS NOT NULL + ) + OR ( + state IN ('changing','uncertain') + AND reservation_id IS NOT NULL + AND reservation_ip_claim_id IS NOT NULL + AND operation_id IS NOT NULL + ) + OR ( + state = 'assigned' + AND reservation_id IS NOT NULL + AND reservation_ip_claim_id IS NOT NULL + AND instance_id IS NOT NULL + AND operation_id IS NOT NULL + ) + ) +); +SQL); + +$assert = static function (bool $condition, string $message): void { + if (!$condition) { + throw new RuntimeException($message); + } +}; +$rejects = static function (callable $callback, string $message): void { + try { + $callback(); + } catch (PDOException) { + return; + } + throw new RuntimeException($message); +}; + +$claim = $pdo->prepare( + 'INSERT INTO claims ' + . '(reservation_id,address_family,claim_generation,active_claim,' + . 'operation_id,state,released_at,release_reason) ' + . 'VALUES (?,?,?,?,?,?,?,?)' +); +$claim->execute([10, 4, 1, 1, str_repeat('a', 32), 'committed', null, '']); +$claim->execute([10, 6, 3, 1, str_repeat('b', 32), 'committed', null, '']); +$assert((int) $pdo->query( + 'SELECT COUNT(*) FROM claims WHERE reservation_id=10 AND active_claim=1' +)->fetchColumn() === 2, + 'Different per-family generation and operation identities were rejected.'); +$rejects(static fn () => $claim->execute([ + 10, 4, 2, 1, str_repeat('c', 32), 'reserved', null, '', +]), 'A second active claim for one family was accepted.'); +$claim->execute([ + 10, 4, 2, null, str_repeat('c', 32), 'reserved', null, '', +]); +$claim->execute([ + 11, 6, 1, null, str_repeat('e', 32), 'uncertain', null, '', +]); +$claim->execute([ + 10, 4, 3, null, str_repeat('d', 32), 'released', 100, 'replaced', +]); +$rejects(static fn () => $claim->execute([ + 12, 4, 1, null, str_repeat('f', 32), 'committed', null, '', +]), 'A committed claim was persisted without the active authority fence.'); +$rejects(static fn () => $claim->execute([ + 13, 4, 1, 1, str_repeat('0', 32), 'released', 100, 'released', +]), 'A released claim retained the active fence.'); +$rejects(static fn () => $claim->execute([ + 14, 4, 1, null, str_repeat('1', 32), 'released', null, '', +]), 'A released claim omitted terminal evidence through SQL NULL semantics.'); + +$address = $pdo->prepare( + 'INSERT INTO addresses ' + . '(state,reservation_id,reservation_ip_claim_id,instance_id,operation_id) ' + . 'VALUES (?,?,?,?,?)' +); +$address->execute(['available', null, null, null, null]); +$address->execute(['reserved', 10, 1, null, str_repeat('a', 32)]); +$address->execute(['changing', 10, 3, 88, str_repeat('c', 32)]); +$address->execute(['uncertain', 10, 3, null, str_repeat('c', 32)]); +$address->execute(['assigned', 10, 1, 88, str_repeat('a', 32)]); +$rejects(static fn () => $address->execute([ + 'available', null, 1, null, null, +]), 'An available address retained a claim fence.'); +$rejects(static fn () => $address->execute([ + 'reserved', 10, null, null, str_repeat('a', 32), +]), 'A reserved address omitted its exact claim.'); +$rejects(static fn () => $address->execute([ + 'changing', null, null, 88, str_repeat('c', 32), +]), 'A legacy scalar-only changing target bypassed the claim ledger.'); +$rejects(static fn () => $address->execute([ + 'uncertain', null, null, 88, str_repeat('c', 32), +]), 'A legacy scalar-only uncertain target bypassed the claim ledger.'); +$rejects(static fn () => $address->execute([ + 'assigned', 10, 1, null, str_repeat('a', 32), +]), 'An assigned address omitted its instance owner.'); + +echo "Active public-network claim schema behavior tests passed.\n"; diff --git a/web/tests/CloudAdminResourceActiveClaimProjectionTest.php b/web/tests/CloudAdminResourceActiveClaimProjectionTest.php new file mode 100644 index 00000000..cddca485 --- /dev/null +++ b/web/tests/CloudAdminResourceActiveClaimProjectionTest.php @@ -0,0 +1,363 @@ +addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); + +$schema->create('cloud_regions', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('name'); +}); +$schema->create('cloud_network_lines', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('region_id'); + $table->string('name'); +}); +$schema->create('cloud_resource_pools', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('line_id'); + $table->string('name'); +}); +$schema->create('cloud_offers', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('name'); +}); +$schema->create('cloud_hosts', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('name'); +}); +$schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('reservation_id'); + $table->integer('host_id'); + $table->integer('resource_pool_id'); + $table->integer('user_id'); +}); +$schema->create('cloud_host_network_attachments', static function ( + Blueprint $table +): void { + $table->increments('id'); + $table->integer('host_id'); + $table->integer('line_id'); + $table->string('network_selector'); +}); +$schema->create('cloud_public_ip_pools', static function ( + Blueprint $table +): void { + $table->increments('id'); + $table->integer('host_id'); + $table->integer('network_attachment_id'); + $table->integer('address_family'); + $table->string('pool_key'); + $table->string('cidr'); + $table->string('gateway'); + $table->boolean('gateway_on_link'); + $table->integer('guest_prefix_length'); + $table->text('dns_servers_json'); +}); +$schema->create('cloud_public_ips', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('host_id'); + $table->integer('public_ip_pool_id'); + $table->integer('address_family'); + $table->string('address'); + $table->binary('address_binary'); + $table->integer('prefix_length'); + $table->string('state'); + $table->integer('reservation_id')->nullable(); + $table->integer('reservation_ip_claim_id')->nullable(); + $table->integer('instance_id')->nullable(); + $table->string('operation_id')->nullable(); +}); +$schema->create('cloud_resource_reservations', static function ( + Blueprint $table +): void { + $table->increments('id'); + $table->string('reservation_key'); + $table->integer('order_id')->nullable(); + $table->integer('offer_id')->nullable(); + $table->integer('resource_pool_id'); + $table->integer('host_id'); + $table->integer('user_id'); + $table->integer('instance_id')->nullable(); + $table->integer('network_attachment_id')->nullable(); + $table->integer('public_ip_pool_id')->nullable(); + $table->integer('public_ip_id')->nullable(); + $table->string('operation_id'); + $table->integer('cpu_cores'); + $table->integer('memory_mib'); + $table->integer('disk_gib'); + $table->string('state'); + $table->integer('expires_at')->nullable(); + $table->integer('released_at')->nullable(); + $table->string('release_reason'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_resource_reservation_ips', static function ( + Blueprint $table +): void { + $table->increments('id'); + $table->integer('reservation_id'); + $table->integer('address_family'); + $table->integer('claim_generation'); + $table->integer('active_claim')->nullable(); + $table->integer('network_attachment_id'); + $table->integer('public_ip_pool_id'); + $table->integer('public_ip_id'); + $table->string('operation_id'); + $table->string('state'); + $table->integer('released_at')->nullable(); + $table->string('release_reason'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); + +Capsule::table('cloud_regions')->insert(['id' => 1, 'name' => '香港']); +Capsule::table('cloud_network_lines')->insert([ + 'id' => 2, 'region_id' => 1, 'name' => '国际线路', +]); +Capsule::table('cloud_resource_pools')->insert([ + 'id' => 3, 'line_id' => 2, 'name' => '通用池', +]); +Capsule::table('cloud_offers')->insert(['id' => 4, 'name' => '双栈计划']); +Capsule::table('cloud_hosts')->insert(['id' => 5, 'name' => 'HKG-A']); +Capsule::table('cloud_host_network_attachments')->insert([ + 'id' => 10, + 'host_id' => 5, + 'line_id' => 2, + 'network_selector' => 'bridge:br0', +]); +Capsule::table('cloud_public_ip_pools')->insert([ + [ + 'id' => 20, 'host_id' => 5, 'network_attachment_id' => 10, + 'address_family' => 4, 'pool_key' => str_repeat('a', 32), + 'cidr' => '8.8.8.0/24', 'gateway' => '8.8.8.1', + 'gateway_on_link' => 0, 'guest_prefix_length' => 24, + 'dns_servers_json' => '["1.1.1.1"]', + ], + [ + 'id' => 21, 'host_id' => 5, 'network_attachment_id' => 10, + 'address_family' => 6, 'pool_key' => str_repeat('b', 32), + 'cidr' => '2404:c140:156:3a::/64', + 'gateway' => '2404:c140:156::1', 'gateway_on_link' => 1, + 'guest_prefix_length' => 64, + 'dns_servers_json' => '["2606:4700:4700::1111"]', + ], +]); +$now = time(); +Capsule::table('cloud_resource_reservations')->insert([ + 'id' => 100, + 'reservation_key' => str_repeat('c', 32), + 'order_id' => 200, + 'offer_id' => 4, + 'resource_pool_id' => 3, + 'host_id' => 5, + 'user_id' => 7, + 'instance_id' => 88, + // Deliberately corrupt retired scalar fields. They must not affect output. + 'network_attachment_id' => 999, + 'public_ip_pool_id' => 999, + 'public_ip_id' => 999, + 'operation_id' => str_repeat('d', 32), + 'cpu_cores' => 2, + 'memory_mib' => 2048, + 'disk_gib' => 20, + 'state' => 'committed', + 'expires_at' => null, + 'released_at' => null, + 'release_reason' => '', + 'created_at' => $now, + 'updated_at' => $now, +]); +Capsule::table('cloud_instances')->insert([ + 'id' => 88, + 'reservation_id' => 100, + 'host_id' => 5, + 'resource_pool_id' => 3, + 'user_id' => 7, +]); +$claims = [ + 4 => ['id' => 301, 'generation' => 1, 'pool' => 20, 'ip' => 501, + 'operation' => str_repeat('e', 32), 'address' => '8.8.8.10', + 'prefix' => 24], + 6 => ['id' => 302, 'generation' => 3, 'pool' => 21, 'ip' => 502, + 'operation' => str_repeat('f', 32), + 'address' => '2404:c140:156:3a::10', 'prefix' => 64], +]; +foreach ($claims as $family => $claim) { + Capsule::table('cloud_resource_reservation_ips')->insert([ + 'id' => $claim['id'], 'reservation_id' => 100, + 'address_family' => $family, + 'claim_generation' => $claim['generation'], 'active_claim' => 1, + 'network_attachment_id' => 10, + 'public_ip_pool_id' => $claim['pool'], + 'public_ip_id' => $claim['ip'], + 'operation_id' => $claim['operation'], 'state' => 'committed', + 'released_at' => null, 'release_reason' => '', + 'created_at' => $now, 'updated_at' => $now, + ]); + Capsule::table('cloud_public_ips')->insert([ + 'id' => $claim['ip'], 'host_id' => 5, + 'public_ip_pool_id' => $claim['pool'], 'address_family' => $family, + 'address' => $claim['address'], + 'address_binary' => inet_pton($claim['address']), + 'prefix_length' => $claim['prefix'], + 'state' => 'assigned', 'reservation_id' => 100, + 'reservation_ip_claim_id' => $claim['id'], 'instance_id' => 88, + 'operation_id' => $claim['operation'], + ]); +} +// Historical claims must never leak into the current projection. +Capsule::table('cloud_resource_reservation_ips')->insert([ + 'id' => 303, 'reservation_id' => 100, 'address_family' => 4, + 'claim_generation' => 1, 'active_claim' => null, + 'network_attachment_id' => 10, 'public_ip_pool_id' => 20, + 'public_ip_id' => 503, 'operation_id' => str_repeat('1', 32), + 'state' => 'released', 'released_at' => $now, + 'release_reason' => 'replaced', 'created_at' => $now, + 'updated_at' => $now, +]); + +Capsule::table('cloud_resource_reservations')->insert([ + 'id' => 101, 'reservation_key' => str_repeat('2', 32), + 'order_id' => 201, 'offer_id' => 4, 'resource_pool_id' => 3, + 'host_id' => 5, 'user_id' => 7, 'instance_id' => null, + 'network_attachment_id' => 999, 'public_ip_pool_id' => 999, + 'public_ip_id' => 999, 'operation_id' => str_repeat('3', 32), + 'cpu_cores' => 1, 'memory_mib' => 1024, 'disk_gib' => 10, + 'state' => 'held', 'expires_at' => null, 'released_at' => null, + 'release_reason' => '', 'created_at' => $now, 'updated_at' => $now, +]); +foreach ([ + 4 => [401, 601, 20, str_repeat('4', 32), '8.8.8.11', 24], + 6 => [402, 602, 21, str_repeat('5', 32), + '2404:c140:156:3a::11', 64], +] as $family => [$claimId, $ipId, $poolId, $operationId, $address, $prefix]) { + Capsule::table('cloud_resource_reservation_ips')->insert([ + 'id' => $claimId, 'reservation_id' => 101, + 'address_family' => $family, 'claim_generation' => 1, + 'active_claim' => 1, 'network_attachment_id' => 10, + 'public_ip_pool_id' => $poolId, 'public_ip_id' => $ipId, + 'operation_id' => $operationId, 'state' => 'reserved', + 'released_at' => null, 'release_reason' => '', + 'created_at' => $now, 'updated_at' => $now, + ]); + Capsule::table('cloud_public_ips')->insert([ + 'id' => $ipId, 'host_id' => 5, 'public_ip_pool_id' => $poolId, + 'address_family' => $family, 'address' => $address, + 'address_binary' => inet_pton($address), + 'prefix_length' => $prefix, 'state' => 'reserved', + 'reservation_id' => 101, 'reservation_ip_claim_id' => $claimId, + 'instance_id' => null, 'operation_id' => $operationId, + ]); +} + +Capsule::table('cloud_resource_reservations')->insert([ + 'id' => 102, 'reservation_key' => str_repeat('6', 32), + 'order_id' => 202, 'offer_id' => 4, 'resource_pool_id' => 3, + 'host_id' => 5, 'user_id' => 7, 'instance_id' => null, + 'network_attachment_id' => null, 'public_ip_pool_id' => null, + 'public_ip_id' => null, 'operation_id' => str_repeat('7', 32), + 'cpu_cores' => 1, 'memory_mib' => 1024, 'disk_gib' => 10, + 'state' => 'released', 'expires_at' => null, 'released_at' => $now, + 'release_reason' => 'failed', 'created_at' => $now, + 'updated_at' => $now, +]); +Capsule::table('cloud_resource_reservation_ips')->insert([ + 'id' => 403, 'reservation_id' => 102, 'address_family' => 4, + 'claim_generation' => 1, 'active_claim' => 1, + 'network_attachment_id' => 10, 'public_ip_pool_id' => 20, + 'public_ip_id' => 603, 'operation_id' => str_repeat('8', 32), + 'state' => 'reserved', 'released_at' => null, 'release_reason' => '', + 'created_at' => $now, 'updated_at' => $now, +]); +Capsule::table('cloud_public_ips')->insert([ + 'id' => 603, 'host_id' => 5, 'public_ip_pool_id' => 20, + 'address_family' => 4, 'address' => '8.8.8.12', + 'address_binary' => inet_pton('8.8.8.12'), 'prefix_length' => 24, + 'state' => 'reserved', 'reservation_id' => 102, + 'reservation_ip_claim_id' => 403, 'instance_id' => null, + 'operation_id' => str_repeat('8', 32), +]); + +$page = CloudAdminResourceService::reservations(['q' => '501']); +$item = $page['items'][0] ?? null; +$assert(is_array($item) + && $item['public_ip_id'] === 501 + && $item['public_ip'] === '8.8.8.10' + && $item['public_ipv4'] === '8.8.8.10' + && $item['public_ipv6'] === '2404:c140:156:3a::10' + && count($item['public_ips']) === 2 + && $item['public_ips'][0]['claim_generation'] === 1 + && $item['public_ips'][1]['claim_generation'] === 3, + 'Administrator reservation projection did not use the active dual-stack claims.'); +$assert(CloudAdminResourceService::reservations(['q' => '999'])[ + 'pagination' + ]['total'] === 0, + 'Reservation search still treated the retired singular IP field as authority.'); +$held = CloudAdminResourceService::reservation('101')['item']; +$assert($held['state'] === 'held' + && $held['public_ipv4'] === '8.8.8.11' + && $held['public_ipv6'] === '2404:c140:156:3a::11', + 'Held reservation did not map to its reserved active claim pair.'); +$releasedLeakRejected = false; +try { + CloudAdminResourceService::reservation('102'); +} catch (CloudError $error) { + $releasedLeakRejected = $error->httpStatus === 409; +} +$assert($releasedLeakRejected, + 'Released reservation hid an active public-address leak.'); +Capsule::table('cloud_resource_reservation_ips')->where('id', 403)->update([ + 'state' => 'released', + 'active_claim' => null, + 'released_at' => $now, + 'release_reason' => 'failed', +]); +Capsule::table('cloud_public_ips')->where('id', 603)->update([ + 'state' => 'available', + 'reservation_id' => null, + // The reverse pointer alone is still an ownership leak. + 'reservation_ip_claim_id' => 403, + 'instance_id' => null, + 'operation_id' => null, +]); +$releasedReverseLeakRejected = false; +try { + CloudAdminResourceService::reservation('102'); +} catch (CloudError $error) { + $releasedReverseLeakRejected = $error->httpStatus === 409; +} +$assert($releasedReverseLeakRejected, + 'Released reservation hid a reverse claim-to-address leak.'); +Capsule::table('cloud_public_ips')->where('id', 603)->update([ + 'reservation_ip_claim_id' => null, +]); +$released = CloudAdminResourceService::reservation('102')['item']; +$assert($released['public_ip_id'] === null + && $released['public_ip'] === '' + && $released['public_ipv4'] === '' + && $released['public_ipv6'] === '' + && $released['public_ips'] === [], + 'Clean released reservation did not project an empty current authority.'); + +echo "Administrator active-claim reservation projection tests passed.\n"; diff --git a/web/tests/CloudFinancialWorkflowTest.php b/web/tests/CloudFinancialWorkflowTest.php index b483da66..82645a23 100644 --- a/web/tests/CloudFinancialWorkflowTest.php +++ b/web/tests/CloudFinancialWorkflowTest.php @@ -288,7 +288,7 @@ namespace { $schema->create('cloud_host_network_attachments', function (Blueprint $t) { $t->increments('id'); $t->string('attachment_key'); $t->integer('host_id'); $t->integer('line_id'); $t->string('name'); $t->string('network_mode')->default('selector'); $t->string('network_selector'); $t->integer('vlan_id')->nullable(); $t->integer('routing_table')->nullable(); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('config_revision')->default(1); $t->integer('verified_agent_revision')->default(0); $t->string('verification_state')->default('never'); $t->integer('last_verified_at')->default(0); $t->string('verification_error_code')->default(''); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_public_ip_pools', function (Blueprint $t) { $t->increments('id'); $t->string('pool_key'); $t->integer('host_id'); $t->integer('network_attachment_id'); $t->string('name'); $t->integer('address_family'); $t->string('cidr'); $t->string('gateway'); $t->boolean('gateway_on_link')->default(false); $t->integer('guest_prefix_length'); $t->text('dns_servers_json'); $t->text('reserved_ips_json'); $t->string('allocation_start')->nullable(); $t->string('allocation_end')->nullable(); $t->string('allocation_cursor')->nullable(); $t->integer('max_allocations')->default(0); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_host_capacity_policies', function (Blueprint $t) { $t->integer('host_id')->primary(); foreach (['configured_cpu_cores', 'configured_memory_mib', 'configured_disk_gib', 'safety_cpu_cores', 'safety_memory_mib', 'safety_disk_gib', 'max_instances', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } }); - $schema->create('cloud_public_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('public_ip_pool_id'); $t->integer('address_family'); $t->string('address'); $t->binary('address_binary'); $t->integer('prefix_length'); $t->string('state'); $t->integer('reservation_id')->nullable(); $t->integer('instance_id')->nullable(); $t->string('operation_id')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['address_family', 'address_binary']); }); + $schema->create('cloud_public_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('public_ip_pool_id'); $t->integer('address_family'); $t->string('address'); $t->binary('address_binary'); $t->integer('prefix_length'); $t->string('state'); $t->integer('reservation_id')->nullable(); $t->integer('reservation_ip_claim_id')->nullable(); $t->integer('instance_id')->nullable(); $t->string('operation_id')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['address_family', 'address_binary']); }); $schema->create('cloud_offers', function (Blueprint $t) { $t->increments('id'); $t->integer('plan_id'); $t->integer('resource_pool_id'); $t->string('code')->unique(); $t->string('name'); $t->string('price'); $t->string('backup_price')->default('0.00'); $t->string('currency')->default('USD'); $t->integer('price_version')->default(1); $t->integer('revision')->default(1); $t->integer('status')->default(1); $t->integer('stock')->default(-1); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['plan_id', 'resource_pool_id']); }); $schema->create('cloud_templates', function (Blueprint $t) { $t->string('id')->primary(); $t->string('catalog_key')->default('test-catalog'); $t->string('version_label')->default('test-version'); $t->boolean('is_default')->default(true); $t->string('name'); $t->string('os_family'); $t->string('os_version'); $t->integer('image_bytes'); $t->string('sha256'); $t->text('startup_script'); $t->integer('revision'); $t->string('generation_token'); $t->string('state'); $t->integer('active_job_id')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_user_isos', function (Blueprint $t) { $t->string('id')->primary(); $t->integer('active_job_id')->nullable(); }); @@ -298,7 +298,7 @@ namespace { $schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'offer_id', 'resource_pool_id'] as $v) { $t->integer($v); } $t->integer('host_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->integer('deployment_snapshot_id')->nullable(); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('currency')->default('USD'); $t->string('status'); $t->text('spec_json'); $t->text('sealed_payload')->nullable(); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('stock_reserved_at')->nullable(); $t->integer('stock_released_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); }); $schema->create('cloud_order_items', function (Blueprint $t) { $t->increments('id'); $t->integer('order_id'); $t->string('code'); $t->string('label'); $t->string('amount'); $t->string('currency')->default('USD'); $t->text('snapshot_json'); $t->integer('created_at'); $t->unique(['order_id', 'code']); }); $schema->create('cloud_resource_reservations', function (Blueprint $t) { $t->increments('id'); $t->string('reservation_key')->unique(); $t->string('operation_id')->unique(); $t->integer('order_id')->nullable(); $t->integer('backup_restore_id')->nullable(); $t->integer('offer_id')->nullable(); foreach (['resource_pool_id', 'host_id', 'user_id'] as $v) { $t->integer($v); } $t->integer('instance_id')->nullable(); $t->integer('network_attachment_id')->nullable(); $t->integer('public_ip_pool_id')->nullable(); $t->integer('public_ip_id')->nullable(); foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $v) { $t->integer($v); } $t->string('state'); $t->integer('expires_at')->nullable(); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique('backup_restore_id'); }); - $schema->create('cloud_resource_reservation_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('reservation_id'); $t->integer('address_family'); $t->integer('network_attachment_id'); $t->integer('public_ip_pool_id'); $t->integer('public_ip_id'); $t->string('operation_id'); $t->string('state'); $t->integer('created_at'); $t->integer('updated_at'); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->unique(['reservation_id', 'address_family']); }); + $schema->create('cloud_resource_reservation_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('reservation_id'); $t->integer('address_family'); $t->integer('claim_generation')->default(1); $t->integer('active_claim')->nullable()->default(1); $t->integer('network_attachment_id'); $t->integer('public_ip_pool_id'); $t->integer('public_ip_id'); $t->string('operation_id'); $t->string('state'); $t->integer('created_at'); $t->integer('updated_at'); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->unique(['reservation_id', 'address_family', 'active_claim']); $t->unique(['reservation_id', 'claim_generation', 'address_family']); }); $schema->create('cloud_backup_restores', function (Blueprint $t) { $t->increments('id'); $t->string('restore_key')->unique(); $t->integer('backup_id'); $t->integer('target_host_id'); $t->integer('target_instance_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->integer('job_id')->nullable(); $t->string('operation_id')->unique(); $t->string('new_uuid'); $t->string('new_name'); $t->string('state'); $t->string('error_code')->default(''); $t->integer('ready_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_instance_migrations', function (Blueprint $t) { $t->increments('id'); $t->integer('instance_id'); $t->integer('restore_id'); $t->integer('source_host_id'); $t->integer('source_reservation_id'); $t->integer('target_host_id'); $t->integer('target_reservation_id'); $t->string('state'); }); $schema->create('cloud_instance_backups', function (Blueprint $t) { $t->increments('id'); $t->string('backup_key')->unique(); $t->integer('source_instance_id'); $t->integer('source_host_id'); $t->integer('user_id'); $t->string('source_uuid'); $t->string('name'); $t->string('purpose')->default('portable'); $t->string('source')->default('manual'); $t->integer('subscription_id')->nullable(); $t->integer('scheduled_for')->nullable(); $t->string('state')->default('creating'); $t->string('consistency'); $t->string('object_key')->unique(); $t->integer('object_size_bytes')->default(0); $t->integer('virtual_size_bytes')->default(0); $t->string('sha256')->default(''); $t->text('spec_json'); $t->text('sealed_storage_runtime'); $t->text('sealed_credential')->nullable(); $t->integer('storage_revision'); $t->integer('active_job_id')->nullable(); $t->string('last_operation_id')->nullable(); $t->string('error_code')->default(''); $t->integer('ready_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['subscription_id', 'scheduled_for']); }); @@ -2374,45 +2374,33 @@ namespace { 'test fixture confirms replacement guest committed'; $partialJob->save(); - // Network-change transition ledgers are migrated in a later IPv6 stage. - // Adapt this pre-existing scalar-only financial scenario to the committed - // IPv4 leg without changing production provisioning authority. - $legacySourceClaim = Capsule::table('cloud_resource_reservation_ips') - ->where('reservation_id', (int) $openingReservation->id) - ->where('address_family', 4)->first(); - $assert($legacySourceClaim !== null, - 'The dual-stack opening reservation has no IPv4 transition fixture.'); - $openingReservation->network_attachment_id = - (int) $legacySourceClaim->network_attachment_id; - $openingReservation->public_ip_pool_id = - (int) $legacySourceClaim->public_ip_pool_id; - $openingReservation->public_ip_id = - (int) $legacySourceClaim->public_ip_id; - $openingReservation->save(); - $legacyInstanceSpec = json_decode( - (string) $instance->fresh()->spec_json, - true, - 64, - JSON_THROW_ON_ERROR - ); - $legacyInstanceSpec['network'] = 'bridge:br0'; - $legacyInstanceSpec['public_pool_key'] = $sourcePoolKey; - $legacyInstanceSpec['public_pool_cidr'] = '8.8.8.0/24'; - $legacyInstanceSpec['public_ip_cidr'] = '8.8.8.10/24'; - $legacyInstanceSpec['gateway'] = '8.8.8.1'; - $legacyInstanceSpec['dns_servers'] = ['1.1.1.1']; - $instance->spec_json = json_encode( - $legacyInstanceSpec, - JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES - ); - $instance->save(); - // A network change reserves only a locally available target. The encrypted // job keeps both ledger IDs, while the Agent receives only its existing // request body. An ambiguous response keeps both addresses unavailable and // a reconciled success atomically moves the reservation to the target. $networkInput = ['public_ip_cidr' => '9.9.9.10/24', 'public_pool_key' => $targetPoolKey, 'confirm_restart' => true]; + $beforeLegacyNetworkJobs = CloudJob::count(); + try { + CloudJobService::enqueue( + $instance->fresh(), + $actor, + 'network_change', + 'POST', + '/network', + $networkInput + ); + throw new RuntimeException( + 'Legacy scalar network writer bypassed the transition gate.' + ); + } catch (CloudError $error) { + $assert($error->httpStatus === 409 + && CloudJob::count() === $beforeLegacyNetworkJobs, + 'Transition gate created a network job before rejecting it.'); + } + // Retain the old scalar cases as a dormant migration fixture until the + // later transition-ledger stage rewrites them as all-family operations. + if (false) { try { CloudJobService::enqueue($instance->fresh(), $actor, 'network_change', 'POST', '/network', @@ -2991,33 +2979,25 @@ namespace { && (string) $unknownAppliedInvoice->fresh()->status === 'paid', 'Applied recovery did not publish exactly once with the recovered network and payment ledgers.'); - // The scalar IPv4 transition scenarios above predate the dual-stack - // transition ledger. Restore the canonical committed bundle before the - // C7 delete/settlement scenarios; C11 replaces this fixture bridge with a - // real all-family transition. - $canonicalIpv4Claim = Capsule::table('cloud_resource_reservation_ips') - ->where('reservation_id', (int) $openingReservation->id) - ->where('address_family', 4)->first(); - $canonicalIpv4 = CloudPublicIp::findOrFail( - (int) $canonicalIpv4Claim->public_ip_id - ); - $transitionIpv4 = CloudPublicIp::findOrFail( - (int) $openingReservation->fresh()->public_ip_id - ); - if ((int) $transitionIpv4->id !== (int) $canonicalIpv4->id) { - $transitionIpv4->state = 'available'; - $transitionIpv4->reservation_id = null; - $transitionIpv4->instance_id = null; - $transitionIpv4->operation_id = null; - $transitionIpv4->updated_at = time(); - $transitionIpv4->save(); } - $canonicalIpv4->state = 'assigned'; - $canonicalIpv4->reservation_id = (int) $openingReservation->id; - $canonicalIpv4->instance_id = (int) $instance->id; - $canonicalIpv4->operation_id = (string) $openingReservation->operation_id; - $canonicalIpv4->updated_at = time(); - $canonicalIpv4->save(); + + // The old scalar transition scenarios stay dormant until C11. Deletion + // must therefore consume the unchanged exact dual-stack authority, never + // reconstruct it from the retained singular reservation columns. + $canonicalClaimSet = + \App\Services\Cloud\CloudPublicNetworkAllocationService::currentClaimSet( + (int) $openingReservation->id, + 'committed', + (int) $instance->id + ); + $canonicalClaimIds = [ + $canonicalClaimSet->claimId(4), + $canonicalClaimSet->claimId(6), + ]; + $canonicalPublicIpIds = [ + $canonicalClaimSet->publicIpId(4), + $canonicalClaimSet->publicIpId(6), + ]; $interruptedDelete = CloudJobService::enqueue($instance, $actor, 'delete', 'DELETE', '', @@ -3109,9 +3089,6 @@ namespace { $retainedDeleteReservation = CloudResourceReservation::where( 'order_id', $first->id )->first(); - $retainedDeleteIp = CloudPublicIp::find( - $retainedDeleteReservation->public_ip_id - ); $assert($forced['method'] === 'POST' && str_ends_with($forced['request_target'], '/force-delete') && $forceDelete->operation_id !== $failedForceDelete->operation_id @@ -3125,9 +3102,16 @@ namespace { && $instance->fresh()->status === 'deleted' && $instance->fresh()->sealed_credential === null && $retainedDeleteReservation->state === 'released' - && $retainedDeleteIp->state === 'available' - && CloudPublicIp::find($networkTarget->id)->state === 'available' - && CloudPublicIp::find($failedNetworkTarget->id)->state === 'available', + && CloudPublicIp::whereIn('id', $canonicalPublicIpIds) + ->where('state', 'available') + ->whereNull('reservation_id') + ->whereNull('reservation_ip_claim_id') + ->whereNull('instance_id') + ->whereNull('operation_id')->count() === 2 + && Capsule::table('cloud_resource_reservation_ips') + ->whereIn('id', $canonicalClaimIds) + ->where('state', 'released') + ->whereNull('active_claim')->count() === 2, 'Force-delete identity, acknowledgement, cleanup, or immutable prior receipt failed.'); $beforeForceReplay = count($history); $worker->tick(); @@ -3225,40 +3209,58 @@ namespace { $backupRestore->target_instance_id = (int) $restoredInstance->id; $backupRestore->reservation_id = (int) $restoredReservation->id; $backupRestore->save(); - $restoredDelete = CloudJobService::enqueue( - $restoredInstance, - $adminActor, - 'delete', - 'DELETE', - '', - ['remove_managed_disks' => true] - ); - $mock->append(new Response(200, [], json_encode([ - 'operation_id' => $restoredDelete->operation_id, - 'status' => 'succeeded', - ...CloudOperationRecoveryIdentity::expected($restoredDelete, true), - 'result' => [ - 'uuid' => $restoredUuid, - 'deleted' => true, - 'managed_artifacts_absent' => true, - 'forced' => false, - ], - ]))); - $worker->tick(); - $restoredDelete->refresh(); + $beforeRestoredDeleteJobs = CloudJob::count(); + $beforeRestoredDeleteRequests = count($history); + try { + CloudJobService::enqueue( + $restoredInstance, + $adminActor, + 'delete', + 'DELETE', + '', + ['remove_managed_disks' => true] + ); + throw new RuntimeException( + 'A restored instance bypassed the dual-stack transition gate.' + ); + } catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'Restored-instance delete gate returned the wrong status.'); + } $restoredInstance->refresh(); $restoredReservation->refresh(); $restoredIp->refresh(); - $assert($restoredDelete->phase === 'terminal' - && $restoredDelete->outcome === 'succeeded' - && $restoredInstance->status === 'deleted' - && $restoredReservation->state === 'released' - && $restoredReservation->release_reason === 'instance_deleted' - && $restoredIp->state === 'available' - && $restoredIp->reservation_id === null - && $restoredIp->instance_id === null - && $restoredIp->operation_id === null, - 'Deleting an independent restored instance leaked capacity or its public IP.'); + $assert(CloudJob::count() === $beforeRestoredDeleteJobs + && count($history) === $beforeRestoredDeleteRequests + && $restoredInstance->status === 'active' + && $restoredReservation->state === 'committed' + && $restoredIp->state === 'assigned' + && (int) $restoredIp->reservation_id + === (int) $restoredReservation->id + && (int) $restoredIp->instance_id === (int) $restoredInstance->id, + 'Restored-instance delete gate created work or changed its old ledger.'); + $restoredInstance->status = 'deleting'; + $restoredInstance->service_status = 'purge_deleting'; + $restoredInstance->save(); + try { + CloudJobService::enqueueExpiryDelete($restoredInstance); + throw new RuntimeException( + 'A restored instance bypassed the expiry-delete transition gate.' + ); + } catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'Restored-instance expiry-delete gate returned the wrong status.'); + } + $assert(CloudJob::count() === $beforeRestoredDeleteJobs + && count($history) === $beforeRestoredDeleteRequests, + 'Restored-instance expiry-delete gate created durable work.'); + // This clean-break fixture intentionally models the retired singular + // restore shape. Remove it explicitly after proving the gate so it cannot + // poison later active-pair placement scans in this long scenario. + $restoredInstance->delete(); + $restoredIp->delete(); + $restoredReservation->delete(); + $backupRestore->delete(); // Provider callbacks credit the wallet before the invoice bridge runs. @@ -5004,6 +5006,7 @@ namespace { CloudPublicIp::where('public_ip_pool_id', $sourceIpv6Pool->id)->update([ 'state' => 'disabled', 'reservation_id' => null, + 'reservation_ip_claim_id' => null, 'instance_id' => null, 'operation_id' => null, 'updated_at' => time(), @@ -5014,6 +5017,7 @@ namespace { // before exercising host-capacity fallback. CloudPublicIp::where('state', 'disabled')->update([ 'reservation_id' => null, + 'reservation_ip_claim_id' => null, 'instance_id' => null, 'operation_id' => null, 'updated_at' => time(), diff --git a/web/tests/CloudFreshSchemaContractTest.php b/web/tests/CloudFreshSchemaContractTest.php index dd453773..b81baac8 100644 --- a/web/tests/CloudFreshSchemaContractTest.php +++ b/web/tests/CloudFreshSchemaContractTest.php @@ -22,7 +22,7 @@ $assert(stripos($schema, 'compatibility import') === false $assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema), 'cloud.sql retained an engine-prefixed identifier.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v28-public-network-transition'") + "SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'") && !str_contains($setup, "SCHEMA_VERSION = 'go-v1'"), 'Outbound Agent schema must reject the incompatible earlier Go database.'); $assert(str_contains($schema, diff --git a/web/tests/CloudNetworkIpLedgerContractTest.php b/web/tests/CloudNetworkIpLedgerContractTest.php index 5ab5be1b..881080df 100644 --- a/web/tests/CloudNetworkIpLedgerContractTest.php +++ b/web/tests/CloudNetworkIpLedgerContractTest.php @@ -8,6 +8,12 @@ $placement = file_get_contents($root . '/app/Services/Cloud/CloudPlacementServic $placementNetwork = file_get_contents( $root . '/app/Services/Cloud/CloudPlacementNetworkService.php' ); +$allocation = file_get_contents( + $root . '/app/Services/Cloud/CloudPublicNetworkAllocationService.php' +); +$adminInstanceService = file_get_contents( + $root . '/app/Services/Cloud/CloudAdminInstanceService.php' +); $worker = file_get_contents($root . '/app/Services/Cloud/CloudWorkerService.php'); $input = file_get_contents($root . '/app/Services/Cloud/CloudInput.php'); $adminInstances = file_get_contents($root . '/public/cloud/admin-instances.js') @@ -23,7 +29,7 @@ $pendingMethod = $pendingStart !== false && $pendingEnd !== false $availableStart = is_string($placement) ? strpos($placement, 'private static function availablePublicIpQuery') : false; $availableEnd = is_string($placement) - ? strpos($placement, 'private static function reservationNetworkMatches') : false; + ? strpos($placement, 'private static function publicIpBelongsToPool') : false; $availableMethod = $availableStart !== false && $availableEnd !== false ? substr($placement, $availableStart, $availableEnd - $availableStart) : ''; $finishStart = is_string($placement) @@ -41,6 +47,8 @@ $assert = static function ($condition, string $message): void { $assert(is_string($controller) && is_string($options) && str_contains($controller, 'CloudNetworkChangeOptionsService::forInstance') + && str_contains($options, + 'CloudPublicNetworkTransitionGate::assertWriterReady()') && str_contains($options, "->where('state', 'available')") && str_contains($options, 'CloudPublicIp::where(\'host_id\'') && str_contains($options, "public_pool.sync_state', 'applied'") @@ -55,6 +63,12 @@ $assert(is_string($controller) && is_string($options) '(int) $attachment->line_id !== (int) $reservationPool->line_id') && str_contains($controller, "['public_ip_cidr', 'public_pool_key', 'confirm_restart']"), 'Shared network choices no longer intersect configured pools with the local ledger or require a pool key.'); +$assert(is_string($adminInstanceService) + && str_contains( + $adminInstanceService, + "'network_change_supported' => false" + ), + 'Administrator network changes were exposed before the dual-stack transition ledger is ready.'); $assert(is_string($adminInstances) && str_contains($adminInstances, 'available_ip_options') && str_contains($adminInstances, 'option.dataset.publicPoolKey') @@ -66,6 +80,8 @@ $assert(is_string($input) && str_contains($input, '/^[a-f0-9]{32}$/D'), 'Public pool keys no longer have a fixed lowercase-hex input boundary.'); $assert(is_string($jobs) + && str_contains($jobs, + 'CloudPublicNetworkTransitionGate::assertWriterReady()') && str_contains($jobs, '(string) $reservation->state !== \'committed\'') && str_contains($jobs, '(string) $source->state !== \'assigned\'') && str_contains($jobs, '(string) $target->state !== \'available\'') @@ -96,6 +112,8 @@ $assert(is_string($jobs) && str_contains($jobs, '$jobPayload[\'target_public_ip_pool_id\']'), 'Network-change enqueue no longer locks and persists the attachment/pool/address ledger identity.'); $assert(is_string($worker) + && str_contains($worker, + 'CloudPublicNetworkTransitionGate::assertWriterReady()') && str_contains($worker, 'CloudPlacementService::finishNetworkChange') && str_contains($worker, '$confirmedPoolKey') && str_contains($worker, '$sourceAttachmentId') @@ -107,6 +125,7 @@ $assert(is_string($worker) 'Worker no longer confirms pool identity or settles network changes from one terminal receipt.'); $assert(is_string($placement) && is_string($placementNetwork) + && is_string($allocation) && str_contains($placement, 'cloud_host_resource_pool_memberships as pool_membership') && !str_contains($placement, 'eligible_host.host') && !str_contains($placement, "->where('cloud_hosts.resource_pool_id', \$poolId)") @@ -114,29 +133,17 @@ $assert(is_string($placement) 'CloudPublicNetworkAllocationService::reserveBundle(') && str_contains($placement, "\$payload['body']['public_network'] = \$publicNetwork->toArray()") - && str_contains($placement, '$reservation->public_ip_id = $targetIpId') && str_contains($placement, - '$reservation->network_attachment_id = $targetAttachmentId') - && str_contains($placement, '$reservation->public_ip_pool_id = $targetPoolId') + 'CloudPublicNetworkAllocationService::releaseBundle(') && str_contains($placement, - '(int) $sourceAttachment->line_id') - && str_contains($placement, - '(int) $targetAttachment->line_id') - && str_contains($placement, - 'sort($attachmentIds, SORT_NUMERIC)') + 'releaseCommittedBundle(') + && str_contains($allocation, "->where('active_claim', 1)") + && str_contains($allocation, 'reservation_ip_claim_id') && str_contains($placement, '(int) $ip->prefix_length !== (int) $pool->guest_prefix_length') - && str_contains($placement, '$target->state = \'assigned\'') - && str_contains($placement, '$target->state = \'uncertain\'') - && str_contains($placement, '$source->state = \'available\'') - && str_contains($finishMethod, - "CloudHost::where('id', (int) \$instance->host_id)") && str_contains($finishMethod, - "CloudResourceReservation::where('id',") - && substr_count($finishMethod, 'lockForUpdate()') >= 4 - && str_contains($placement, '(string) $reservation->state === \'committed\'') - && str_contains($placement, '$ip->instance_id ?? 0'), - 'Placement no longer uses membership/pool-scoped allocation or enforce atomic multi-pool ledger swaps.'); + 'CloudPublicNetworkTransitionGate::assertWriterReady()'), + 'Placement no longer uses active dual-stack claims or fails closed for retired scalar network changes.'); $assert(str_contains($placement, 'CloudPlacementNetworkService::lockedCandidates(') && str_contains($placement, diff --git a/web/tests/CloudProvisioningPublicNetworkLedgerTest.php b/web/tests/CloudProvisioningPublicNetworkLedgerTest.php index 8cbdb240..aaa02d34 100644 --- a/web/tests/CloudProvisioningPublicNetworkLedgerTest.php +++ b/web/tests/CloudProvisioningPublicNetworkLedgerTest.php @@ -91,6 +91,7 @@ $schema->create('cloud_public_ips', static function (Blueprint $table): void { $table->integer('prefix_length'); $table->string('state'); $table->integer('reservation_id')->nullable(); + $table->integer('reservation_ip_claim_id')->nullable(); $table->integer('instance_id')->nullable(); $table->string('operation_id')->nullable(); $table->integer('created_at'); @@ -149,6 +150,8 @@ $schema->create('cloud_resource_reservation_ips', static function ( $table->increments('id'); $table->integer('reservation_id'); $table->integer('address_family'); + $table->integer('claim_generation')->default(1); + $table->integer('active_claim')->nullable()->default(1); $table->integer('network_attachment_id'); $table->integer('public_ip_pool_id'); $table->integer('public_ip_id'); @@ -158,7 +161,8 @@ $schema->create('cloud_resource_reservation_ips', static function ( $table->integer('updated_at'); $table->integer('released_at')->nullable(); $table->string('release_reason')->default(''); - $table->unique(['reservation_id', 'address_family']); + $table->unique(['reservation_id', 'address_family', 'active_claim']); + $table->unique(['reservation_id', 'claim_generation', 'address_family']); }); $schema->create('cloud_instances', static function (Blueprint $table): void { $table->increments('id'); diff --git a/web/tests/CloudPublicIpPoolReplacementBatchServiceTest.php b/web/tests/CloudPublicIpPoolReplacementBatchServiceTest.php index 238128e0..52fbcac9 100644 --- a/web/tests/CloudPublicIpPoolReplacementBatchServiceTest.php +++ b/web/tests/CloudPublicIpPoolReplacementBatchServiceTest.php @@ -151,6 +151,15 @@ namespace { $table->integer('created_at')->default(0); $table->integer('updated_at')->default(0); }); + $schema->create('cloud_resource_reservation_ips', static function ( + Blueprint $table + ): void { + $table->increments('id'); + $table->integer('reservation_id'); + $table->integer('public_ip_pool_id'); + $table->integer('active_claim')->nullable(); + $table->string('state'); + }); $schema->create('cloud_instances', static function ( Blueprint $table ): void { @@ -373,6 +382,14 @@ namespace { 'public_ip_pool_id' => 33, 'public_ip_id' => 63, 'state' => 'committed'], ]); + Capsule::table('cloud_resource_reservation_ips')->insert([ + ['id' => 101, 'reservation_id' => 41, 'public_ip_pool_id' => 31, + 'active_claim' => 1, 'state' => 'committed'], + ['id' => 102, 'reservation_id' => 42, 'public_ip_pool_id' => 31, + 'active_claim' => 1, 'state' => 'committed'], + ['id' => 103, 'reservation_id' => 43, 'public_ip_pool_id' => 33, + 'active_claim' => 1, 'state' => 'committed'], + ]); $instanceSpec = static function (string $publicIp): string { return json_encode([ 'managed' => true, @@ -482,6 +499,35 @@ namespace { 'Tenant must not read administrator replacement batches.' ); + // C10 keeps the read-only occupancy projection on active claims while the + // scalar replacement writer is fail-closed until C11 owns a claim pair. + $gatedInput = [ + 'target_pool_key' => $targetKey, + 'expected_source_revision' => 7, + 'expected_target_revision' => 9, + 'confirm_replacement' => true, + 'request_key' => 'replacement-c10-gated-0001', + ]; + $expectCloudError( + static fn () => CloudPublicIpPoolReplacementBatchService::start( + 1, + $sourceKey, + $admin, + $gatedInput + ), + 409, + 'Pool replacement must remain gated before its dual-stack writer.' + ); + $assert(CloudJob::count() === 0 + && CloudPublicIpPoolReplacementBatch::count() === 0 + && Capsule::table('cloud_public_ip_pools')->where('id', 31) + ->value('state') === 'active' + && Capsule::table('cloud_public_ips')->whereIn('id', [71, 72, 73, 74]) + ->where('state', 'available')->count() === 4, + 'Gated pool replacement created durable or address-side effects.'); + echo "Cloud public IP pool replacement C10 gate tests passed\n"; + return; + $staleInput = [ 'target_pool_key' => $targetKey, 'expected_source_revision' => 6, diff --git a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php index cc41f5d3..12f619f8 100644 --- a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php +++ b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php @@ -32,7 +32,7 @@ $assert(is_string($schema) 'Public-pool replacement lacks durable batch, child, or active-claim schema.'); $assert(is_string($setup) && str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v28-public-network-transition'") + "SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'") && str_contains($setup, "'cloud_public_ip_pool_replacement_batches'") && str_contains($setup, diff --git a/web/tests/CloudPublicNetworkAllocationServiceTest.php b/web/tests/CloudPublicNetworkAllocationServiceTest.php index 0073fa0e..25879d72 100644 --- a/web/tests/CloudPublicNetworkAllocationServiceTest.php +++ b/web/tests/CloudPublicNetworkAllocationServiceTest.php @@ -4,6 +4,8 @@ require dirname(__DIR__) . '/vendor/autoload.php'; use App\Services\Cloud\CloudPublicNetworkAllocationService; use App\Services\Cloud\CloudPublicNetworkCapacityUnavailable; +use App\Services\Cloud\CloudActivePublicNetworkClaimSet; +use App\Services\Cloud\CloudPublicNetworkSnapshot; use App\Services\Cloud\CloudError; use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Schema\Blueprint; @@ -34,6 +36,12 @@ $schema = $capsule->schema('default'); $schema->create('cloud_hosts', static function (Blueprint $table): void { $table->increments('id'); }); +$schema->create('cloud_resource_pools', static function ( + Blueprint $table +): void { + $table->increments('id'); + $table->integer('line_id'); +}); $schema->create('cloud_host_agents', static function (Blueprint $table): void { $table->integer('host_id')->primary(); $table->boolean('enabled'); @@ -90,6 +98,7 @@ $schema->create('cloud_public_ips', static function (Blueprint $table): void { $table->integer('prefix_length'); $table->string('state'); $table->integer('reservation_id')->nullable(); + $table->integer('reservation_ip_claim_id')->nullable(); $table->integer('instance_id')->nullable(); $table->string('operation_id')->nullable(); $table->integer('created_at'); @@ -101,6 +110,8 @@ $schema->create('cloud_resource_reservations', static function ( ): void { $table->increments('id'); $table->integer('host_id'); + $table->integer('resource_pool_id')->nullable(); + $table->integer('user_id')->nullable(); $table->string('operation_id'); $table->string('state'); $table->integer('order_id')->nullable(); @@ -110,6 +121,13 @@ $schema->create('cloud_resource_reservations', static function ( $table->integer('public_ip_pool_id')->nullable(); $table->integer('public_ip_id')->nullable(); }); +$schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('reservation_id'); + $table->integer('host_id'); + $table->integer('resource_pool_id'); + $table->integer('user_id'); +}); $schema->create('cloud_instance_migrations', static function ( Blueprint $table ): void { @@ -128,6 +146,8 @@ $schema->create('cloud_resource_reservation_ips', static function ( $table->increments('id'); $table->integer('reservation_id'); $table->integer('address_family'); + $table->integer('claim_generation')->default(1); + $table->integer('active_claim')->nullable()->default(1); $table->integer('network_attachment_id'); $table->integer('public_ip_pool_id'); $table->integer('public_ip_id'); @@ -137,7 +157,8 @@ $schema->create('cloud_resource_reservation_ips', static function ( $table->integer('updated_at'); $table->integer('released_at')->nullable(); $table->string('release_reason')->default(''); - $table->unique(['reservation_id', 'address_family']); + $table->unique(['reservation_id', 'address_family', 'active_claim']); + $table->unique(['reservation_id', 'claim_generation', 'address_family']); }); Capsule::table('cloud_host_network_attachments')->insert([ @@ -152,6 +173,10 @@ Capsule::table('cloud_host_network_attachments')->insert([ 'last_verified_at' => time(), ]); Capsule::table('cloud_hosts')->insert(['id' => 1]); +Capsule::table('cloud_resource_pools')->insert([ + ['id' => 30, 'line_id' => 7], + ['id' => 31, 'line_id' => 8], +]); Capsule::table('cloud_host_agents')->insert([ 'host_id' => 1, 'enabled' => 1, @@ -251,10 +276,22 @@ foreach ($operations as $id => $operationId) { Capsule::table('cloud_resource_reservations')->insert([ 'id' => $id, 'host_id' => 1, + 'resource_pool_id' => 30, + 'user_id' => 42, 'operation_id' => $operationId, 'state' => 'held', ]); } +Capsule::table('cloud_instances')->insert([ + [ + 'id' => 900, 'reservation_id' => 500, 'host_id' => 1, + 'resource_pool_id' => 30, 'user_id' => 42, + ], + [ + 'id' => 901, 'reservation_id' => 504, 'host_id' => 1, + 'resource_pool_id' => 30, 'user_id' => 42, + ], +]); $materializedBefore = Capsule::table('cloud_public_ips')->count(); $first = CloudPublicNetworkAllocationService::reserveBundle( @@ -291,6 +328,10 @@ $assert(hash_equals($first->fingerprint(), $committed->fingerprint()) && Capsule::table('cloud_public_ips')->where('instance_id', 900) ->where('state', 'assigned')->count() === 2, 'Commit did not bind the complete dual-stack identity to the instance.'); +Capsule::table('cloud_resource_reservations')->where('id', 500)->update([ + 'state' => 'committed', + 'instance_id' => 900, +]); $replacementAttempt = CloudPublicNetworkAllocationService::reserveBundle( 1, 7, @@ -328,6 +369,10 @@ $assert($second->address(4) === '8.8.8.11/24' && $second->address(6) === '2404:c140:156:3a::102e/64', 'The allocation cursor did not advance across a second reservation.'); CloudPublicNetworkAllocationService::fenceBundle(501, $operations[501]); +Capsule::table('cloud_resource_reservations')->where('id', 501)->update([ + 'state' => 'uncertain', +]); +CloudPublicNetworkAllocationService::fenceBundle(501, $operations[501]); $assert(Capsule::table('cloud_public_ips')->where('reservation_id', 501) ->where('state', 'uncertain')->count() === 2, 'Unknown effect did not fence both public addresses.'); @@ -356,6 +401,9 @@ $uncertainSuccess = CloudPublicNetworkAllocationService::reserveBundle( $operations[504] ); CloudPublicNetworkAllocationService::fenceBundle(504, $operations[504]); +Capsule::table('cloud_resource_reservations')->where('id', 504)->update([ + 'state' => 'uncertain', +]); $rejects(static fn () => CloudPublicNetworkAllocationService::commitBundle( 504, 901, @@ -374,6 +422,10 @@ $assert(hash_equals( && Capsule::table('cloud_resource_reservation_ips') ->where('reservation_id', 504)->where('state', 'committed')->count() === 2, 'A recovered success did not atomically commit its uncertain dual-stack bundle.'); +Capsule::table('cloud_resource_reservations')->where('id', 504)->update([ + 'state' => 'committed', + 'instance_id' => 901, +]); $rejects(static fn () => CloudPublicNetworkAllocationService::commitBundle( 504, 902, @@ -393,6 +445,284 @@ $assert(Capsule::table('cloud_resource_reservation_ips') ->where('reservation_id', 502)->count() === 0, 'A failed upper-bound check retained a partial address claim.'); +Capsule::table('cloud_resource_reservations')->where('id', 500)->update([ + 'state' => 'committed', + 'instance_id' => 900, +]); +$ipv6Claim = Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', 500)->where('address_family', 6)->first(); +$familySixOperation = str_repeat('b', 32); +Capsule::table('cloud_resource_reservation_ips') + ->where('id', (int) $ipv6Claim->id)->update([ + 'claim_generation' => 2, + 'operation_id' => $familySixOperation, + ]); +Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv6Claim->public_ip_id)->update([ + 'operation_id' => $familySixOperation, + ]); +$mixedGeneration = CloudPublicNetworkAllocationService::currentClaimSet( + 500, + 'committed', + 900 +); +$assert($mixedGeneration->generation(4) === 1 + && $mixedGeneration->generation(6) === 2 + && strlen($mixedGeneration->digest()) === 64, + 'A legal active pair required both families to share generation or operation.'); +$activeRows = Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', 500)->where('active_claim', 1) + ->orderBy('address_family')->get()->all(); +$activeAddresses = []; +foreach ($activeRows as $activeRow) { + $address = Capsule::table('cloud_public_ips') + ->where('id', (int) $activeRow->public_ip_id)->first(); + $activeAddresses[(int) $activeRow->public_ip_id] = $address; +} +$mismatchedSnapshot = $mixedGeneration->publicNetwork()->toArray(); +$mismatchedSnapshot['ipv4']['address_cidr'] = '8.8.8.11/24'; +$rejects(static fn () => CloudActivePublicNetworkClaimSet::fromLedger( + 500, + $activeRows, + $activeAddresses, + CloudPublicNetworkSnapshot::fromArray($mismatchedSnapshot) +), 'A claim set accepted a snapshot describing another concrete address.'); +Capsule::table('cloud_resource_reservation_ips') + ->where('id', (int) $ipv6Claim->id)->update(['state' => 'uncertain']); +Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv6Claim->public_ip_id)->update([ + 'state' => 'uncertain', + 'instance_id' => null, + ]); +$rejects(static fn () => + CloudPublicNetworkAllocationService::currentClaimSet( + 500, + 'committed', + 900 + ), + 'A mixed-state active pair was accepted as current authority.' +); +Capsule::table('cloud_resource_reservation_ips') + ->where('id', (int) $ipv6Claim->id)->update(['state' => 'committed']); +Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv6Claim->public_ip_id)->update([ + 'state' => 'assigned', + 'instance_id' => 900, + ]); + +$assertCurrentAuthorityRejects = static function ( + callable $mutate, + callable $restore, + string $message +) use ($rejects): void { + $mutate(); + try { + $rejects(static fn () => + CloudPublicNetworkAllocationService::currentClaimSet( + 500, + 'committed', + 900 + ), + $message + ); + } finally { + $restore(); + } +}; +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_resource_reservations') + ->where('id', 500)->update(['host_id' => 2]), + static fn () => Capsule::table('cloud_resource_reservations') + ->where('id', 500)->update(['host_id' => 1]), + 'A claim set accepted a reservation bound to a missing host.' +); +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_resource_reservations') + ->where('id', 500)->update([ + 'state' => 'held', + 'instance_id' => null, + ]), + static fn () => Capsule::table('cloud_resource_reservations') + ->where('id', 500)->update([ + 'state' => 'committed', + 'instance_id' => 900, + ]), + 'A claim set accepted the wrong reservation lifecycle state.' +); +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_resource_reservations') + ->where('id', 500)->update(['instance_id' => 999]), + static fn () => Capsule::table('cloud_resource_reservations') + ->where('id', 500)->update(['instance_id' => 900]), + 'A claim set accepted the wrong reservation instance owner.' +); +$instance900 = [ + 'id' => 900, + 'reservation_id' => 500, + 'host_id' => 1, + 'resource_pool_id' => 30, + 'user_id' => 42, +]; +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_instances') + ->where('id', 900)->delete(), + static fn () => Capsule::table('cloud_instances')->insert($instance900), + 'A claim set accepted a missing reverse instance authority.' +); +foreach ([ + 'reservation_id' => 999, + 'host_id' => 2, + 'resource_pool_id' => 31, + 'user_id' => 43, +] as $field => $invalidValue) { + $expectedValue = $instance900[$field]; + $assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_instances') + ->where('id', 900)->update([$field => $invalidValue]), + static fn () => Capsule::table('cloud_instances') + ->where('id', 900)->update([$field => $expectedValue]), + 'A claim set accepted an instance with a broken ' . $field + . ' reverse authority.' + ); +} +$ipv4Claim = Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', 500)->where('address_family', 4)->first(); +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv4Claim->public_ip_id) + ->update(['instance_id' => 999]), + static fn () => Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv4Claim->public_ip_id) + ->update(['instance_id' => 900]), + 'A claim set accepted an address owned by another instance.' +); +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv4Claim->public_ip_id) + ->update(['reservation_ip_claim_id' => (int) $ipv6Claim->id]), + static fn () => Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv4Claim->public_ip_id) + ->update(['reservation_ip_claim_id' => (int) $ipv4Claim->id]), + 'A claim set accepted an address pointing at another active claim.' +); +$otherIpv4Id = (int) Capsule::table('cloud_public_ips') + ->where('address_family', 4)->where('address', '8.8.8.11')->value('id'); +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_resource_reservation_ips') + ->where('id', (int) $ipv4Claim->id) + ->update(['public_ip_id' => $otherIpv4Id]), + static fn () => Capsule::table('cloud_resource_reservation_ips') + ->where('id', (int) $ipv4Claim->id) + ->update(['public_ip_id' => (int) $ipv4Claim->public_ip_id]), + 'A claim set accepted a claim pointing at another concrete address.' +); +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv4Claim->public_ip_id) + ->update(['operation_id' => str_repeat('0', 32)]), + static fn () => Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv4Claim->public_ip_id) + ->update(['operation_id' => (string) $ipv4Claim->operation_id]), + 'A claim set accepted an address with another operation identity.' +); +Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv4Claim->public_ip_id) + ->update(['instance_id' => 999]); +try { + $rejects( + static fn () => + CloudPublicNetworkAllocationService::currentClaimSet(500), + 'Default current authority ignored the reservation instance owner.' + ); +} finally { + Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv4Claim->public_ip_id) + ->update(['instance_id' => 900]); +} +Capsule::table('cloud_resource_reservations')->where('id', 500)->update([ + 'state' => 'held', + 'instance_id' => null, +]); +$rejects(static fn () => + CloudPublicNetworkAllocationService::currentClaimSet(500, 'held'), + 'A held reservation accepted committed active claims.' +); +Capsule::table('cloud_resource_reservations')->where('id', 500)->update([ + 'state' => 'committed', + 'instance_id' => 900, +]); +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_host_network_attachments') + ->where('id', 10)->update(['host_id' => 2]), + static fn () => Capsule::table('cloud_host_network_attachments') + ->where('id', 10)->update(['host_id' => 1]), + 'A claim set accepted an attachment outside the reservation host.' +); +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_host_network_attachments') + ->where('id', 10)->update(['line_id' => 8]), + static fn () => Capsule::table('cloud_host_network_attachments') + ->where('id', 10)->update(['line_id' => 7]), + 'A claim set accepted an attachment outside the reservation line.' +); +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_resource_reservations') + ->where('id', 500)->update(['resource_pool_id' => 31]), + static fn () => Capsule::table('cloud_resource_reservations') + ->where('id', 500)->update(['resource_pool_id' => 30]), + 'A claim set accepted a reservation pool from another commercial line.' +); +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_public_ip_pools') + ->where('id', 100)->update(['host_id' => 2]), + static fn () => Capsule::table('cloud_public_ip_pools') + ->where('id', 100)->update(['host_id' => 1]), + 'A claim set accepted a pool outside the reservation host.' +); +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv4Claim->public_ip_id) + ->update(['host_id' => 2]), + static fn () => Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv4Claim->public_ip_id) + ->update(['host_id' => 1]), + 'A claim set accepted an address outside the reservation host.' +); +$assertCurrentAuthorityRejects( + static fn () => Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv4Claim->public_ip_id) + ->update(['address_binary' => inet_pton('8.8.8.250')]), + static fn () => Capsule::table('cloud_public_ips') + ->where('id', (int) $ipv4Claim->public_ip_id) + ->update(['address_binary' => inet_pton('8.8.8.10')]), + 'A claim set accepted an address with a forged canonical binary identity.' +); + +Capsule::table('cloud_resource_reservations')->where('id', 500)->update([ + 'instance_id' => 999, +]); +$rejects(static fn () => CloudPublicNetworkAllocationService::commitBundle( + 500, + 900, + $operations[500] +), 'A committed replay ignored the locked reservation instance owner.'); +$rejects(static fn () => + CloudPublicNetworkAllocationService::releaseCommittedBundle( + 500, + 900, + $operations[500], + 'instance_deleted', + true + ), 'Committed release ignored the locked reservation instance owner.'); +$assert(Capsule::table('cloud_public_ips')->where('instance_id', 900) + ->where('state', 'assigned')->count() === 2 + && Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', 500)->where('active_claim', 1)->count() === 2, + 'Rejecting a mismatched reservation owner released public-network state.'); +Capsule::table('cloud_resource_reservations')->where('id', 500)->update([ + 'instance_id' => 900, +]); + $rejects(static fn () => CloudPublicNetworkAllocationService::releaseCommittedBundle( 500, @@ -401,6 +731,22 @@ $rejects(static fn () => 'instance_deleted', false ), 'An assigned bundle was released before deletion was confirmed.'); +Capsule::table('cloud_resource_reservations')->where('id', 500)->update([ + 'state' => 'held', + 'instance_id' => null, +]); +$rejects(static fn () => + CloudPublicNetworkAllocationService::releaseCommittedBundle( + 500, + 900, + $operations[500], + 'instance_deleted', + true + ), 'Committed claims were released through a held reservation state.'); +Capsule::table('cloud_resource_reservations')->where('id', 500)->update([ + 'state' => 'committed', + 'instance_id' => 900, +]); CloudPublicNetworkAllocationService::releaseCommittedBundle( 500, 900, @@ -500,19 +846,58 @@ $addPool = static function (int $id, int $hostId, int $attachmentId, }; $addIp = static function (int $hostId, int $poolId, int $family, string $address, int $prefix, string $state = 'available'): void { - Capsule::table('cloud_public_ips')->insert([ + $now = time(); + $ipId = Capsule::table('cloud_public_ips')->insertGetId([ 'host_id' => $hostId, 'public_ip_pool_id' => $poolId, 'address_family' => $family, 'address' => $address, 'address_binary' => inet_pton($address), 'prefix_length' => $prefix, - 'state' => $state, - 'reservation_id' => $state === 'assigned' ? 9999 : null, - 'instance_id' => $state === 'assigned' ? 9999 : null, - 'operation_id' => $state === 'assigned' ? str_repeat('7', 32) : null, - 'created_at' => time(), - 'updated_at' => time(), + 'state' => 'available', + 'reservation_id' => null, + 'reservation_ip_claim_id' => null, + 'instance_id' => null, + 'operation_id' => null, + 'created_at' => $now, + 'updated_at' => $now, + ]); + if ($state !== 'assigned') { + return; + } + $reservationId = 900000 + (int) $ipId; + $operationId = str_pad(dechex($reservationId), 32, '0', STR_PAD_LEFT); + $attachmentId = (int) Capsule::table('cloud_public_ip_pools') + ->where('id', $poolId)->value('network_attachment_id'); + Capsule::table('cloud_resource_reservations')->insert([ + 'id' => $reservationId, + 'host_id' => $hostId, + 'operation_id' => $operationId, + 'state' => 'committed', + 'instance_id' => $reservationId, + ]); + $claimId = Capsule::table('cloud_resource_reservation_ips') + ->insertGetId([ + 'reservation_id' => $reservationId, + 'address_family' => $family, + 'claim_generation' => 1, + 'active_claim' => 1, + 'network_attachment_id' => $attachmentId, + 'public_ip_pool_id' => $poolId, + 'public_ip_id' => $ipId, + 'operation_id' => $operationId, + 'state' => 'committed', + 'created_at' => $now, + 'updated_at' => $now, + 'released_at' => null, + 'release_reason' => '', + ]); + Capsule::table('cloud_public_ips')->where('id', $ipId)->update([ + 'state' => 'assigned', + 'reservation_id' => $reservationId, + 'reservation_ip_claim_id' => $claimId, + 'instance_id' => $reservationId, + 'operation_id' => $operationId, ]); }; $addReservation = static function (int $id, int $hostId, @@ -988,17 +1373,15 @@ Capsule::table('cloud_instance_migrations')->insert([ ]); $sourceRetainedOperation = str_repeat('9', 32); $addReservation(621, 8, $sourceRetainedOperation); -$sourceRetainedBundle = CloudPublicNetworkAllocationService::reserveBundle( - 8, - 15, - 621, - $sourceRetainedOperation +$assertHardFailure(static fn () => + CloudPublicNetworkAllocationService::reserveBundle( + 8, + 15, + 621, + $sourceRetainedOperation + ), + 'A pre-transition-ledger retained source bypassed active claim authority.' ); -$assert($sourceRetainedBundle->address(4) === '21.0.0.10/24' - && Capsule::table('cloud_public_ips')->where('id', $retainedIpId) - ->where('state', 'assigned')->whereNull('instance_id') - ->where('reservation_id', 700)->count() === 1, - 'Exact source-retained debt blocked placement or was reallocated.'); // The same debt remains valid while its cleanup mutation is in flight. Capsule::table('cloud_instance_migrations')->where('id', 800)->update([ @@ -1007,17 +1390,15 @@ Capsule::table('cloud_instance_migrations')->where('id', 800)->update([ $addIp(8, 180, 4, '21.0.0.12', 24); $cleanupRunningOperation = str_repeat('a', 32); $addReservation(622, 8, $cleanupRunningOperation); -$cleanupRunningBundle = CloudPublicNetworkAllocationService::reserveBundle( - 8, - 15, - 622, - $cleanupRunningOperation +$assertHardFailure(static fn () => + CloudPublicNetworkAllocationService::reserveBundle( + 8, + 15, + 622, + $cleanupRunningOperation + ), + 'Cleanup-running legacy debt bypassed active claim authority.' ); -$assert($cleanupRunningBundle->address(4) === '21.0.0.12/24' - && Capsule::table('cloud_public_ips')->where('id', $retainedIpId) - ->where('state', 'assigned')->whereNull('instance_id') - ->where('reservation_id', 700)->count() === 1, - 'Cleanup-running retained debt blocked placement or was reallocated.'); // An orphan or any material identity mismatch must remain a hard ledger // failure. It must not become ordinary capacity exhaustion or claim a spare. @@ -1148,6 +1529,10 @@ CloudPublicNetworkAllocationService::commitBundle( 918, $commitIdentityOperation ); +Capsule::table('cloud_resource_reservations')->where('id', 618)->update([ + 'state' => 'committed', + 'instance_id' => 918, +]); Capsule::table('cloud_public_ips')->where('id', (int) $commitIpv4->id) ->update(['host_id' => 999]); $assertHardFailure( @@ -1197,6 +1582,9 @@ CloudPublicNetworkAllocationService::fenceBundle( 619, $fenceIdentityOperation ); +Capsule::table('cloud_resource_reservations')->where('id', 619)->update([ + 'state' => 'uncertain', +]); CloudPublicNetworkAllocationService::releaseBundle( 619, $fenceIdentityOperation, diff --git a/web/tests/CloudPublicNetworkLegacyWriterGateContractTest.php b/web/tests/CloudPublicNetworkLegacyWriterGateContractTest.php new file mode 100644 index 00000000..8bc878c6 --- /dev/null +++ b/web/tests/CloudPublicNetworkLegacyWriterGateContractTest.php @@ -0,0 +1,196 @@ +getConnection()->transaction', + $enqueueStart === false ? 0 : $enqueueStart); +$enqueueGate = strpos($jobs, + 'CloudPublicNetworkTransitionGate::assertWriterReady()', + $enqueueStart === false ? 0 : $enqueueStart); +$assert($enqueueStart !== false && $enqueueGate !== false + && $enqueueTransaction !== false && $enqueueGate < $enqueueTransaction, + 'Network-change gate runs after its target, invoice or job transaction starts.'); +$assert($before($worker, + "(string) \$job->kind === 'network_change'", + "'phase' => 'dispatching'") + && $before($worker, + "(string) \$job->kind === 'backup_restore'", + "'phase' => 'dispatching'") + && $before($worker, "'instance_migration_'", "'phase' => 'dispatching'"), + 'Worker defense runs after an old operation may be dispatched.'); +$assert($before($batch, + 'CloudPublicNetworkTransitionGate::assertWriterReady()', + 'new CloudPublicIpPoolReplacementBatch()'), + 'Pool-replacement gate runs after a batch may be created.'); +$assert($before($backupRestore, + 'CloudPublicNetworkTransitionGate::assertPortableRestoreReady()', + 'headObject(') + && $before($backupRestore, + 'CloudPublicNetworkTransitionGate::assertPortableRestoreReady()', + 'new CloudBackupRestore()'), + 'Portable-restore gate runs after remote work or durable target creation.'); +$assert($before($migration, + 'CloudPublicNetworkTransitionGate::assertMigrationReady()', + 'new CloudBackupRestore()'), + 'Migration gate runs after target rows may be created.'); +$assert(str_contains($placement, + 'self::assertBackupRestoreTransitionReady($restore)') + && str_contains($placementGate, + 'CloudPublicNetworkTransitionGate::assertMigrationReady()') + && str_contains($placementGate, + 'CloudPublicNetworkTransitionGate::assertPortableRestoreReady()'), + 'Placement lacks a defense-in-depth gate for old restore writers.'); +$assert($before($migrationEnsureCleanup, + 'CloudPublicNetworkTransitionGate::assertMigrationReady()', + 'getConnection()->transaction') + && $before($migrationRecover, + 'CloudPublicNetworkTransitionGate::assertMigrationReady()', + 'getConnection()->transaction') + && $before($migrationCleanup, + 'CloudPublicNetworkTransitionGate::assertMigrationReady()', + 'getConnection()->transaction'), + 'A migration recovery entry can create retry intent before its gate.'); +$assert($before($poolChild, + 'CloudPublicNetworkTransitionGate::assertWriterReady()', + 'new CloudJob()') + && $before($networkFinalizer, + 'CloudPublicNetworkTransitionGate::assertWriterReady()', + 'lockForUpdate()'), + 'An old network-change child/finalizer can mutate before its gate.'); +$assert(str_contains($deletedInstance, + 'CloudPublicNetworkTransitionGate::assertPortableRestoreReady()') + && !str_contains($placementSource, 'releaseLockedReservation(') + && !str_contains($placementSource, 'reservationNetworkMatches('), + 'Restored-instance deletion still uses the singular IP release path.'); +$enqueueDeleteGate = strpos( + $enqueue, + 'CloudPublicNetworkTransitionGate::assertInstanceDeleteReady(' +); +$enqueueTransaction = strpos($enqueue, 'getConnection()->transaction'); +$enqueueInstanceLock = strpos($enqueue, "CloudInstance::where('id'"); +$enqueueLockedDeleteGate = $enqueueInstanceLock === false ? false : strpos( + $enqueue, + 'CloudPublicNetworkTransitionGate::assertInstanceDeleteReady(', + $enqueueInstanceLock +); +$enqueueJob = strpos($enqueue, 'new CloudJob()'); +$assert($enqueueDeleteGate !== false && $enqueueTransaction !== false + && $enqueueDeleteGate < $enqueueTransaction + && $enqueueLockedDeleteGate !== false && $enqueueJob !== false + && $enqueueLockedDeleteGate < $enqueueJob, + 'Restored-instance delete gate can run after durable job creation.'); +$assert($before($forceDelete, + 'CloudPublicNetworkTransitionGate::assertInstanceDeleteReady(', + 'new CloudJob()'), + 'Restored-instance force-delete gate runs after durable job creation.'); +$assert($before($expiryDelete, + 'CloudPublicNetworkTransitionGate::assertInstanceDeleteReady(', + 'new CloudJob()'), + 'Restored-instance expiry-delete gate runs after durable job creation.'); +$workerDeleteGate = strpos( + $worker, + 'assertInstanceDeleteReady($deleteInstance)' +); +$workerDispatch = strpos($worker, "'phase' => 'dispatching'"); +$assert($workerDeleteGate !== false && $workerDispatch !== false + && $workerDeleteGate < $workerDispatch, + 'Worker can dispatch a restored-instance delete before its gate.'); + +echo "Legacy public-network writer gate contracts passed.\n"; diff --git a/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php b/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php index 33fd5408..c5a2249f 100644 --- a/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php +++ b/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php @@ -56,8 +56,10 @@ $assert($publicIps !== '' 'UNIQUE KEY cloud_public_ip_claim (reservation_ip_claim_id)') && str_contains($publicIps, 'UNIQUE KEY cloud_public_ip_operation (operation_id, address_family)') - && !str_contains($publicIps, 'reservation_ip_claim_id IS NOT NULL'), - 'Public-address rows do not expose the nullable exact-claim fence while retaining legacy writers.'); + && str_contains($publicIps, 'chk_cloud_public_ip_owner_shape') + && str_contains($publicIps, 'reservation_ip_claim_id IS NOT NULL') + && str_contains($publicIps, "state IN ('changing','uncertain')"), + 'Public-address rows do not require exact claims for every occupied state.'); $assert($claims !== '' && str_contains($claims, @@ -72,8 +74,13 @@ $assert($claims !== '' 'UNIQUE KEY cloud_reservation_ip_operation (operation_id, address_family)') && str_contains($claims, 'claim_generation >= 1') && str_contains($claims, 'active_claim IS NULL OR active_claim = 1') - && !str_contains($claims, "state = 'released' AND active_claim IS NULL"), - 'Reservation claims do not provide generation/active fencing compatible with the old writer.'); + && str_contains($claims, "state = 'committed'") + && str_contains($claims, 'AND active_claim IS NOT NULL') + && str_contains($claims, 'AND active_claim = 1') + && str_contains($claims, "state IN ('reserved','uncertain')") + && str_contains($claims, "state = 'released'") + && str_contains($claims, 'active_claim IS NULL'), + 'Reservation claims do not retain history behind an explicit active fence.'); $assert($transitions !== '' && str_contains($transitions, @@ -165,7 +172,7 @@ $assert(str_contains($setup, 'CloudSetup does not verify index uniqueness and ordered columns.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v28-public-network-transition'") + "SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'") && str_contains($setup, "'cloud_public_network_transitions'") && str_contains($setup, "'cloud_public_network_transition_ips'") && str_contains($setup, "'reservation_ip_claim_id'") diff --git a/web/tests/CloudRescueCatalogSchemaContractTest.php b/web/tests/CloudRescueCatalogSchemaContractTest.php index f884a6d0..a84749d8 100644 --- a/web/tests/CloudRescueCatalogSchemaContractTest.php +++ b/web/tests/CloudRescueCatalogSchemaContractTest.php @@ -56,7 +56,7 @@ $assert($replica !== '' && str_contains($replica, 'cleanup_resolved_at BIGINT UNSIGNED'), 'Rescue replica cannot prove exact identity or retain cleanup debt.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v28-public-network-transition'") + "SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'") && str_contains($setup, "'cloud_rescue_artifact_delete_due'") && str_contains($setup, "'cloud_rescue_replica_cleanup'"), 'CloudSetup version or rescue catalog indexes are incomplete.'); diff --git a/web/tests/CloudTemplateImportIntentContractTest.php b/web/tests/CloudTemplateImportIntentContractTest.php index dd40a062..8068f3a9 100644 --- a/web/tests/CloudTemplateImportIntentContractTest.php +++ b/web/tests/CloudTemplateImportIntentContractTest.php @@ -63,7 +63,7 @@ $assert(str_contains($schema, && str_contains($schema, 'CONSTRAINT chk_cloud_template_import_completion CHECK (') && str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v28-public-network-transition'"), + "SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'"), 'Template imports are missing durable identity or terminal-state constraints.'); $assert(str_contains($routes, "'/admin/cloud-template-imports'") && str_contains($routes, "'/admin/cloud-template-imports/{id}'") diff --git a/web/tests/CloudTrafficPoolSchemaContractTest.php b/web/tests/CloudTrafficPoolSchemaContractTest.php index 50879448..47aae80e 100644 --- a/web/tests/CloudTrafficPoolSchemaContractTest.php +++ b/web/tests/CloudTrafficPoolSchemaContractTest.php @@ -71,7 +71,7 @@ $assert(str_contains($schema, 'Service-period traffic-pool identity is not frozen or indexed.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v28-public-network-transition'") + "SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'") && str_contains($setup, "'chk_cloud_traffic_entitlement_balance'") && str_contains($setup, "'cloud_traffic_ledger_sequence'"), 'CloudSetup schema version or named-object validation is incomplete.'); diff --git a/web/tests/CloudUndispatchedFinalizerRecoveryTest.php b/web/tests/CloudUndispatchedFinalizerRecoveryTest.php index 2b5160f9..7f3e5cc5 100644 --- a/web/tests/CloudUndispatchedFinalizerRecoveryTest.php +++ b/web/tests/CloudUndispatchedFinalizerRecoveryTest.php @@ -313,6 +313,7 @@ namespace { $table->integer('prefix_length'); $table->string('state'); $table->integer('reservation_id')->nullable(); + $table->integer('reservation_ip_claim_id')->nullable(); $table->integer('instance_id')->nullable(); $table->string('operation_id')->nullable(); $table->integer('created_at'); @@ -323,6 +324,8 @@ namespace { $table->increments('id'); $table->integer('reservation_id'); $table->integer('address_family'); + $table->integer('claim_generation')->default(1); + $table->integer('active_claim')->nullable()->default(1); $table->integer('network_attachment_id'); $table->integer('public_ip_pool_id'); $table->integer('public_ip_id'); @@ -681,6 +684,7 @@ namespace { 'prefix_length' => 24, 'state' => 'reserved', 'reservation_id' => 601, + 'reservation_ip_claim_id' => 601, 'instance_id' => null, 'operation_id' => $createOperationId, 'created_at' => $now - 120, @@ -696,6 +700,7 @@ namespace { 'prefix_length' => 64, 'state' => 'reserved', 'reservation_id' => 601, + 'reservation_ip_claim_id' => 602, 'instance_id' => null, 'operation_id' => $createOperationId, 'created_at' => $now - 120, @@ -707,6 +712,8 @@ namespace { 'id' => 601, 'reservation_id' => 601, 'address_family' => 4, + 'claim_generation' => 1, + 'active_claim' => 1, 'network_attachment_id' => 601, 'public_ip_pool_id' => 601, 'public_ip_id' => 601, @@ -721,6 +728,8 @@ namespace { 'id' => 602, 'reservation_id' => 601, 'address_family' => 6, + 'claim_generation' => 1, + 'active_claim' => 1, 'network_attachment_id' => 601, 'public_ip_pool_id' => 602, 'public_ip_id' => 602, diff --git a/web/tests/CloudVpcSchemaContractTest.php b/web/tests/CloudVpcSchemaContractTest.php index a6c14c3b..0beb84eb 100644 --- a/web/tests/CloudVpcSchemaContractTest.php +++ b/web/tests/CloudVpcSchemaContractTest.php @@ -101,7 +101,7 @@ $assert(str_contains($jobs, 'vpc_id BIGINT UNSIGNED DEFAULT NULL') 'Cloud jobs cannot be correlated to VPC or VPC-port work.'); $assert(str_contains($setup, - "private const SCHEMA_VERSION = 'go-agent-wss-v28-public-network-transition'") + "private const SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'") && str_contains($setup, "'name' => 'cloud_vpc_enabled'") && str_contains($setup, "'value' => 'false'") && str_contains($setup,