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/CloudSnapshotContractTest.php

115 lines
5.7 KiB
PHP

<?php
$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);
}
};
$section = static function (string $source, string $start, string $end): string {
$offset = strpos($source, $start);
if ($offset === false) {
return '';
}
$finish = strpos($source, $end, $offset + strlen($start));
return $finish === false ? substr($source, $offset)
: substr($source, $offset, $finish - $offset);
};
$schema = $read('sql/cloud.sql');
$routes = $read('config/routes_cloud.php');
$middleware = $read('app/Middleware/CloudApi.php');
$service = $read('app/Services/Cloud/CloudSnapshotService.php');
$jobService = $read('app/Services/Cloud/CloudJobService.php');
$worker = $read('app/Services/Cloud/CloudWorkerService.php');
$catalog = $read('app/Services/Cloud/CloudOperationErrorCatalog.php');
$listing = $section($service, 'public static function listing(',
'public static function create(');
$create = $section($service, 'public static function create(',
'public static function restore(');
$lockInstance = $section($service, 'private static function lockInstance(',
'private static function assertNoActiveJob(');
$snapshotSchema = $section($schema,
'CREATE TABLE IF NOT EXISTS cloud_instance_snapshots (',
'-- Last-known Agent power state');
$assert(str_contains($schema, 'CREATE TABLE IF NOT EXISTS cloud_instance_snapshots')
&& str_contains($schema, 'UNIQUE KEY cloud_instance_snapshot_key (snapshot_key)')
&& str_contains($schema, 'cloud_instance_snapshot_slots (instance_id, state, id)')
&& str_contains($schema, 'snapshot_id BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($schema, 'cloud_job_snapshot (snapshot_id, id)')
&& !preg_match('/\b(?:ALTER|DROP)\s+TABLE\b/i', $schema),
'Fresh schema lost the snapshot/job catalog or retained upgrade DDL.');
$instanceLock = strpos($jobService,
"CloudInstance::where('id', \$instance->id)->lockForUpdate()->first()");
$identityGate = strpos($jobService,
'CloudSnapshotService::assertReinstallAllowedLocked($locked)');
$assert($snapshotSchema !== ''
&& !str_contains($snapshotSchema, 'credential_cipher')
&& !str_contains($snapshotSchema, 'system_metadata_json')
&& str_contains($jobService, "\$kind === 'reinstall'")
&& $instanceLock !== false && $identityGate !== false
&& $instanceLock < $identityGate
&& str_contains($service,
'public static function assertReinstallAllowedLocked(')
&& str_contains($service, "->whereIn('state', self::SLOT_STATES)->exists()"),
'Retained snapshots did not preserve the reinstall boundary.');
$assert(str_contains($routes, "['GET', 'POST'], '/vms/{id:[0-9]+}/snapshots'")
&& str_contains($routes,
"'/vms/{id:[0-9]+}/snapshots/{snapshot_key:[0-9a-f]{32}}/restore'")
&& str_contains($routes,
"'/vms/{id:[0-9]+}/snapshots/{snapshot_key:[0-9a-f]{32}}'")
&& str_contains($middleware, 'AdminCsrf::requiresProtection($request->getMethod())')
&& str_contains($middleware,
"#^/api/v1/vms/[0-9]+/snapshots(?:/[0-9a-f]{32}(?:/restore)?)?$#D")
&& str_contains($middleware,
"#^/api/v1/(?:jobs|reinstall-jobs|rescue-jobs)/[0-9]+$#D"),
'Snapshot routes are missing, unbounded, or outside the shared CSRF boundary.');
$slotCount = strpos($create, "->whereIn('state', self::SLOT_STATES)->count('id')");
$assert(str_contains($lockInstance,
"CloudInstance::where('id', (int) \$instance->id)")
&& str_contains($lockInstance, '->lockForUpdate()->first()')
&& $slotCount !== false
&& strpos($create, 'self::lockInstance($instance, $actor)') < $slotCount
&& str_contains($create, 'self::MAX_PER_INSTANCE'),
'The two-snapshot limit is not serialized by the parent instance row.');
$assert($listing !== ''
&& !str_contains($listing, 'CloudEngineClient')
&& !str_contains($listing, '->host(')
&& !preg_match('/volume|storage[_ -]?path|source[_ -]?path/i', $listing)
&& str_contains($listing, "'snapshots' => \$snapshots")
&& str_contains($listing, "'active_job' =>")
&& str_contains($listing, '(int) $active->user_id === (int)')
&& str_contains($service, 'private static function jobSummary(CloudJob $job, bool $includeId)')
&& str_contains($service, 'if ($includeId) {'),
'Opening the snapshot panel can contact the engine or disclose storage details.');
$assert(str_contains($catalog, "'volume_name'")
&& !str_contains($listing, "'volume_name'")
&& !str_contains($listing, "'snapshot_volume_name'"),
'Snapshot storage identifiers are not explicitly excluded from tenant DTOs.');
$assert(str_contains($worker,
'CloudSnapshotService::finishJobLocked($job, $status, $result, $payload)')
&& str_contains($worker,
'CloudSnapshotService::finishInstanceDeleteLocked($job, $status)')
&& str_contains($worker, 'CloudSnapshotService::markJobUncertain($job)')
&& str_contains($service, "\$snapshot->state = 'uncertain'")
&& str_contains($service,
"\$snapshot->state = \$job->kind === 'snapshot_create'")
&& str_contains($service, "\$snapshot->state = 'ready'")
&& str_contains($service, "\$snapshot->state = 'deleted'"),
'Worker success, failure, uncertain, or VM-delete cascade mapping is incomplete.');
$assert(str_contains($catalog, "'snapshot_guest_agent_unavailable'")
&& str_contains($catalog, "'snapshot_qga_unavailable'")
&& str_contains($catalog, 'QEMU Guest Agent 不可用'),
'Guest-agent failure is not mapped to a stable safe tenant diagnostic.');
echo "Cloud snapshot schema, route, CSRF and safety contract passed.\n";