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

233 lines
15 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
if ((error_reporting() & $severity) && ($severity & (E_WARNING | E_USER_WARNING | E_DEPRECATED))) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
return false;
});
// Only synthetic data: this fixture never connects to a database or an engine.
$now = time();
$common = [
'operation_id' => '11111111111141118111111111111111',
'kind' => 'reinstall', 'kind_label' => '重装系统',
'completed' => true, 'status' => 'failed', 'attempts' => 1,
'effect_may_have_applied' => true, 'safe_to_resubmit' => false,
'effect_resolution' => 'unknown',
'recovery' => [
'pending' => true,
'code' => 'recovery_waiting_connection',
'message' => '宿主机 Agent 或网络暂不可用;通信恢复后系统仍会继续自动核对。',
'last_checked_at' => $now - 60,
'next_check_at' => $now + 240,
],
'error' => '回执超时,操作效果可能已发生', 'phase' => null,
'host_id' => '7', 'host_name' => '香港宿主机 A', 'region' => 'HongKong',
'actor_id' => '42', 'actor_name' => '演示管理员', 'actor_email' => 'a***@example.test',
'owner_id' => '43', 'owner_name' => '演示客户', 'owner_email' => 'd***@example.test',
'instance_id' => '101', 'instance_name' => 'vm-demo',
'instance_uuid' => '22222222-2222-4222-8222-222222222222', 'instance_status' => 'active',
'order_id' => null, 'created_at' => $now - 7200, 'updated_at' => $now - 60,
'dispatched_at' => $now - 7100, 'available_at' => $now - 30, 'lease_until' => null,
'attention' => true, 'attention_reason' => 'unresolved_effect',
'can_inspect' => true, 'inspect_reason' => '可执行只读核对',
'links' => ['instance' => '/admin/cloud/instances?q=22222222-2222-4222-8222-222222222222', 'billing' => null],
'display' => ['kind' => '重装系统', 'status' => '已失败', 'attention' => '资源已锁定', 'lease' => '已终止'],
];
$items = [
$common + ['id' => '41'],
array_replace($common, ['id' => '42', 'kind' => 'create', 'kind_label' => '创建实例',
'error' => '镜像不可用,创建未完成', 'attention_reason' => 'failed', 'order_id' => '301',
'effect_may_have_applied' => false, 'safe_to_resubmit' => false,
'effect_resolution' => 'not_applicable',
'recovery' => null,
'links' => ['instance' => null, 'billing' => '/admin/billing?view=orders&q=301'],
'display' => ['kind' => '创建实例', 'status' => '失败', 'attention' => '执行失败', 'lease' => '未持有执行租约']]),
array_replace($common, ['id' => '43', 'kind' => 'expiry_delete', 'kind_label' => '到期清理',
'completed' => false, 'status' => 'active',
'effect_may_have_applied' => null, 'safe_to_resubmit' => null,
'effect_resolution' => 'not_applicable',
'recovery' => null,
'can_inspect' => false, 'inspect_reason' => '任务未关联可核对的宿主机操作',
'attempts' => 0, 'error' => null, 'phase' => null, 'dispatched_at' => null,
'available_at' => $now - 600, 'attention' => false, 'attention_reason' => null,
'actor_id' => null, 'actor_name' => '系统策略', 'actor_email' => null,
'owner_id' => null, 'owner_name' => null, 'owner_email' => null,
'instance_id' => null, 'instance_name' => null, 'instance_uuid' => null, 'instance_status' => null,
'host_id' => null, 'host_name' => '', 'region' => '', 'links' => ['instance' => null, 'billing' => null],
'display' => ['kind' => '到期清理', 'status' => '执行中', 'attention' => '', 'lease' => '未持有执行租约']]),
array_replace($common, ['id' => '44', 'kind' => 'host_storage_configure',
'kind_label' => '配置宿主机存储', 'instance_id' => null,
'instance_name' => null, 'instance_uuid' => null,
'instance_status' => null, 'owner_id' => null, 'owner_name' => null,
'owner_email' => null, 'recovery' => null]),
array_replace($common, ['id' => '45', 'status' => 'succeeded',
'error' => null, 'effect_may_have_applied' => false,
'effect_resolution' => 'applied',
'recovery' => [
'pending' => true,
'code' => 'recovery_dispatch_repair_instance_state_conflict',
'message' => '派发账本已修复,但任务状态仍与恢复证据矛盾;资源保持锁定并持续核对。',
'last_checked_at' => $now - 60,
'next_check_at' => $now + 240,
]]),
];
$page = [
'items' => $items,
'pagination' => ['page' => 1, 'per_page' => 20, 'total' => 44, 'total_pages' => 3, 'from' => 1, 'to' => 4],
'summary' => ['total' => 44, 'active' => 1, 'succeeded' => 20,
'failed' => 22, 'attention' => 24, 'locked' => 1],
'summary_links' => [
'all' => '/admin/operations',
'active' => '/admin/operations?status=active',
'attention' => '/admin/operations?status=attention',
'failed' => '/admin/operations?status=failed',
'locked' => '/admin/operations?status=locked',
],
'filters' => ['status' => 'all', 'kind' => '', 'host_id' => null, 'q' => '', 'page' => 1, 'per_page' => 20],
'hosts' => [['id' => '7', 'name' => '香港宿主机 A', 'region' => 'HongKong']],
'kinds' => [['value' => 'create', 'label' => '创建实例'], ['value' => 'reinstall', 'label' => '重装系统'], ['value' => 'expiry_delete', 'label' => '到期清理']],
'generated_at' => $now,
];
$details = [];
foreach ($items as $item) {
$details[$item['id']] = ['job' => $item, 'notes' => [
'任务记录来自数据库快照,不是引擎实时状态。',
'最早可执行时间并不保证任务会在该时刻执行;本页只在明确只读证据和清理计划后开放对应操作。',
], 'generated_at' => $now];
}
$health = ['checked_at' => $now, 'checks' => [
['key' => 'main_database', 'label' => '业务数据库', 'status' => 'ok', 'message' => '数据库可读', 'checked_at' => $now],
['key' => 'log_database', 'label' => '日志数据库', 'status' => 'ok', 'message' => '数据库可读', 'checked_at' => $now],
['key' => 'engine', 'label' => '引擎', 'status' => 'ok', 'message' => '已验证引擎响应,不代表宿主机均正常', 'checked_at' => $now],
['key' => 'redis', 'label' => 'Redis', 'status' => 'disabled', 'message' => '未启用 Redis 缓存', 'checked_at' => $now],
['key' => 'worker', 'label' => '任务处理', 'status' => 'busy', 'message' => '正在处理任务', 'checked_at' => $now, 'last_seen_at' => $now - 3, 'last_success_at' => $now - 60, 'active_count' => 1],
['key' => 'policy', 'label' => '策略检查', 'status' => 'unknown', 'message' => '未收到心跳,请确认服务已启动', 'checked_at' => $now, 'last_seen_at' => null],
['key' => 'lifecycle', 'label' => '生命周期', 'status' => 'warning', 'message' => '最近活动已超过预期时间', 'checked_at' => $now, 'last_seen_at' => $now - 600],
]];
$smarty = new Smarty();
$compileDir = sys_get_temp_dir() . '/admin-operations-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('operations_page', $payload);
$smarty->assign('operations_error', $error);
$smarty->assign('operations_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/operations.tpl');
};
foreach ($argv ?? [] as $arg) {
if (str_starts_with($arg, '--render-page=')) {
$payload = json_decode(base64_decode(substr($arg, 14), true), true, 512, JSON_THROW_ON_ERROR);
echo $render($payload, $payload === null ? '任务数据暂不可用,请稍后重试' : '');
exit;
}
}
$html = $render($page);
$failedHtml = $render(null, '任务数据暂不可用,请稍后重试');
if (in_array('--fixture', $argv ?? [], true)) {
echo json_encode(['html' => $html, 'failed_html' => $failedHtml, 'page' => $page, 'details' => $details, 'health' => $health],
JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
exit;
}
$assert = static function (bool $ok, string $message): void { if (!$ok) throw new RuntimeException($message); };
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="UTF-8">' . $html);
$xpath = new DOMXPath($dom);
$assert($xpath->query('//tbody[@id="operations-body"]/tr')->length === 5, 'SSR must include all task rows.');
$assert($xpath->query('//tr[@data-operation-id="45"]//strong[contains(@class,"text-warning") and contains(.,"安全恢复中")]')->length === 1
&& $xpath->query('//tr[@data-operation-id="45"]//strong[contains(@class,"text-success")]')->length === 0,
'A succeeded terminal receipt with a sticky repair incident was falsely rendered as ordinary success.');
$assert(str_contains($dom->textContent, 'vm-demo') && str_contains($dom->textContent, '系统策略')
&& str_contains($dom->textContent, '安全恢复中')
&& str_contains($dom->textContent, '仍会继续自动核对')
&& str_contains($dom->textContent, '后续任务须沿用已定义固定池的路径')
&& str_contains($dom->textContent, '执行中'),
'Useful task records and terminal safety state are absent before JavaScript.');
$assert($xpath->query('//select[@name="status"]/option[@value="all" and @selected]')->length === 1,
'The default task list must expose all active and terminal receipts.');
$assert($xpath->query('//select[@name="status"]/option[@value="locked" and contains(.,"资源已锁定")]')->length === 1,
'The task list must expose the exact resource-locked filter.');
$assert($xpath->query('//select[@name="status"]/option[@value="attention" and contains(.,"需要处理")]')->length === 1,
'The task list must expose the actionable attention filter.');
$assert($xpath->query('//*[@data-operation-summary-status]')->length === 5
&& $xpath->query('//*[@data-operation-summary-status="all" and @aria-current="page" and @href="/admin/operations"]')->length === 1
&& $xpath->query('//*[@data-operation-summary-status="attention" and @href="/admin/operations?status=attention"]')->length === 1,
'Task summaries must be progressively enhanced links with one active state.');
$assert($xpath->query('//dialog[@data-admin-instance-drawer and @id="operation-detail"]')->length === 1,
'Task detail must reuse the existing drawer.');
$assert($xpath->query('//*[@id="operations-health-body"]//p')->length === 1
&& !str_contains($html, '数据库可读'), 'SSR must not pretend to have checked runtime health.');
$assert($xpath->query('//button[contains(@id,"retry") or contains(@id,"refund") or contains(@id,"stop-auto") or contains(@id,"abort-job") or contains(@id,"cleanup")]')->length === 0
&& $xpath->query('//button[@id="operation-detail-inspect" and @hidden]')->length === 1
&& $xpath->query('//button[@id="operation-detail-repair-vpc" and @hidden]')->length === 1
&& $xpath->query('//button[@id="operation-detail-retire-vpc-host" and @hidden]')->length === 1
&& $xpath->query('//button[@id="operation-detail-force-delete" and @hidden]')->length === 1
&& $xpath->query('//*[@id="operation-effect-resolution" and @hidden]')->length === 1,
'The task list must expose no replay/stop mutation and keep audited fence resolution inside detail.');
$smarty->assign('admin_can_manage', false);
$readOnlyHtml = $render($page);
$assert(!str_contains($readOnlyHtml, 'operation-effect-submit" type="button" hidden')
&& !str_contains($readOnlyHtml, 'data-operation-stop-auto'),
'Read-only rendering must not reintroduce a task replay/stop control.');
$smarty->assign('admin_can_manage', true);
$filtered = $page;
$filtered['filters'] = array_replace($page['filters'], ['status' => 'failed', 'kind' => 'create', 'host_id' => '7', 'q' => 'sample']);
$filtered['pagination']['per_page'] = 50;
$filtered['summary_links'] = [
'all' => '/admin/operations?q=sample&kind=create&host_id=7&per_page=50',
'active' => '/admin/operations?status=active&q=sample&kind=create&host_id=7&per_page=50',
'attention' => '/admin/operations?status=attention&q=sample&kind=create&host_id=7&per_page=50',
'failed' => '/admin/operations?status=failed&q=sample&kind=create&host_id=7&per_page=50',
'locked' => '/admin/operations?status=locked&q=sample&kind=create&host_id=7&per_page=50',
];
$dom->loadHTML('<?xml encoding="UTF-8">' . $render($filtered));
$xpath = new DOMXPath($dom);
foreach (['status' => 'failed', 'kind' => 'create', 'host_id' => '7', 'per_page' => '50'] as $name => $value) {
$assert($xpath->query('//select[@name="' . $name . '"]/option[@value="' . $value . '" and @selected]')->length === 1,
'SSR filter selection missing: ' . $name);
}
$assert($xpath->query('//*[@data-operation-summary-status="failed" and @aria-current="page"]')->length === 1
&& $xpath->query('//*[@data-operation-summary-status="attention" and contains(@href,"status=attention") and contains(@href,"q=sample")]')->length === 1,
'Filtered summary navigation lost its active state or scope filters.');
$unsafe = $page;
$unsafe['items'][0]['instance_name'] = '</script><img src=x onerror=alert(1)>';
$unsafe['items'][0]['error'] = '<script>window.unsafe=1</script>';
$unsafe['hosts'][0]['name'] = '" onmouseover="alert(2)';
$unsafe['filters']['q'] = '" autofocus onfocus="alert(3)';
$unsafeHtml = $render($unsafe);
$dom->loadHTML('<?xml encoding="UTF-8">' . $unsafeHtml);
$xpath = new DOMXPath($dom);
$assert($xpath->query('//*[@onerror or @onmouseover or @onfocus]')->length === 0,
'Untrusted task content became an executable attribute.');
$assert(!str_contains($unsafeHtml, '<script>window.unsafe=1</script>')
&& str_contains($dom->textContent, '</script><img src=x onerror=alert(1)>'),
'Task names and error summaries must render as text.');
$empty = $page;
$empty['items'] = [];
$empty['pagination'] = ['page' => 1, 'per_page' => 20, 'total' => 0, 'total_pages' => 1, 'from' => 0, 'to' => 0];
$empty['summary'] = array_fill_keys(array_keys($page['summary']), 0);
$emptyHtml = $render($empty);
$assert(str_contains($emptyHtml, '没有符合条件的任务。') && !str_contains($emptyHtml, 'vm-demo'),
'Empty results must not show stale rows.');
$dom->loadHTML('<?xml encoding="UTF-8">' . $failedHtml);
$xpath = new DOMXPath($dom);
$assert(str_contains($failedHtml, '任务数据暂不可用,请稍后重试')
&& trim($xpath->query('//*[@id="operations-summary-total"]')->item(0)->textContent) === '—'
&& !str_contains($failedHtml, '已读取 0 条任务'), 'Unavailable task data must not be disguised as a successful zero.');
echo "Administrator operations SSR, filters, read-only, escaping and empty/error rendering passed.\n";