feat: add read-only System Info admin page with health checks and module inventory

New page at /admin/system-info with three tabs:
- Overview: PHP version, SAPI, environment, 6 health checks (DB, schema,
  storage, RBAC baseline, admin role, scheduler heartbeat)
- Modules: table of active modules with version, dependencies, permission count
- Permissions: active/inactive counts and per-source breakdown

Gated behind new system_info.view permission assigned to Admin role.
No mutations — purely diagnostic/observability.

Includes SystemHealthService, SystemInfoService, SystemHealthRepository
with interface, DI registration, i18n keys (de+en), idempotent DB update
script, and 17 new PHPUnit tests.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-22 15:08:02 +01:00
parent be8bf496cb
commit cf8c59d3f8
17 changed files with 1164 additions and 4 deletions

View File

@@ -4,6 +4,7 @@ namespace MintyPHP\App\Container\Registrars;
use MintyPHP\App\AppContainer;
use MintyPHP\App\Container\ContainerRegistrar;
use MintyPHP\App\Module\ModuleRegistry;
use MintyPHP\Http\ApiSystemAuditReporter;
use MintyPHP\Http\CookieStore;
use MintyPHP\Http\CookieStoreInterface;
@@ -42,6 +43,9 @@ use MintyPHP\Service\Security\RateLimiterService;
use MintyPHP\Service\Security\SecurityServicesFactory;
use MintyPHP\Service\Settings\SettingsFrontendTelemetryGateway;
use MintyPHP\Service\Stats\AdminStatsViewDataService;
use MintyPHP\Service\System\SystemHealthService;
use MintyPHP\Service\System\SystemInfoService;
use MintyPHP\Repository\System\SystemHealthRepository;
final class AppServicesRegistrar implements ContainerRegistrar
{
@@ -50,6 +54,15 @@ final class AppServicesRegistrar implements ContainerRegistrar
$container->set(AdminStatsViewDataService::class, static fn (AppContainer $c): AdminStatsViewDataService => new AdminStatsViewDataService(
$c->get(AdminStatsRepository::class)
));
$container->set(SystemHealthRepository::class, static fn (): SystemHealthRepository => new SystemHealthRepository());
$container->set(SystemHealthService::class, static fn (AppContainer $c): SystemHealthService => new SystemHealthService(
$c->get(SystemHealthRepository::class)
));
$container->set(SystemInfoService::class, static fn (AppContainer $c): SystemInfoService => new SystemInfoService(
$c->get(SystemHealthService::class),
$c->get(SystemHealthRepository::class),
$c->has(ModuleRegistry::class) ? $c->get(ModuleRegistry::class) : null
));
$container->set(SearchDataService::class, static fn (AppContainer $c): SearchDataService => new SearchDataService(
$c->get(PermissionService::class),
$c->get(UserTenantRepository::class),

View File

@@ -0,0 +1,113 @@
<?php
namespace MintyPHP\Repository\System;
use MintyPHP\DB;
class SystemHealthRepository implements SystemHealthRepositoryInterface
{
/**
* @return bool True if DB responds to SELECT 1.
*/
public function checkDatabaseConnectivity(): bool
{
return (int) (DB::selectValue('select 1') ?? 0) === 1;
}
/**
* @return list<string> Table names present in the current schema.
*/
public function listPresentTables(array $requiredTables): array
{
$rows = DB::select(
'select table_name from information_schema.tables where table_schema = database() and table_name in (???)',
$requiredTables
);
$present = [];
foreach ((array) $rows as $row) {
$table = (string) (($row['tables']['table_name'] ?? $row['table_name'] ?? ''));
if ($table !== '') {
$present[] = $table;
}
}
return array_values(array_unique($present));
}
/**
* @return array{last_heartbeat_at: string, last_result: string, last_error_code: string}|null
*/
public function getSchedulerStatus(): ?array
{
$row = DB::selectOne('select last_heartbeat_at, last_result, last_error_code from scheduler_runtime_status where id = 1 limit 1');
$status = is_array($row) ? ($row['scheduler_runtime_status'] ?? $row) : null;
if (!is_array($status)) {
return null;
}
return [
'last_heartbeat_at' => trim((string) ($status['last_heartbeat_at'] ?? '')),
'last_result' => trim((string) ($status['last_result'] ?? 'unknown')),
'last_error_code' => trim((string) ($status['last_error_code'] ?? '')),
];
}
/**
* @return list<string> Active permission keys matching the given list.
*/
public function listActivePermissionKeys(array $keys): array
{
$rows = DB::select(
'select `key` from permissions where active = 1 and `key` in (???)',
$keys
);
$present = [];
foreach ((array) $rows as $row) {
$key = (string) (($row['permissions']['key'] ?? $row['key'] ?? ''));
if ($key !== '') {
$present[] = $key;
}
}
return array_values(array_unique($present));
}
public function countAdminUsers(): int
{
return (int) (DB::selectValue(
'select count(distinct ur.user_id) from user_roles ur join roles r on r.id = ur.role_id and r.active = 1 where r.description in (?, ?) or r.id = 1',
'Admin',
'Administrator'
) ?? 0);
}
public function countActivePermissions(): int
{
return (int) (DB::selectValue('select count(*) from permissions where active = 1') ?? 0);
}
public function countInactivePermissions(): int
{
return (int) (DB::selectValue('select count(*) from permissions where active = 0') ?? 0);
}
/**
* @return list<string> All active permission keys.
*/
public function listAllActivePermissionKeys(): array
{
$rows = DB::select('select `key` from permissions where active = 1 order by `key`');
$keys = [];
foreach ((array) $rows as $row) {
$key = (string) (($row['permissions']['key'] ?? $row['key'] ?? ''));
if ($key !== '') {
$keys[] = $key;
}
}
return $keys;
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace MintyPHP\Repository\System;
interface SystemHealthRepositoryInterface
{
public function checkDatabaseConnectivity(): bool;
/**
* @param list<string> $requiredTables
* @return list<string>
*/
public function listPresentTables(array $requiredTables): array;
/**
* @return array{last_heartbeat_at: string, last_result: string, last_error_code: string}|null
*/
public function getSchedulerStatus(): ?array;
/**
* @param list<string> $keys
* @return list<string>
*/
public function listActivePermissionKeys(array $keys): array;
public function countAdminUsers(): int;
public function countActivePermissions(): int;
public function countInactivePermissions(): int;
/**
* @return list<string>
*/
public function listAllActivePermissionKeys(): array;
}

View File

@@ -17,6 +17,7 @@ final class OperationsAuthorizationPolicy implements AuthorizationPolicyInterfac
public const ABILITY_ADMIN_JOBS_MANAGE = 'ops.admin.jobs.manage';
public const ABILITY_ADMIN_MAIL_LOG_VIEW = 'ops.admin.mail_log.view';
public const ABILITY_ADMIN_STATS_VIEW = 'ops.admin.stats.view';
public const ABILITY_ADMIN_SYSTEM_INFO_VIEW = 'ops.admin.system_info.view';
public const ABILITY_ADMIN_API_DOCS_VIEW = 'ops.admin.api_docs.view';
public const ABILITY_ADMIN_IMPORTS_TYPE_USERS = 'ops.admin.imports.type.users';
public const ABILITY_ADMIN_IMPORTS_TYPE_DEPARTMENTS = 'ops.admin.imports.type.departments';
@@ -61,6 +62,7 @@ final class OperationsAuthorizationPolicy implements AuthorizationPolicyInterfac
self::ABILITY_ADMIN_JOBS_MANAGE,
self::ABILITY_ADMIN_MAIL_LOG_VIEW,
self::ABILITY_ADMIN_STATS_VIEW,
self::ABILITY_ADMIN_SYSTEM_INFO_VIEW,
self::ABILITY_ADMIN_API_DOCS_VIEW,
self::ABILITY_ADMIN_IMPORTS_TYPE_USERS,
self::ABILITY_ADMIN_IMPORTS_TYPE_DEPARTMENTS,
@@ -109,6 +111,7 @@ final class OperationsAuthorizationPolicy implements AuthorizationPolicyInterfac
self::ABILITY_ADMIN_JOBS_MANAGE => $this->allowIfHas($actorUserId, PermissionService::JOBS_MANAGE),
self::ABILITY_ADMIN_MAIL_LOG_VIEW => $this->allowIfHas($actorUserId, PermissionService::MAIL_LOG_VIEW),
self::ABILITY_ADMIN_STATS_VIEW => $this->allowIfHas($actorUserId, PermissionService::STATS_VIEW),
self::ABILITY_ADMIN_SYSTEM_INFO_VIEW => $this->allowIfHas($actorUserId, PermissionService::SYSTEM_INFO_VIEW),
self::ABILITY_ADMIN_API_DOCS_VIEW => $this->allowIfHas($actorUserId, PermissionService::API_DOCS_VIEW),
self::ABILITY_ADMIN_IMPORTS_TYPE_USERS => $this->allowIfHas($actorUserId, PermissionService::USERS_IMPORT),
self::ABILITY_ADMIN_IMPORTS_TYPE_DEPARTMENTS => $this->allowIfHas($actorUserId, PermissionService::DEPARTMENTS_IMPORT),

View File

@@ -82,6 +82,7 @@ class PermissionService
public const SYSTEM_AUDIT_VIEW = 'system_audit.view';
public const SYSTEM_AUDIT_PURGE = 'system_audit.purge';
public const STATS_VIEW = 'stats.view';
public const SYSTEM_INFO_VIEW = 'system_info.view';
public const API_TOKENS_MANAGE = 'api_tokens.manage';
public function userHas(int $userId, string $permissionKey): bool

View File

@@ -29,6 +29,7 @@ final class UiCapabilityMap
'can_view_imports_audit' => OperationsAuthorizationPolicy::ABILITY_ADMIN_IMPORTS_AUDIT_VIEW,
'can_view_user_lifecycle_audit' => OperationsAuthorizationPolicy::ABILITY_ADMIN_USER_LIFECYCLE_AUDIT_VIEW,
'can_view_stats' => OperationsAuthorizationPolicy::ABILITY_ADMIN_STATS_VIEW,
'can_view_system_info' => OperationsAuthorizationPolicy::ABILITY_ADMIN_SYSTEM_INFO_VIEW,
];
/**

View File

@@ -0,0 +1,263 @@
<?php
namespace MintyPHP\Service\System;
use MintyPHP\Repository\System\SystemHealthRepositoryInterface;
use MintyPHP\Service\Access\PermissionService;
class SystemHealthService
{
private const REQUIRED_TABLES = [
'users',
'roles',
'permissions',
'user_roles',
'role_permissions',
'tenants',
'departments',
'settings',
'scheduler_runtime_status',
];
private const REQUIRED_PERMISSIONS = [
PermissionService::USERS_VIEW,
PermissionService::TENANTS_VIEW,
PermissionService::DEPARTMENTS_VIEW,
PermissionService::ROLES_VIEW,
PermissionService::PERMISSIONS_VIEW,
PermissionService::SETTINGS_VIEW,
];
private const SCHEDULER_STALE_THRESHOLD_SECONDS = 300;
public function __construct(
private readonly SystemHealthRepositoryInterface $repository
) {
}
/**
* @return list<array{status: string, name: string, message: string}>
*/
public function runAll(): array
{
return [
$this->checkDatabase(),
$this->checkDatabaseSchema(),
$this->checkStorageWriteability(),
$this->checkRbacBaseline(),
$this->checkAdminRoleAssignment(),
$this->checkSchedulerHeartbeat(),
];
}
/**
* @return array{status: string, name: string, message: string}
*/
public function checkDatabase(): array
{
try {
$ok = $this->repository->checkDatabaseConnectivity();
return [
'status' => $ok ? 'ok' : 'fail',
'name' => 'Database connectivity',
'message' => $ok ? 'connection established' : 'select 1 did not return expected value',
];
} catch (\Throwable $e) {
return [
'status' => 'fail',
'name' => 'Database connectivity',
'message' => 'check failed',
];
}
}
/**
* @return array{status: string, name: string, message: string}
*/
public function checkDatabaseSchema(): array
{
try {
$present = $this->repository->listPresentTables(self::REQUIRED_TABLES);
sort($present, SORT_STRING);
$missing = array_values(array_diff(self::REQUIRED_TABLES, $present));
if ($missing) {
return [
'status' => 'fail',
'name' => 'Database schema',
'message' => 'missing tables: ' . implode(', ', $missing),
];
}
return [
'status' => 'ok',
'name' => 'Database schema',
'message' => sprintf('%d core tables present', count(self::REQUIRED_TABLES)),
];
} catch (\Throwable $e) {
return [
'status' => 'fail',
'name' => 'Database schema',
'message' => 'check failed',
];
}
}
/**
* @return array{status: string, name: string, message: string}
*/
public function checkStorageWriteability(): array
{
try {
$storagePath = defined('APP_STORAGE_PATH') && APP_STORAGE_PATH
? rtrim((string) APP_STORAGE_PATH, '/')
: rtrim(dirname(__DIR__, 3) . '/storage', '/');
if (!is_dir($storagePath)) {
return [
'status' => 'fail',
'name' => 'Storage writeability',
'message' => 'storage directory not found',
];
}
if (!is_writable($storagePath)) {
return [
'status' => 'fail',
'name' => 'Storage writeability',
'message' => 'storage directory not writable',
];
}
$probeFile = $storagePath . '/.doctor-write-probe-' . uniqid('', true);
$written = @file_put_contents($probeFile, 'ok');
if ($written === false) {
return [
'status' => 'fail',
'name' => 'Storage writeability',
'message' => 'write probe failed',
];
}
@unlink($probeFile);
return [
'status' => 'ok',
'name' => 'Storage writeability',
'message' => 'storage path is writable',
];
} catch (\Throwable $e) {
return [
'status' => 'fail',
'name' => 'Storage writeability',
'message' => 'check failed',
];
}
}
/**
* @return array{status: string, name: string, message: string}
*/
public function checkRbacBaseline(): array
{
try {
$present = $this->repository->listActivePermissionKeys(self::REQUIRED_PERMISSIONS);
sort($present, SORT_STRING);
$missing = array_values(array_diff(self::REQUIRED_PERMISSIONS, $present));
if ($missing) {
return [
'status' => 'fail',
'name' => 'RBAC baseline',
'message' => 'missing active permissions: ' . implode(', ', $missing),
];
}
return [
'status' => 'ok',
'name' => 'RBAC baseline',
'message' => sprintf('%d baseline permissions active', count(self::REQUIRED_PERMISSIONS)),
];
} catch (\Throwable $e) {
return [
'status' => 'fail',
'name' => 'RBAC baseline',
'message' => 'check failed',
];
}
}
/**
* @return array{status: string, name: string, message: string}
*/
public function checkAdminRoleAssignment(): array
{
try {
$count = $this->repository->countAdminUsers();
if ($count <= 0) {
return [
'status' => 'fail',
'name' => 'Admin role assignment',
'message' => 'no active user assigned to Admin/Administrator role',
];
}
return [
'status' => 'ok',
'name' => 'Admin role assignment',
'message' => sprintf('%d admin user(s) assigned', $count),
];
} catch (\Throwable $e) {
return [
'status' => 'fail',
'name' => 'Admin role assignment',
'message' => 'check failed',
];
}
}
/**
* @return array{status: string, name: string, message: string}
*/
public function checkSchedulerHeartbeat(): array
{
try {
$status = $this->repository->getSchedulerStatus();
if ($status === null) {
return [
'status' => 'warn',
'name' => 'Scheduler heartbeat',
'message' => 'no scheduler runtime status row found yet',
];
}
$heartbeat = $status['last_heartbeat_at'];
$result = $status['last_result'];
$errorCode = $status['last_error_code'];
if ($heartbeat === '') {
return [
'status' => 'warn',
'name' => 'Scheduler heartbeat',
'message' => 'scheduler heartbeat is empty',
];
}
$seconds = max(0, time() - strtotime($heartbeat . ' UTC'));
$detail = "last heartbeat {$seconds}s ago (result={$result}" . ($errorCode !== '' ? ", error={$errorCode}" : '') . ')';
return [
'status' => $seconds > self::SCHEDULER_STALE_THRESHOLD_SECONDS ? 'warn' : 'ok',
'name' => 'Scheduler heartbeat',
'message' => $detail,
];
} catch (\Throwable $e) {
return [
'status' => 'fail',
'name' => 'Scheduler heartbeat',
'message' => 'check failed',
];
}
}
}

View File

@@ -0,0 +1,121 @@
<?php
namespace MintyPHP\Service\System;
use MintyPHP\App\Module\ModuleRegistry;
use MintyPHP\Repository\System\SystemHealthRepositoryInterface;
class SystemInfoService
{
public function __construct(
private readonly SystemHealthService $healthService,
private readonly SystemHealthRepositoryInterface $healthRepository,
private readonly ?ModuleRegistry $moduleRegistry = null
) {
}
/**
* @return array<string, mixed>
*/
public function buildPageData(): array
{
return [
'overview' => $this->buildOverview(),
'modules' => $this->buildModuleInventory(),
'permissions' => $this->buildPermissionSummary(),
];
}
/**
* @return array<string, mixed>
*/
private function buildOverview(): array
{
return [
'php_version' => PHP_VERSION,
'php_sapi' => PHP_SAPI,
'app_environment' => $this->resolveEnvironment(),
'health_checks' => $this->healthService->runAll(),
];
}
/**
* @return list<array{id: string, version: string, enabled_by_default: bool, requires: list<string>, permissions_count: int}>
*/
private function buildModuleInventory(): array
{
if ($this->moduleRegistry === null) {
return [];
}
$modules = [];
foreach ($this->moduleRegistry->getModules() as $manifest) {
$modules[] = [
'id' => $manifest->id,
'version' => $manifest->version,
'enabled_by_default' => $manifest->enabledByDefault,
'requires' => $manifest->requires,
'permissions_count' => count($manifest->permissions),
];
}
usort($modules, static fn (array $a, array $b): int => strcmp($a['id'], $b['id']));
return $modules;
}
/**
* @return array{active_count: int, inactive_count: int, by_source: array<string, int>}
*/
private function buildPermissionSummary(): array
{
$activeKeys = $this->healthRepository->listAllActivePermissionKeys();
$bySource = $this->derivePermissionsBySource($activeKeys);
return [
'active_count' => $this->healthRepository->countActivePermissions(),
'inactive_count' => $this->healthRepository->countInactivePermissions(),
'by_source' => $bySource,
];
}
/**
* @param list<string> $activeKeys
* @return array<string, int>
*/
private function derivePermissionsBySource(array $activeKeys): array
{
$moduleKeys = [];
if ($this->moduleRegistry !== null) {
foreach ($this->moduleRegistry->getModules() as $manifest) {
foreach ($manifest->permissions as $perm) {
$key = $perm['key'] ?? '';
if ($key !== '') {
$moduleKeys[$key] = $manifest->id;
}
}
}
}
$counts = [];
foreach ($activeKeys as $key) {
$source = $moduleKeys[$key] ?? 'core';
$counts[$source] = ($counts[$source] ?? 0) + 1;
}
ksort($counts);
return $counts;
}
private function resolveEnvironment(): string
{
if (defined('APP_ENV')) {
return (string) APP_ENV;
}
$env = getenv('APP_ENV');
return is_string($env) && $env !== '' ? $env : 'unknown';
}
}