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

201 lines
8.2 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudTemplate;
use App\Models\CloudTemplateReplica;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudTemplateCatalogService;
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);
}
};
$expect = static function (callable $callable, int $status,
string $message) use ($assert): void {
try {
$callable();
} catch (CloudError $error) {
$assert($error->httpStatus === $status,
$message . ' Unexpected status: ' . $error->httpStatus);
return;
}
throw new RuntimeException($message);
};
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$capsule->schema('default')->create('cloud_templates',
static function (Blueprint $table): void {
$table->string('id')->primary();
$table->string('name');
$table->string('os_family');
$table->string('os_version');
$table->string('source_type');
$table->text('sealed_source_url');
$table->integer('image_bytes');
$table->string('sha256');
$table->text('startup_script');
$table->integer('revision');
$table->string('generation_token')->unique();
$table->string('state');
$table->integer('created_at');
$table->integer('updated_at');
});
$capsule->schema('default')->create('cloud_template_replicas',
static function (Blueprint $table): void {
$table->integer('host_id');
$table->string('template_id');
$table->integer('revision');
$table->string('generation_token');
$table->string('state')->default('pending');
$table->integer('image_bytes')->default(0);
$table->string('sha256')->default('');
$table->string('operation_id')->default('');
$table->string('error_code')->default('');
$table->integer('created_at');
$table->integer('updated_at');
$table->primary(['host_id', 'template_id']);
});
$generation = bin2hex(random_bytes(16));
$now = time();
$template = new CloudTemplate();
foreach ([
'id' => 'debian-12-template',
'name' => 'Debian 12',
'os_family' => 'Debian',
'os_version' => '12',
'source_type' => 'remote',
'sealed_source_url' => 'test-only-sealed-template-source',
'image_bytes' => 1024,
'sha256' => str_repeat('a', 64),
'startup_script' => '',
'revision' => 1,
'generation_token' => $generation,
'state' => 'active',
'created_at' => $now,
'updated_at' => $now,
] as $field => $value) {
$template->{$field} = $value;
}
$template->save();
$replica = new CloudTemplateReplica();
foreach ([
'host_id' => 1,
'template_id' => 'debian-12-template',
'revision' => 1,
'generation_token' => $generation,
'state' => 'active',
'image_bytes' => 1024,
'sha256' => str_repeat('a', 64),
'operation_id' => bin2hex(random_bytes(16)),
'error_code' => '',
'created_at' => $now,
'updated_at' => $now,
] as $field => $value) {
$replica->{$field} = $value;
}
$replica->save();
$registered = CloudTemplateCatalogService::adminCatalog()['templates'][0];
$assert(preg_match('/^[a-f0-9]{32}$/D', $generation) === 1
&& $registered['revision'] === 1
&& $registered['startup_script_configured'] === false,
'New PHP-owned template did not receive immutable CAS identity.');
$saved = CloudTemplateCatalogService::saveStartupScript(
'debian-12-template', "#!/bin/bash\r\necho 中文\r\n", 1, $generation
);
$assert($saved['startup_script'] === "#!/bin/bash\necho 中文\n"
&& $saved['revision'] === 2
&& $saved['generation_token'] === $generation,
'Startup script did not normalize CRLF or preserve generation.');
$sealed = CloudTemplateCatalogService::applyProvisioningSnapshot([
'template_id' => 'debian-12-template',
'startup_script' => 'tenant supplied',
'template_revision' => 999,
'template_generation_token' => str_repeat('f', 32),
]);
$assert($sealed['startup_script'] === "#!/bin/bash\necho 中文\n"
&& $sealed['template_revision'] === 2
&& $sealed['template_generation_token'] === $generation,
'Provisioning did not replace untrusted template/script fields with the PHP snapshot.');
$reinstall = CloudTemplateCatalogService::applyProvisioningSnapshot([
'template_id' => 'debian-12-template', 'startup_script' => 'tenant supplied',
], false);
$assert(!array_key_exists('startup_script', $reinstall)
&& $reinstall['template_revision'] === 2
&& $reinstall['template_generation_token'] === $generation,
'Reinstall received a first-install script or lost immutable template identity.');
$expect(static fn () => CloudTemplateCatalogService::saveStartupScript(
'debian-12-template', 'stale overwrite', 1, $generation
), 409, 'Stale startup-script revision was accepted.');
foreach (["echo\0bad", str_repeat('中', 10923), ["echo bad"]] as $invalid) {
$expect(static fn () => CloudTemplateCatalogService::saveStartupScript(
'debian-12-template', $invalid, 2, $generation
), 422, 'Invalid startup-script content was accepted.');
}
$cleared = CloudTemplateCatalogService::saveStartupScript(
'debian-12-template', '', 2, $generation
);
$assert($cleared['startup_script'] === '' && $cleared['revision'] === 3,
'An empty script did not disable first-boot execution.');
$operationBeforeBlockedMutation = (string) CloudTemplateReplica::query()
->where('host_id', 1)->where('template_id', 'debian-12-template')
->value('operation_id');
foreach (['importing', 'error'] as $blockedState) {
Capsule::table('cloud_templates')->where('id', 'debian-12-template')
->update(['state' => $blockedState]);
$expect(static fn () => CloudTemplateCatalogService::rename(
'debian-12-template', 'Blocked rename', 3, $generation
), 409, 'A non-active template was renamed.');
$expect(static fn () => CloudTemplateCatalogService::saveStartupScript(
'debian-12-template', 'blocked script', 3, $generation
), 409, 'A non-active template startup script was changed.');
$blocked = CloudTemplate::find('debian-12-template');
$assert((int) $blocked->revision === 3
&& (string) $blocked->name === 'Debian 12'
&& (string) $blocked->startup_script === ''
&& (string) CloudTemplateReplica::query()->where('host_id', 1)
->where('template_id', 'debian-12-template')
->value('operation_id') === $operationBeforeBlockedMutation,
'A blocked metadata mutation changed template or replica identity.');
}
Capsule::table('cloud_templates')->where('id', 'debian-12-template')
->update(['state' => 'active']);
$public = CloudTemplateCatalogService::publicCatalog()['templates'][0];
$admin = CloudTemplateCatalogService::adminCatalog()['templates'][0];
foreach (['startup_script', 'startup_script_configured', 'revision',
'generation_token', 'source_url', 'sealed_source_url', 'sha256', 'replicas']
as $privateField) {
$assert(!array_key_exists($privateField, $public),
'Tenant catalog exposed private template field: ' . $privateField);
}
$assert($admin['startup_script_configured'] === false
&& !array_key_exists('startup_script', $admin)
&& $admin['replicas'] === [[
'host_id' => 1,
'state' => 'active',
'error_code' => '',
'operation_id' => $operationBeforeBlockedMutation,
]],
'Admin catalog must show script state without returning script content.');
$row = CloudTemplate::find('debian-12-template');
$replica = CloudTemplateReplica::query()->where('host_id', 1)
->where('template_id', 'debian-12-template')->first();
$assert((string) $row->generation_token === $generation,
'Template generation token changed after script mutations.');
$assert($replica !== null && (int) $replica->revision === 3
&& (string) $replica->generation_token === $generation
&& (string) $replica->state === 'active',
'Startup-script CAS did not keep the active Agent replica revision aligned.');
echo "PHP template catalog and startup-script CAS contract passed.\n";