From 89cb5e537286c6780570932439e57f342cb980bc Mon Sep 17 00:00:00 2001 From: codex Date: Tue, 3 Nov 2026 21:38:13 +0800 Subject: [PATCH] feat: plan portable restore targets --- .../Cloud/CloudPlacementNetworkService.php | 95 ++- .../CloudPortableRestoreCompatibility.php | 8 +- .../Cloud/CloudPortableRestoreTargetPlan.php | 316 +++++++++ .../CloudPortableRestoreTargetService.php | 456 +++++++++++++ .../CloudDualStackPlacementAdvisoryTest.php | 12 + ...CloudPortableRestoreTargetContractTest.php | 65 ++ .../CloudPortableRestoreTargetServiceTest.php | 599 ++++++++++++++++++ 7 files changed, 1530 insertions(+), 21 deletions(-) create mode 100644 web/app/Services/Cloud/CloudPortableRestoreTargetPlan.php create mode 100644 web/app/Services/Cloud/CloudPortableRestoreTargetService.php create mode 100644 web/tests/CloudPortableRestoreTargetContractTest.php create mode 100644 web/tests/CloudPortableRestoreTargetServiceTest.php diff --git a/web/app/Services/Cloud/CloudPlacementNetworkService.php b/web/app/Services/Cloud/CloudPlacementNetworkService.php index f18d1dd8..7741b315 100644 --- a/web/app/Services/Cloud/CloudPlacementNetworkService.php +++ b/web/app/Services/Cloud/CloudPlacementNetworkService.php @@ -48,6 +48,31 @@ final class CloudPlacementNetworkService */ public static function advisoryDualStackAvailableHosts( $candidateRows + ): array { + $bundles = self::advisoryDualStackBundleEvidence($candidateRows); + $available = []; + foreach ($bundles as $hostId => $lines) { + foreach ($lines as $lineBundles) { + if ($lineBundles !== []) { + $available[(int) $hostId] = true; + break; + } + } + } + ksort($available, SORT_NUMERIC); + return $available; + } + + /** + * Read-only host+line evidence for one currently available IPv4+IPv6 + * bundle. Both families must use the same current Agent-verified network + * attachment. No address is selected or exposed, and admission must still + * repeat every predicate while holding the placement ledgers. + * + * @return array>>> + */ + public static function advisoryDualStackBundleEvidence( + $candidateRows ): array { $hostLines = []; foreach ($candidateRows as $candidate) { @@ -66,7 +91,7 @@ final class CloudPlacementNetworkService 'host_id', array_keys($hostLines) )->where('state', 'active')->where('verification_state', 'verified') - ->orderBy('id')->get(); + ->orderBy('priority')->orderBy('id')->get(); if ($attachments->isEmpty()) { return []; } @@ -77,6 +102,7 @@ final class CloudPlacementNetworkService $agent = $agents->get($hostId); if ($agent instanceof CloudHostAgent && isset($hostLines[$hostId][$lineId]) + && (int) $attachment->config_revision > 0 && self::attachmentReadyForAgent($attachment, $agent) && CloudAgentSettingsService::publicNetworkReady( $agent, @@ -94,7 +120,7 @@ final class CloudPlacementNetworkService array_keys($eligible) )->where('state', 'active')->where('sync_state', 'applied') ->whereColumn('observed_revision', 'desired_revision') - ->orderBy('id')->get(); + ->orderBy('priority')->orderBy('id')->get(); $poolIds = $pools->pluck('id')->map( static fn ($id): int => (int) $id )->all(); @@ -124,15 +150,25 @@ final class CloudPlacementNetworkService continue; } $poolIps = $ipsByPool[(int) $pool->id] ?? []; - $hasCapacity = $family === 4 - ? self::advisoryIpv4PoolHasCapacity( + $availableUnits = $family === 4 + ? self::advisoryIpv4PoolAvailableUnits( $pool, $poolIps, $hosts->get((int) $pool->host_id) ) - : self::advisoryIpv6PoolHasCapacity($pool, $poolIps); - if ($hasCapacity) { - $capacity[(int) $attachment->id][$family] = true; + : self::advisoryIpv6PoolAvailableUnits($pool, $poolIps); + if ($availableUnits > 0 + && !isset($capacity[(int) $attachment->id][$family])) { + $capacity[(int) $attachment->id][$family] = [ + 'public_ip_pool_id' => (int) $pool->id, + 'pool_key' => (string) $pool->pool_key, + 'network_attachment_id' => + (int) $pool->network_attachment_id, + 'address_family' => $family, + 'desired_revision' => (int) $pool->desired_revision, + 'observed_revision' => (int) $pool->observed_revision, + 'available_units' => $availableUnits, + ]; } } $available = []; @@ -141,9 +177,27 @@ final class CloudPlacementNetworkService continue; } $attachment = $eligible[(int) $attachmentId]; - $available[(int) $attachment->host_id] = true; + $hostId = (int) $attachment->host_id; + $lineId = (int) $attachment->line_id; + $available[$hostId][$lineId][] = [ + 'network_attachment_id' => (int) $attachment->id, + 'host_id' => $hostId, + 'line_id' => $lineId, + 'attachment_key' => (string) $attachment->attachment_key, + 'network_selector' => (string) $attachment->network_selector, + 'attachment_config_revision' => + (int) $attachment->config_revision, + 'attachment_verified_agent_revision' => + (int) $attachment->verified_agent_revision, + 'ipv4' => $families[4], + 'ipv6' => $families[6], + ]; } ksort($available, SORT_NUMERIC); + foreach ($available as &$lines) { + ksort($lines, SORT_NUMERIC); + } + unset($lines); return $available; } @@ -497,23 +551,23 @@ final class CloudPlacementNetworkService ->orderBy('id'); } - private static function advisoryIpv4PoolHasCapacity( + private static function advisoryIpv4PoolAvailableUnits( CloudPublicIpPool $pool, array $ips, ?CloudHost $host - ): bool { + ): int { try { $network = CloudIpPrefix::network((string) $pool->cidr); $gateway = CloudIpAddress::parse((string) $pool->gateway); } catch (\InvalidArgumentException) { - return false; + return 0; } if ($network->family() !== 4 || $network->prefixLength() > 30 || (int) $pool->guest_prefix_length !== $network->prefixLength() || !$gateway->isPublicUnicast() || !$network->contains($gateway)) { - return false; + return 0; } $available = array_values(array_filter( $ips, @@ -524,8 +578,9 @@ final class CloudPlacementNetworkService && $ip->operation_id === null )); if (count($available) > self::MAX_PUBLIC_IPS_PER_POOL) { - return false; + return 0; } + $count = 0; foreach ($available as $ip) { try { $address = CloudIpAddress::parse((string) $ip->address); @@ -534,23 +589,23 @@ final class CloudPlacementNetworkService } if ($address->isPublicUnicast() && self::publicIpBelongsToPool($ip, $pool, $host)) { - return true; + $count++; } } - return false; + return $count; } - private static function advisoryIpv6PoolHasCapacity( + private static function advisoryIpv6PoolAvailableUnits( CloudPublicIpPool $pool, array $ips - ): bool { + ): int { try { $network = CloudIpPrefix::network((string) $pool->cidr); $gateway = CloudIpAddress::parse((string) $pool->gateway); $start = CloudIpAddress::parse((string) $pool->allocation_start); $end = CloudIpAddress::parse((string) $pool->allocation_end); } catch (\InvalidArgumentException) { - return false; + return 0; } if ($network->family() !== 6 || $network->prefixLength() > 120 || (int) $pool->guest_prefix_length @@ -563,7 +618,7 @@ final class CloudPlacementNetworkService || !$network->contains($start) || !$network->contains($end) || $start->compare($end) > 0 || (int) $pool->max_allocations < 1) { - return false; + return 0; } $active = count(array_filter( $ips, @@ -572,7 +627,7 @@ final class CloudPlacementNetworkService && in_array((string) $ip->state, ['reserved', 'changing', 'uncertain', 'assigned'], true) )); - return $active < (int) $pool->max_allocations; + return max(0, (int) $pool->max_allocations - $active); } private static function publicIpBelongsToPool(CloudPublicIp $ip, diff --git a/web/app/Services/Cloud/CloudPortableRestoreCompatibility.php b/web/app/Services/Cloud/CloudPortableRestoreCompatibility.php index cf9769e7..3f9d2d89 100644 --- a/web/app/Services/Cloud/CloudPortableRestoreCompatibility.php +++ b/web/app/Services/Cloud/CloudPortableRestoreCompatibility.php @@ -25,6 +25,12 @@ final class CloudPortableRestoreCompatibility { } + /** The one fixed platform contract supported by this clean-break release. */ + public static function supported(): self + { + return new self(); + } + public static function fromPayload(mixed $value): self { if (!is_array($value) || array_is_list($value) @@ -40,7 +46,7 @@ final class CloudPortableRestoreCompatibility ); } } - return new self(); + return self::supported(); } public static function fromStored(string $json, string $sha256): self diff --git a/web/app/Services/Cloud/CloudPortableRestoreTargetPlan.php b/web/app/Services/Cloud/CloudPortableRestoreTargetPlan.php new file mode 100644 index 00000000..8746db48 --- /dev/null +++ b/web/app/Services/Cloud/CloudPortableRestoreTargetPlan.php @@ -0,0 +1,316 @@ +plan = self::canonical($plan); + $this->json = json_encode( + $this->plan, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ); + $this->sha256 = hash('sha256', $this->json); + } + + /** + * Validate and freeze the complete advisory-evidence contract. The target + * scheduler is the only production caller; accepting arbitrary arrays here + * would make a forged value indistinguishable from scheduler evidence. + */ + public static function fromEvidence(array $plan): self + { + self::exactKeys($plan, [ + 'contract', 'backup', 'target', 'resources', 'capacity', + 'public_network', 'vpc_inherited', + ]); + if (($plan['contract'] ?? null) !== 1 + || ($plan['vpc_inherited'] ?? null) !== false) { + throw new \InvalidArgumentException( + 'Portable restore plan contract is invalid' + ); + } + $backup = self::object($plan['backup'] ?? null, [ + 'id', 'backup_key', 'object_size_bytes', 'object_sha256', + 'object_identity_sha256', 'source_contract_sha256', + 'source_public_network_sha256', 'source_host_id', + 'source_line_id', 'source_storage_revision', + 'virtual_size_bytes', + ]); + self::positiveInt($backup['id']); + self::hex($backup['backup_key'], 32); + self::positiveInt($backup['object_size_bytes']); + self::hex($backup['object_sha256'], 64); + self::hex($backup['object_identity_sha256'], 64); + self::hex($backup['source_contract_sha256'], 64); + self::hex($backup['source_public_network_sha256'], 64); + self::positiveInt($backup['source_host_id']); + self::positiveInt($backup['source_line_id']); + self::positiveInt($backup['source_storage_revision']); + self::positiveInt($backup['virtual_size_bytes']); + + $target = self::object($plan['target'] ?? null, [ + 'host_id', 'host_name', 'is_source_host', 'resource_pool_id', + 'resource_pool_name', 'membership_revision', 'line_id', + 'line_name', 'region_id', 'region_name', 'country_code', + 'agent_revision', 'agent_contract_sha256', 'storage_revision', + ]); + foreach (['host_id', 'resource_pool_id', 'membership_revision', + 'line_id', 'region_id', 'agent_revision', 'storage_revision'] + as $field) { + self::positiveInt($target[$field]); + } + foreach (['host_name', 'resource_pool_name', 'line_name', + 'region_name'] as $field) { + self::nonEmptyString($target[$field]); + } + if (!is_bool($target['is_source_host']) + || $target['is_source_host'] !== + ($target['host_id'] === $backup['source_host_id']) + || !is_string($target['country_code']) + || preg_match('/^[A-Z]{2}$/D', $target['country_code']) !== 1) { + throw new \InvalidArgumentException( + 'Portable restore target identity is invalid' + ); + } + self::hex($target['agent_contract_sha256'], 64); + $supportedContractSha256 = + CloudPortableRestoreCompatibility::supported()->sha256(); + if (!hash_equals( + $supportedContractSha256, + $backup['source_contract_sha256'] + ) || !hash_equals( + $backup['source_contract_sha256'], + $target['agent_contract_sha256'] + )) { + throw new \InvalidArgumentException( + 'Portable restore contracts do not match' + ); + } + + $resources = self::object($plan['resources'] ?? null, [ + 'cpu_cores', 'memory_mib', 'disk_gib', 'bandwidth_mbps', + 'system_disk_virtual_size_bytes', + ]); + foreach ($resources as $value) { + self::positiveInt($value); + } + if ($resources['disk_gib'] > intdiv(PHP_INT_MAX, self::GIB) + || $resources['system_disk_virtual_size_bytes'] + > $resources['disk_gib'] * self::GIB + || $resources['system_disk_virtual_size_bytes'] + !== $backup['virtual_size_bytes']) { + throw new \InvalidArgumentException( + 'Portable restore disk evidence is invalid' + ); + } + + $capacity = self::object($plan['capacity'] ?? null, [ + 'policy_updated_at', 'requested', 'used', 'limits', + ]); + self::positiveInt($capacity['policy_updated_at']); + $requested = self::object($capacity['requested'], [ + 'cpu_cores', 'memory_mib', 'disk_gib', + ]); + $used = self::object($capacity['used'], [ + 'instance_count', 'cpu_cores', 'memory_mib', 'disk_gib', + ]); + $limits = self::object($capacity['limits'], [ + 'instance_count', 'cpu_cores', 'memory_mib', 'disk_gib', + ]); + foreach ($requested as $field => $value) { + self::positiveInt($value); + if ($value !== $resources[$field]) { + throw new \InvalidArgumentException( + 'Portable restore capacity request drifted' + ); + } + } + foreach ($used as $value) { + self::nonNegativeInt($value); + } + self::nonNegativeInt($limits['instance_count']); + foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $field) { + self::positiveInt($limits[$field]); + if ($requested[$field] > $limits[$field] + || $used[$field] > $limits[$field] - $requested[$field]) { + throw new \InvalidArgumentException( + 'Portable restore capacity is insufficient' + ); + } + } + if ($limits['instance_count'] > 0 + && $used['instance_count'] + 1 > $limits['instance_count']) { + throw new \InvalidArgumentException( + 'Portable restore instance capacity is insufficient' + ); + } + + $network = self::object($plan['public_network'] ?? null, [ + 'mode', 'host_id', 'line_id', 'network_attachment_id', + 'attachment_key', 'network_selector', + 'attachment_config_revision', + 'attachment_verified_agent_revision', 'ipv4_pool', 'ipv6_pool', + ]); + if (($network['mode'] ?? null) !== 'fresh_dual_stack') { + throw new \InvalidArgumentException( + 'Portable restore network mode is invalid' + ); + } + foreach (['host_id', 'line_id', 'network_attachment_id', + 'attachment_config_revision', + 'attachment_verified_agent_revision'] as $field) { + self::positiveInt($network[$field]); + } + self::hex($network['attachment_key'], 32); + if (!CloudNetworkSelector::isValid($network['network_selector']) + || $network['host_id'] !== $target['host_id'] + || $network['line_id'] !== $target['line_id'] + || $network['attachment_verified_agent_revision'] + !== $target['agent_revision']) { + throw new \InvalidArgumentException( + 'Portable restore network attachment is inconsistent' + ); + } + $ipv4 = self::pool($network['ipv4_pool'], 4, + $network['network_attachment_id']); + $ipv6 = self::pool($network['ipv6_pool'], 6, + $network['network_attachment_id']); + if ($ipv4['public_ip_pool_id'] === $ipv6['public_ip_pool_id'] + || hash_equals($ipv4['pool_key'], $ipv6['pool_key'])) { + throw new \InvalidArgumentException( + 'Portable restore network pools are not distinct' + ); + } + return new self($plan); + } + + public function toArray(): array + { + return $this->plan; + } + + public function json(): string + { + return $this->json; + } + + public function sha256(): string + { + return $this->sha256; + } + + private static function canonical(array $value): array + { + if (array_is_list($value)) { + return array_map( + static fn ($item) => is_array($item) + ? self::canonical($item) : $item, + $value + ); + } + ksort($value, SORT_STRING); + foreach ($value as $key => $item) { + if (is_array($item)) { + $value[$key] = self::canonical($item); + } + } + return $value; + } + + private static function object(mixed $value, array $keys): array + { + if (!is_array($value) || array_is_list($value)) { + throw new \InvalidArgumentException( + 'Portable restore plan object is invalid' + ); + } + self::exactKeys($value, $keys); + return $value; + } + + private static function pool(mixed $value, int $family, + int $attachmentId): array + { + $pool = self::object($value, [ + 'public_ip_pool_id', 'pool_key', 'network_attachment_id', + 'address_family', 'desired_revision', 'observed_revision', + 'available_units', + ]); + foreach (['public_ip_pool_id', 'network_attachment_id', + 'address_family', 'desired_revision', 'observed_revision', + 'available_units'] as $field) { + self::positiveInt($pool[$field]); + } + self::hex($pool['pool_key'], 32); + if ($pool['address_family'] !== $family + || $pool['network_attachment_id'] !== $attachmentId + || $pool['observed_revision'] !== $pool['desired_revision']) { + throw new \InvalidArgumentException( + 'Portable restore public pool evidence is inconsistent' + ); + } + return $pool; + } + + private static function exactKeys(array $value, array $expected): void + { + $actual = array_keys($value); + sort($actual, SORT_STRING); + sort($expected, SORT_STRING); + if ($actual !== $expected) { + throw new \InvalidArgumentException( + 'Portable restore plan fields are invalid' + ); + } + } + + private static function positiveInt(mixed $value): void + { + if (!is_int($value) || $value < 1) { + throw new \InvalidArgumentException( + 'Portable restore positive integer is invalid' + ); + } + } + + private static function nonNegativeInt(mixed $value): void + { + if (!is_int($value) || $value < 0) { + throw new \InvalidArgumentException( + 'Portable restore non-negative integer is invalid' + ); + } + } + + private static function hex(mixed $value, int $length): void + { + if (!is_string($value) + || preg_match('/^[a-f0-9]{' . $length . '}$/D', $value) !== 1) { + throw new \InvalidArgumentException( + 'Portable restore digest or key is invalid' + ); + } + } + + private static function nonEmptyString(mixed $value): void + { + if (!is_string($value) || trim($value) === '' + || strlen($value) > 255) { + throw new \InvalidArgumentException( + 'Portable restore label is invalid' + ); + } + } +} diff --git a/web/app/Services/Cloud/CloudPortableRestoreTargetService.php b/web/app/Services/Cloud/CloudPortableRestoreTargetService.php new file mode 100644 index 00000000..d7dcf2b9 --- /dev/null +++ b/web/app/Services/Cloud/CloudPortableRestoreTargetService.php @@ -0,0 +1,456 @@ + */ + public static function candidates( + CloudInstanceBackup $backup + ): array { + $backupId = (int) $backup->id; + if ($backupId < 1) { + throw new CloudError('备份缺少可信的可移植恢复证据', 409); + } + return $backup->getConnection()->transaction( + static function () use ($backupId): array { + $current = CloudInstanceBackup::where('id', $backupId) + ->first(); + if (!$current instanceof CloudInstanceBackup) { + throw new CloudError('备份不存在', 404); + } + return self::candidatesFromSnapshot($current); + }, + 1 + ); + } + + /** @return list */ + private static function candidatesFromSnapshot( + CloudInstanceBackup $backup + ): array { + [$sourceContract, $sourceLineId, $resources, $virtualSize, + $sourceNetworkSha256, $objectIdentitySha256] = + self::backupContext($backup); + $rows = self::candidateRows(); + if ($rows->isEmpty()) { + return []; + } + $hostIds = $rows->pluck('id')->map( + static fn ($id): int => (int) $id + )->unique()->values()->all(); + $usageByHost = CloudPanelUsageService::forHosts($hostIds); + $networkByHostLine = CloudPlacementNetworkService:: + advisoryDualStackBundleEvidence($rows); + $plans = []; + foreach ($rows as $row) { + $hostId = (int) $row->id; + $lineId = (int) $row->resource_pool_line_id; + $agent = self::agentFromRow($row); + $targetContract = $agent->testedPortableRestoreCompatibility(); + $usage = $usageByHost[$hostId] ?? null; + if ($targetContract === null + || !$sourceContract->matches($targetContract) + || (int) $row->membership_revision < 1 + || (int) $row->storage_revision < 1 + || !is_array($usage) + || !self::hasCapacity($row, $usage, $resources)) { + continue; + } + foreach ($networkByHostLine[$hostId][$lineId] ?? [] as $network) { + if (!self::networkEvidenceMatchesAgent($network, $agent)) { + continue; + } + $evidence = [ + 'contract' => 1, + 'backup' => [ + 'id' => (int) $backup->id, + 'backup_key' => (string) $backup->backup_key, + 'object_size_bytes' => + (int) $backup->object_size_bytes, + 'object_sha256' => (string) $backup->sha256, + 'object_identity_sha256' => $objectIdentitySha256, + 'source_contract_sha256' => $sourceContract->sha256(), + 'source_public_network_sha256' => + $sourceNetworkSha256, + 'source_host_id' => (int) $backup->source_host_id, + 'source_line_id' => $sourceLineId, + 'source_storage_revision' => + (int) $backup->storage_revision, + 'virtual_size_bytes' => $virtualSize, + ], + 'target' => [ + 'host_id' => $hostId, + 'host_name' => (string) $row->name, + 'is_source_host' => + $hostId === (int) $backup->source_host_id, + 'resource_pool_id' => + (int) $row->resource_pool_id, + 'resource_pool_name' => + (string) $row->resource_pool_name, + 'membership_revision' => + (int) $row->membership_revision, + 'line_id' => $lineId, + 'line_name' => (string) $row->line_name, + 'region_id' => (int) $row->region_id, + 'region_name' => (string) $row->region_name, + 'country_code' => strtoupper( + (string) $row->country_code + ), + 'agent_revision' => (int) $agent->revision, + 'agent_contract_sha256' => $targetContract->sha256(), + 'storage_revision' => (int) $row->storage_revision, + ], + 'resources' => [ + 'cpu_cores' => $resources['cpu_cores'], + 'memory_mib' => $resources['memory_mib'], + 'disk_gib' => $resources['disk_gib'], + 'bandwidth_mbps' => $resources['bandwidth_mbps'], + 'system_disk_virtual_size_bytes' => $virtualSize, + ], + 'capacity' => self::capacityEvidence( + $row, + $usage, + $resources + ), + 'public_network' => [ + 'mode' => 'fresh_dual_stack', + 'host_id' => (int) $network['host_id'], + 'line_id' => (int) $network['line_id'], + 'network_attachment_id' => + (int) $network['network_attachment_id'], + 'attachment_key' => + (string) $network['attachment_key'], + 'network_selector' => + (string) $network['network_selector'], + 'attachment_config_revision' => + (int) $network['attachment_config_revision'], + 'attachment_verified_agent_revision' => + (int) $network[ + 'attachment_verified_agent_revision' + ], + 'ipv4_pool' => $network['ipv4'], + 'ipv6_pool' => $network['ipv6'], + ], + 'vpc_inherited' => false, + ]; + try { + $plans[] = CloudPortableRestoreTargetPlan::fromEvidence( + $evidence + ); + } catch (\InvalidArgumentException) { + continue; + } + } + } + return $plans; + } + + /** + * @return array{0:CloudPortableRestoreCompatibility,1:int, + * 2:array{cpu_cores:int,memory_mib:int,disk_gib:int, + * bandwidth_mbps:int},3:int,4:string,5:string} + */ + private static function backupContext(CloudInstanceBackup $backup): array + { + $contract = $backup->sourcePortableRestoreCompatibility(); + $objectKey = (string) $backup->object_key; + $sealedRuntime = (string) $backup->sealed_storage_runtime; + $objectEtag = (string) $backup->object_etag; + $objectVersionId = (string) $backup->object_version_id; + if ((int) $backup->id < 1 + || preg_match('/^[a-f0-9]{32}$/D', + (string) $backup->backup_key) !== 1 + || (int) $backup->source_host_id < 1 + || !self::validObjectKey($objectKey) + || trim($sealedRuntime) === '' + || strlen($objectEtag) > 256 + || preg_match('/[\x00-\x1f\x7f]/D', $objectEtag) === 1 + || strlen($objectVersionId) > 1024 + || preg_match('/[\x00-\x1f\x7f]/D', $objectVersionId) === 1 + || ($objectVersionId !== '' && $objectEtag === '') + || (string) $backup->purpose !== 'portable' + || (string) $backup->state !== 'ready' + || $contract === null + || (int) $backup->object_size_bytes < 1 + || (int) $backup->virtual_size_bytes < 1 + || (int) $backup->storage_revision < 1 + || preg_match('/^[a-f0-9]{64}$/D', + (string) $backup->sha256) !== 1) { + throw new CloudError('备份缺少可信的可移植恢复证据', 409); + } + try { + $spec = json_decode( + (string) $backup->spec_json, + true, + 64, + JSON_THROW_ON_ERROR + ); + if (!is_array($spec) || array_is_list($spec)) { + throw new \InvalidArgumentException(); + } + $sourceNetwork = CloudPublicNetworkSnapshot::fromArray( + $spec['public_network'] ?? null + ); + } catch (\Throwable) { + throw new CloudError('备份缺少可信的冻结双栈网络快照', 409); + } + $lineId = self::positiveInt($spec['line_id'] ?? null); + $resources = [ + 'cpu_cores' => self::positiveInt( + $spec['vcpu'] ?? $spec['cpu_cores'] ?? null + ), + 'memory_mib' => self::positiveInt( + $spec['memory_mib'] ?? $spec['ram_mib'] ?? null + ), + 'disk_gib' => self::positiveInt($spec['disk_gib'] ?? null), + 'bandwidth_mbps' => self::positiveInt( + $spec['bandwidth_mbps'] ?? null + ), + ]; + if ($lineId === null || in_array(null, $resources, true) + || $resources['disk_gib'] > intdiv(PHP_INT_MAX, self::GIB)) { + throw new CloudError('备份缺少可信的资源与商业线路快照', 409); + } + $virtualSize = (int) $backup->virtual_size_bytes; + if ($virtualSize > $resources['disk_gib'] * self::GIB) { + throw new CloudError('备份系统盘容量超过冻结规格', 409); + } + $objectIdentitySha256 = hash('sha256', json_encode([ + 'object_key' => $objectKey, + 'object_size_bytes' => (int) $backup->object_size_bytes, + 'object_sha256' => (string) $backup->sha256, + 'object_etag' => $objectEtag, + 'object_version_id' => $objectVersionId, + 'storage_revision' => (int) $backup->storage_revision, + 'sealed_storage_runtime_sha256' => hash( + 'sha256', + $sealedRuntime + ), + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)); + return [ + $contract, + $lineId, + $resources, + $virtualSize, + $sourceNetwork->fingerprint(), + $objectIdentitySha256, + ]; + } + + private static function candidateRows() + { + return CloudHost::query()->join( + 'cloud_host_resource_pool_memberships as restore_membership', + 'restore_membership.host_id', '=', 'cloud_hosts.id' + )->join( + 'cloud_resource_pools as restore_pool', + 'restore_pool.id', '=', 'restore_membership.resource_pool_id' + )->join( + 'cloud_network_lines as restore_line', + 'restore_line.id', '=', 'restore_pool.line_id' + )->join( + 'cloud_regions as restore_region', + 'restore_region.id', '=', 'restore_line.region_id' + )->join( + 'cloud_host_capacity_policies as restore_capacity', + 'restore_capacity.host_id', '=', 'cloud_hosts.id' + )->join( + 'cloud_host_agents as restore_agent', + 'restore_agent.host_id', '=', 'cloud_hosts.id' + )->join( + 'cloud_host_storage_configurations as restore_storage', + 'restore_storage.host_id', '=', 'cloud_hosts.id' + )->where('cloud_hosts.enabled', 1) + ->where('restore_membership.scheduler_state', 'active') + ->where('restore_pool.status', 'active') + ->where('restore_line.status', 'active') + ->where('restore_region.status', 'active') + ->where('restore_agent.enabled', 1) + ->where('restore_agent.last_test_status', 'healthy') + ->where('restore_agent.tested_revision', '>', 0) + ->whereColumn( + 'restore_agent.tested_revision', + 'restore_agent.revision' + )->where('restore_storage.state', 'applied') + ->where('restore_storage.revision', '>', 0) + ->where('restore_membership.revision', '>', 0) + ->where('restore_capacity.configured_cpu_cores', '>', 0) + ->where('restore_capacity.configured_memory_mib', '>', 0) + ->where('restore_capacity.configured_disk_gib', '>', 0) + ->orderBy('restore_membership.priority') + ->orderBy('cloud_hosts.id') + ->orderBy('restore_pool.id') + ->get([ + 'cloud_hosts.id', 'cloud_hosts.name', + 'restore_pool.id as resource_pool_id', + 'restore_pool.name as resource_pool_name', + 'restore_line.id as resource_pool_line_id', + 'restore_line.name as line_name', + 'restore_region.id as region_id', + 'restore_region.name as region_name', + 'restore_region.country_code', + 'restore_membership.revision as membership_revision', + 'restore_capacity.configured_cpu_cores', + 'restore_capacity.configured_memory_mib', + 'restore_capacity.configured_disk_gib', + 'restore_capacity.safety_cpu_cores', + 'restore_capacity.safety_memory_mib', + 'restore_capacity.safety_disk_gib', + 'restore_capacity.max_instances', + 'restore_capacity.updated_at as capacity_updated_at', + 'restore_storage.revision as storage_revision', + 'restore_agent.enabled as agent_enabled', + 'restore_agent.revision as agent_revision', + 'restore_agent.tested_revision as agent_tested_revision', + 'restore_agent.last_test_status as agent_last_test_status', + 'restore_agent.portable_restore_contract_json as ' + . 'agent_portable_restore_contract_json', + 'restore_agent.portable_restore_contract_sha256 as ' + . 'agent_portable_restore_contract_sha256', + ]); + } + + private static function agentFromRow($row): CloudHostAgent + { + $agent = new CloudHostAgent(); + $agent->setRawAttributes([ + 'host_id' => (int) $row->id, + 'enabled' => (bool) $row->agent_enabled, + 'revision' => (int) $row->agent_revision, + 'tested_revision' => (int) $row->agent_tested_revision, + 'last_test_status' => (string) $row->agent_last_test_status, + 'portable_restore_contract_json' => + (string) $row->agent_portable_restore_contract_json, + 'portable_restore_contract_sha256' => + (string) $row->agent_portable_restore_contract_sha256, + ], true); + return $agent; + } + + private static function networkEvidenceMatchesAgent( + array $network, + CloudHostAgent $agent + ): bool { + foreach (['ipv4' => 4, 'ipv6' => 6] as $family => $number) { + $pool = $network[$family] ?? null; + if (!is_array($pool) + || (int) ($pool['public_ip_pool_id'] ?? 0) < 1 + || (int) ($pool['network_attachment_id'] ?? 0) + !== (int) ($network['network_attachment_id'] ?? 0) + || (int) ($pool['address_family'] ?? 0) !== $number + || preg_match('/^[a-f0-9]{32}$/D', + (string) ($pool['pool_key'] ?? '')) !== 1 + || (int) ($pool['desired_revision'] ?? 0) < 1 + || (int) ($pool['observed_revision'] ?? 0) + !== (int) $pool['desired_revision'] + || (int) ($pool['available_units'] ?? 0) < 1) { + return false; + } + } + return (int) ($network['network_attachment_id'] ?? 0) > 0 + && (int) ($network['host_id'] ?? 0) === (int) $agent->host_id + && (int) ($network['line_id'] ?? 0) > 0 + && preg_match('/^[a-f0-9]{32}$/D', + (string) ($network['attachment_key'] ?? '')) === 1 + && CloudNetworkSelector::isValid( + $network['network_selector'] ?? null + ) + && (int) ($network['attachment_config_revision'] ?? 0) > 0 + && (int) ($network[ + 'attachment_verified_agent_revision' + ] ?? 0) === (int) $agent->revision; + } + + private static function hasCapacity($policy, array $usage, + array $resources): bool + { + if ((int) ($usage['unknown'] ?? 0) > 0) { + return false; + } + $cpuLimit = max(0, (int) $policy->configured_cpu_cores + - (int) $policy->safety_cpu_cores); + $memoryLimit = max(0, (int) $policy->configured_memory_mib + - (int) $policy->safety_memory_mib); + $diskLimit = max(0, (int) $policy->configured_disk_gib + - (int) $policy->safety_disk_gib); + $maxInstances = (int) $policy->max_instances; + return (int) ($usage['cpu_sum'] ?? PHP_INT_MAX) + + $resources['cpu_cores'] <= $cpuLimit + && (int) ($usage['memory_sum'] ?? PHP_INT_MAX) + + $resources['memory_mib'] <= $memoryLimit + && (int) ($usage['disk_sum'] ?? PHP_INT_MAX) + + $resources['disk_gib'] <= $diskLimit + && ($maxInstances < 1 + || (int) ($usage['instance_count'] ?? PHP_INT_MAX) + 1 + <= $maxInstances); + } + + private static function capacityEvidence($policy, array $usage, + array $resources): array + { + return [ + 'policy_updated_at' => max( + 0, + (int) $policy->capacity_updated_at + ), + 'requested' => [ + 'cpu_cores' => $resources['cpu_cores'], + 'memory_mib' => $resources['memory_mib'], + 'disk_gib' => $resources['disk_gib'], + ], + 'used' => [ + 'instance_count' => (int) $usage['instance_count'], + 'cpu_cores' => (int) $usage['cpu_sum'], + 'memory_mib' => (int) $usage['memory_sum'], + 'disk_gib' => (int) $usage['disk_sum'], + ], + 'limits' => [ + 'instance_count' => (int) $policy->max_instances, + 'cpu_cores' => max(0, + (int) $policy->configured_cpu_cores + - (int) $policy->safety_cpu_cores), + 'memory_mib' => max(0, + (int) $policy->configured_memory_mib + - (int) $policy->safety_memory_mib), + 'disk_gib' => max(0, + (int) $policy->configured_disk_gib + - (int) $policy->safety_disk_gib), + ], + ]; + } + + private static function positiveInt(mixed $value): ?int + { + $normalized = filter_var( + $value, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1, 'max_range' => PHP_INT_MAX]] + ); + return $normalized === false ? null : (int) $normalized; + } + + private static function validObjectKey(string $objectKey): bool + { + return $objectKey !== '' + && strlen($objectKey) <= 512 + && !str_starts_with($objectKey, '/') + && !str_ends_with($objectKey, '/') + && !str_contains($objectKey, '\\') + && preg_match('/[\x00-\x1f\x7f]/D', $objectKey) !== 1 + && !in_array('', explode('/', $objectKey), true); + } +} diff --git a/web/tests/CloudDualStackPlacementAdvisoryTest.php b/web/tests/CloudDualStackPlacementAdvisoryTest.php index f12be858..40d5ecc7 100644 --- a/web/tests/CloudDualStackPlacementAdvisoryTest.php +++ b/web/tests/CloudDualStackPlacementAdvisoryTest.php @@ -39,6 +39,7 @@ $schema->create('cloud_host_network_attachments', static function ( Blueprint $table ): void { $table->increments('id'); + $table->string('attachment_key'); $table->integer('host_id'); $table->integer('line_id'); $table->string('network_selector'); @@ -47,6 +48,9 @@ $schema->create('cloud_host_network_attachments', static function ( $table->string('verification_state'); $table->integer('verified_agent_revision'); $table->integer('last_verified_at'); + $table->integer('config_revision'); + $table->integer('desired_revision'); + $table->integer('observed_revision'); }); $schema->create('cloud_public_ip_pools', static function ( Blueprint $table @@ -102,6 +106,7 @@ Capsule::table('cloud_host_agents')->insert([ Capsule::table('cloud_host_network_attachments')->insert([ [ 'id' => 10, + 'attachment_key' => str_repeat('1', 32), 'host_id' => 1, 'line_id' => 7, 'network_selector' => 'bridge:br0', @@ -110,9 +115,13 @@ Capsule::table('cloud_host_network_attachments')->insert([ 'verification_state' => 'verified', 'verified_agent_revision' => 5, 'last_verified_at' => time(), + 'config_revision' => 3, + 'desired_revision' => 3, + 'observed_revision' => 3, ], [ 'id' => 11, + 'attachment_key' => str_repeat('2', 32), 'host_id' => 1, 'line_id' => 7, 'network_selector' => 'bridge:br1', @@ -121,6 +130,9 @@ Capsule::table('cloud_host_network_attachments')->insert([ 'verification_state' => 'verified', 'verified_agent_revision' => 5, 'last_verified_at' => time(), + 'config_revision' => 4, + 'desired_revision' => 4, + 'observed_revision' => 4, ], ]); $common = [ diff --git a/web/tests/CloudPortableRestoreTargetContractTest.php b/web/tests/CloudPortableRestoreTargetContractTest.php new file mode 100644 index 00000000..0e069b50 --- /dev/null +++ b/web/tests/CloudPortableRestoreTargetContractTest.php @@ -0,0 +1,65 @@ +getMethods(ReflectionMethod::IS_PUBLIC), + static fn (ReflectionMethod $method): bool => + $method->getDeclaringClass()->getName() + === CloudPortableRestoreTargetService::class +)); +$assert(count($public) === 1 && $public[0]->getName() === 'candidates', + 'Portable restore target scheduler exposed more than one interface method.'); +$assert(str_contains($network, 'advisoryDualStackBundleEvidence') + && str_contains($network, '$available[$hostId][$lineId][]') + && str_contains($network, "'network_attachment_id'") + && str_contains($network, "'ipv4' => \$families[4]") + && str_contains($network, "'ipv6' => \$families[6]"), + 'Dual-stack advisory evidence lost host+line or same-attachment identity.'); +$assert(str_contains($service, '->getConnection()->transaction(') + && str_contains($service, 'advisoryDualStackBundleEvidence(') + && !str_contains($service, 'backupRestoreTargets(') + && !str_contains($service, 'advisoryDualStackAvailableHosts(') + && str_contains($service, 'object_identity_sha256') + && str_contains($service, 'source_public_network_sha256') + && str_contains($plan, 'public static function fromEvidence(') + && str_contains($plan, 'self::exactKeys(') + && str_contains($plan, "'address_family'") + && str_contains($plan, "'vpc_inherited'") + && !str_contains($plan, 'public static function freeze('), + 'Plan validation or one-snapshot advisory evidence was weakened.'); +foreach (['->save(', '->insert(', 'insertGetId(', '->update(', + '->delete(', 'lockForUpdate(', 'headObject(', 'presignedGet('] as $write) { + $assert(!str_contains($service, $write), + 'Portable restore target scheduler gained a side effect: ' . $write); +} +$assert(!str_contains($backup, 'CloudPortableRestoreTargetService::') + && str_contains( + $backup, + 'CloudPublicNetworkTransitionGate::assertPortableRestoreReady();' + ), + 'Closed restore flow or existing UI was connected to advisory scheduling.'); + +echo "Portable restore target scheduling contract passed.\n"; diff --git a/web/tests/CloudPortableRestoreTargetServiceTest.php b/web/tests/CloudPortableRestoreTargetServiceTest.php new file mode 100644 index 00000000..3709eeba --- /dev/null +++ b/web/tests/CloudPortableRestoreTargetServiceTest.php @@ -0,0 +1,599 @@ +addConnection([ + 'driver' => 'sqlite', 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); + +$schema->create('cloud_regions', static function (Blueprint $t): void { + $t->increments('id'); $t->string('name'); $t->string('country_code'); + $t->string('status'); +}); +$schema->create('cloud_network_lines', static function (Blueprint $t): void { + $t->increments('id'); $t->integer('region_id'); $t->string('name'); + $t->string('status'); +}); +$schema->create('cloud_resource_pools', static function (Blueprint $t): void { + $t->increments('id'); $t->integer('line_id'); $t->string('name'); + $t->string('status'); +}); +$schema->create('cloud_hosts', static function (Blueprint $t): void { + $t->increments('id'); $t->string('name'); $t->boolean('enabled'); +}); +$schema->create('cloud_host_resource_pool_memberships', + static function (Blueprint $t): void { + $t->increments('id'); $t->integer('host_id'); + $t->integer('resource_pool_id'); $t->string('scheduler_state'); + $t->integer('priority'); $t->integer('revision'); + }); +$schema->create('cloud_host_capacity_policies', + static function (Blueprint $t): void { + $t->integer('host_id')->primary(); + $t->integer('configured_cpu_cores'); + $t->integer('configured_memory_mib'); + $t->integer('configured_disk_gib'); + $t->integer('safety_cpu_cores'); + $t->integer('safety_memory_mib'); + $t->integer('safety_disk_gib'); + $t->integer('max_instances'); $t->integer('updated_at'); + }); +$schema->create('cloud_host_storage_configurations', + static function (Blueprint $t): void { + $t->integer('host_id')->primary(); $t->integer('revision'); + $t->string('state'); + }); +$schema->create('cloud_host_agents', static function (Blueprint $t): void { + $t->integer('host_id')->primary(); $t->boolean('enabled'); + $t->integer('revision'); $t->integer('tested_revision'); + $t->string('last_test_status'); $t->text('network_selectors_json'); + $t->text('public_network_capabilities_json'); + $t->text('portable_restore_contract_json'); + $t->string('portable_restore_contract_sha256', 64); +}); +$schema->create('cloud_host_network_attachments', + static function (Blueprint $t): void { + $t->increments('id'); $t->string('attachment_key'); + $t->integer('host_id'); $t->integer('line_id'); + $t->string('network_selector'); $t->string('state'); + $t->integer('priority'); $t->integer('config_revision'); + $t->integer('verified_agent_revision'); + $t->string('verification_state'); $t->integer('last_verified_at'); + $t->integer('desired_revision'); $t->integer('observed_revision'); + }); +$schema->create('cloud_public_ip_pools', + static function (Blueprint $t): void { + $t->increments('id'); $t->string('pool_key'); + $t->integer('host_id'); $t->integer('network_attachment_id'); + $t->integer('address_family'); $t->string('cidr'); + $t->string('gateway'); $t->boolean('gateway_on_link'); + $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->integer('max_allocations'); + $t->string('state'); $t->integer('priority'); + $t->integer('desired_revision'); $t->integer('observed_revision'); + $t->string('sync_state'); + }); +$schema->create('cloud_public_ips', static function (Blueprint $t): void { + $t->increments('id'); $t->integer('host_id'); + $t->integer('public_ip_pool_id'); $t->integer('address_family'); + $t->string('address'); $t->integer('prefix_length'); $t->string('state'); + $t->integer('reservation_id')->nullable(); + $t->integer('instance_id')->nullable(); + $t->string('operation_id')->nullable(); +}); +$schema->create('cloud_resource_reservations', + static function (Blueprint $t): void { + $t->increments('id'); $t->integer('host_id'); $t->string('state'); + $t->integer('instance_id')->nullable(); $t->integer('cpu_cores'); + $t->integer('memory_mib'); $t->integer('disk_gib'); + }); +$schema->create('cloud_instances', static function (Blueprint $t): void { + $t->increments('id'); $t->integer('host_id'); $t->string('status'); + $t->text('spec_json'); +}); +$schema->create('cloud_instance_snapshots', + static function (Blueprint $t): void { + $t->increments('id'); $t->integer('instance_id'); + $t->integer('host_id'); $t->string('state'); + $t->integer('size_bytes')->nullable(); + }); +$schema->create('cloud_backup_restores', + static function (Blueprint $t): void { $t->increments('id'); }); +$schema->create('cloud_jobs', + static function (Blueprint $t): void { $t->increments('id'); }); +$schema->create('cloud_resource_reservation_ips', + static function (Blueprint $t): void { $t->increments('id'); }); +$schema->create('cloud_instance_backups', + static function (Blueprint $t): void { + $t->increments('id'); $t->string('backup_key'); + $t->integer('source_instance_id'); $t->integer('source_host_id'); + $t->integer('user_id'); $t->string('purpose'); $t->string('state'); + $t->integer('object_size_bytes'); $t->integer('virtual_size_bytes'); + $t->string('sha256', 64); $t->text('spec_json'); + $t->string('object_key'); $t->string('object_etag')->default(''); + $t->string('object_version_id')->default(''); + $t->text('sealed_storage_runtime'); + $t->integer('storage_revision'); + $t->text('source_portable_restore_contract_json'); + $t->string('source_portable_restore_contract_sha256', 64); + }); + +$now = 1800000000; +$compatibility = CloudPortableRestoreCompatibility::fromPayload([ + 'contract' => 1, 'architecture' => 'x86_64', 'machine' => 'q35', + 'firmware' => 'uefi', 'secure_boot' => false, 'disk_format' => 'qcow2', + 'system_disk_only' => true, 'public_network_contract' => 1, + 'vpc_inherited' => false, +]); +Capsule::table('cloud_regions')->insert([ + ['id' => 1, 'name' => 'Hong Kong', 'country_code' => 'HK', + 'status' => 'active'], + ['id' => 2, 'name' => 'Singapore', 'country_code' => 'SG', + 'status' => 'active'], +]); +Capsule::table('cloud_network_lines')->insert([ + ['id' => 10, 'region_id' => 1, 'name' => 'International', + 'status' => 'active'], + ['id' => 20, 'region_id' => 2, 'name' => 'Premium', + 'status' => 'active'], +]); +Capsule::table('cloud_resource_pools')->insert([ + ['id' => 100, 'line_id' => 10, 'name' => 'HKG-A', 'status' => 'active'], + ['id' => 200, 'line_id' => 10, 'name' => 'HKG-B', 'status' => 'active'], + ['id' => 300, 'line_id' => 20, 'name' => 'SG-A', 'status' => 'active'], +]); + +$publicCapabilities = json_encode([ + 'contract' => 1, 'dual_stack_required' => true, + 'project_owned_filter' => true, 'ndp_guard' => true, +], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES); +foreach ([1 => 100, 2 => 200, 3 => 300] as $hostId => $poolId) { + Capsule::table('cloud_hosts')->insert([ + 'id' => $hostId, 'name' => 'host-' . $hostId, 'enabled' => 1, + ]); + Capsule::table('cloud_host_resource_pool_memberships')->insert([ + 'host_id' => $hostId, 'resource_pool_id' => $poolId, + 'scheduler_state' => 'active', 'priority' => $hostId, + 'revision' => 10 + $hostId, + ]); + Capsule::table('cloud_host_capacity_policies')->insert([ + 'host_id' => $hostId, 'configured_cpu_cores' => 16, + 'configured_memory_mib' => 32768, 'configured_disk_gib' => 1000, + 'safety_cpu_cores' => 0, 'safety_memory_mib' => 0, + 'safety_disk_gib' => 0, 'max_instances' => 20, + 'updated_at' => $now + $hostId, + ]); + Capsule::table('cloud_host_storage_configurations')->insert([ + 'host_id' => $hostId, 'revision' => 30 + $hostId, + 'state' => 'applied', + ]); + Capsule::table('cloud_host_agents')->insert([ + 'host_id' => $hostId, 'enabled' => 1, 'revision' => 40 + $hostId, + 'tested_revision' => 40 + $hostId, 'last_test_status' => 'healthy', + 'network_selectors_json' => json_encode( + ['bridge:br' . $hostId], JSON_THROW_ON_ERROR + ), + 'public_network_capabilities_json' => $publicCapabilities, + 'portable_restore_contract_json' => $compatibility->json(), + 'portable_restore_contract_sha256' => $compatibility->sha256(), + ]); +} + +$addNetwork = static function (int $hostId, int $lineId, int $base) use ( + $now +): void { + $attachmentId = $base; + $revision = 40 + $hostId; + Capsule::table('cloud_host_network_attachments')->insert([ + 'id' => $attachmentId, 'attachment_key' => str_pad( + dechex($attachmentId), 32, '0', STR_PAD_LEFT + ), 'host_id' => $hostId, 'line_id' => $lineId, + 'network_selector' => 'bridge:br' . $hostId, 'state' => 'active', + 'priority' => 0, 'config_revision' => 5, + 'verified_agent_revision' => $revision, + 'verification_state' => 'verified', 'last_verified_at' => $now, + 'desired_revision' => 7, 'observed_revision' => 7, + ]); + $ipv4Pool = $base * 10 + 4; + $ipv6Pool = $base * 10 + 6; + $ipv4Base = $hostId === 1 ? '8.8.8' : ($hostId === 2 ? '9.9.9' : '11.11.11'); + $ipv6Base = '2404:c140:156:' . dechex(0x30 + $hostId); + $common = [ + 'host_id' => $hostId, 'network_attachment_id' => $attachmentId, + 'state' => 'active', 'priority' => 0, 'desired_revision' => 9, + 'observed_revision' => 9, 'sync_state' => 'applied', + 'reserved_ips_json' => '[]', + ]; + Capsule::table('cloud_public_ip_pools')->insert([ + $common + [ + 'id' => $ipv4Pool, 'pool_key' => str_pad( + dechex($ipv4Pool), 32, 'a', STR_PAD_LEFT + ), 'address_family' => 4, 'cidr' => $ipv4Base . '.0/24', + 'gateway' => $ipv4Base . '.1', 'gateway_on_link' => 0, + 'guest_prefix_length' => 24, 'dns_servers_json' => '["1.1.1.1"]', + 'allocation_start' => null, 'allocation_end' => null, + 'max_allocations' => 0, + ], + $common + [ + 'id' => $ipv6Pool, 'pool_key' => str_pad( + dechex($ipv6Pool), 32, 'b', STR_PAD_LEFT + ), 'address_family' => 6, 'cidr' => $ipv6Base . '::/64', + 'gateway' => '2404:c140:156::1', 'gateway_on_link' => 1, + 'guest_prefix_length' => 64, + 'dns_servers_json' => '["2606:4700:4700::1111"]', + 'allocation_start' => $ipv6Base . '::10', + 'allocation_end' => $ipv6Base . '::ff', 'max_allocations' => 8, + ], + ]); + Capsule::table('cloud_public_ips')->insert([ + 'host_id' => $hostId, 'public_ip_pool_id' => $ipv4Pool, + 'address_family' => 4, 'address' => $ipv4Base . '.10', + 'prefix_length' => 24, 'state' => 'available', + 'reservation_id' => null, 'instance_id' => null, + 'operation_id' => null, + ]); +}; +$addNetwork(1, 10, 101); +$addNetwork(2, 10, 201); +$addNetwork(3, 20, 301); + +$sourceNetwork = [ + 'contract' => 1, 'network_selector' => 'bridge:source', + 'ipv4' => [ + 'pool_key' => str_repeat('c', 32), 'pool_cidr' => '8.8.4.0/24', + 'address_cidr' => '8.8.4.10/24', 'gateway' => '8.8.4.1', + 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('d', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::20/64', + 'gateway' => '2404:c140:156::1', 'gateway_on_link' => true, + ], + 'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'], +]; +Capsule::table('cloud_instances')->insert([ + 'id' => 1, 'host_id' => 1, 'status' => 'active', + 'spec_json' => json_encode([ + 'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 20, + ], JSON_THROW_ON_ERROR), +]); +Capsule::table('cloud_instance_backups')->insert([ + 'id' => 1, 'backup_key' => str_repeat('e', 32), + 'source_instance_id' => 1, 'source_host_id' => 1, 'user_id' => 9, + 'purpose' => 'portable', 'state' => 'ready', + 'object_size_bytes' => 1024, 'virtual_size_bytes' => 20 * 1073741824, + 'sha256' => str_repeat('f', 64), + 'object_key' => 'vm-backups/' . str_repeat('e', 32) . '/system.qcow2', + 'object_etag' => '"etag-v1"', 'object_version_id' => 'version-v1', + 'sealed_storage_runtime' => 'sealed-runtime-v1', + 'storage_revision' => 7, + 'spec_json' => json_encode([ + 'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 20, + 'bandwidth_mbps' => 1000, 'line_id' => 10, + 'public_network' => $sourceNetwork, + 'vpc_port_id' => 987, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), + 'source_portable_restore_contract_json' => $compatibility->json(), + 'source_portable_restore_contract_sha256' => $compatibility->sha256(), +]); + +$backup = CloudInstanceBackup::findOrFail(1); +$before = []; +foreach (['cloud_backup_restores', 'cloud_jobs', 'cloud_resource_reservations', + 'cloud_resource_reservation_ips'] as $table) { + $before[$table] = Capsule::table($table)->count(); +} +$plans = CloudPortableRestoreTargetService::candidates($backup); +$assert(count($plans) === 3 + && $plans[0] instanceof CloudPortableRestoreTargetPlan + && $plans[1] instanceof CloudPortableRestoreTargetPlan, + 'Same-line same-host and remote-host restore candidates were not returned.'); +$byHost = []; +foreach ($plans as $plan) { + $value = $plan->toArray(); + $byHost[(int) $value['target']['host_id']] = $plan; + $assert(hash_equals(hash('sha256', $plan->json()), $plan->sha256()), + 'Portable restore plan digest is not canonical.'); + $assert($value['public_network']['mode'] === 'fresh_dual_stack' + && $value['vpc_inherited'] === false + && $value['public_network']['ipv4_pool']['available_units'] > 0 + && $value['public_network']['ipv6_pool']['available_units'] > 0, + 'Target plan does not freeze a fresh same-attachment dual-stack bundle.'); + $assert(!str_contains($plan->json(), '8.8.4.10') + && !str_contains($plan->json(), '2404:c140:156:3a::20') + && !str_contains($plan->json(), 'vpc_port_id') + && !str_contains($plan->json(), 'source_url') + && !str_contains($plan->json(), 'credential') + && !str_contains($plan->json(), 'vm-backups/') + && !str_contains($plan->json(), 'etag-v1') + && !str_contains($plan->json(), 'version-v1') + && !str_contains($plan->json(), 'sealed-runtime-v1'), + 'Target plan leaked source identity, VPC, URL or credential data.'); +} +$assert(isset($byHost[1], $byHost[2], $byHost[3]) + && $byHost[1]->toArray()['target']['is_source_host'] === true + && $byHost[2]->toArray()['target']['is_source_host'] === false + && $byHost[3]->toArray()['target']['line_id'] === 20 + && $byHost[3]->toArray()['target']['region_id'] === 2, + 'Same-host or cross-region/cross-line restore evidence was lost.'); +$remote = $byHost[2]->toArray(); +$assert($remote['target']['line_id'] === 10 + && $remote['target']['membership_revision'] === 12 + && $remote['target']['agent_revision'] === 42 + && $remote['target']['storage_revision'] === 32 + && $remote['public_network']['attachment_verified_agent_revision'] === 42 + && $remote['backup']['object_size_bytes'] === 1024 + && $remote['backup']['object_sha256'] === str_repeat('f', 64) + && preg_match('/^[a-f0-9]{64}$/D', + $remote['backup']['object_identity_sha256']) === 1 + && preg_match('/^[a-f0-9]{64}$/D', + $remote['backup']['source_public_network_sha256']) === 1 + && $remote['backup']['source_storage_revision'] === 7 + && $remote['backup']['virtual_size_bytes'] === 20 * 1073741824 + && $remote['resources']['system_disk_virtual_size_bytes'] + === 20 * 1073741824, + 'Target host, storage, membership, network or disk evidence was not frozen.'); +$copy = $byHost[2]->toArray(); +$copy['target']['host_id'] = 999; +$assert($byHost[2]->toArray()['target']['host_id'] === 2, + 'Portable restore target value object was externally mutable.'); +$rejectPlan = static function (array $value, string $message): void { + try { + CloudPortableRestoreTargetPlan::fromEvidence($value); + throw new RuntimeException($message); + } catch (InvalidArgumentException) { + } +}; +$validPlan = $byHost[2]->toArray(); +$invalid = $validPlan; $invalid['extra'] = true; +$rejectPlan($invalid, 'Plan accepted an extra top-level field.'); +$invalid = $validPlan; unset($invalid['backup']['object_sha256']); +$rejectPlan($invalid, 'Plan accepted a missing nested field.'); +$invalid = $validPlan; $invalid['target']['host_id'] = '2'; +$rejectPlan($invalid, 'Plan accepted a string target ID.'); +$invalid = $validPlan; $invalid['backup']['object_identity_sha256'] = 'bad'; +$rejectPlan($invalid, 'Plan accepted a bad object digest.'); +$invalid = $validPlan; +$invalid['backup']['source_contract_sha256'] = str_repeat('a', 64); +$invalid['target']['agent_contract_sha256'] = str_repeat('a', 64); +$rejectPlan($invalid, 'Plan accepted an unsupported matching contract.'); +$invalid = $validPlan; $invalid['public_network']['network_selector'] = 'bad'; +$rejectPlan($invalid, 'Plan accepted a bad network selector.'); +$invalid = $validPlan; $invalid['public_network']['mode'] = 'inherited'; +$rejectPlan($invalid, 'Plan accepted an inherited network mode.'); +$invalid = $validPlan; $invalid['vpc_inherited'] = true; +$rejectPlan($invalid, 'Plan accepted inherited VPC state.'); +$invalid = $validPlan; +$invalid['public_network']['ipv4_pool']['address_family'] = 6; +$rejectPlan($invalid, 'Plan accepted the wrong IPv4 family.'); +$invalid = $validPlan; +$invalid['public_network']['ipv6_pool']['public_ip_pool_id'] = + $invalid['public_network']['ipv4_pool']['public_ip_pool_id']; +$rejectPlan($invalid, 'Plan accepted the same pool for both families.'); +foreach ($before as $table => $count) { + $assert(Capsule::table($table)->count() === $count, + 'Advisory target scheduling wrote to ' . $table . '.'); +} + +$baselinePlanSha = $byHost[2]->sha256(); +$identityMutations = [ + ['object_size_bytes' => 2048], + ['sha256' => str_repeat('a', 64)], + ['virtual_size_bytes' => 19 * 1073741824], + ['storage_revision' => 8], + ['object_key' => 'vm-backups/changed/system.qcow2'], + ['object_etag' => '"etag-v2"'], + ['object_version_id' => 'version-v2'], + ['sealed_storage_runtime' => 'sealed-runtime-v2'], +]; +foreach ($identityMutations as $mutation) { + Capsule::table('cloud_instance_backups')->where('id', 1) + ->update($mutation); + $changed = CloudPortableRestoreTargetService::candidates( + CloudInstanceBackup::findOrFail(1) + ); + $changedHostTwo = array_values(array_filter( + $changed, + static fn (CloudPortableRestoreTargetPlan $plan): bool => + $plan->toArray()['target']['host_id'] === 2 + && $plan->toArray()['target']['resource_pool_id'] === 200 + )); + $assert(count($changedHostTwo) === 1 + && !hash_equals($baselinePlanSha, $changedHostTwo[0]->sha256()), + 'Backup object identity changed without changing target plan identity.'); + Capsule::table('cloud_instance_backups')->where('id', 1)->update([ + 'object_size_bytes' => 1024, + 'sha256' => str_repeat('f', 64), + 'virtual_size_bytes' => 20 * 1073741824, + 'storage_revision' => 7, + 'object_key' => + 'vm-backups/' . str_repeat('e', 32) . '/system.qcow2', + 'object_etag' => '"etag-v1"', + 'object_version_id' => 'version-v1', + 'sealed_storage_runtime' => 'sealed-runtime-v1', + ]); +} +$originalSpec = (string) $backup->spec_json; +$networkChangedSpec = json_decode( + $originalSpec, + true, + 64, + JSON_THROW_ON_ERROR +); +$networkChangedSpec['public_network']['dns_servers'] = ['9.9.9.9']; +Capsule::table('cloud_instance_backups')->where('id', 1)->update([ + 'spec_json' => json_encode( + $networkChangedSpec, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ), +]); +$networkChangedPlans = CloudPortableRestoreTargetService::candidates( + CloudInstanceBackup::findOrFail(1) +); +$networkChangedHostTwo = array_values(array_filter( + $networkChangedPlans, + static fn (CloudPortableRestoreTargetPlan $plan): bool => + $plan->toArray()['target']['host_id'] === 2 + && $plan->toArray()['target']['resource_pool_id'] === 200 +)); +$assert(count($networkChangedHostTwo) === 1 + && !hash_equals($baselinePlanSha, $networkChangedHostTwo[0]->sha256()), + 'Source public-network drift did not change target plan identity.'); +Capsule::table('cloud_instance_backups')->where('id', 1)->update([ + 'spec_json' => $originalSpec, +]); +$invalidBackupRows = [ + ['backup_key' => 'bad'], + ['object_key' => ''], + ['sealed_storage_runtime' => ''], + ['object_etag' => '', 'object_version_id' => 'version-without-etag'], +]; +foreach ($invalidBackupRows as $invalidBackupRow) { + Capsule::table('cloud_instance_backups')->where('id', 1) + ->update($invalidBackupRow); + try { + CloudPortableRestoreTargetService::candidates( + CloudInstanceBackup::findOrFail(1) + ); + throw new RuntimeException('Invalid backup object identity was accepted.'); + } catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'Invalid backup object identity returned the wrong status.'); + } + Capsule::table('cloud_instance_backups')->where('id', 1)->update([ + 'backup_key' => str_repeat('e', 32), + 'object_key' => + 'vm-backups/' . str_repeat('e', 32) . '/system.qcow2', + 'sealed_storage_runtime' => 'sealed-runtime-v1', + 'object_etag' => '"etag-v1"', + 'object_version_id' => 'version-v1', + ]); +} +$backup = CloudInstanceBackup::findOrFail(1); + +Capsule::table('cloud_host_agents')->where('host_id', 2)->update([ + 'portable_restore_contract_json' => '{}', + 'portable_restore_contract_sha256' => '', +]); +$assert(count(CloudPortableRestoreTargetService::candidates($backup)) === 2, + 'A target without the exact tested portable contract remained eligible.'); +Capsule::table('cloud_host_agents')->where('host_id', 2)->update([ + 'portable_restore_contract_json' => $compatibility->json(), + 'portable_restore_contract_sha256' => $compatibility->sha256(), +]); + +Capsule::table('cloud_host_network_attachments')->insert([ + 'id' => 202, 'attachment_key' => str_repeat('2', 32), + 'host_id' => 2, 'line_id' => 20, 'network_selector' => 'bridge:br20', + 'state' => 'active', 'priority' => 2, 'config_revision' => 1, + 'verified_agent_revision' => 42, 'verification_state' => 'verified', + 'last_verified_at' => $now, 'desired_revision' => 1, + 'observed_revision' => 1, +]); +Capsule::table('cloud_host_agents')->where('host_id', 2)->update([ + 'network_selectors_json' => '["bridge:br2","bridge:br20"]', +]); +Capsule::table('cloud_public_ip_pools')->where('id', 2016)->update([ + 'network_attachment_id' => 202, +]); +Capsule::table('cloud_public_ip_pools')->insert([ + 'id' => 2024, 'pool_key' => str_repeat('2', 32), 'host_id' => 2, + 'network_attachment_id' => 202, 'address_family' => 4, + 'cidr' => '12.12.12.0/24', 'gateway' => '12.12.12.1', + 'gateway_on_link' => 0, 'guest_prefix_length' => 24, + 'dns_servers_json' => '["1.1.1.1"]', 'reserved_ips_json' => '[]', + 'allocation_start' => null, 'allocation_end' => null, + 'max_allocations' => 0, 'state' => 'active', 'priority' => 0, + 'desired_revision' => 1, 'observed_revision' => 1, + 'sync_state' => 'applied', +]); +Capsule::table('cloud_public_ips')->insert([ + 'host_id' => 2, 'public_ip_pool_id' => 2024, 'address_family' => 4, + 'address' => '12.12.12.10', 'prefix_length' => 24, + 'state' => 'available', 'reservation_id' => null, + 'instance_id' => null, 'operation_id' => null, +]); +Capsule::table('cloud_host_resource_pool_memberships')->insert([ + 'host_id' => 2, 'resource_pool_id' => 300, + 'scheduler_state' => 'active', 'priority' => 5, 'revision' => 15, +]); +$lineAware = CloudPortableRestoreTargetService::candidates($backup); +$hostTwoTargets = array_values(array_filter( + $lineAware, + static fn (CloudPortableRestoreTargetPlan $plan): bool => + $plan->toArray()['target']['host_id'] === 2 +)); +$assert(count($hostTwoTargets) === 1 + && $hostTwoTargets[0]->toArray()['target']['line_id'] === 20 + && $hostTwoTargets[0]->toArray()['public_network'][ + 'network_attachment_id' + ] === 202, + 'A line-A single stack target borrowed line-B dual-stack evidence.'); +Capsule::table('cloud_public_ip_pools')->where('id', 2016)->update([ + 'network_attachment_id' => 201, +]); +Capsule::table('cloud_public_ips')->where('public_ip_pool_id', 2024)->delete(); +Capsule::table('cloud_public_ip_pools')->where('id', 2024)->delete(); +Capsule::table('cloud_host_resource_pool_memberships') + ->where('host_id', 2)->where('resource_pool_id', 300)->delete(); +Capsule::table('cloud_host_network_attachments')->where('id', 202)->delete(); +Capsule::table('cloud_host_agents')->where('host_id', 2)->update([ + 'network_selectors_json' => '["bridge:br2"]', +]); + +Capsule::table('cloud_resource_reservations')->insert([ + 'host_id' => 2, 'state' => 'held', 'instance_id' => null, + 'cpu_cores' => 15, 'memory_mib' => 1024, 'disk_gib' => 1, +]); +$assert(count(CloudPortableRestoreTargetService::candidates($backup)) === 2, + 'A target without enough current CPU capacity remained eligible.'); +Capsule::table('cloud_resource_reservations')->truncate(); +Capsule::table('cloud_host_storage_configurations')->where('host_id', 2) + ->update(['revision' => 0]); +$assert(count(CloudPortableRestoreTargetService::candidates($backup)) === 2, + 'A target without an applied positive storage revision remained eligible.'); +Capsule::table('cloud_host_storage_configurations')->where('host_id', 2) + ->update(['revision' => 32]); + +Capsule::table('cloud_instance_backups')->where('id', 1)->update([ + 'virtual_size_bytes' => 21 * 1073741824, +]); +try { + CloudPortableRestoreTargetService::candidates( + CloudInstanceBackup::findOrFail(1) + ); + throw new RuntimeException('Oversized frozen system disk was accepted.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'Oversized system disk returned the wrong error status.'); +} + +try { + CloudPublicNetworkTransitionGate::assertPortableRestoreReady(); + throw new RuntimeException('Portable restore dispatch gate opened.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'Closed portable restore gate returned the wrong status.'); +} + +echo "Portable restore target scheduling tests passed.\n";