-
-
-
-
Instances
-
实例目录
-
客户资源与操作权限仍由后台校验,此页面仅用于集中查看。
-
-
-
-
-
- | 实例 | 用户 | 宿主机 | 状态 | 公网 IP | 配置 |
- | 实例数据加载中 |
-
-
-
+
+ 在管实例
{$instance_page.summary.total|escape}
+ 7 天内到期
{$instance_page.summary.expiring|escape}
+ 网络受限
{$instance_page.summary.network_restricted|escape}
+ 异常任务实例
{$instance_page.summary.attention|escape}
+
+
+
+
+ 管理员虚拟机列表| 实例 | 用户 | 所在位置 | 公网 IP | 配置 | 状态 | 用量与期限 | 操作 |
+ {foreach $instance_page.items as $vm}
+
+ | {$vm.name|escape}#{$vm.id|escape} · {$vm.os_name|default:'系统未记录'|escape} |
+ {if $vm.user_url}{$vm.user_name|escape}{else}{$vm.user_name|escape}{/if}ID {$vm.user_id|escape} |
+ {$vm.host_name|escape}{$vm.region|default:'地区未记录'|escape} |
+ {$vm.public_ip|default:'未记录'|escape}{if $vm.public_ip}{/if} |
+ {$vm.display.configuration|escape}{$vm.plan_name|default:'无关联套餐'|escape} |
+ 电源:待获取服务:{$vm.display.service|escape}网络:{$vm.display.network|escape}{if $vm.active_job}任务 #{$vm.active_job.id|escape} · {if $vm.active_job.status == 'uncertain'}待核对{elseif $vm.active_job.status == 'running'}执行中{elseif $vm.active_job.status == 'queued'}已排队{else}{$vm.active_job.status|escape}{/if}{/if} |
+ {$vm.display.traffic|escape}{$vm.display.expiry|escape}{if $vm.service_expires_at && $vm.service_status != 'exempt'}到期 {$vm.service_expires_at|date_format:'%Y-%m-%d'|escape}{/if} |
+ |
+
+ {foreachelse}| {if $instance_error}实例暂时无法读取,请点击刷新重试。{else}没有符合条件的实例。{/if} |
{/foreach}
+
+
+
+
+
+
+
{include file='admin/static_footer.tpl'}
diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl
index 99d6b93b..ceb3a5de 100644
--- a/web/resources/views/venix/layout_assets.tpl
+++ b/web/resources/views/venix/layout_assets.tpl
@@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
-{assign var=venix_asset_version value='2026093004' scope='global'}
+{assign var=venix_asset_version value='2026093005' scope='global'}
diff --git a/web/tests/AdminInstanceViewTest.php b/web/tests/AdminInstanceViewTest.php
new file mode 100644
index 00000000..c419e981
--- /dev/null
+++ b/web/tests/AdminInstanceViewTest.php
@@ -0,0 +1,141 @@
+ '11111111-1111-4111-8111-111111111111',
+ 'user_id' => 42, 'user_name' => '演示客户', 'user_email' => 'd***@example.test',
+ 'user_url' => '/admin/user/42/edit', 'host_id' => 7,
+ 'host_name' => '香港宿主机 A', 'region' => 'HongKong', 'plan_name' => '标准云服务器',
+ 'os_name' => 'Debian 12', 'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 40,
+ 'instance_status' => 'active', 'service_status' => 'active', 'network_status' => 'active',
+ 'service_expires_at' => $now + 4 * 86400, 'traffic_used_bytes' => 21474836480,
+ 'traffic_quota_bytes' => 107374182400, 'traffic_synced_at' => $now - 60,
+ 'created_at' => $now - 86400, 'active_job' => null, 'state' => 'unknown',
+ 'can_manage' => true,
+ 'display' => [
+ 'configuration' => '2 vCPU · 2 GiB · 40 GiB', 'traffic' => '20 GiB / 100 GiB',
+ 'expiry' => '4 天后到期', 'service' => '服务正常',
+ 'network' => '网络正常', 'lifecycle' => '在管',
+ ],
+];
+$items = [
+ array_replace($common, ['id' => '101', 'name' => 'vm-production',
+ 'public_ip' => '192.0.2.101', 'detail_url' => '/user/cloud/instances/101']),
+ array_replace($common, ['id' => '102', 'name' => 'vm-network-limited',
+ 'public_ip' => '192.0.2.102', 'detail_url' => '/user/cloud/instances/102',
+ 'network_status' => 'blocked_traffic', 'traffic_used_bytes' => 107374182400,
+ 'display' => array_replace($common['display'], [
+ 'traffic' => '100 GiB / 100 GiB', 'network' => '流量耗尽已断网',
+ ])]),
+ array_replace($common, ['id' => '103', 'name' => 'vm-task-reconciliation',
+ 'public_ip' => '192.0.2.103', 'detail_url' => '/user/cloud/instances/103',
+ 'active_job' => ['id' => '61', 'kind' => 'reinstall', 'status' => 'uncertain',
+ 'attempts' => 3, 'error' => '等待核对操作结果', 'phase' => 'reconcile',
+ 'created_at' => $now - 300, 'updated_at' => $now - 10]]),
+];
+$page = [
+ 'items' => $items,
+ 'pagination' => ['page' => 1, 'per_page' => 20, 'total' => 43,
+ 'total_pages' => 3, 'from' => 1, 'to' => 3],
+ 'summary' => ['total' => 43, 'expiring' => 3, 'network_restricted' => 1, 'attention' => 1],
+ 'filters' => ['q' => '', 'user_id' => null, 'host_id' => null, 'service_status' => '',
+ 'expiry' => 'all', 'attention' => 'all', 'sort' => 'newest', 'page' => 1, 'per_page' => 20],
+ 'hosts' => [['id' => 7, 'name' => '香港宿主机 A', 'region' => 'HongKong']],
+ 'generated_at' => $now,
+];
+$detail = [
+ 'instance' => array_replace($items[0], [
+ 'public_ip_cidr' => '192.0.2.101/24', 'gateway' => '192.0.2.1',
+ 'dns_servers' => ['1.1.1.1', '8.8.8.8'], 'engine_name' => 'vc-1111111111114111',
+ 'bandwidth_mbps' => 100, 'os_source' => 'cloud', 'login_name' => 'root',
+ 'current_period_started_at' => $now - 26 * 86400,
+ 'current_period_ends_at' => $now + 4 * 86400, 'renewal_price' => '10.00',
+ 'renewal_days' => 30, 'renewal_traffic_bytes' => 107374182400,
+ 'traffic_download_bytes' => 10737418240, 'traffic_upload_bytes' => 10737418240,
+ 'updated_at' => $now - 60,
+ ]),
+ 'jobs' => [['id' => '62', 'kind' => 'action', 'status' => 'succeeded',
+ 'attempts' => 1, 'error' => null, 'phase' => 'complete',
+ 'created_at' => $now - 3600, 'updated_at' => $now - 3500]],
+ 'jobs_truncated' => false,
+ 'invoices' => [['id' => '201', 'purpose' => 'provision', 'status' => 'paid',
+ 'amount' => '10.00', 'created_at' => $now - 86400,
+ 'detail_url' => '/admin/billing?detail=201']],
+ 'invoices_truncated' => false,
+];
+
+$smarty = new Smarty();
+$compileDir = sys_get_temp_dir() . '/admin-instance-view-' . bin2hex(random_bytes(6));
+mkdir($compileDir);
+$smarty->setCompileDir($compileDir);
+$smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix');
+$smarty->assign('config', ['appName' => 'Venix Test']);
+$smarty->assign('cdn', '');
+$smarty->assign('user', (object) ['isLogin' => false]);
+$smarty->assign('admin_can_manage', true);
+$smarty->assign('admin_csrf_token', 'fixture-not-a-real-token');
+$render = static function (?array $payload, string $error = '') use ($smarty): string {
+ $smarty->assign('instance_page', $payload);
+ $smarty->assign('instance_error', $error);
+ $smarty->assign('instance_bootstrap_json', json_encode($payload,
+ JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
+ | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE));
+ return $smarty->fetch('admin/cloud/instances.tpl');
+};
+$assert = static function (bool $ok, string $message): void {
+ if (!$ok) throw new RuntimeException($message);
+};
+$html = $render($page);
+if (in_array('--fixture', $argv ?? [], true)) {
+ echo json_encode(['html' => $html, 'billing_html' => $smarty->fetch('admin/billing.tpl'),
+ 'page' => $page, 'detail' => $detail],
+ JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
+ exit;
+}
+
+// The table is usable without waiting for JavaScript or any host connection.
+$dom = new DOMDocument();
+libxml_use_internal_errors(true);
+$dom->loadHTML('' . $html);
+$xpath = new DOMXPath($dom);
+$assert($xpath->query('//tbody//tr')->length === 3, 'SSR did not render all fixture rows.');
+$assert(str_contains($dom->textContent, '192.0.2.101')
+ && str_contains($dom->textContent, '20 GiB / 100 GiB')
+ && str_contains($dom->textContent, '香港宿主机 A'), 'Useful instance data is missing before scripts run.');
+$assert($xpath->query('//select[@name="per_page"]/option[@value="20"]')->length === 1
+ && $xpath->query('//select[@name="per_page"]/option[@selected and @value!="20"]')->length === 0,
+ 'SSR did not retain the current page size.');
+
+$unsafe = $page;
+$unsafe['items'][0]['name'] = '

';
+$unsafe['items'][0]['user_name'] = '';
+$unsafe['items'][0]['host_name'] = '" onmouseover="alert(2)';
+$unsafeHtml = $render($unsafe);
+$dom->loadHTML('' . $unsafeHtml);
+$xpath = new DOMXPath($dom);
+$assert($xpath->query('//*[@onerror or @onmouseover]')->length === 0,
+ 'Untrusted row content escaped into an executable attribute.');
+$assert(!str_contains($unsafeHtml, '')
+ && str_contains($dom->textContent, '

'),
+ 'Untrusted names must render as text, not active markup.');
+
+$empty = $page;
+$empty['items'] = [];
+$empty['pagination'] = ['page' => 1, 'per_page' => 20, 'total' => 0, 'total_pages' => 1, 'from' => 0, 'to' => 0];
+$empty['summary'] = ['total' => 0, 'expiring' => 0, 'network_restricted' => 0, 'attention' => 0];
+$emptyHtml = $render($empty);
+$assert(!str_contains($emptyHtml, 'vm-production'), 'Empty result retained an old instance.');
+$failedHtml = $render(null, '实例信息暂不可用,请重试');
+$assert(str_contains($failedHtml, '实例信息暂不可用,请重试')
+ && !str_contains($failedHtml, 'vm-production'), 'Unavailable data was disguised as a successful list.');
+
+echo "Administrator instance SSR, escaping and empty/error rendering passed.\n";
diff --git a/web/tests/CloudAdminInstanceServiceTest.php b/web/tests/CloudAdminInstanceServiceTest.php
new file mode 100644
index 00000000..6d627f6d
--- /dev/null
+++ b/web/tests/CloudAdminInstanceServiceTest.php
@@ -0,0 +1,502 @@
+httpStatus === $status, $message . ': unexpected HTTP status ' . $error->httpStatus);
+ return;
+ }
+ throw new RuntimeException($message . ': request was accepted.');
+ };
+ $ids = static fn (array $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('default');
+ $schema->create('user', static function (Blueprint $table): void {
+ $table->increments('id');
+ $table->string('user_name');
+ $table->string('email');
+ $table->boolean('is_admin')->default(false);
+ $table->boolean('enable')->default(true);
+ $table->string('pass')->default('must-not-expose-account-password');
+ });
+ $schema->create('cloud_hosts', static function (Blueprint $table): void {
+ $table->increments('id');
+ $table->string('name');
+ $table->string('region')->default('');
+ $table->string('country_code')->default('');
+ $table->boolean('enabled')->default(true);
+ });
+ $schema->create('shop', static function (Blueprint $table): void {
+ $table->increments('id');
+ $table->string('name');
+ });
+ $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('order_id')->nullable();
+ $table->integer('plan_id')->nullable();
+ $table->integer('current_period_id')->nullable();
+ $table->string('name');
+ $table->string('status')->default('active');
+ $table->string('service_status')->default('active');
+ $table->string('network_status')->default('active');
+ $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->integer('lifetime_download_bytes')->default(0);
+ $table->integer('lifetime_upload_bytes')->default(0);
+ $table->integer('traffic_synced_at')->default(0);
+ $table->integer('suspended_at')->nullable();
+ $table->integer('network_suspended_at')->nullable();
+ $table->text('spec_json');
+ $table->text('credential_cipher')->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('user_id');
+ $table->integer('starts_at');
+ $table->integer('ends_at');
+ $table->string('status');
+ });
+ $schema->create('cloud_orders', static function (Blueprint $table): void {
+ $table->increments('id');
+ $table->integer('instance_id')->nullable();
+ $table->integer('user_id');
+ $table->integer('plan_id')->nullable();
+ $table->integer('host_id')->default(7);
+ $table->string('amount')->default('10.00');
+ $table->string('status')->default('succeeded');
+ $table->text('spec_json')->default('{}');
+ $table->text('payload_cipher')->default('must-not-expose-order-payload');
+ $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->string('operation_id');
+ $table->integer('instance_id')->nullable();
+ $table->integer('order_id')->nullable();
+ $table->integer('user_id');
+ $table->integer('host_id')->default(7);
+ $table->string('kind');
+ $table->string('status');
+ $table->integer('attempts')->default(0);
+ $table->string('error_code')->nullable();
+ $table->text('payload_cipher')->default('must-not-expose-job-payload');
+ $table->text('result_json')->nullable();
+ $table->integer('created_at');
+ $table->integer('updated_at');
+ });
+ $schema->create('cloud_invoices', static function (Blueprint $table): void {
+ $table->increments('id');
+ $table->string('invoice_no');
+ $table->string('purpose')->default('renewal');
+ $table->integer('instance_id')->nullable();
+ $table->integer('order_id')->nullable();
+ $table->integer('user_id');
+ $table->integer('plan_id')->nullable();
+ $table->integer('renewal_id')->nullable();
+ $table->integer('due_at');
+ $table->string('amount')->default('10.00');
+ $table->string('status')->default('open');
+ $table->string('paid_via')->nullable();
+ $table->string('payment_reference')->default('must-not-expose-payment-reference');
+ $table->integer('paid_at')->nullable();
+ $table->integer('created_at');
+ $table->integer('updated_at');
+ });
+ Capsule::table('user')->insert([
+ ['id' => 1, 'user_name' => 'Alice Ops', 'email' => 'alice@example.test'],
+ ['id' => 2, 'user_name' => 'Bob Client', 'email' => 'bob@example.test'],
+ ['id' => 99, 'user_name' => 'Root Operator', 'email' => 'root@example.test'],
+ ]);
+ Capsule::table('cloud_hosts')->insert([
+ ['id' => 7, 'name' => 'Hong Kong 07', 'region' => 'HongKong', 'country_code' => 'HK'],
+ ['id' => 8, 'name' => 'Tokyo 08', 'region' => 'Tokyo', 'country_code' => 'JP'],
+ ]);
+ Capsule::table('shop')->insert(['id' => 3, 'name' => 'Small Cloud']);
+ $now = time();
+ $base = [
+ 'host_id' => 7, 'user_id' => 1, 'plan_id' => 3,
+ 'status' => 'active', 'service_status' => 'active', 'network_status' => 'active',
+ 'expires_at' => $now + 30 * 86400, 'renewal_price' => '10.00',
+ 'renewal_days' => 30, 'renewal_traffic_bytes' => 2000,
+ 'traffic_quota_bytes' => 2000, 'traffic_download_bytes' => 300,
+ 'traffic_upload_bytes' => 200, 'traffic_synced_at' => $now - 30,
+ 'credential_cipher' => 'must-not-expose-instance-credential',
+ 'spec_json' => json_encode([
+ 'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 40,
+ 'os_source' => 'cloud_template', 'os_name' => 'AlmaLinux 10',
+ 'public_ip_cidr' => '198.51.100.10/24',
+ 'state' => 'running', 'console_port' => 5900,
+ 'password' => 'must-not-expose-spec-password',
+ 'api_token' => 'must-not-expose-api-token',
+ 'unreviewed_note' => 'must-not-expose-unknown-spec-field',
+ 'disks' => [['capacity_gib' => 40, 'source' => 'must-not-expose-disk-path']],
+ ]),
+ 'created_at' => $now - 600, 'updated_at' => $now - 300,
+ ];
+ $insertInstance = static function (int $id, array $overrides = []) use ($base): void {
+ Capsule::table('cloud_instances')->insert(array_replace($base, [
+ 'id' => $id, 'uuid' => sprintf('11111111-1111-4111-8111-%012d', $id),
+ 'name' => 'vm-' . $id,
+ ], $overrides));
+ };
+ for ($id = 1; $id <= 205; $id++) {
+ $insertInstance($id);
+ }
+ $insertInstance(206, ['user_id' => 2, 'host_id' => 8, 'order_id' => 601,
+ 'current_period_id' => 1, 'expires_at' => $now + 2 * 86400]);
+ $insertInstance(207, ['expires_at' => $now - 3600, 'service_status' => 'expired', 'order_id' => 602]);
+ $insertInstance(208, ['expires_at' => null, 'service_status' => 'exempt']);
+ $insertInstance(209, ['network_status' => 'blocked_traffic']);
+ $insertInstance(210, ['network_status' => 'restore_failed']);
+ $insertInstance(211, ['status' => 'deleted', 'expires_at' => $now + 3600]);
+ $insertInstance(212, ['user_id' => 404, 'host_id' => 404, 'plan_id' => 404, 'expires_at' => null]);
+ $insertInstance(213, ['name' => "tenant's 100%_ready"]);
+ $insertInstance(214, ['spec_json' => json_encode([
+ 'public_ip_cidr' => '203.0.113.74/24', 'vcpu' => 4, 'memory_mib' => 4096,
+ ])]);
+ Capsule::table('cloud_service_periods')->insert([
+ 'id' => 1, 'instance_id' => 206, 'user_id' => 2,
+ 'starts_at' => $now - 28 * 86400, 'ends_at' => $now + 2 * 86400, 'status' => 'active',
+ ]);
+ Capsule::table('cloud_orders')->insert([
+ ['id' => 601, 'instance_id' => 206, 'user_id' => 2],
+ ['id' => 602, 'instance_id' => 207, 'user_id' => 2],
+ ]);
+ $insertJob = static function (int $id, array $overrides = []) use ($now): void {
+ Capsule::table('cloud_jobs')->insert(array_replace([
+ 'id' => $id, 'operation_id' => sprintf('%032d', $id),
+ 'instance_id' => 206, 'user_id' => 99, 'kind' => 'action',
+ 'status' => 'succeeded', 'created_at' => $now - 100, 'updated_at' => $now,
+ 'result_json' => json_encode([
+ 'phase' => 'finished', 'generated_password' => 'must-not-expose-job-password',
+ 'unreviewed_note' => 'must-not-expose-unknown-job-result',
+ ]),
+ ], $overrides));
+ };
+ for ($id = 1; $id <= 26; $id++) {
+ $insertJob($id, ['status' => $id === 26 ? 'running' : 'succeeded']);
+ }
+ $insertJob(27, ['instance_id' => 209, 'status' => 'failed', 'error_code' => 'test_failure']);
+ $insertJob(28, ['instance_id' => 210, 'status' => 'uncertain', 'updated_at' => $now - 172800]);
+ $insertJob(29, ['instance_id' => 207, 'status' => 'failed', 'updated_at' => $now - 172800]);
+ $insertJob(30, ['instance_id' => 211, 'status' => 'failed']);
+ $insertInvoice = static function (int $id, array $overrides = []) use ($now): void {
+ Capsule::table('cloud_invoices')->insert(array_replace([
+ 'id' => $id, 'invoice_no' => 'TEST-' . $id,
+ 'instance_id' => 206, 'user_id' => 2,
+ 'due_at' => $now + 3600, 'created_at' => $now - 100, 'updated_at' => $now,
+ ], $overrides));
+ };
+ for ($id = 1; $id <= 25; $id++) {
+ $insertInvoice($id);
+ }
+ $insertInvoice(26, ['user_id' => 1]);
+ $insertInvoice(27, ['instance_id' => null, 'order_id' => 601]);
+ $insertInvoice(28, ['instance_id' => null, 'order_id' => 602, 'user_id' => 1]);
+
+ $admin = ['user_id' => 99, 'is_admin' => true, 'is_super_admin' => true, 'can_manage' => true];
+ $readOnly = ['user_id' => 99, 'is_admin' => true, 'is_super_admin' => false, 'can_manage' => false];
+ $customer = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false, 'can_manage' => false];
+
+ // All timestamps are deliberately identical: ordering must include the ID.
+ $page = CloudAdminInstanceService::page($admin);
+ $assert($page['pagination']['total'] === 213 && count($page['items']) === 20
+ && $ids($page['items']) === array_values(array_diff(range(214, 194), [211])),
+ 'Administrator first page lost records above 200, included deleted rows, or sorted ties unstably.');
+ $assert($page['summary']['total'] === 213 && $page['summary']['expiring'] === 1
+ && $page['summary']['network_restricted'] === 2 && $page['summary']['attention'] === 2,
+ 'Database statistics must cover the complete filtered population and preserve state meanings.');
+ $assert(!isset($page['summary']['running']) && !isset($page['summary']['stopped']),
+ 'Database-only summary fabricated a live power-state count.');
+ $seen = [];
+ for ($number = 1; $number <= 3; $number++) {
+ $chunk = CloudAdminInstanceService::page($admin, ['page' => (string) $number, 'per_page' => '100']);
+ $seen = array_merge($seen, $ids($chunk['items']));
+ }
+ $assert(count($seen) === 213 && count(array_unique($seen)) === 213
+ && $seen === array_values(array_diff(range(214, 1), [211])),
+ 'Paging beyond 200 duplicated or silently truncated instances.');
+ $last = CloudAdminInstanceService::page($admin, ['page' => '9999', 'per_page' => '100']);
+ $assert($last['pagination']['page'] === 3 && count($last['items']) === 13,
+ 'Out-of-range pages did not clamp to the last valid page.');
+ $oldest = CloudAdminInstanceService::page($admin, ['sort' => 'oldest']);
+ $assert($ids($oldest['items']) === range(1, 20), 'Oldest sorting needs a stable ascending ID order.');
+ $expiry = CloudAdminInstanceService::page($admin, ['sort' => 'expiry']);
+ $assert((int) $expiry['items'][0]['id'] === 207, 'Expiry sorting did not put the oldest expiry first.');
+
+ foreach ([['user_id' => '2'], ['host_id' => '8'], ['user_id' => '2', 'host_id' => '8']] as $filter) {
+ $filtered = CloudAdminInstanceService::page($admin, $filter);
+ $assert($ids($filtered['items']) === [206] && $filtered['summary']['total'] === 1
+ && $filtered['summary']['expiring'] === 1,
+ 'Exact owner/host filters or filtered summary crossed instance boundaries.');
+ }
+ $empty = CloudAdminInstanceService::page($admin, ['user_id' => '2', 'host_id' => '7']);
+ $assert($empty['items'] === [] && $empty['pagination']['total'] === 0
+ && $empty['pagination']['total_pages'] === 1 && $empty['pagination']['page'] === 1
+ && $empty['summary']['total'] === 0,
+ 'Empty filtered collections returned stale rows or invalid pagination.');
+ foreach ([
+ "tenant's" => [213], '100%_ready' => [213], '%' => [213], '_ready' => [213],
+ '203.0.113.74' => [214], "' OR 1=1 --" => [],
+ '11111111-1111-4111-8111-000000000214' => [214],
+ 'bob@example.test' => [206],
+ ] as $query => $expected) {
+ $searched = CloudAdminInstanceService::page($admin, ['q' => $query]);
+ $assert($ids($searched['items']) === $expected,
+ 'Search must bind quotes, escape SQL wildcards, and correctly match IP/UUID/account: ' . $query);
+ }
+ foreach (['soon' => [206], 'expired' => [207], 'exempt' => [208]] as $mode => $expected) {
+ $filtered = CloudAdminInstanceService::page($admin, ['expiry' => $mode]);
+ $assert($ids($filtered['items']) === $expected,
+ 'Expiry filter confused paid periods, expired instances, or exempt instances: ' . $mode);
+ }
+ $exempt = CloudAdminInstanceService::page($admin, ['service_status' => 'exempt']);
+ $assert($ids($exempt['items']) === [208], 'Exact service-status filter was ignored.');
+ foreach (['network', 'jobs'] as $mode) {
+ $attention = CloudAdminInstanceService::page($admin, ['attention' => $mode]);
+ $assert($ids($attention['items']) === [210, 209],
+ 'Attention filter included deleted/old failed jobs or omitted unresolved jobs/network restrictions.');
+ foreach ($attention['items'] as $item) {
+ $assert($item['state'] === 'unknown', 'Business/network/job state was mistaken for live VM power state.');
+ }
+ }
+ foreach (['page', 'per_page', 'q', 'user_id', 'host_id', 'service_status', 'expiry', 'attention', 'sort'] as $key) {
+ $expectError(static fn () => CloudAdminInstanceService::page($admin, [$key => ['1']]), 400,
+ 'Array-valued filter must be rejected: ' . $key);
+ }
+ foreach ([['page' => '0'], ['page' => '-1'], ['page' => '1.5'], ['user_id' => '0'],
+ ['host_id' => '1 OR 1=1'], ['expiry' => 'running'], ['attention' => 'powered'],
+ ['sort' => 'id; DROP TABLE user'], ['service_status' => 'invented'], ['q' => str_repeat('x', 81)]] as $filter) {
+ $expectError(static fn () => CloudAdminInstanceService::page($admin, $filter), 400,
+ 'Malformed filters must return a controlled client error');
+ }
+ $expectError(static fn () => CloudAdminInstanceService::page($customer), 403,
+ 'Ordinary customers must not access the administrator read model');
+ $expectError(static fn () => CloudAdminInstanceService::detail($customer, '206'), 403,
+ 'Ordinary customers must not inspect another owner through admin detail');
+ foreach (['211', '999999'] as $id) {
+ $expectError(static fn () => CloudAdminInstanceService::detail($admin, $id), 404,
+ 'Missing or deleted detail must not disclose an instance');
+ }
+ $orphan = CloudAdminInstanceService::detail($admin, '212');
+ $assert((int) $orphan['instance']['id'] === 212 && $orphan['instance']['state'] === 'unknown',
+ 'Missing user, host or plan caused an instance to disappear.');
+ $assert($orphan['instance']['display']['service'] === '期限未记录',
+ 'An active record with an unknown billing deadline must not be labelled service-available.');
+
+ $detail = CloudAdminInstanceService::detail($admin, '206');
+ $assert((int) $detail['instance']['active_job']['id'] === 26
+ && $detail['instance']['active_job']['status'] === 'running'
+ && $detail['instance']['can_manage'] === true,
+ 'An operation submitted by a super-admin was lost because the job actor differs from the instance owner.');
+ $assert(count($detail['jobs']) === 20 && $detail['jobs_truncated'] === true
+ && $ids($detail['jobs']) === range(26, 7),
+ 'Instance tasks must be newest-first, bounded to 20, and explicitly marked truncated.');
+ $expectedInvoiceIds = array_merge([27], range(25, 7));
+ $assert(count($detail['invoices']) === 20 && $detail['invoices_truncated'] === true
+ && $ids($detail['invoices']) === $expectedInvoiceIds,
+ 'Invoice detail included a foreign owner, missed the valid order link, or silently truncated history.');
+ $crossOwner = CloudAdminInstanceService::detail($admin, '207');
+ $assert($crossOwner['invoices'] === [],
+ 'A same-owner invoice joined through another owner\'s order crossed the billing boundary.');
+ foreach ($detail['invoices'] as $invoice) {
+ $assert(str_starts_with($invoice['detail_url'], '/admin/billing?detail='),
+ 'Invoice links must target the administrator ledger, not the customer route.');
+ }
+ $encoded = json_encode([$page, $detail, $crossOwner, $orphan], JSON_THROW_ON_ERROR);
+ $assert(!str_contains($encoded, 'must-not-expose')
+ && !str_contains($encoded, 'credential_cipher')
+ && !str_contains($encoded, 'payload_cipher')
+ && !str_contains($encoded, 'result_json')
+ && !str_contains($encoded, 'console_port')
+ && !str_contains($encoded, 'unreviewed_note'),
+ 'The administrator DTO allowlist leaked credentials, paths, or an unreviewed metadata/result field.');
+
+ AdminPermission::$superAdmin = false;
+ $masked = CloudAdminInstanceService::page($readOnly, ['user_id' => '2']);
+ $assert($masked['items'][0]['can_manage'] === false
+ && $masked['items'][0]['user_email'] !== 'bob@example.test'
+ && $masked['items'][0]['user_name'] !== 'Bob Client',
+ 'Read-only administrators gained global operation controls or unmasked account data.');
+ $hiddenSearch = CloudAdminInstanceService::page($readOnly, ['q' => 'bob@example.test']);
+ $assert($hiddenSearch['items'] === [], 'Read-only account search became an oracle for masked email addresses.');
+ AdminPermission::$superAdmin = true;
+
+ $queryCounts = [];
+ foreach ([20, 100] as $size) {
+ $connection = Capsule::connection('default');
+ $connection->flushQueryLog();
+ $connection->enableQueryLog();
+ CloudAdminInstanceService::page($admin, ['per_page' => (string) $size]);
+ $queries = $connection->getQueryLog();
+ $connection->disableQueryLog();
+ $queryCounts[] = count($queries);
+ foreach ($queries as $query) {
+ $assert(preg_match('/^\s*(select|with)\b/i', $query['query']) === 1,
+ 'Instance reads unexpectedly wrote business or session data.');
+ $assert(!str_contains(strtolower($query['query']), 'cloud_sessions'),
+ 'Database-only instance reads touched the private engine session table.');
+ }
+ }
+ $assert($queryCounts[0] <= 8 && $queryCounts[1] <= $queryCounts[0],
+ 'Increasing page size introduced per-instance SQL queries: ' . implode(', ', $queryCounts));
+ $login = static function (bool $isAdmin, bool $isSuper = false, bool $enabled = true): void {
+ $user = new User();
+ $user->id = $isAdmin ? 99 : 1;
+ $user->enable = $enabled ? 1 : 0;
+ $user->is_admin = $isAdmin;
+ $user->isLogin = true;
+ Auth::$user = $user;
+ AdminPermission::$superAdmin = $isSuper;
+ };
+ $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(true, true);
+ [$response, $payload] = $requestApi('/api/v1/admin/instances', ['user_id' => '2']);
+ $assert($response->getStatusCode() === 200 && $ids($payload['items']) === [206]
+ && $response->getHeaderLine('Cache-Control') === 'private, no-store',
+ 'The registered administrator list route did not provide a private scoped database response.');
+ [$response, $payload] = $requestApi('/api/v1/admin/instances/206');
+ $assert($response->getStatusCode() === 200 && (int) $payload['instance']['id'] === 206,
+ 'The registered administrator detail route did not dispatch the database read model.');
+ foreach ([['q' => ['bad']], ['page' => '0'], ['host_id' => ['8']]] as $query) {
+ [$response, $payload] = $requestApi('/api/v1/admin/instances', $query);
+ $assert($response->getStatusCode() === 400 && isset($payload['error']),
+ 'Malformed query parameters escaped CloudApi as a server error.');
+ }
+ foreach (['211', '999999'] as $id) {
+ [$response] = $requestApi('/api/v1/admin/instances/' . $id);
+ $assert($response->getStatusCode() === 404, 'Registered detail disclosed a missing/deleted instance.');
+ }
+ $login(true);
+ [$response, $payload] = $requestApi('/api/v1/admin/instances/206');
+ $assert($response->getStatusCode() === 200 && $payload['instance']['can_manage'] === false,
+ 'Read-only administrators must retain global read access without mutation capability.');
+ $login(false);
+ foreach (['/api/v1/admin/instances', '/api/v1/admin/instances/206'] as $path) {
+ [$response] = $requestApi($path);
+ $assert($response->getStatusCode() === 403, 'A customer reached a registered administrator route.');
+ }
+ $login(true, true, false);
+ [$response] = $requestApi('/api/v1/admin/instances');
+ $assert($response->getStatusCode() === 401, 'Disabled accounts bypassed CloudAccess authentication.');
+ Auth::$user = null;
+ [$response] = $requestApi('/api/v1/admin/instances');
+ $assert($response->getStatusCode() === 401, 'Anonymous requests bypassed CloudAccess authentication.');
+
+ // The controller also works without middleware attributes and must request
+ // actor(false), preserving the no-engine-session guarantee in this path.
+ $login(true, true);
+ $direct = (new CloudAdminInstanceController())->index(
+ Request::createFromEnvironment(Environment::mock([
+ 'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/api/v1/admin/instances',
+ ])), new Response()
+ );
+ $assert($direct->getStatusCode() === 200, 'Controller fallback authentication broke database-only reads.');
+ $assert(CloudEngineClient::$calls === 0 && CloudSessionService::$calls === 0,
+ 'The service, middleware, or controller read path contacted the private engine/session service.');
+
+ echo 'Administrator instance SQL filtering, pagination, ownership, DTO safety and bounded queries passed ('
+ . implode('/', $queryCounts) . " queries for 20/100 rows).\n";
+ echo "Administrator instance registered API routes, authorization, validation and session isolation passed.\n";
+}
diff --git a/web/tests/VirtualizationAssetsTest.php b/web/tests/VirtualizationAssetsTest.php
index 85b36001..e6781d81 100644
--- a/web/tests/VirtualizationAssetsTest.php
+++ b/web/tests/VirtualizationAssetsTest.php
@@ -601,9 +601,6 @@ $assert(str_contains($cloudSchema, 'CREATE TABLE IF NOT EXISTS cloud_template_re
'CloudTemplateDeletionService::fetchAuthoritativeCatalog')
&& str_contains($deploymentPageService, 'forgetTemplate('),
'Template retirement must block active provisioning/reinstall references and stale SSR catalogs.');
-$assert(str_contains($adminScript, 'function unixTime(value)')
- && str_contains($adminScript, 'orderStatus(record.status)'),
- 'Order diagnostics must format timestamps and localize task status');
$assert(str_contains($clientScript,
"makeElement('div', 'cloud-order-actions cloud-invoice-list-actions')")
&& str_contains($clientStyles, '.cloud-orders { min-height: 0;'),
@@ -746,7 +743,7 @@ $assert(!str_contains($clientScript, '/renewals')
'Retired direct-renewal controls must not remain in the user UI');
$assert(str_contains($cloudAdminController, "'known_owners' => (object) CloudInstanceDiscovery::knownOwners"),
'Empty VM ownership maps must be encoded as a JSON object for engine discovery');
-foreach (['hosts/index.tpl', 'cloud/instances.tpl', 'cloud/rescue.tpl', 'cloud/templates.tpl'] as $template) {
+foreach (['hosts/index.tpl', 'cloud/rescue.tpl', 'cloud/templates.tpl'] as $template) {
$source = file_get_contents($views . '/admin/' . $template);
$assert(str_contains($source, '/cloud/admin.js?v={$venix_asset_version}'),
'Cloud admin script cache busting missing: ' . $template);