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/CloudVpcControlPlaneContrac...

213 lines
13 KiB
PHP

<?php
// Source contract remains useful on developer checkouts that do not have a
// PHP CLI or a configured database. The runtime integration suite can bind
// these same models to MariaDB/SQLite separately.
$root = dirname(__DIR__);
$read = static fn (string $path): string => (string) file_get_contents($root . '/' . $path);
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$schema = $read('sql/cloud.sql');
$service = $read('app/Services/Cloud/CloudVpcService.php');
$regionFabricModel = $read('app/Models/CloudRegionFabric.php');
$adminResource = $read('app/Services/Cloud/CloudAdminResourceService.php');
$adminResourceController = $read('app/Controllers/CloudAdminResourceController.php');
$controller = $read('app/Controllers/CloudVpcController.php');
$routes = $read('config/routes_cloud.php');
$middleware = $read('app/Middleware/CloudApi.php');
$engineClient = $read('app/Services/Cloud/CloudEngineClient.php');
$accountDeletion = $read('app/Services/UserDataDeletionService.php');
$jobService = $read('app/Services/Cloud/CloudJobService.php');
$orderService = $read('app/Services/Cloud/CloudOrderService.php');
$workerService = $read('app/Services/Cloud/CloudWorkerService.php');
$vpcWorkerService = $read('app/Services/Cloud/CloudVpcWorkerService.php');
foreach ([
'cloud_region_fabrics',
'cloud_vpcs', 'cloud_vpc_subnets', 'cloud_vpc_private_ips', 'cloud_vpc_members',
'cloud_vpc_routes', 'cloud_vpc_acl_rules',
'cloud_vpc_host_deployments', 'cloud_vpc_operations',
] as $table) {
$assert(str_contains($schema,
'CREATE TABLE IF NOT EXISTS ' . $table . ' ('),
'VPC schema lost ' . $table . '.');
}
$assert(str_contains($schema, 'UNIQUE KEY cloud_vpc_member_instance_global (instance_id)')
&& str_contains($schema, 'UNIQUE KEY cloud_vpc_private_ip_address (vpc_id, private_ip)')
&& str_contains($schema, 'UNIQUE KEY cloud_vpc_member_private_ip (private_ip_id)')
&& str_contains($schema, 'UNIQUE KEY cloud_vpc_operation_idempotency (vpc_id, idempotency_key)')
&& str_contains($schema, 'source_int BIGINT UNSIGNED NOT NULL')
&& str_contains($schema, 'destination_broadcast_int BIGINT UNSIGNED NOT NULL')
&& str_contains($schema, 'desired_digest CHAR(64)')
&& str_contains($schema, 'observed_digest CHAR(64)'),
'VPC schema lost the single-NIC, idempotency or revision digest guards.');
$assert(str_contains($service, 'lockForUpdate()')
&& str_contains($service, 'desired_revision')
&& str_contains($service, 'observed_revision')
&& str_contains($service, 'CloudVpcOperation')
&& str_contains($service, 'CloudVpcPrivateIp')
&& str_contains($service, 'lockedPrivateIpForMember')
&& str_contains($service, 'CloudVpcHostDeployment')
&& str_contains($service, 'CloudEngineClient())->vpc')
&& str_contains($service, 'canonicalJson')
&& str_contains($service, 'next_stage_allowed'),
'VPC service lost independent locking, desired/observed revisions or Fabric gate.');
$assert(str_contains($service, 'CloudRegionFabric')
&& str_contains($service, 'fabric_region')
&& str_contains($adminResource, 'saveRegionFabric')
&& str_contains($adminResource, 'fabricStatus')
&& str_contains($adminResource, 'next_stage_allowed')
&& str_contains($adminResourceController, 'regionFabric')
&& str_contains($regionFabricModel, 'cloud_region_fabrics'),
'VPC creation must pin an explicit platform-owned region/Fabric mapping and verify its active engine gate.');
$assert(str_contains($service, "'status' => 'superseded'")
&& str_contains($service, 'where(\'lease_token\', $leaseToken)')
&& str_contains($service, "where('status', 'running')"),
'VPC operation lease/supersede guards are incomplete.');
$assert(str_contains($service, 'waiting_observed')
&& str_contains($service, 'allowDeferredRetry')
&& str_contains($service, 'vpc_no_members')
&& str_contains($service, "terminalGate ? 'failed'")
&& str_contains($service, "result['operation_id']")
&& str_contains($service, "result['desired_digest']")
&& str_contains($service, "existing->subnet_id")
&& str_contains($service, 'hasBlockingMembership'),
'VPC deferred observation, response identity or membership gates are incomplete.');
$assert(str_contains($service, 'canViewInfrastructure')
&& str_contains($service, 'publicRoot($vpc, $includeHostDetails)')
&& str_contains($service, 'digestMatches($desiredDigest, $observedDigest)'),
'VPC public projection or usable digest gate leaks infrastructure or is incomplete.');
$assert(str_contains($service, "'observed_revision' => " . '$revision')
&& str_contains($service, 'CloudVpcAclRule::class')
&& str_contains($service, 'whereNotIn(\'state\', [\'deleted\'])'),
'VPC child observed revisions are not advanced with the all-host gate.');
$assert(str_contains($service, 'deletedByDestination')
&& str_contains($service, 'deletedByPriority')
&& str_contains($service, 'CloudVpcRoute::class, CloudVpcAclRule::class')
&& str_contains($service, '$allLiveHostsExact')
&& str_contains($service, "where('desired_revision', \$revision)")
&& str_contains($service, 'individually matched above'),
'VPC route/ACL tombstones must close only after exact readback and remain safely reusable.');
$terminalProofStart = strpos($service, '$noDataPlaneTerminalProof');
$terminalProofEnd = $terminalProofStart === false ? false
: strpos($service, '// Routes and ACLs are part of the exact host dataplane digest.',
$terminalProofStart);
$terminalProofBlock = ($terminalProofStart !== false && $terminalProofEnd !== false)
? substr($service, $terminalProofStart, $terminalProofEnd - $terminalProofStart) : '';
$assert($terminalProofBlock !== ''
&& str_contains($terminalProofBlock, '$terminalGate')
&& str_contains($terminalProofBlock, '$required->count() === 0')
&& str_contains($terminalProofBlock, '$liveRequired->count() === 0')
&& str_contains($terminalProofBlock, '$hosts === []')
&& str_contains($terminalProofBlock, '!$pendingHostTombstone')
&& str_contains($terminalProofBlock, 'no_data_plane_terminal_proof')
&& str_contains($terminalProofBlock, 'CloudVpcRoute::class, CloudVpcAclRule::class')
&& !str_contains($terminalProofBlock, 'CloudVpcMember::class')
&& !str_contains($terminalProofBlock, 'CloudVpcPrivateIp::class')
&& !str_contains($terminalProofBlock, 'CloudVpcSubnet::class'),
'Empty-VPC terminal proof may close only route/ACL tombstones and must not release private member resources.');
$assert(!str_contains($service, 'CloudJob')
&& !str_contains($service, 'network_change')
&& !str_contains($service, 'publicIpCidr'),
'VPC service must not reuse the public network_change/job payload.');
$assert(str_contains($service, '$orphanLease')
&& str_contains($service, '$stateMatches')
&& str_contains($service, "where('instance_id', \$instanceId)")
&& str_contains($service, "where('vpc_id', (int) \$vpc->id)")
&& str_contains($service, 'hash_equals($rootOperationId')
&& str_contains($service, "where('status', 'succeeded')")
&& str_contains($service, '$operationFresh')
&& str_contains($service, '$vpc->last_success_at')
&& str_contains($service, '$privateIp->observed_revision')
&& str_contains($service, '$privateIp->observed_digest')
&& str_contains($service, "(string) \$privateIp->state === 'active'")
&& str_contains($service, '$private->state = $privateState'),
'VPC private projections must fail closed on orphan/mismatched leases and require current root readback proof.');
$assert(str_contains($service, '当前 VPC 控制面不支持子网网关')
&& str_contains($service, "'private_ip_cidr'")
&& str_contains($service, "'next_hop_member_id'")
&& str_contains($service, "self::cidr(\$item['destination_cidr'] ?? null, 32, 32, '路由目标')")
&& str_contains($service, 'VPC 私网地址账本与成员不一致')
&& str_contains($service, 'firstFreeIp($subnet, $privateIps)'),
'VPC service lost no-gateway, /32 member or typed route boundaries.');
$assert(str_contains($service, 'privateMacForMember')
&& str_contains($service, "'private_mac' => \$privateMac")
&& str_contains($service, 'validateHostDataplaneEvidence')
&& str_contains($service, 'member_nics')
&& str_contains($service, 'wg_allowed_ips')
&& str_contains($service, 'privateRouteTableForVpc')
&& str_contains($service, 'expectedRouteSet')
&& str_contains($service, 'desiredContractValid')
&& str_contains($service, "array_key_exists('observed_digest', \$item)")
&& str_contains($service, "base64_decode(\$publicKey, true)")
&& str_contains($service, 'FABRIC_INTERFACE')
&& str_contains($service, 'PRIVATE_DATAPLANE_OWNER'),
'VPC desired DTO or host dataplane readback contract lost stable NIC identity/ACL gates.');
$assert(str_contains($vpcWorkerService, "'waiting_observed'")
&& str_contains($vpcWorkerService, 'allowDeferredRetry')
&& str_contains($vpcWorkerService, 'CloudVpcService::reconcile($vpcKey, $actor, $allowDeferredRetry)'),
'VPC worker must retry waiting_observed through its independent apply lane.');
$assert(str_contains($routes, "'/vpcs'")
&& str_contains($routes, "'/vpcs/{vpc_key:[0-9a-f]{32}}/reconcile'")
&& str_contains($controller, 'CloudVpcService::replaceRoutes')
&& str_contains($controller, 'CloudVpcService::replaceAcl')
&& preg_match('#/api/v1/vpcs#', $middleware) === 1,
'VPC API routes/controller/middleware are incomplete.');
$assert(str_contains($engineClient, 'function vpc(')
&& str_contains($engineClient, '/internal/v1/vpcs'),
'PHP engine client has no bounded VPC endpoint.');
$assert(str_contains($accountDeletion, "cloud_vpcs")
&& str_contains($accountDeletion, "cloud_private_networks")
&& str_contains($jobService, 'assertInstanceCanBeDeleted')
&& str_contains($orderService, "private_expectation")
&& str_contains($workerService, '旧删除任务缺少 VPC 删除门禁'),
'Account/VM creation/deletion can bypass the independent VPC control-plane ledger.');
$legacyPrivateGate = strpos($workerService,
"if ((\$expectation['required'] ?? false) !== true && !\$hasPrivateState)");
$privateReadback = strpos($workerService,
"'vms/' . rawurlencode(\$uuid) . '/private-state'");
$assert(str_contains($workerService, '$hasPrivateState')
&& str_contains($workerService, "&& !\$hasPrivateState")
&& str_contains($workerService, "array_key_exists('private_state', \$result)")
&& str_contains($workerService, 'Pre-VPC engines')
&& $legacyPrivateGate !== false
&& $privateReadback !== false
&& $legacyPrivateGate < $privateReadback,
'Legacy public-only jobs without private_state must remain compatible while structured observations stay gated.');
$assert(str_contains($workerService, 'Missing/invalid vm_uuid')
&& str_contains($workerService, 'hash_equals(strtolower($uuid)')
&& str_contains($workerService, "\$candidate['vm_uuid']"),
'Host private-state readback must remain bound to the requested VM UUID.');
$assert(str_contains($workerService, 'Never accept stale nested evidence')
&& str_contains($workerService, "['succeeded', 'completed', 'done']")
&& str_contains($workerService, "array_key_exists('operation_id', \$result)")
&& str_contains($workerService, "array_key_exists('vm_uuid', \$result)"),
'A failed or misbound reconcile envelope must never supply private-state proof.');
$assert(str_contains($workerService, "'_private_policy_skipped' => true")
&& str_contains($workerService, 'Only the PHP policy short-circuit carries this private marker')
&& str_contains($workerService, "'link_state' => self::privateReconcileLinkState"),
'A superseded PHP policy must preserve the private link without weakening real engine target proof.');
$assert(str_contains($service, '?string $expectedVmUuid = null')
&& str_contains($service, '$observedVmUuid')
&& str_contains($service, 'hash_equals(strtolower($expectedVmUuid)')
&& str_contains($workerService, "? 'action' : \$kind, \$uuid"),
'Private observation validation must enforce the lifecycle VM UUID binding.');
$assert(str_contains($workerService, "'private_mac', 'desired_revision'")
&& str_contains($service, "'private_mac', 'desired_revision'"),
'Private MAC must remain part of the immutable lifecycle/VPC target tuple.');
$assert(
str_contains($workerService, 'deleteTombstoneDetached')
&& str_contains($workerService, "['delete', 'expiry_delete']")
&& str_contains($workerService, "'desired_state'] ?? null) !== 'removed'")
&& str_contains($workerService, "'link_state'] ?? null) !== 'absent'"),
'Destructive deletion must preserve a removed tombstone until host-side absent readback is confirmed.'
);
echo "VPC control-plane schema, API, typed DTO and independent operation contracts passed.\n";