fix(daemon): catch unhandled exceptions, preserve audit trail, and serialize homepage sync
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m0s

This commit was merged in pull request #26.
This commit is contained in:
kiskaadee committed 2026-10-31 21:38:46 -05:00
1 parent c8c79bef89
commit 55acf00c10
6 files changed
+130 -4

No files matched your search

+1 -1
View File
@@ -338,7 +338,7 @@ def enforce_rbac(
return
# Target checks for operations targeting infrastructure
if target is not None and target in CORE_TARGETS:
if target is not None and target.strip().lower() in CORE_TARGETS:
raise AuthorizationError(
f"Role 'homelab-operator' is not permitted to target core service '{target}'",
code=ErrorCode.ERR_PERMISSION_DENIED,
+14
View File
@@ -386,6 +386,7 @@ class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
return
# Dispatch operation to OperationalRouter
try:
resp = self.appctl_server.router.dispatch(
request=req,
principal=principal,
@@ -393,6 +394,19 @@ class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
origin=origin,
client=client_header,
)
except Exception as exc:
logger.exception("Top-level unhandled exception during operation dispatch")
self._send_operation_error(
status_code=500,
error=OperationError(
code=ErrorCode.ERR_EXECUTION_FAILED,
message=f"Internal daemon execution error: {exc}",
),
operation=req.operation,
target=req.target,
op_id=generate_operation_id(),
)
return
status_code = resp.error.code.http_status if (not resp.success and resp.error) else 200
self._send_operation_response(status_code, resp)
+5 -1
View File
@@ -742,8 +742,12 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
lines.append("")
content = "\n".join(lines).strip() + "\n"
with open(services_yaml_path, "w", encoding="utf-8") as f:
tmp_services_path = services_yaml_path + ".tmp"
with open(tmp_services_path, "w", encoding="utf-8") as f:
f.write(content)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_services_path, services_yaml_path)
print(
f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)"
+49 -2
View File
@@ -12,6 +12,7 @@ Implements the single command execution pipeline for homelab-appctl.service:
from __future__ import annotations
import logging
import os
import subprocess
import time
@@ -19,6 +20,8 @@ from pathlib import Path
from typing import Any
import yaml
logger = logging.getLogger("appctl_router")
from appctl_audit import (
AuditLogger,
AuditPersistenceError,
@@ -619,11 +622,13 @@ class OperationalRouter:
duration_ms = int((time.perf_counter() - start_time) * 1000)
# Audit COMPLETED for mutating ops and sensitive reads
# Audit COMPLETED for mutating ops and sensitive reads
if (
operation in MUTATING_OPERATIONS
or operation in SENSITIVE_READ_OPERATIONS
):
try:
self.audit_logger.log_completed(
operation_id=op_id,
principal=principal_audit,
@@ -639,6 +644,8 @@ class OperationalRouter:
"message", "Operation completed successfully"
),
)
except AuditPersistenceError as audit_err:
logger.error("Failed to persist COMPLETED audit record: %s", audit_err)
return OperationResponse(
version="1.0",
@@ -658,6 +665,7 @@ class OperationalRouter:
operation in MUTATING_OPERATIONS
or operation in SENSITIVE_READ_OPERATIONS
):
try:
self.audit_logger.log_failed(
operation_id=op_id,
principal=principal_audit,
@@ -672,6 +680,8 @@ class OperationalRouter:
error_code=err.code.value,
message=str(err),
)
except AuditPersistenceError as audit_err:
logger.error("Failed to persist FAILED audit record: %s", audit_err)
return OperationResponse(
version="1.0",
success=False,
@@ -681,6 +691,42 @@ class OperationalRouter:
duration_ms=duration_ms,
error=OperationError(code=err.code, message=str(err)),
)
except Exception as err:
logger.exception("Unexpected execution error in router")
duration_ms = int((time.perf_counter() - start_time) * 1000)
if (
operation in MUTATING_OPERATIONS
or operation in SENSITIVE_READ_OPERATIONS
):
try:
self.audit_logger.log_failed(
operation_id=op_id,
principal=principal_audit,
action=operation.value,
target=target,
transport=transport,
origin=origin,
client=client,
parameters=request.parameters,
duration_ms=duration_ms,
exit_code=1,
error_code=ErrorCode.ERR_EXECUTION_FAILED.value,
message=f"Unexpected execution failure: {err}",
)
except AuditPersistenceError as audit_err:
logger.error("Failed to persist FAILED audit record: %s", audit_err)
return OperationResponse(
version="1.0",
success=False,
operation_id=op_id,
operation=operation,
target=target,
duration_ms=duration_ms,
error=OperationError(
code=ErrorCode.ERR_EXECUTION_FAILED,
message=f"Unexpected execution failure: {err}",
),
)
# -----------------------------------------------------------------------
# Domain Operation Implementations
@@ -1104,7 +1150,7 @@ class OperationalRouter:
}, commit_sha
def _op_platform_sync_homepage(self) -> dict[str, Any]:
self._trigger_homepage_sync()
cmd_sync_homepage()
return {
"action": "sync_homepage",
"message": "Homepage dashboard synchronized successfully",
@@ -1113,8 +1159,9 @@ class OperationalRouter:
def _trigger_homepage_sync(self) -> None:
"""Atomic compile of Homepage dashboard services.yaml under _homepage_sync.lock."""
try:
with self.lock_manager.homepage_sync_lock():
cmd_sync_homepage()
except (OSError, ValueError, RuntimeError) as exc:
except (OSError, ValueError, RuntimeError, ConcurrentMutationError) as exc:
import sys
print(f"Warning: Homepage sync non-fatal error: {exc}", file=sys.stderr)
+11
View File
@@ -366,6 +366,17 @@ def test_rbac_operator_denied_on_core_targets(
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_operator_denied_on_case_variant_core_targets(admitted_workloads: set[str]):
"""Ensure case variants ('Core', 'TRAEFIK', 'Authelia') are rejected for operator role (CR-DI-06)."""
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
for variant in ["Core", "CORE", "Traefik", "TRAEFIK", "Authelia"]:
with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, variant, admitted_workloads)
assert "not permitted to target core service" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_operator_denied_without_target_on_mutating_or_sensitive_ops(
admitted_workloads: set[str],
):
+50
View File
@@ -7,6 +7,7 @@ test_<subject>_<accepts|rejects|enforces>_<condition>
from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -1466,3 +1467,52 @@ deployment:
assert "Post-pull branch mismatch" in resp.error.message
assert "expected 'main'" in resp.error.message
assert "declared 'production'" in resp.error.message
def test_operational_router_catches_unhandled_runtime_exceptions_and_records_failed_audit(
tmp_path: Path, admin_principal: Principal, mock_sites_dir: Path
):
"""Ensure unexpected exceptions in router return 500 ERR_EXECUTION_FAILED and log FAILED audit (CR-SO-04)."""
audit_file = tmp_path / "audit.jsonl"
router = OperationalRouter(
audit_logger=AuditLogger(audit_file),
lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_sites_dir,
)
req = OperationRequest.model_validate({
"operation": "platform.sync_homepage",
})
with patch("appctl_router.cmd_sync_homepage", side_effect=RuntimeError("Corrupt filesystem")):
resp = router.dispatch(req, admin_principal)
assert resp.success is False
assert resp.error is not None
assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED
assert "Unexpected execution failure" in resp.error.message
events = [json.loads(line) for line in audit_file.read_text().splitlines() if line.strip()]
assert len(events) == 2
assert events[0]["phase"] == "DISPATCHED"
assert events[1]["phase"] == "FAILED"
assert events[1]["result"]["error_code"] == ErrorCode.ERR_EXECUTION_FAILED.value
def test_trigger_homepage_sync_acquires_homepage_sync_lock(tmp_path: Path, mock_sites_dir: Path):
"""Ensure _trigger_homepage_sync executes under homepage_sync_lock (CR-DI-05)."""
lock_mgr = TargetLockManager(tmp_path / "locks")
router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=lock_mgr,
sites_dir=mock_sites_dir,
)
lock_acquired = False
def mock_sync():
nonlocal lock_acquired
lock_file = lock_mgr.lock_dir / "_homepage_sync.lock"
assert lock_file.exists()
lock_acquired = True
with patch("appctl_router.cmd_sync_homepage", side_effect=mock_sync):
router._trigger_homepage_sync()
assert lock_acquired is True