You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/CloudPortableRestoreTargetS...

918 lines
39 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudInstanceBackup;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudBackupService;
use App\Services\Cloud\CloudBackupStorageAuthority;
use App\Services\Cloud\CloudPlatformTestNetworkPolicy;
use App\Services\Cloud\CloudPortableRestoreCompatibility;
use App\Services\Cloud\CloudPortableRestoreTargetPlan;
use App\Services\Cloud\CloudPortableRestoreTargetService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$capsule = new Capsule();
$capsule->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('storage_artifact_id')->nullable();
$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);
});
$schema->create('cloud_storage_artifacts',
static function (Blueprint $t): void {
$t->increments('id'); $t->string('artifact_key');
$t->string('kind'); $t->integer('maximum_size_bytes');
$t->integer('size_bytes'); $t->string('sha256', 64);
$t->string('durability_policy'); $t->integer('desired_copies');
$t->integer('required_copies'); $t->string('state');
$t->string('last_operation_id')->nullable();
$t->integer('verified_at'); $t->integer('created_at');
$t->integer('updated_at');
});
$schema->create('cloud_storage_publications',
static function (Blueprint $t): void {
$t->increments('id'); $t->integer('artifact_id');
$t->integer('backup_id')->nullable(); $t->string('state');
$t->integer('created_at'); $t->integer('updated_at');
});
$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',
'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,
'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(),
'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
&& 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']
=== 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.');
$canonicalize = static function (array $value) use (&$canonicalize): array {
if (array_is_list($value)) {
return array_map(
static fn ($item) => is_array($item)
? $canonicalize($item) : $item,
$value
);
}
ksort($value, SORT_STRING);
foreach ($value as $key => $item) {
if (is_array($item)) {
$value[$key] = $canonicalize($item);
}
}
return $value;
};
$historical = $validPlan;
$historical['backup']['source_contract_sha256'] = str_repeat('a', 64);
$historical['target']['agent_contract_sha256'] = str_repeat('a', 64);
$historicalJson = json_encode(
$canonicalize($historical),
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
);
$historicalSha = hash('sha256', $historicalJson);
$assert(CloudPortableRestoreTargetPlan::fromHistoricalStored(
$historicalJson,
$historicalSha
)->sha256() === $historicalSha,
'Historical terminal plan still depended on the current runtime contract.');
try {
CloudPortableRestoreTargetPlan::fromStored(
$historicalJson,
$historicalSha
);
throw new RuntimeException('Current admission accepted a historical contract.');
} catch (InvalidArgumentException) {
}
$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();
$expectedLegacyBusinessIdentity = hash('sha256', json_encode([
'id' => (int) $backup->id,
'backup_key' => (string) $backup->backup_key,
'source_instance_id' => (int) $backup->source_instance_id,
'source_host_id' => (int) $backup->source_host_id,
'user_id' => (int) $backup->user_id,
'source_uuid' => (string) $backup->source_uuid,
'purpose' => (string) $backup->purpose,
'source' => (string) $backup->source,
'subscription_id' => (int) $backup->subscription_id,
'object_key' => (string) $backup->object_key,
'object_size_bytes' => (int) $backup->object_size_bytes,
'virtual_size_bytes' => (int) $backup->virtual_size_bytes,
'sha256' => (string) $backup->sha256,
'storage_revision' => (int) $backup->storage_revision,
'source_portable_restore_contract_json' =>
(string) $backup->source_portable_restore_contract_json,
'source_portable_restore_contract_sha256' =>
(string) $backup->source_portable_restore_contract_sha256,
'storage_runtime_sha256' => hash(
'sha256',
(string) $backup->sealed_storage_runtime
),
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES));
$assert(hash_equals(
$expectedLegacyBusinessIdentity,
CloudBackupStorageAuthority::backingBackupIdentity($backup)
), 'Legacy backup business identity changed during artifact integration.');
$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',
]);
}
foreach ([81, 82] as $artifactId) {
Capsule::table('cloud_storage_artifacts')->insert([
'id' => $artifactId,
'artifact_key' => str_pad(dechex($artifactId), 32, '0', STR_PAD_LEFT),
'kind' => 'backup',
'maximum_size_bytes' => 2048,
'size_bytes' => 1024,
'sha256' => str_repeat('f', 64),
'durability_policy' => 'mirror_async_2',
'desired_copies' => 2,
'required_copies' => 1,
'state' => 'available',
'last_operation_id' => str_pad(
dechex($artifactId + 100),
32,
'0',
STR_PAD_LEFT
),
'verified_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
Capsule::table('cloud_storage_publications')->insert([
'artifact_id' => $artifactId,
'backup_id' => 1,
'state' => 'ready_to_finalize',
'created_at' => $now,
'updated_at' => $now,
]);
}
Capsule::table('cloud_instance_backups')->where('id', 1)->update([
'storage_artifact_id' => 81,
'sealed_storage_runtime' => '',
'storage_revision' => 0,
]);
$portableOwnerGuardCounts = [];
foreach (['cloud_backup_restores', 'cloud_jobs',
'cloud_resource_reservations', 'cloud_resource_reservation_ips']
as $table) {
$portableOwnerGuardCounts[$table] = Capsule::table($table)->count();
}
Capsule::table('cloud_storage_publications')->where('artifact_id', 81)
->update(['backup_id' => 999]);
try {
CloudPortableRestoreTargetService::candidates(
CloudInstanceBackup::findOrFail(1)
);
throw new RuntimeException(
'Portable restore accepted a cross-backup artifact publication.'
);
} catch (CloudError $error) {
$assert($error->httpStatus === 409,
'Cross-backup artifact publication returned the wrong status.');
}
foreach ($portableOwnerGuardCounts as $table => $count) {
$assert(Capsule::table($table)->count() === $count,
'Cross-backup artifact publication authorized state in ' . $table);
}
$assert(Capsule::table('cloud_storage_artifacts')->where('id', 81)
->value('state') === 'available'
&& Capsule::table('cloud_storage_publications')
->where('artifact_id', 81)->value('state') === 'ready_to_finalize'
&& (int) Capsule::table('cloud_storage_publications')
->where('artifact_id', 81)->value('backup_id') === 999,
'Rejected cross-backup artifact publication changed storage state.');
Capsule::table('cloud_storage_publications')->where('artifact_id', 81)
->update(['backup_id' => 1]);
$artifactPlans = CloudPortableRestoreTargetService::candidates(
CloudInstanceBackup::findOrFail(1)
);
$artifactHostTwo = array_values(array_filter(
$artifactPlans,
static fn (CloudPortableRestoreTargetPlan $plan): bool =>
$plan->toArray()['target']['host_id'] === 2
&& $plan->toArray()['target']['resource_pool_id'] === 200
));
$assert(count($artifactHostTwo) === 1
&& $artifactHostTwo[0]->toArray()['backup']['source_storage_revision'] === 0
&& !hash_equals($baselinePlanSha, $artifactHostTwo[0]->sha256()),
'Artifact-backed backup did not produce portable restore evidence.');
$artifactIdentity = $artifactHostTwo[0]
->toArray()['backup']['object_identity_sha256'];
Capsule::table('cloud_instance_backups')->where('id', 1)->update([
'storage_artifact_id' => 82,
]);
$secondArtifactPlans = CloudPortableRestoreTargetService::candidates(
CloudInstanceBackup::findOrFail(1)
);
$secondArtifactHostTwo = array_values(array_filter(
$secondArtifactPlans,
static fn (CloudPortableRestoreTargetPlan $plan): bool =>
$plan->toArray()['target']['host_id'] === 2
&& $plan->toArray()['target']['resource_pool_id'] === 200
));
$assert(count($secondArtifactHostTwo) === 1
&& !hash_equals(
$artifactIdentity,
$secondArtifactHostTwo[0]
->toArray()['backup']['object_identity_sha256']
), 'Portable restore evidence did not bind the storage artifact ID.');
Capsule::table('cloud_storage_artifacts')->where('id', 82)->update([
'size_bytes' => 2048,
]);
try {
CloudPortableRestoreTargetService::candidates(
CloudInstanceBackup::findOrFail(1)
);
throw new RuntimeException(
'Portable restore accepted mismatched artifact size evidence.'
);
} catch (CloudError $error) {
$assert($error->httpStatus === 409,
'Mismatched artifact evidence returned the wrong status.');
}
Capsule::table('cloud_instance_backups')->where('id', 1)->update([
'storage_artifact_id' => null,
'sealed_storage_runtime' => 'sealed-runtime-v1',
'storage_revision' => 7,
]);
$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,
]);
$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.');
}
$projection = (new ReflectionMethod(
CloudBackupService::class,
'restoreTargetProjection'
))->invoke(null, CloudInstanceBackup::findOrFail(1));
$assert(($projection['targets'] ?? null) === []
&& is_string($projection['reason'] ?? null)
&& $projection['reason'] !== '',
'One invalid ready backup made its management projection unavailable.');
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' => ''],
['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.');
}
echo "Portable restore target scheduling tests passed.\n";