feat: add admin system journal log page
parent
e290872e5a
commit
b1429f61b4
@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Services\Cloud\CloudAccess;
|
||||
use App\Services\Cloud\CloudSystemJournalService;
|
||||
|
||||
/** Read-only administrator endpoint for the managed system journal. */
|
||||
final class CloudAdminSystemLogsController
|
||||
{
|
||||
public function index($request, $response)
|
||||
{
|
||||
$payload = CloudSystemJournalService::page(
|
||||
$request->getAttribute('cloud_actor') ?? CloudAccess::actor(false),
|
||||
$request->getQueryParams()
|
||||
);
|
||||
return $response->withJson($payload)->withHeader('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,353 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
|
||||
/**
|
||||
* Read-only access to the journal entries emitted by the Virt Cloud units.
|
||||
*
|
||||
* The panel deliberately does not expose an arbitrary unit or a shell
|
||||
* command. Journal messages can contain operational secrets, so the scope is
|
||||
* limited to the services owned by this application and every response is
|
||||
* bounded by a line and message limit.
|
||||
*/
|
||||
final class CloudSystemJournalService
|
||||
{
|
||||
private const MAX_FETCH_LINES = 500;
|
||||
private const MAX_PROCESS_SECONDS = 10;
|
||||
private const MAX_OUTPUT_BYTES = 8388608;
|
||||
private const MAX_MESSAGE_LENGTH = 16000;
|
||||
private const MAX_CURSOR_LENGTH = 512;
|
||||
private const MAX_QUERY_LENGTH = 120;
|
||||
|
||||
private const UNITS = [
|
||||
'virt-cloud-engine.service',
|
||||
'virt-cloud-worker.service',
|
||||
'virt-cloud-lifecycle.service',
|
||||
'virt-cloud-policy-worker@1.service',
|
||||
'virt-cloud-policy-worker@2.service',
|
||||
'virt-cloud-update.service',
|
||||
// libvirt may be provided by either the legacy daemon or the split
|
||||
// virtqemud stack; both are read-only host diagnostics.
|
||||
'libvirtd.service',
|
||||
'virtqemud.service',
|
||||
'virtlogd.service',
|
||||
'virtlockd.service',
|
||||
];
|
||||
|
||||
private const PRIORITIES = [
|
||||
'error' => '0..3',
|
||||
'warning' => '4',
|
||||
'notice' => '5',
|
||||
'info' => '6',
|
||||
'debug' => '7',
|
||||
];
|
||||
|
||||
private const PRIORITY_LABELS = [
|
||||
0 => '紧急', 1 => '警报', 2 => '严重', 3 => '错误',
|
||||
4 => '警告', 5 => '通知', 6 => '信息', 7 => '调试',
|
||||
];
|
||||
|
||||
public static function page(array $actor, array $input): array
|
||||
{
|
||||
self::authorize($actor);
|
||||
return (new self())->read($input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse journalctl's JSON-lines output. Kept public for contract tests and
|
||||
* for deployments that want to validate a captured journal fixture.
|
||||
*/
|
||||
public static function parseJournalJson(string $output, ?array $allowedUnits = null): array
|
||||
{
|
||||
$allowed = array_fill_keys($allowedUnits ?? self::UNITS, true);
|
||||
$rows = [];
|
||||
foreach (preg_split('/\r?\n/', $output) ?: [] as $line) {
|
||||
if ($line === '') {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$entry = json_decode($line, true, 32,
|
||||
JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR);
|
||||
} catch (\Throwable $ignored) {
|
||||
continue;
|
||||
}
|
||||
if (!is_array($entry)) {
|
||||
continue;
|
||||
}
|
||||
$unit = self::cleanText($entry['_SYSTEMD_UNIT'] ?? '');
|
||||
if ($unit === '' || !isset($allowed[$unit])) {
|
||||
continue;
|
||||
}
|
||||
$priority = filter_var($entry['PRIORITY'] ?? null, FILTER_VALIDATE_INT);
|
||||
if ($priority === false || $priority === null || $priority < 0 || $priority > 7) {
|
||||
$priority = 6;
|
||||
}
|
||||
$micros = filter_var($entry['__REALTIME_TIMESTAMP'] ?? null, FILTER_VALIDATE_INT);
|
||||
$timestamp = $micros !== false && $micros !== null && $micros > 0
|
||||
? self::timestamp((int) $micros) : null;
|
||||
$message = self::cleanMessage($entry['MESSAGE'] ?? '');
|
||||
$rows[] = [
|
||||
'timestamp' => $timestamp,
|
||||
'unit' => $unit,
|
||||
'priority' => $priority,
|
||||
'level' => self::PRIORITY_LABELS[$priority],
|
||||
'message' => $message,
|
||||
'pid' => self::cleanText($entry['_PID'] ?? ''),
|
||||
'process' => self::cleanText($entry['_COMM'] ?? ($entry['SYSLOG_IDENTIFIER'] ?? '')),
|
||||
'hostname' => self::cleanText($entry['_HOSTNAME'] ?? ''),
|
||||
'cursor' => self::cleanCursor($entry['__CURSOR'] ?? ''),
|
||||
];
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
private function read(array $input): array
|
||||
{
|
||||
$filters = $this->filters($input);
|
||||
$units = $filters['unit'] === '' ? self::UNITS : [$filters['unit']];
|
||||
$args = [
|
||||
'--no-pager', '--output=json', '--utc', '--all', '--reverse',
|
||||
'--lines=' . min(self::MAX_FETCH_LINES, $filters['limit'] + 1),
|
||||
];
|
||||
foreach ($units as $unit) {
|
||||
$args[] = '--unit=' . $unit;
|
||||
}
|
||||
if ($filters['priority'] !== '') {
|
||||
$args[] = '--priority=' . self::PRIORITIES[$filters['priority']];
|
||||
}
|
||||
if ($filters['since'] !== '') {
|
||||
$args[] = '--since=@' . $this->epoch($filters['since']);
|
||||
}
|
||||
if ($filters['until'] !== '') {
|
||||
$args[] = '--until=@' . $this->epoch($filters['until']);
|
||||
}
|
||||
if ($filters['cursor'] !== '') {
|
||||
$args[] = '--before-cursor=' . $filters['cursor'];
|
||||
}
|
||||
|
||||
$result = $this->run($args);
|
||||
if ($result['exit_code'] !== 0) {
|
||||
$stderr = strtolower($result['stderr']);
|
||||
if ($result['stdout'] === '' && str_contains($stderr, 'no journal files')) {
|
||||
$result['stdout'] = '';
|
||||
} else {
|
||||
throw new CloudError(
|
||||
'系统日志暂时无法读取,请确认 PHP-FPM 用户有 systemd journal 读取权限。',
|
||||
503
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$rows = self::parseJournalJson($result['stdout'], $units);
|
||||
if ($filters['query'] !== '') {
|
||||
$needle = function_exists('mb_strtolower')
|
||||
? mb_strtolower($filters['query'], 'UTF-8') : strtolower($filters['query']);
|
||||
$rows = array_values(array_filter($rows, static function (array $row) use ($needle): bool {
|
||||
$haystack = $row['unit'] . ' ' . $row['process'] . ' ' . $row['message'];
|
||||
$haystack = function_exists('mb_strtolower')
|
||||
? mb_strtolower($haystack, 'UTF-8') : strtolower($haystack);
|
||||
return str_contains($haystack, $needle);
|
||||
}));
|
||||
}
|
||||
|
||||
$hasMore = count($rows) > $filters['limit'];
|
||||
if ($hasMore) {
|
||||
$rows = array_slice($rows, 0, $filters['limit']);
|
||||
}
|
||||
$nextCursor = $hasMore && $rows !== [] ? ($rows[array_key_last($rows)]['cursor'] ?? null) : null;
|
||||
// A journal without cursors cannot be paged safely; report the
|
||||
// bounded first window instead of presenting a dead “load more” link.
|
||||
$hasMore = $hasMore && $nextCursor !== null && $nextCursor !== '';
|
||||
$errorCount = 0;
|
||||
$warningCount = 0;
|
||||
foreach ($rows as $row) {
|
||||
if ((int) $row['priority'] <= 3) {
|
||||
$errorCount++;
|
||||
} elseif ((int) $row['priority'] === 4) {
|
||||
$warningCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'items' => $rows,
|
||||
'units' => self::UNITS,
|
||||
'summary' => [
|
||||
'total' => count($rows), 'error_count' => $errorCount,
|
||||
'warning_count' => $warningCount,
|
||||
'latest_at' => $rows[0]['timestamp'] ?? null,
|
||||
],
|
||||
'filters' => [
|
||||
'unit' => $filters['unit'], 'priority' => $filters['priority'],
|
||||
'query' => $filters['query'], 'since' => $filters['since'],
|
||||
'until' => $filters['until'], 'limit' => $filters['limit'],
|
||||
],
|
||||
'pagination' => ['next_cursor' => $nextCursor, 'has_more' => $hasMore],
|
||||
'generated_at' => time(),
|
||||
'limited' => $hasMore,
|
||||
];
|
||||
}
|
||||
|
||||
private function filters(array $input): array
|
||||
{
|
||||
$unit = trim((string) ($input['unit'] ?? ''));
|
||||
if ($unit !== '' && !in_array($unit, self::UNITS, true)) {
|
||||
throw new CloudError('日志服务筛选项无效', 400);
|
||||
}
|
||||
$priority = strtolower(trim((string) ($input['priority'] ?? '')));
|
||||
if ($priority !== '' && !isset(self::PRIORITIES[$priority])) {
|
||||
throw new CloudError('日志级别筛选项无效', 400);
|
||||
}
|
||||
$query = trim((string) ($input['query'] ?? ''));
|
||||
if (strlen($query) > self::MAX_QUERY_LENGTH) {
|
||||
throw new CloudError('日志关键词过长', 400);
|
||||
}
|
||||
$limit = (int) ($input['limit'] ?? 100);
|
||||
if (!in_array($limit, [50, 100, 200], true)) {
|
||||
throw new CloudError('日志条数只能为 50、100 或 200', 400);
|
||||
}
|
||||
$since = $this->dateFilter($input['since'] ?? '');
|
||||
$until = $this->dateFilter($input['until'] ?? '');
|
||||
if ($since !== '' && $until !== '' && $this->epoch($since) > $this->epoch($until)) {
|
||||
throw new CloudError('日志开始时间不能晚于结束时间', 400);
|
||||
}
|
||||
$cursor = self::cleanCursor($input['cursor'] ?? '');
|
||||
if ((string) ($input['cursor'] ?? '') !== '' && $cursor === '') {
|
||||
throw new CloudError('日志游标无效', 400);
|
||||
}
|
||||
return compact('unit', 'priority', 'query', 'limit', 'since', 'until', 'cursor');
|
||||
}
|
||||
|
||||
private function dateFilter($value): string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
if ($value === '') {
|
||||
return '';
|
||||
}
|
||||
if (!preg_match('/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2})?$/D', $value)) {
|
||||
throw new CloudError('日志时间格式无效', 400);
|
||||
}
|
||||
$value = str_replace(' ', 'T', $value);
|
||||
$format = strlen($value) === 16 ? '!Y-m-d\\TH:i' : '!Y-m-d\\TH:i:s';
|
||||
$zone = new DateTimeZone(date_default_timezone_get());
|
||||
$date = DateTimeImmutable::createFromFormat($format, $value, $zone);
|
||||
$errors = DateTimeImmutable::getLastErrors();
|
||||
if (!$date || ($errors !== false && ($errors['warning_count'] || $errors['error_count']))) {
|
||||
throw new CloudError('日志时间无效', 400);
|
||||
}
|
||||
// Keep the canonical value in the panel timezone so datetime-local
|
||||
// controls round-trip correctly. epoch() performs the UTC conversion
|
||||
// only when building journalctl arguments.
|
||||
return $date->format('Y-m-d\\TH:i');
|
||||
}
|
||||
|
||||
private function epoch(string $value): int
|
||||
{
|
||||
$date = new DateTimeImmutable($value, new DateTimeZone(date_default_timezone_get()));
|
||||
return $date->getTimestamp();
|
||||
}
|
||||
|
||||
private function run(array $args): array
|
||||
{
|
||||
$binary = is_executable('/usr/bin/journalctl') ? '/usr/bin/journalctl'
|
||||
: (is_executable('/bin/journalctl') ? '/bin/journalctl' : '');
|
||||
if ($binary === '') {
|
||||
throw new CloudError('系统日志工具 journalctl 不可用', 503);
|
||||
}
|
||||
$stderrPath = tempnam(sys_get_temp_dir(), 'virt-cloud-journal-');
|
||||
if ($stderrPath === false) {
|
||||
throw new CloudError('系统日志读取暂不可用', 503);
|
||||
}
|
||||
$stdin = fopen('/dev/null', 'r');
|
||||
$descriptors = [0 => $stdin, 1 => ['pipe', 'w'], 2 => ['file', $stderrPath, 'a']];
|
||||
$process = proc_open(array_merge([$binary], $args), $descriptors, $pipes, null, null,
|
||||
['bypass_shell' => true]);
|
||||
if (!is_resource($process)) {
|
||||
@fclose($stdin);
|
||||
@unlink($stderrPath);
|
||||
throw new CloudError('系统日志读取进程无法启动', 503);
|
||||
}
|
||||
stream_set_blocking($pipes[1], false);
|
||||
$stdout = '';
|
||||
$deadline = microtime(true) + self::MAX_PROCESS_SECONDS;
|
||||
$timedOut = false;
|
||||
while (true) {
|
||||
$status = proc_get_status($process);
|
||||
$read = [$pipes[1]];
|
||||
$write = null;
|
||||
$except = null;
|
||||
$remaining = max(0.0, $deadline - microtime(true));
|
||||
$seconds = (int) min(1, floor($remaining));
|
||||
$microseconds = (int) min(999999, max(0, round(($remaining - $seconds) * 1000000)));
|
||||
$ready = $remaining > 0 ? @stream_select($read, $write, $except, $seconds, $microseconds) : 0;
|
||||
if ($ready > 0) {
|
||||
$chunk = fread($pipes[1], 65536);
|
||||
if ($chunk !== false && $chunk !== '') {
|
||||
$stdout .= $chunk;
|
||||
if (strlen($stdout) > self::MAX_OUTPUT_BYTES) {
|
||||
proc_terminate($process, 9);
|
||||
fclose($pipes[1]);
|
||||
proc_close($process);
|
||||
@fclose($stdin);
|
||||
@unlink($stderrPath);
|
||||
throw new CloudError('系统日志输出过大,请缩小时间范围后重试。', 422);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!$status['running'] && feof($pipes[1])) {
|
||||
break;
|
||||
}
|
||||
if (microtime(true) >= $deadline) {
|
||||
$timedOut = true;
|
||||
proc_terminate($process, 9);
|
||||
break;
|
||||
}
|
||||
}
|
||||
fclose($pipes[1]);
|
||||
$exitCode = proc_close($process);
|
||||
@fclose($stdin);
|
||||
$stderr = (string) @file_get_contents($stderrPath);
|
||||
@unlink($stderrPath);
|
||||
if ($timedOut) {
|
||||
throw new CloudError('读取系统日志超时,请缩小时间范围后重试。', 503);
|
||||
}
|
||||
return ['exit_code' => $exitCode, 'stdout' => (string) $stdout, 'stderr' => $stderr];
|
||||
}
|
||||
|
||||
private static function authorize(array $actor): void
|
||||
{
|
||||
if (!($actor['is_admin'] ?? false)) {
|
||||
throw new CloudError('需要管理员权限', 403);
|
||||
}
|
||||
}
|
||||
|
||||
private static function timestamp(int $micros): string
|
||||
{
|
||||
$seconds = intdiv($micros, 1000000);
|
||||
$fraction = $micros % 1000000;
|
||||
return gmdate('Y-m-d\\TH:i:s', $seconds) . sprintf('.%06dZ', $fraction);
|
||||
}
|
||||
|
||||
private static function cleanMessage($value): string
|
||||
{
|
||||
$value = is_scalar($value) ? (string) $value : json_encode($value, JSON_UNESCAPED_UNICODE);
|
||||
$value = (string) $value;
|
||||
$value = preg_replace('/(?:\\x1B\\[[0-?]*[ -\\/]*[@-~])|[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]/', '', $value) ?? '';
|
||||
return function_exists('mb_substr') ? mb_substr($value, 0, self::MAX_MESSAGE_LENGTH, 'UTF-8')
|
||||
: substr($value, 0, self::MAX_MESSAGE_LENGTH);
|
||||
}
|
||||
|
||||
private static function cleanText($value): string
|
||||
{
|
||||
return self::cleanMessage($value);
|
||||
}
|
||||
|
||||
private static function cleanCursor($value): string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
return strlen($value) <= self::MAX_CURSOR_LENGTH
|
||||
&& preg_match('/^[A-Za-z0-9_.:;=+@\\/-]+$/D', $value) === 1 ? $value : '';
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,131 @@
|
||||
[data-admin-system-logs] .system-logs-help {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-advanced {
|
||||
border-top: 1px solid #e5ebf2;
|
||||
margin-top: 12px;
|
||||
padding-top: 10px;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-advanced summary {
|
||||
color: #475467;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-table-wrap {
|
||||
max-height: min(68vh, 760px);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-table thead th {
|
||||
background: #f8fafc;
|
||||
color: #667085;
|
||||
font-size: 12px;
|
||||
letter-spacing: .02em;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
white-space: nowrap;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-row {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-row:focus-visible {
|
||||
outline: 2px solid #18a87f;
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-row td:first-child {
|
||||
color: #667085;
|
||||
font-family: var(--bs-font-monospace, monospace);
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-message {
|
||||
display: block;
|
||||
max-width: 900px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-level {
|
||||
font-weight: 800;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-pagination {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-detail-message {
|
||||
max-height: 420px;
|
||||
margin: 20px 0 0;
|
||||
padding: 16px;
|
||||
border: 1px solid #e5ebf2;
|
||||
border-radius: 8px;
|
||||
background: #f8fafc;
|
||||
color: #1d2939;
|
||||
font: 13px/1.65 var(--bs-font-monospace, monospace);
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
@media (max-width: 767.98px) {
|
||||
[data-admin-system-logs] .system-logs-help {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-table thead {
|
||||
display: none;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-table,
|
||||
[data-admin-system-logs] .system-logs-table tbody,
|
||||
[data-admin-system-logs] .system-logs-table tr,
|
||||
[data-admin-system-logs] .system-logs-table td {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-table tr {
|
||||
border-bottom: 1px solid #e5ebf2;
|
||||
padding: 10px 0;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-table td {
|
||||
border: 0;
|
||||
padding: 5px 0 5px 42%;
|
||||
position: relative;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-table td::before {
|
||||
color: #667085;
|
||||
content: attr(data-label);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
left: 0;
|
||||
position: absolute;
|
||||
text-align: left;
|
||||
top: 5px;
|
||||
}
|
||||
|
||||
[data-admin-system-logs] .system-logs-message {
|
||||
max-width: none;
|
||||
white-space: normal;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,106 @@
|
||||
<?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-engine.service',
|
||||
'PRIORITY' => '3',
|
||||
'__REALTIME_TIMESTAMP' => '1791273697115460',
|
||||
'MESSAGE' => "engine failed\x1b[31m\nwith control",
|
||||
'_PID' => '12', '_COMM' => 'python', '_HOSTNAME' => 'host-a',
|
||||
'__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-worker.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-engine.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")
|
||||
&& !str_contains($rows[0]['message'], "\x0a"),
|
||||
'Journal message control characters must be removed before rendering.');
|
||||
$assert($rows[1]['priority'] === 6 && $rows[1]['level'] === '信息',
|
||||
'Out-of-range journal priorities must normalize to informational logs.');
|
||||
|
||||
$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');
|
||||
|
||||
$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($middleware, '/api/v1/admin/system-logs'),
|
||||
'System journal API route or its API middleware boundary is 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"),
|
||||
'The page controller must authorize a local administrator and bootstrap safe data.');
|
||||
$assert(str_contains($apiController, 'CloudSystemJournalService::page(')
|
||||
&& str_contains($apiController, "getAttribute('cloud_actor')"),
|
||||
'The API controller must use the journal service and authenticated cloud actor.');
|
||||
|
||||
$assert(str_contains($service, "'/usr/bin/journalctl'")
|
||||
&& str_contains($service, "'--output=json'")
|
||||
&& str_contains($service, "'bypass_shell' => true")
|
||||
&& 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-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, '/api/v1/admin/system-logs'),
|
||||
'Browser log rendering must remain text-only, same-origin and cancellable.');
|
||||
|
||||
echo "Administrator system journal route, parser, authorization and safety contracts passed.\n";
|
||||
Loading…
Reference in New Issue