httpStatus === $status, 'Unexpected rejection status.'); return; } throw new \RuntimeException('Invalid or unauthorized request was accepted.'); }; $ids = static fn ($items): array => array_map('intval', array_column($items, 'id')); $capsule = new Capsule(); $capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default'); $capsule->setAsGlobal(); $capsule->bootEloquent(); $schema = $capsule->schema(); $schema->create('user', static function (Blueprint $table): void { $table->increments('id'); $table->string('user_name'); $table->string('email'); $table->boolean('enable')->default(true); $table->boolean('is_admin')->default(false); }); $schema->create('cloud_hosts', static function (Blueprint $table): void { $table->increments('id'); $table->string('name'); $table->string('region'); }); $schema->create('cloud_instances', static function (Blueprint $table): void { $table->increments('id'); $table->string('uuid'); $table->string('name'); $table->integer('host_id'); $table->integer('user_id'); $table->string('status'); }); $schema->create('cloud_orders', static function (Blueprint $table): void { $table->increments('id'); $table->integer('host_id'); $table->integer('user_id'); $table->integer('instance_id')->nullable(); }); $schema->create('cloud_jobs', static function (Blueprint $table): void { $table->increments('id'); $table->string('operation_id'); $table->integer('order_id')->nullable(); $table->integer('instance_id')->nullable(); $table->integer('user_id'); $table->integer('host_id'); $table->string('kind'); $table->string('status'); $table->integer('attempts')->default(0); $table->integer('dispatched_at')->nullable(); $table->integer('available_at'); $table->integer('lease_until')->default(0); $table->integer('created_at'); $table->integer('updated_at'); $table->string('error_code')->nullable(); $table->text('result_json')->nullable(); $table->text('sealed_payload')->default('forbidden-payload'); $table->string('lease_token')->nullable()->default('forbidden-lease'); }); $schema->create('cloud_instance_snapshots', static function (Blueprint $table): void { $table->increments('id'); $table->string('snapshot_key'); $table->integer('instance_id'); $table->integer('user_id'); $table->integer('host_id'); $table->string('name'); $table->string('state'); $table->string('consistency'); $table->integer('size_bytes')->nullable(); $table->string('last_operation_id')->nullable(); $table->integer('ready_at')->nullable(); $table->integer('last_restored_at')->nullable(); $table->integer('deleted_at')->nullable(); $table->integer('created_at'); $table->integer('updated_at'); }); Capsule::table('user')->insert([ ['id' => 1, 'user_name' => 'AliceOwner', 'email' => 'alice@example.test'], ['id' => 2, 'user_name' => 'BobOwner', 'email' => 'bob@example.test'], ['id' => 99, 'user_name' => 'AdminActor', 'email' => 'admin@example.test'], ]); Capsule::table('cloud_hosts')->insert([ ['id' => 7, 'name' => 'Host Seven', 'region' => 'region-seven'], ['id' => 8, 'name' => 'Host Eight', 'region' => 'region-eight'], ]); Capsule::table('cloud_instances')->insert([ ['id' => 10, 'uuid' => '11111111-1111-4111-8111-111111111110', 'name' => "tenant's 100%_vm", 'host_id' => 7, 'user_id' => 1, 'status' => 'active'], ['id' => 20, 'uuid' => '11111111-1111-4111-8111-111111111120', 'name' => 'Bob VM', 'host_id' => 7, 'user_id' => 2, 'status' => 'active'], ['id' => 30, 'uuid' => '11111111-1111-4111-8111-111111111130', 'name' => 'Deleted VM', 'host_id' => 8, 'user_id' => 1, 'status' => 'deleted'], ]); Capsule::table('cloud_orders')->insert([ ['id' => 100, 'host_id' => 7, 'user_id' => 1, 'instance_id' => 10], ['id' => 200, 'host_id' => 7, 'user_id' => 2, 'instance_id' => 20], ['id' => 300, 'host_id' => 7, 'user_id' => 2, 'instance_id' => 10], ['id' => 400, 'host_id' => 7, 'user_id' => 1, 'instance_id' => null], ]); $now = time(); $insertJob = static function (int $id, array $replace = []) use ($now): void { Capsule::table('cloud_jobs')->insert(array_replace([ 'id' => $id, 'operation_id' => sprintf('%032x', $id), 'order_id' => null, 'instance_id' => 10, 'user_id' => 99, 'host_id' => 7, 'kind' => 'action', 'status' => 'succeeded', 'attempts' => 1, 'available_at' => $now - 1000, 'lease_until' => 0, 'created_at' => $now - 1200, 'updated_at' => $now - 10, 'result_json' => '{"phase":"完成","credential":"forbidden-result-secret"}', ], $replace)); }; for ($id = 1; $id <= 205; $id++) { $insertJob($id); } $insertJob(206, ['status' => 'failed', 'kind' => 'reinstall', 'error_code' => 'password=never-expose-password token=never-expose-token']); $insertJob(207, ['status' => 'uncertain', 'kind' => 'rescue', 'result_json' => '{"phase":"Bearer never-expose-bearer","private_key":"forbidden-result-key","cause_code":"bad/path"}']); $insertJob(208, ['status' => 'queued', 'available_at' => $now - 301, 'order_id' => 100]); $insertJob(209, ['status' => 'queued', 'available_at' => $now - 290]); $insertJob(210, ['status' => 'queued', 'available_at' => $now - 600, 'lease_until' => $now + 50]); $insertJob(211, ['status' => 'running', 'lease_until' => $now - 1, 'kind' => 'delete', 'dispatched_at' => $now - 1]); $insertJob(212, ['status' => 'running', 'lease_until' => $now + 50]); $insertJob(213, ['status' => 'running', 'lease_until' => 0]); $insertJob(214, ['status' => 'queued', 'available_at' => $now + 600]); $insertJob(215, ['status' => 'uncertain', 'kind' => 'create', 'order_id' => 100, 'instance_id' => null, 'result_json' => '{"phase":"等待核对结果","cause_code":"storage_clone_failed","message":"/srv/private/template.qcow2"}']); $insertJob(216, ['status' => 'failed', 'order_id' => 200, 'instance_id' => 10]); $insertJob(217, ['status' => 'failed', 'order_id' => 100, 'instance_id' => 20]); $insertJob(218, ['status' => 'failed', 'order_id' => 300, 'instance_id' => null]); $insertJob(219, ['status' => 'failed', 'order_id' => 400, 'instance_id' => null]); $insertJob(220, ['status' => 'failed', 'host_id' => 8, 'instance_id' => 30, 'kind' => 'expiry_delete']); $insertJob(221, ['status' => 'failed', 'host_id' => 999, 'instance_id' => 999, 'user_id' => 999, 'order_id' => 999, 'result_json' => 'broken json']); $insertJob(222, ['status' => 'succeeded', 'host_id' => 8, 'instance_id' => 10, 'order_id' => 100]); $tables = ['user', 'cloud_hosts', 'cloud_instances', 'cloud_orders', 'cloud_jobs']; $snapshot = static function () use ($tables): string { $rows = []; foreach ($tables as $table) { $rows[$table] = Capsule::table($table)->orderBy('id')->get()->all(); } return json_encode($rows, JSON_THROW_ON_ERROR); }; $before = $snapshot(); $admin = ['user_id' => 99, 'is_admin' => true, 'is_super_admin' => true, 'can_manage' => true]; $readonlyAdmin = ['user_id' => 99, 'is_admin' => true, 'is_super_admin' => false, 'can_manage' => false]; $customer = ['user_id' => 1, 'is_admin' => false]; $page = Operations::page($admin); $networkFilter = Operations::filters(['kind' => 'network_change']); $assert($networkFilter['kind'] === 'network_change' && array_filter($page['kinds'], static fn ($item): bool => $item['value'] === 'network_change' && $item['label'] === '更换公网 IP') !== [], 'Network-change jobs are missing from the canonical administrator kind catalog.'); $assert($ids($page['items']) === [221, 220, 219, 218, 217, 216, 215, 211, 208, 207, 206], 'Attention failed to distinguish overdue scheduling, active leases and normal reconciliation waits.'); $assert($page['summary'] === ['total' => 11, 'attention' => 11, 'failed' => 7, 'uncertain' => 2, 'queued_delayed' => 1, 'lease_expired' => 1], 'Filtered summary differs from the matching dataset.'); $seen = []; for ($number = 1; $number <= 12; $number++) { $batch = Operations::page($admin, ['status' => 'all', 'page' => $number]); $seen = array_merge($seen, $ids($batch['items'])); } $assert($seen === range(222, 1), 'Global inventory silently truncated at 200 or duplicated page rows.'); $last = Operations::page($admin, ['status' => 'all', 'page' => 9999, 'per_page' => 100]); $assert($last['pagination']['page'] === 3 && count($last['items']) === 22, 'Last-page clamping failed.'); $filtered = Operations::page($admin, ['kind' => 'expiry_delete', 'host_id' => '8']); $assert($ids($filtered['items']) === [220] && $filtered['summary']['total'] === 1, 'Host/kind filters ignored.'); foreach (["tenant's", '100%_vm', '11111111-1111-4111-8111-111111111110'] as $q) { $matches = Operations::page($admin, ['status' => 'all', 'q' => $q, 'per_page' => 100]); $assert($matches['pagination']['total'] === 216, 'Bound instance name/UUID search mismatch: ' . $q); } $empty = Operations::page($admin, ['q' => "' OR 1=1 --"]); $assert($empty['items'] === [] && $empty['pagination']['from'] === 0 && $empty['pagination']['total_pages'] === 1, 'Search injection or empty-pagination handling failed.'); $exact = Operations::page($admin, ['status' => 'all', 'q' => sprintf('%032x', 219)]); $assert($ids($exact['items']) === [219], 'Operation identifier search failed.'); $detail = Operations::detail($admin, '208'); $assert($detail['job']['actor_id'] === '99' && $detail['job']['owner_id'] === '1' && $detail['job']['instance_id'] === '10' && $detail['job']['order_id'] === '100' && $detail['job']['links']['instance'] === '/admin/cloud/instances?q=11111111-1111-4111-8111-111111111110', 'Administrator actor was incorrectly treated as owner or UUID link was inexact.'); $fallback = Operations::detail($admin, '215')['job']; $assert($fallback['instance_id'] === '10' && $fallback['owner_id'] === '1' && ($fallback['agent_cause_code'] ?? null) === 'storage_clone_failed', 'Verified creation-order fallback or stable Agent cause code missing.'); $assert((Operations::detail($admin, '207')['job']['agent_cause_code'] ?? null) === null, 'Malformed Agent cause code reached the administrator operations DTO.'); foreach (['216' => '1', '217' => '2'] as $id => $owner) { $item = Operations::detail($admin, (string) $id)['job']; $assert($item['owner_id'] === $owner && $item['order_id'] === null && $item['links']['billing'] === null, 'Explicit instance relation was replaced by an unrelated order/owner.'); } $assert(Operations::detail($admin, '218')['job']['instance_id'] === null, 'Cross-owner instance was joined from a malformed order.'); $assert(Operations::detail($admin, '219')['job']['owner_id'] === '1', 'Pre-instance order owner was lost.'); $assert(Operations::detail($admin, '220')['job']['links']['instance'] === null, 'Deleted instance linked to an unavailable active inventory record.'); $orphan = Operations::detail($admin, '221')['job']; $assert($orphan['owner_id'] === null && $orphan['instance_id'] === null && $orphan['phase'] === null, 'Orphan/malformed relation hid a task or fabricated an owner.'); $assert(Operations::detail($admin, '222')['job']['instance_id'] === null, 'Cross-host instance attached to an unrelated job.'); $encoded = json_encode([$page, $detail, Operations::detail($admin, '207')]); foreach (['forbidden-', 'never-expose-', '/srv/private', 'sealed_payload', 'lease_token', 'sealed_credential', 'result_json'] as $secret) { $assert(!str_contains($encoded, $secret), 'Response exposed secret/unsafe field: ' . $secret); } AdminPermission::$superAdmin = false; $masked = Operations::detail($admin, '208')['job']; $assert($masked['owner_email'] !== 'alice@example.test' && $masked['actor_email'] !== 'admin@example.test', 'Read-only administrator identities were not masked.'); $assert(Operations::page($admin, ['status' => 'all', 'q' => 'alice@example.test'])['items'] === [], 'Masked accounts could be inferred via a non-public search field.'); foreach (['status', 'kind', 'host_id', 'q', 'page', 'per_page'] as $key) { $reject(static fn () => Operations::page($admin, [$key => ['bad']]), 400); } foreach ([['status' => 'invented'], ['kind' => 'invented'], ['host_id' => 0], ['per_page' => 30], ['page' => -1], ['page' => '1.5'], ['q' => str_repeat('x', 81)], ['q' => "bad\nquery"], ['unknown' => 'x']] as $input) { $reject(static fn () => Operations::page($admin, $input), 400); } $reject(static fn () => Operations::page($customer), 403); $reject(static fn () => Operations::detail($customer, '208'), 403); $reject(static fn () => Operations::detail($admin, '0'), 400); $reject(static fn () => Operations::detail($admin, '999999'), 404); $connection = $capsule->getConnection(); $counts = []; foreach ([20, 100] as $size) { $connection->enableQueryLog(); $connection->flushQueryLog(); Operations::page($admin, ['status' => 'all', 'per_page' => $size]); $log = $connection->getQueryLog(); $counts[] = count($log); foreach ($log as $query) { $sql = strtolower($query['query']); $assert(str_starts_with($sql, 'select ') && !str_contains($sql, 'cloud_sessions') && !str_contains($sql, 'sealed_payload') && !str_contains($sql, 'lease_token'), 'Read path touched a sensitive field/session or wrote state.'); } } $assert($counts === [3, 3], 'Per-row query amplification detected.'); $app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]); require dirname(__DIR__) . '/config/routes_cloud.php'; $requestApi = static function (string $path, array $query = []) use ($app): array { $request = Request::createFromEnvironment(Environment::mock([ 'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => $path, ]))->withQueryParams($query); $response = $app->process($request, new Response()); return [$response, json_decode((string) $response->getBody(), true)]; }; $login = static function (bool $admin, bool $enabled = true): void { $user = new User(); $user->id = $admin ? 99 : 1; $user->is_admin = $admin; $user->enable = $enabled; $user->isLogin = true; Auth::$user = $user; }; $login(true); [$response, $payload] = $requestApi('/api/v1/admin/operations'); $assert($response->getStatusCode() === 200 && $payload['summary']['total'] === 11 && $response->getHeaderLine('Cache-Control') === 'private, no-store', 'Registered API list contract failed.'); [$response, $payload] = $requestApi('/api/v1/admin/operations/jobs/208'); $assert($response->getStatusCode() === 200 && $payload['job']['owner_id'] === '1', 'Registered detail contract failed.'); [$response] = $requestApi('/api/v1/admin/operations', ['q' => ['bad']]); $assert($response->getStatusCode() === 400, 'Malformed input did not produce a controlled 400.'); [$response] = $requestApi('/api/v1/admin/operations/jobs/999999'); $assert($response->getStatusCode() === 404, 'Unknown job did not return 404.'); $login(false); foreach (['/api/v1/admin/operations', '/api/v1/admin/operations/jobs/208'] as $path) { [$response] = $requestApi($path); $assert($response->getStatusCode() === 403, 'Customer reached administrator operations.'); } $login(true, false); [$response] = $requestApi('/api/v1/admin/operations'); $assert($response->getStatusCode() === 401, 'Disabled account accessed operations.'); Auth::$user = null; [$response] = $requestApi('/api/v1/admin/operations'); $assert($response->getStatusCode() === 401, 'Anonymous account accessed operations.'); $login(true); $direct = (new CloudAdminOperationsController())->index(Request::createFromEnvironment(Environment::mock([ 'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/api/v1/admin/operations', ])), new Response()); $assert($direct->getStatusCode() === 200 && CloudAgentSettingsService::$calls === 0 && CloudSessionService::$calls === 0, 'Controller fallback created a console session or contacted a host Agent.'); $assert($snapshot() === $before, 'Operations read model modified business records.'); $assert(Operations::detail($readonlyAdmin, '211')['job']['can_cancel'] === false, 'Read-only administrators received the task cancellation control.'); $reject(static fn () => Operations::cancel($readonlyAdmin, '211'), 403); // A reboot/reset response can be lost without any durable state that // proves whether the pulse occurred. Administrators must be able to stop // local polling without replaying that power action or mutating the VM. $insertJob(223, ['status' => 'uncertain', 'kind' => 'action', 'dispatched_at' => $now - 20]); $cancelledAction = Operations::cancel($admin, '223'); $assert(($cancelledAction['job']['status'] ?? null) === 'cancelled' && Capsule::table('cloud_instances')->where('id', 10)->value('status') === 'active', 'Administrator could not stop an irreducible uncertain power action safely.'); $cancelled = Operations::cancel($admin, '211'); $cancelledRow = Capsule::table('cloud_jobs')->where('id', 211)->first(); $assert(($cancelled['job']['status'] ?? null) === 'cancelled' && ($cancelled['job']['error_code'] ?? null) === 'admin_cancelled' && ($cancelled['job']['can_cancel'] ?? true) === false && $cancelledRow !== null && $cancelledRow->lease_token === null && (int) $cancelledRow->lease_until === 0 && (int) $cancelledRow->available_at === 0 && (int) $cancelledRow->dispatched_at === $now - 1, 'Administrator cancellation did not persist a terminal retry-stop state.'); $cancelledAgain = Operations::cancel($admin, '211'); $assert(($cancelledAgain['job']['status'] ?? null) === 'cancelled', 'Administrator cancellation was not idempotent.'); $reject(static fn () => Operations::cancel($admin, '207'), 409); $reject(static fn () => Operations::cancel($customer, '211'), 403); echo "Administrator operations SQLite filtering, pagination, privacy, ownership, attention and real API authorization passed (3/3 list queries).\n"; }