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

174 lines
9.7 KiB
PHP

<?php
/**
* Contract checks for the read-only administrator system journal page.
*
* This intentionally avoids the application bootstrap: a checkout without
* Composer dependencies can still validate the route, command and escaping
* boundaries, while the parser fixture exercises the service directly.
*/
$root = dirname(__DIR__);
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
require_once $root . '/app/Services/Cloud/CloudSystemJournalService.php';
$fixture = implode("\n", [
json_encode([
'_SYSTEMD_UNIT' => 'virt-cloud-worker.service',
'PRIORITY' => '3',
'__REALTIME_TIMESTAMP' => '1791273697115460',
'MESSAGE' => "worker failed\x1b[31m\nwith control token=sk-1234567890",
'_PID' => '12', '_COMM' => 'php', '_HOSTNAME' => 'panel-a',
'CODE_FILE' => '/srv/virt-cloud/web/app/Command/CloudWorker.php',
'_CMDLINE' => 'secret command',
'SECRET_TOKEN' => 'do-not-render', 'ACCESS_TOKEN' => 'do-not-render',
'DATABASE_URL' => 'do-not-render', 'COOKIE_HEADER' => 'do-not-render',
'OPERATION_ID' => 'operation-123',
'__CURSOR' => 's=abc;i=1',
], JSON_UNESCAPED_UNICODE),
// Entries from other units must not cross the service allowlist.
json_encode([
'_SYSTEMD_UNIT' => 'ssh.service', 'PRIORITY' => 3,
'MESSAGE' => 'private host log',
], JSON_UNESCAPED_UNICODE),
'{invalid json',
json_encode([
'_SYSTEMD_UNIT' => 'virt-cloud-lifecycle.service',
'PRIORITY' => 99, 'MESSAGE' => 'invalid priority is normalized',
], JSON_UNESCAPED_UNICODE),
]);
$rows = \App\Services\Cloud\CloudSystemJournalService::parseJournalJson($fixture);
$assert(count($rows) === 2, 'Journal parser must ignore malformed and disallowed units.');
$assert($rows[0]['unit'] === 'virt-cloud-worker.service'
&& $rows[0]['priority'] === 3
&& $rows[0]['timestamp'] === '2026-10-06T08:01:37.115460Z',
'Journal timestamp, unit and priority normalization changed.');
$assert(!str_contains($rows[0]['message'], "\x1b"),
'Journal message ANSI control sequences must be removed before rendering.');
$assert(!str_contains($rows[0]['message'], 'sk-1234567890')
&& $rows[0]['message_redacted'] === true,
'Journal list previews must hide obvious credential material.');
$assert($rows[1]['priority'] === 6 && $rows[1]['level'] === '信息',
'Out-of-range journal priorities must normalize to informational logs.');
$searchRows = \App\Services\Cloud\CloudSystemJournalService::parseJournalJson($fixture, null, true);
$assert(str_contains($searchRows[0]['_search_fields'], 'OPERATION_ID operation-123'),
'Journal keyword matching must include bounded structured fields.');
$detail = \App\Services\Cloud\CloudSystemJournalService::parseJournalDetailJson($fixture, 's=abc;i=1');
$assert(is_array($detail)
&& $detail['cursor'] === 's=abc;i=1'
&& $detail['fields']['CODE_FILE'] === '/srv/virt-cloud/web/app/Command/CloudWorker.php'
&& $detail['fields']['OPERATION_ID'] === 'operation-123'
&& $detail['fields']['SECRET_TOKEN'] === '[已隐藏]'
&& $detail['fields']['ACCESS_TOKEN'] === '[已隐藏]'
&& $detail['fields']['DATABASE_URL'] === '[已隐藏]'
&& $detail['fields']['COOKIE_HEADER'] === '[已隐藏]'
&& $detail['message_redacted'] === true
&& in_array('_CMDLINE', $detail['omitted_fields'], true)
&& !in_array('SECRET_TOKEN', $detail['omitted_fields'], true),
'Journal detail must bind the exact cursor, retain diagnostics and hide secret fields.');
$assert(\App\Services\Cloud\CloudSystemJournalService::parseJournalDetailJson(
$fixture, 's=missing;i=9'
) === null, 'Journal detail must reject a cursor that was not returned.');
$routes = file_get_contents($root . '/config/routes.php');
$apiRoutes = file_get_contents($root . '/config/routes_cloud.php');
$middleware = file_get_contents($root . '/app/Middleware/CloudApi.php');
$pageController = file_get_contents($root . '/app/Controllers/Admin/CloudPageController.php');
$apiController = file_get_contents($root . '/app/Controllers/CloudAdminSystemLogsController.php');
$service = file_get_contents($root . '/app/Services/Cloud/CloudSystemJournalService.php');
$template = file_get_contents($root . '/resources/views/venix/admin/cloud/system_logs.tpl');
$header = file_get_contents($root . '/resources/views/venix/admin/static_header.tpl');
$browser = file_get_contents($root . '/public/cloud/admin-system-logs.js');
$styles = file_get_contents($root . '/public/cloud/admin-system-logs.css');
$assert(substr_count($routes,
"get('/system-logs', 'App\\Controllers\\Admin\\CloudPageController:systemLogs')") === 1,
'Administrator system log page route is missing or duplicated.');
$assert(substr_count($apiRoutes,
"get('/admin/system-logs', 'App\\Controllers\\CloudAdminSystemLogsController:index')") === 1
&& str_contains($apiRoutes, "get('/admin/system-logs/detail', 'App\\Controllers\\CloudAdminSystemLogsController:detail')")
&& str_contains($middleware, '/api/v1/admin/system-logs'),
'System journal API routes or their API middleware boundary are missing.');
$assert(str_contains($pageController, 'public function systemLogs(')
&& str_contains($pageController, "CloudAccess::actor(false)")
&& str_contains($pageController, "system_logs_bootstrap_json")
&& str_contains($pageController, "admin/cloud/system_logs.tpl")
&& !str_contains($pageController, 'CloudSystemJournalService::page('),
'The page controller must authorize a local administrator without synchronously reading journalctl.');
$assert(str_contains($apiController, 'CloudSystemJournalService::page(')
&& str_contains($apiController, 'CloudSystemJournalService::detail(')
&& str_contains($apiController, "getAttribute('cloud_actor')"),
'The API controller must use the journal service for list and detail reads.');
$assert(str_contains($service, "'/usr/bin/journalctl'")
&& str_contains($service, "'--output=json'")
&& str_contains($service, "'--cursor=' . \$filters['cursor']")
&& str_contains($service, "'--since=' . \$timestamp")
&& str_contains($service, "'--until=' . \$timestamp")
&& str_contains($service, "'--lines=all'")
&& str_contains($service, "'--unit=' . \$unit")
&& str_contains($service, 'cleanJournalTimestamp')
&& str_contains($service, "'--system'")
&& !str_contains($service, "'--after-cursor='")
&& !str_contains($service, '--before-cursor')
&& str_contains($service, "'bypass_shell' => true")
&& str_contains($service, 'MAX_STDERR_BYTES')
&& str_contains($service, 'MAX_PROCESS_SECONDS')
&& str_contains($service, 'stream_set_blocking')
&& str_contains($service, 'stream_select')
&& str_contains($service, 'connection_aborted')
&& str_contains($service, 'insufficient permissions')
&& str_contains($service, 'terminateProcess')
&& str_contains($service, 'message_redacted')
&& str_contains($service, 'redacted_fields')
&& str_contains($service, 'private static function authorize('),
'Journal reads must use fixed journalctl JSON arguments without a shell.');
$assert(str_contains($service, 'private const UNITS = [')
&& str_contains($service, 'virt-cloud-worker.service')
&& str_contains($service, 'virt-cloud-recovery-worker.service')
&& str_contains($service, 'virt-cloud-policy-worker.service')
&& str_contains($service, 'virt-cloud-agent-gateway.service')
&& !str_contains($service, 'virt-cloud-engine.service')
&& str_contains($service, 'MAX_FETCH_LINES')
&& str_contains($service, 'MAX_MESSAGE_LENGTH')
&& str_contains($service, 'MAX_CURSOR_LENGTH'),
'Journal service must keep a fixed unit allowlist and bounded output.');
$assert(!str_contains($service, 'shell_exec(')
&& !str_contains($service, 'exec(')
&& !str_contains($service, 'system(')
&& !str_contains($service, 'popen('),
'Journal service must not execute user-controlled shell commands.');
$assert(str_contains($template, 'system_logs_bootstrap_json|default:\'null\' nofilter')
&& str_contains($pageController, 'JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT'),
'The template must only render the controller-produced, JSON-hex-escaped bootstrap.');
$assert(str_contains($header, 'href="/admin/system-logs"')
&& str_contains($header, "admin_active|default:'' == 'system-logs'"),
'Administrator navigation must expose the system log page with active state.');
$assert(!str_contains($browser, 'innerHTML')
&& str_contains($browser, "credentials: 'same-origin'")
&& str_contains($browser, 'AbortController')
&& str_contains($browser, 'LIST_TIMEOUT_MS')
&& str_contains($browser, 'DETAIL_TIMEOUT_MS')
&& str_contains($browser, 'system-logs-cancel')
&& str_contains($browser, '/detail')
&& str_contains($browser, 'openDrawerWithMotion')
&& str_contains($browser, 'closeDrawerWithMotion')
&& str_contains($browser, 'is-drawer-visible')
&& str_contains($browser, 'state.request !== controller')
&& str_contains($browser, '/api/v1/admin/system-logs'),
'Browser log rendering must remain text-only, same-origin, cancellable, deadline-bound and use the shared visible drawer.');
$assert(str_contains($styles, '#system-logs-detail .system-logs-detail-message')
&& str_contains($styles, '#system-logs-detail #system-logs-detail-fields'),
'Detail styles must target the dialog outside the system log main container.');
$assert(str_contains($template, 'system-logs-detail-fields')
&& str_contains($template, 'system-logs-detail-state')
&& str_contains($template, 'system-logs-cancel'),
'The log page must expose a detail state, full-field container and cancel action.');
echo "Administrator system journal route, parser, authorization and safety contracts passed.\n";