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

529 lines
25 KiB
PHP

<?php
namespace App\Services {
final class Config
{
public static function get($name, $default = null)
{
if ($name === 'cloud_max_renewal_periods_ahead') {
return 24;
}
if ($name === 'cloud_data_key') {
return base64_encode(str_repeat('k', 32));
}
return $default;
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudInstancePageService;
use App\Services\Cloud\CloudInstanceRuntimeService;
use App\Services\Cloud\CloudSecrets;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$assertNoPlacement = static function (array $payload, string $message)
use (&$assertNoPlacement): void {
foreach ($payload as $key => $value) {
if (is_string($key) && in_array($key, [
'host', 'host_id', 'host_name', 'resource_pool',
'resource_pool_id', 'resource_pool_name', 'pool_id', 'pool_name',
], true)) {
throw new RuntimeException($message . ' Leaked key: ' . $key);
}
if (is_array($value)) {
$assertNoPlacement($value, $message);
}
}
};
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->increments('id');
$table->string('region')->default('');
$table->string('country_code')->default('');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->string('uuid');
$table->integer('host_id');
$table->integer('user_id');
$table->integer('current_period_id')->nullable();
$table->string('name');
$table->string('status');
$table->string('service_status');
$table->string('network_status');
$table->integer('expires_at')->nullable();
$table->string('renewal_price')->nullable();
$table->integer('renewal_days')->default(0);
$table->integer('renewal_traffic_bytes')->default(0);
$table->integer('traffic_quota_bytes')->default(0);
$table->integer('traffic_download_bytes')->default(0);
$table->integer('traffic_upload_bytes')->default(0);
$table->text('spec_json');
$table->text('sealed_credential')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_service_periods', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id');
$table->integer('starts_at');
$table->integer('ends_at');
$table->string('status');
});
$schema->create('cloud_instance_runtime', static function (Blueprint $table): void {
$table->integer('instance_id')->primary();
$table->integer('host_id');
$table->string('uuid');
$table->string('power_state')->default('unknown');
$table->string('sync_state')->default('never');
$table->integer('last_success_at')->default(0);
$table->integer('last_attempt_at')->default(0);
$table->integer('revision')->default(0);
$table->string('last_error_code')->default('');
$table->integer('created_at')->default(0);
$table->integer('updated_at')->default(0);
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id')->nullable();
$table->string('kind');
$table->string('execution_mode')->default('agent');
$table->string('phase');
$table->string('outcome')->nullable();
$table->string('status');
$table->boolean('finalization_incident')->default(0);
$table->string('finalization_error_code')->nullable();
$table->text('sealed_payload');
$table->integer('updated_at')->default(0);
});
Capsule::table('cloud_hosts')->insert([
'id' => 7, 'region' => 'internal-host-location', 'country_code' => 'ZZ',
]);
$now = time();
$common = [
'host_id' => 7, 'current_period_id' => null, 'status' => 'active',
'service_status' => 'active', 'network_status' => 'active',
'expires_at' => $now + 86400, 'renewal_price' => '10.00',
'renewal_days' => 30, 'renewal_traffic_bytes' => 2000,
'traffic_quota_bytes' => 2000, 'traffic_download_bytes' => 300,
'traffic_upload_bytes' => 200,
'spec_json' => json_encode([
'vcpu' => 2,
'memory_mib' => 2048,
'state' => 'running',
'console_port' => 5900,
'api_token' => 'must-not-reach-ssr',
'host_id' => 7,
'host_name' => 'internal-host-name',
'resource_pool_id' => 9,
'resource_pool_name' => 'internal-resource-pool',
'region' => 'Tokyo',
'country_code' => 'JP',
'disk_gib' => 40,
'disks' => [[
'capacity_gib' => 40,
'source' => '/home/kvm/private.qcow2',
'target' => 'vda',
'format' => 'qcow2',
]],
'os_source' => 'cloud_template',
'os_name' => 'AlmaLinux 10',
'login_name' => 'root',
'agent_metadata_version' => 1,
]),
'sealed_credential' => 'test-cipher', 'created_at' => $now - 60,
'updated_at' => $now,
];
Capsule::table('cloud_instances')->insert($common + [
'id' => 1, 'uuid' => '11111111-1111-4111-8111-111111111111',
'user_id' => 1, 'name' => 'owner-vm',
]);
Capsule::table('cloud_instances')->insert($common + [
'id' => 2, 'uuid' => '22222222-2222-4222-8222-222222222222',
'user_id' => 2, 'name' => 'foreign-vm',
]);
$owner = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false,
'can_manage' => false];
$admin = ['user_id' => 1, 'is_admin' => true, 'is_super_admin' => false,
'can_manage' => false];
$global = ['user_id' => 1, 'is_admin' => true, 'is_super_admin' => true,
'can_manage' => true];
Capsule::connection('default')->flushQueryLog();
Capsule::connection('default')->enableQueryLog();
$page = CloudInstancePageService::forActor($owner, 1, 20);
$pageQueryCount = count(Capsule::connection('default')->getQueryLog());
Capsule::connection('default')->disableQueryLog();
$assert($page['stats']['total'] === 1 && count($page['vms']) === 1
&& $page['pagination']['page_count'] === 1
&& $page['vms'][0]['name'] === 'owner-vm',
'Ordinary user instance first page crossed the owner boundary.');
$assert($pageQueryCount <= 3,
'Instance first page regressed beyond count, rows and runtime batch queries.');
$assertNoPlacement($page,
'Instance list SSR exposed an internal placement identifier.');
$assert($page['vms'][0]['region'] === 'Tokyo',
'Instance list did not use the immutable selling-region snapshot.');
$assert($page['vms'][0]['state'] === 'unknown',
'Persisted specification power state was trusted before a live UUID check.');
$assert(count($page['vms'][0]['disks']) === 1
&& array_keys($page['vms'][0]['disks'][0]) === ['capacity_gib']
&& (float) $page['vms'][0]['disks'][0]['capacity_gib'] === 40.0
&& $page['vms'][0]['login_name'] === 'root'
&& $page['vms'][0]['agent_metadata_version'] === 1
&& !array_key_exists('console_port', $page['vms'][0])
&& !array_key_exists('api_token', $page['vms'][0]),
'Instance list SSR exposed an unsafe field from the persisted engine snapshot.');
$assert(!array_key_exists('traffic_quota_bytes', $page['vms'][0])
&& !array_key_exists('password_available', $page['vms'][0]),
'Paginated instance rows leaked detail-only billing or credential metadata.');
// A successful background observation must be available to the detail
// page immediately, without waiting for a host probe.
Capsule::table('cloud_instance_runtime')->insert([
'instance_id' => 1,
'host_id' => 7,
'uuid' => '11111111-1111-4111-8111-111111111111',
'power_state' => 'running',
'sync_state' => 'ok',
'last_success_at' => $now - 5,
'last_attempt_at' => $now - 5,
'revision' => 1,
'last_error_code' => '',
'created_at' => $now - 10,
'updated_at' => $now - 5,
]);
$ownedDetail = CloudInstancePageService::detailForActor($owner, 1);
$assertNoPlacement($ownedDetail,
'Instance detail SSR exposed an internal placement identifier.');
$assert($ownedDetail['region'] === 'Tokyo'
&& $ownedDetail['country_code'] === 'JP',
'Instance detail did not use its safe region and country snapshot.');
$assert($ownedDetail['can_operate'] && $ownedDetail['can_delete']
&& $ownedDetail['can_rename']
&& $ownedDetail['password_available'] && $ownedDetail['can_renew'],
'Owner lost expected instance capabilities.');
$assert($ownedDetail['state'] === 'running'
&& $ownedDetail['state_fresh'] === true
&& $ownedDetail['state_sync_status'] === 'fresh',
'Detail SSR did not use the fresh runtime observation.');
$assert(count($ownedDetail['disks']) === 1
&& array_keys($ownedDetail['disks'][0]) === ['capacity_gib']
&& (float) $ownedDetail['disks'][0]['capacity_gib'] === 40.0
&& $ownedDetail['login_name'] === 'root'
&& $ownedDetail['agent_metadata_version'] === 1
&& !array_key_exists('console_port', $ownedDetail)
&& !array_key_exists('api_token', $ownedDetail),
'Instance detail SSR exposed an unsafe field from the persisted engine snapshot.');
$ownedStatuses = CloudInstancePageService::forActorIds($owner, [1, 2]);
$assert(count($ownedStatuses) === 1,
'Ordinary user batch status scope disclosed a foreign instance.');
$assertNoPlacement($ownedStatuses,
'Instance batch status identity exposed internal placement.');
Capsule::table('cloud_jobs')->insert([
'id' => 101, 'instance_id' => 1, 'kind' => 'action',
'phase' => 'accepted', 'outcome' => null, 'status' => 'queued',
'sealed_payload' => CloudSecrets::encrypt([
'body' => ['action' => 'start'],
], 'job-payload'),
]);
Capsule::table('cloud_jobs')->insert([
'id' => 102, 'instance_id' => 2, 'kind' => 'reinstall',
'phase' => 'awaiting_receipt', 'outcome' => null,
'status' => 'running',
'sealed_payload' => 'must-not-expose-foreign-job',
]);
$startingSnapshots = CloudInstancePageService::forActorIds($owner, [1, 2]);
$starting = CloudInstancePageService::powerStatus($startingSnapshots[0], [
'uuid' => $startingSnapshots[0]['uuid'], 'state' => 'running',
]);
$assert(count($startingSnapshots) === 1
&& $starting['state_transitioning'] === true
&& $starting['state_transition'] === 'start'
&& $starting['operation_transition'] === 'start'
&& !array_key_exists('sealed_payload', $starting)
&& !array_key_exists('host_id', $starting),
'Owner-scoped polling did not expose a queued start transition safely.');
Capsule::table('cloud_jobs')->where('id', 101)->update([
'phase' => 'terminal', 'outcome' => 'succeeded',
'status' => 'succeeded',
]);
Capsule::table('cloud_jobs')->insert([
'id' => 103, 'instance_id' => 1, 'kind' => 'reinstall',
'phase' => 'awaiting_receipt', 'outcome' => null,
'status' => 'running',
'sealed_payload' => 'must-not-expose-reinstall-job',
]);
$reinstallSnapshot = CloudInstancePageService::forActorIds($owner, [1])[0];
$reinstalling = CloudInstancePageService::powerStatus($reinstallSnapshot, [
'uuid' => $reinstallSnapshot['uuid'], 'state' => 'running',
]);
$assert($reinstalling['state_transitioning'] === true
&& $reinstalling['state_transition'] === 'reinstall'
&& $reinstalling['operation_transition'] === 'reinstall',
'A running reinstall was not projected into the instance list.');
Capsule::table('cloud_jobs')->where('id', 103)->update([
'phase' => 'terminal', 'outcome' => 'failed', 'status' => 'failed',
]);
Capsule::table('cloud_jobs')->insert([
'id' => 104, 'instance_id' => 1, 'kind' => 'action',
'phase' => 'awaiting_receipt', 'outcome' => null,
'status' => 'running',
'sealed_payload' => CloudSecrets::encrypt([
'body' => ['action' => 'shutdown'],
], 'job-payload'),
]);
$shutdownSnapshot = CloudInstancePageService::forActorIds($owner, [1])[0];
$shuttingDown = CloudInstancePageService::powerStatus($shutdownSnapshot, [
'uuid' => $shutdownSnapshot['uuid'], 'state' => 'shutoff',
]);
$assert($shuttingDown['state_transitioning'] === true
&& $shuttingDown['state_transition'] === 'shutdown'
&& $shuttingDown['operation_transition'] === 'shutdown',
'A running shutdown was not projected into the instance list.');
Capsule::table('cloud_jobs')->where('id', 104)->update([
'phase' => 'terminal', 'outcome' => 'succeeded',
'status' => 'succeeded', 'updated_at' => time(),
]);
$convergenceSnapshot = CloudInstancePageService::forActorIds($owner, [1])[0];
$converging = CloudInstancePageService::powerStatus($convergenceSnapshot, [
'uuid' => $convergenceSnapshot['uuid'], 'state' => 'running',
]);
$assert($converging['state_transitioning'] === true
&& $converging['state_transition'] === 'shutdown'
&& $converging['operation_transition'] === null
&& is_int($converging['shutdown_convergence_until']),
'A recently succeeded shutdown stopped converging on a transient running observation.');
$stopped = CloudInstancePageService::powerStatus($convergenceSnapshot, [
'uuid' => $convergenceSnapshot['uuid'], 'state' => 'shutoff',
]);
$assert($stopped['state_transitioning'] === false
&& $stopped['state_transition'] === null
&& $stopped['shutdown_convergence_until'] === null,
'A confirmed stopped state did not finish shutdown convergence.');
Capsule::table('cloud_jobs')->where('id', 104)->update([
'updated_at' => time() - 61,
]);
$terminal = CloudInstancePageService::powerStatus(
CloudInstancePageService::forActorIds($owner, [1])[0]
);
$assert($terminal['state_transitioning'] === false
&& $terminal['state_transition'] === null
&& $terminal['operation_transition'] === null
&& $terminal['shutdown_convergence_until'] === null,
'Expired terminal jobs were presented as active instance transitions.');
Capsule::table('cloud_jobs')->where('id', 104)->update([
'updated_at' => time(),
]);
Capsule::table('cloud_jobs')->insert([
'id' => 105, 'instance_id' => 1, 'kind' => 'action',
'phase' => 'terminal', 'outcome' => 'failed', 'status' => 'failed',
'updated_at' => time(),
'sealed_payload' => CloudSecrets::encrypt([
'body' => ['action' => 'start'],
], 'job-payload'),
]);
$superseded = CloudInstancePageService::powerStatus(
CloudInstancePageService::forActorIds($owner, [1])[0]
);
$assert($superseded['state_transitioning'] === false
&& $superseded['shutdown_convergence_until'] === null,
'A newer terminal failed start inherited an older shutdown convergence window.');
Capsule::table('cloud_jobs')->insert([
'id' => 106, 'instance_id' => 1, 'kind' => 'action',
'phase' => 'terminal', 'outcome' => 'failed', 'status' => 'failed',
'updated_at' => time(),
'sealed_payload' => CloudSecrets::encrypt([
'body' => ['action' => 'shutdown'],
], 'job-payload'),
]);
$failedShutdown = CloudInstancePageService::powerStatus(
CloudInstancePageService::forActorIds($owner, [1])[0]
);
$assert($failedShutdown['state_transitioning'] === false
&& $failedShutdown['shutdown_convergence_until'] === null,
'A failed shutdown incorrectly opened a convergence window.');
$adminPage = CloudInstancePageService::forActor($admin, 1, 20);
$assert($adminPage['stats']['total'] === 2,
'Read-only administrator lost the historical all-instance view.');
$assertNoPlacement($adminPage,
'The shared user-facing instance page exposed placement to an administrator session.');
$foreign = CloudInstancePageService::detailForActor($admin, 2);
$assertNoPlacement($foreign,
'The shared user-facing detail exposed placement to an administrator session.');
$assert(!$foreign['is_owner'] && !$foreign['can_operate']
&& !$foreign['can_delete'] && !$foreign['can_rename']
&& !$foreign['can_view_credential']
&& !$foreign['password_available'] && !$foreign['can_renew'],
'Read-only administrator inherited foreign instance mutation or credential access.');
$managed = CloudInstancePageService::detailForActor($global, 2);
$assertNoPlacement($managed,
'The shared user-facing detail exposed placement to a super-administrator session.');
$assert(!$managed['is_owner'] && $managed['can_operate']
&& $managed['can_delete'] && $managed['can_rename']
&& $managed['can_view_credential']
&& $managed['password_available'] && !$managed['can_renew'],
'Super administrator capabilities no longer match the legacy VM boundary.');
Capsule::connection('default')->flushQueryLog();
Capsule::connection('default')->enableQueryLog();
$mutable = CloudInstancePageService::statusForActor($global, 2);
$statusQueryCount = count(Capsule::connection('default')->getQueryLog());
Capsule::connection('default')->disableQueryLog();
$assert($statusQueryCount <= 2 && !array_key_exists('host_id', $mutable)
&& !array_key_exists('sealed_credential', $mutable)
&& !array_key_exists('renewal_price', $mutable),
'Detail status poll exposed host, credential or renewal metadata.');
$assertNoPlacement($mutable,
'Detail status poll exposed internal placement.');
$status = CloudInstancePageService::status($managed,
['uuid' => $managed['uuid'], 'name' => 'vc-2222222222224222', 'state' => 'running']);
$assert($status['state'] === 'running' && $status['traffic_used_bytes'] === 500
&& $status['traffic_remaining_bytes'] === 1500
&& $status['name'] === 'foreign-vm'
&& $status['can_rename'] === true
&& $status['live_state_available'] === true,
'Lightweight status did not merge live state while preserving the database display name.');
$assertNoPlacement($status,
'Merged detail status exposed internal placement.');
$unavailable = CloudInstancePageService::status($managed);
$assert($unavailable['state'] === 'unknown'
&& $unavailable['live_state_available'] === false,
'Unavailable hosts were presented as confirmed live power state.');
$power = CloudInstancePageService::powerStatus($managed,
['uuid' => $managed['uuid'], 'name' => 'vc-2222222222224222', 'state' => 'running']);
$assert($power['state'] === 'running' && $power['live_state_available'] === true
&& $power['name'] === 'foreign-vm'
&& !array_key_exists('traffic_quota_bytes', $power)
&& !array_key_exists('can_delete', $power),
'List polling returned detail-only billing or permission fields.');
$assertNoPlacement($power,
'List polling exposed internal placement.');
Capsule::table('cloud_instance_runtime')->where('instance_id', 1)->update([
'power_state' => 'shutdown',
'sync_state' => 'ok',
'last_success_at' => $now,
'last_attempt_at' => $now,
'updated_at' => $now,
]);
$transitionDetail = CloudInstancePageService::detailForActor($owner, 1);
$assert($transitionDetail['state'] === 'shutdown'
&& $transitionDetail['state_transitioning'] === true
&& $transitionDetail['state_transition'] === 'shutdown',
'Cached graceful shutdown was not exposed as a non-terminal transition.');
$transitionPage = CloudInstancePageService::forActor($owner, 1, 20);
$assert($transitionPage['vms'][0]['state'] === 'shutdown'
&& $transitionPage['vms'][0]['state_transitioning'] === true
&& $transitionPage['vms'][0]['state_transition'] === 'shutdown',
'Instance list omitted the normalized graceful-shutdown transition.');
$transitionStatus = CloudInstancePageService::status($transitionDetail, [
'uuid' => $transitionDetail['uuid'], 'state' => 'shutdown',
]);
$assert($transitionStatus['state'] === 'shutdown'
&& $transitionStatus['live_state_available'] === true
&& $transitionStatus['state_transitioning'] === true
&& $transitionStatus['state_transition'] === 'shutdown',
'Live graceful shutdown lost its explicit transition semantics.');
$failedLiveStatus = CloudInstancePageService::status($transitionDetail, [
'uuid' => $transitionDetail['uuid'], 'state' => 'unexpected-engine-state',
]);
$assert($failedLiveStatus['state'] === 'shutdown'
&& $failedLiveStatus['live_state_available'] === false
&& $failedLiveStatus['state_transitioning'] === true,
'An invalid live observation erased the last identity-checked cache state.');
$runningStatus = CloudInstancePageService::status($transitionDetail, [
'uuid' => $transitionDetail['uuid'], 'state' => 'running',
]);
$assert($runningStatus['state'] === 'running'
&& $runningStatus['state_transitioning'] === false
&& $runningStatus['state_transition'] === null,
'A live running observation inherited a stale shutdown transition.');
// A live request claims its cache revision before the host call. A newer
// worker result must win even if that older live response returns later.
$uuid = '11111111-1111-4111-8111-111111111111';
$liveRevision = CloudInstanceRuntimeService::beginCurrentObservation(
1, 7, $uuid, $now + 1
);
$assert(is_int($liveRevision),
'A current instance identity could not claim a live observation.');
CloudInstanceRuntimeService::markObserved(1, 7, $uuid, 'shutdown', $now + 2);
CloudInstanceRuntimeService::markObserved(
1, 7, $uuid, 'running', $now + 3, $liveRevision
);
$runtimeAfterStaleLive = Capsule::table('cloud_instance_runtime')
->where('instance_id', 1)->first();
$assert($runtimeAfterStaleLive !== null
&& $runtimeAfterStaleLive->power_state === 'shutdown',
'A stale live response overwrote the newer worker shutdown state.');
// A response claimed before deletion must not recreate the cache row.
$deletedRevision = CloudInstanceRuntimeService::beginCurrentObservation(
1, 7, $uuid, $now + 4
);
$assert(is_int($deletedRevision),
'The delete-race fixture could not claim its live observation.');
CloudInstanceRuntimeService::forget(1);
$deletedWriteRejected = false;
try {
CloudInstanceRuntimeService::markObserved(
1, 7, $uuid, 'running', $now + 5, $deletedRevision
);
} catch (RuntimeException $error) {
$deletedWriteRejected = true;
}
$assert($deletedWriteRejected
&& !Capsule::table('cloud_instance_runtime')->where('instance_id', 1)->exists(),
'A stale live response recreated runtime cache after instance deletion.');
// A request holding the old placement identity must not reset a cache row
// already moved to the instance's new host/UUID.
$migratedUuid = '33333333-3333-4333-8333-333333333333';
Capsule::table('cloud_instances')->where('id', 1)->update([
'host_id' => 8, 'uuid' => $migratedUuid,
]);
CloudInstanceRuntimeService::seed(1, 8, $migratedUuid, $now + 6);
$oldIdentityRevision = CloudInstanceRuntimeService::beginCurrentObservation(
1, 7, $uuid, $now + 7
);
$runtimeAfterMigration = Capsule::table('cloud_instance_runtime')
->where('instance_id', 1)->first();
$assert($oldIdentityRevision === null && $runtimeAfterMigration !== null
&& (int) $runtimeAfterMigration->host_id === 8
&& $runtimeAfterMigration->uuid === $migratedUuid,
'An old live request reset the runtime identity after migration.');
// If deletion commits before the live claim begins, the locked current-row
// check must refuse to seed an orphan cache record.
CloudInstanceRuntimeService::forget(1);
Capsule::table('cloud_instances')->where('id', 1)->update(['status' => 'deleted']);
$claimAfterDelete = CloudInstanceRuntimeService::beginCurrentObservation(
1, 8, $migratedUuid, $now + 8
);
$assert($claimAfterDelete === null
&& !Capsule::table('cloud_instance_runtime')->where('instance_id', 1)->exists(),
'A live request recreated runtime cache after deletion had committed.');
echo "Cloud instance page service ownership and administrator permissions passed.\n";
}