From 2d2da15997272062d248448abc3f46c12c74e5c8 Mon Sep 17 00:00:00 2001 From: codex Date: Tue, 3 Nov 2026 22:24:22 +0800 Subject: [PATCH] feat: freeze portable restore request inputs --- .../CloudPortableRestoreBackupEvidence.php | 37 ++++- .../CloudPortableRestoreRequestInput.php | 53 +++++++ .../Cloud/CloudPortableRestoreTargetPlan.php | 3 + .../CloudPortableRestoreTargetService.php | 142 ++---------------- ...CloudPortableRestoreTargetContractTest.php | 10 +- .../CloudPortableRestoreTargetServiceTest.php | 113 ++++++++++++++ 6 files changed, 221 insertions(+), 137 deletions(-) create mode 100644 web/app/Services/Cloud/CloudPortableRestoreRequestInput.php diff --git a/web/app/Services/Cloud/CloudPortableRestoreBackupEvidence.php b/web/app/Services/Cloud/CloudPortableRestoreBackupEvidence.php index 2743dc81..7c47d0c4 100644 --- a/web/app/Services/Cloud/CloudPortableRestoreBackupEvidence.php +++ b/web/app/Services/Cloud/CloudPortableRestoreBackupEvidence.php @@ -12,7 +12,8 @@ final class CloudPortableRestoreBackupEvidence private function __construct( private readonly CloudPortableRestoreCompatibility $compatibility, private readonly array $backup, - private readonly array $resources + private readonly array $resources, + private readonly CloudPortableRestoreRequestInput $requestInput ) { } @@ -60,6 +61,13 @@ final class CloudPortableRestoreBackupEvidence } catch (\Throwable) { throw new CloudError('备份缺少可信的冻结双栈网络快照', 409); } + $requestInput = CloudPortableRestoreRequestInput::fromSpec($spec); + $canonicalSpec = self::canonical($spec); + $sourceSpecSha256 = hash('sha256', json_encode( + $canonicalSpec, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS + )); $lineId = self::positiveInt($spec['line_id'] ?? null); $resources = [ 'cpu_cores' => self::positiveInt( @@ -100,6 +108,8 @@ final class CloudPortableRestoreBackupEvidence 'object_sha256' => (string) $backup->sha256, 'object_identity_sha256' => $objectIdentitySha256, 'source_contract_sha256' => $contract->sha256(), + 'source_spec_sha256' => $sourceSpecSha256, + 'restore_request_sha256' => $requestInput->sha256(), 'source_public_network_sha256' => $sourceNetwork->fingerprint(), 'source_host_id' => (int) $backup->source_host_id, @@ -112,7 +122,7 @@ final class CloudPortableRestoreBackupEvidence 'disk_gib' => $resources['disk_gib'], 'bandwidth_mbps' => $resources['bandwidth_mbps'], 'system_disk_virtual_size_bytes' => $virtualSize, - ]); + ], $requestInput); } public function compatibility(): CloudPortableRestoreCompatibility @@ -139,6 +149,29 @@ final class CloudPortableRestoreBackupEvidence ]; } + public function requestInput(): CloudPortableRestoreRequestInput + { + return $this->requestInput; + } + + 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 positiveInt(mixed $value): ?int { $normalized = filter_var( diff --git a/web/app/Services/Cloud/CloudPortableRestoreRequestInput.php b/web/app/Services/Cloud/CloudPortableRestoreRequestInput.php new file mode 100644 index 00000000..d1b2b5e2 --- /dev/null +++ b/web/app/Services/Cloud/CloudPortableRestoreRequestInput.php @@ -0,0 +1,53 @@ +value = $value; + $this->json = json_encode( + $value, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS + ); + $this->sha256 = hash('sha256', $this->json); + } + + public static function fromSpec(array $spec): self + { + $fix = $spec['debian_12_network_fix'] ?? null; + if (!is_bool($fix)) { + throw new CloudError('备份缺少可信的 Debian 网络修正快照', 409); + } + $policy = CloudPlatformTestNetworkPolicy::assertSnapshot( + $spec['platform_network_policy_snapshot'] ?? null + ); + return new self([ + 'contract' => 1, + 'debian_12_network_fix' => $fix, + 'platform_network_policy_snapshot' => $policy, + ]); + } + + public function toArray(): array + { + return $this->value; + } + + public function json(): string + { + return $this->json; + } + + public function sha256(): string + { + return $this->sha256; + } +} diff --git a/web/app/Services/Cloud/CloudPortableRestoreTargetPlan.php b/web/app/Services/Cloud/CloudPortableRestoreTargetPlan.php index 478ad805..9f4927c2 100644 --- a/web/app/Services/Cloud/CloudPortableRestoreTargetPlan.php +++ b/web/app/Services/Cloud/CloudPortableRestoreTargetPlan.php @@ -44,6 +44,7 @@ final class CloudPortableRestoreTargetPlan $backup = self::object($plan['backup'] ?? null, [ 'id', 'backup_key', 'object_size_bytes', 'object_sha256', 'object_identity_sha256', 'source_contract_sha256', + 'source_spec_sha256', 'restore_request_sha256', 'source_public_network_sha256', 'source_host_id', 'source_line_id', 'source_storage_revision', 'virtual_size_bytes', @@ -54,6 +55,8 @@ final class CloudPortableRestoreTargetPlan self::hex($backup['object_sha256'], 64); self::hex($backup['object_identity_sha256'], 64); self::hex($backup['source_contract_sha256'], 64); + self::hex($backup['source_spec_sha256'], 64); + self::hex($backup['restore_request_sha256'], 64); self::hex($backup['source_public_network_sha256'], 64); self::positiveInt($backup['source_host_id']); self::positiveInt($backup['source_line_id']); diff --git a/web/app/Services/Cloud/CloudPortableRestoreTargetService.php b/web/app/Services/Cloud/CloudPortableRestoreTargetService.php index d7dcf2b9..bad770ea 100644 --- a/web/app/Services/Cloud/CloudPortableRestoreTargetService.php +++ b/web/app/Services/Cloud/CloudPortableRestoreTargetService.php @@ -15,8 +15,6 @@ use App\Models\CloudInstanceBackup; */ final class CloudPortableRestoreTargetService { - private const GIB = 1073741824; - /** @return list */ public static function candidates( CloudInstanceBackup $backup @@ -42,9 +40,14 @@ final class CloudPortableRestoreTargetService private static function candidatesFromSnapshot( CloudInstanceBackup $backup ): array { - [$sourceContract, $sourceLineId, $resources, $virtualSize, - $sourceNetworkSha256, $objectIdentitySha256] = - self::backupContext($backup); + $backupEvidence = CloudPortableRestoreBackupEvidence::fromBackup( + $backup + ); + $sourceContract = $backupEvidence->compatibility(); + $backupIdentity = $backupEvidence->backup(); + $resources = $backupEvidence->resources(); + $sourceLineId = $backupIdentity['source_line_id']; + $virtualSize = $backupIdentity['virtual_size_bytes']; $rows = self::candidateRows(); if ($rows->isEmpty()) { return []; @@ -76,22 +79,7 @@ final class CloudPortableRestoreTargetService } $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, - ], + 'backup' => $backupIdentity, 'target' => [ 'host_id' => $hostId, 'host_name' => (string) $row->name, @@ -159,98 +147,6 @@ final class CloudPortableRestoreTargetService 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( @@ -433,24 +329,4 @@ final class CloudPortableRestoreTargetService ]; } - 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/CloudPortableRestoreTargetContractTest.php b/web/tests/CloudPortableRestoreTargetContractTest.php index 0e069b50..68fac93b 100644 --- a/web/tests/CloudPortableRestoreTargetContractTest.php +++ b/web/tests/CloudPortableRestoreTargetContractTest.php @@ -14,6 +14,9 @@ $network = (string) file_get_contents( $plan = (string) file_get_contents( $root . '/app/Services/Cloud/CloudPortableRestoreTargetPlan.php' ); +$evidence = (string) file_get_contents( + $root . '/app/Services/Cloud/CloudPortableRestoreBackupEvidence.php' +); $backup = (string) file_get_contents( $root . '/app/Services/Cloud/CloudBackupService.php' ); @@ -42,8 +45,11 @@ $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($service, 'CloudPortableRestoreBackupEvidence::fromBackup(') + && str_contains($evidence, 'object_identity_sha256') + && str_contains($evidence, 'source_public_network_sha256') + && str_contains($evidence, 'source_spec_sha256') + && str_contains($evidence, 'restore_request_sha256') && str_contains($plan, 'public static function fromEvidence(') && str_contains($plan, 'self::exactKeys(') && str_contains($plan, "'address_family'") diff --git a/web/tests/CloudPortableRestoreTargetServiceTest.php b/web/tests/CloudPortableRestoreTargetServiceTest.php index 3709eeba..fc538728 100644 --- a/web/tests/CloudPortableRestoreTargetServiceTest.php +++ b/web/tests/CloudPortableRestoreTargetServiceTest.php @@ -4,6 +4,7 @@ require dirname(__DIR__) . '/vendor/autoload.php'; use App\Models\CloudInstanceBackup; use App\Services\Cloud\CloudError; +use App\Services\Cloud\CloudPlatformTestNetworkPolicy; use App\Services\Cloud\CloudPortableRestoreCompatibility; use App\Services\Cloud\CloudPortableRestoreTargetPlan; use App\Services\Cloud\CloudPortableRestoreTargetService; @@ -136,8 +137,39 @@ $schema->create('cloud_instance_backups', $t->text('source_portable_restore_contract_json'); $t->string('source_portable_restore_contract_sha256', 64); }); +$schema->create('cloud_platform_test_policy_state', + static function (Blueprint $t): void { + $t->integer('id')->primary(); + $t->integer('revision'); + $t->integer('updated_by')->nullable(); + $t->integer('updated_at'); + }); +$schema->create('cloud_platform_test_policy_rules', + static function (Blueprint $t): void { + $t->increments('id'); + $t->string('rule_key', 32)->unique(); + $t->string('service', 120); + $t->string('protocol', 8); + $t->integer('port_from'); + $t->integer('port_to'); + $t->string('direction', 8); + $t->string('reason', 500); + $t->integer('created_by'); + $t->integer('updated_by'); + $t->integer('deleted_by')->nullable(); + $t->integer('deleted_at')->nullable(); + $t->integer('created_at'); + $t->integer('updated_at'); + }); $now = 1800000000; +Capsule::table('cloud_platform_test_policy_state')->insert([ + 'id' => 1, + 'revision' => 0, + 'updated_by' => null, + 'updated_at' => $now, +]); +$platformPolicy = CloudPlatformTestNetworkPolicy::snapshotForProvisioning(); $compatibility = CloudPortableRestoreCompatibility::fromPayload([ 'contract' => 1, 'architecture' => 'x86_64', 'machine' => 'q35', 'firmware' => 'uefi', 'secure_boot' => false, 'disk_format' => 'qcow2', @@ -291,6 +323,8 @@ Capsule::table('cloud_instance_backups')->insert([ 'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 20, 'bandwidth_mbps' => 1000, 'line_id' => 10, 'public_network' => $sourceNetwork, + 'platform_network_policy_snapshot' => $platformPolicy, + 'debian_12_network_fix' => false, 'vpc_port_id' => 987, ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), 'source_portable_restore_contract_json' => $compatibility->json(), @@ -348,6 +382,10 @@ $assert($remote['target']['line_id'] === 10 $remote['backup']['object_identity_sha256']) === 1 && preg_match('/^[a-f0-9]{64}$/D', $remote['backup']['source_public_network_sha256']) === 1 + && preg_match('/^[a-f0-9]{64}$/D', + $remote['backup']['source_spec_sha256']) === 1 + && preg_match('/^[a-f0-9]{64}$/D', + $remote['backup']['restore_request_sha256']) === 1 && $remote['backup']['source_storage_revision'] === 7 && $remote['backup']['virtual_size_bytes'] === 20 * 1073741824 && $remote['resources']['system_disk_virtual_size_bytes'] @@ -462,6 +500,81 @@ $assert(count($networkChangedHostTwo) === 1 Capsule::table('cloud_instance_backups')->where('id', 1)->update([ 'spec_json' => $originalSpec, ]); +$requestChangedSpec = json_decode( + $originalSpec, + true, + 64, + JSON_THROW_ON_ERROR +); +$requestChangedSpec['debian_12_network_fix'] = true; +Capsule::table('cloud_instance_backups')->where('id', 1)->update([ + 'spec_json' => json_encode( + $requestChangedSpec, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ), +]); +$requestChangedPlans = CloudPortableRestoreTargetService::candidates( + CloudInstanceBackup::findOrFail(1) +); +$requestChangedHostTwo = array_values(array_filter( + $requestChangedPlans, + static fn (CloudPortableRestoreTargetPlan $plan): bool => + $plan->toArray()['target']['host_id'] === 2 + && $plan->toArray()['target']['resource_pool_id'] === 200 +)); +$assert(count($requestChangedHostTwo) === 1 + && !hash_equals($baselinePlanSha, $requestChangedHostTwo[0]->sha256()) + && !hash_equals( + (string) $remote['backup']['restore_request_sha256'], + (string) $requestChangedHostTwo[0] + ->toArray()['backup']['restore_request_sha256'] + ), + 'Restore request input drift did not change target plan identity.'); +unset($requestChangedSpec['debian_12_network_fix']); +Capsule::table('cloud_instance_backups')->where('id', 1)->update([ + 'spec_json' => json_encode( + $requestChangedSpec, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ), +]); +try { + CloudPortableRestoreTargetService::candidates( + CloudInstanceBackup::findOrFail(1) + ); + throw new RuntimeException('Backup without restore request input was accepted.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'Invalid restore request input returned the wrong status.'); +} +Capsule::table('cloud_instance_backups')->where('id', 1)->update([ + 'spec_json' => $originalSpec, +]); +$invalidPolicySpec = json_decode( + $originalSpec, + true, + 64, + JSON_THROW_ON_ERROR +); +$invalidPolicySpec['platform_network_policy_snapshot']['digest'] = + str_repeat('0', 64); +Capsule::table('cloud_instance_backups')->where('id', 1)->update([ + 'spec_json' => json_encode( + $invalidPolicySpec, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ), +]); +try { + CloudPortableRestoreTargetService::candidates( + CloudInstanceBackup::findOrFail(1) + ); + throw new RuntimeException('Backup with forged policy digest was accepted.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'Forged restore policy returned the wrong status.'); +} +Capsule::table('cloud_instance_backups')->where('id', 1)->update([ + 'spec_json' => $originalSpec, +]); $invalidBackupRows = [ ['backup_key' => 'bad'], ['object_key' => ''],