From 55acf00c10446d3b94168b5048a6fd6126756b74 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 20:24:35 -0500 Subject: [PATCH] fix(daemon): catch unhandled exceptions, preserve audit trail, and serialize homepage sync --- scripts/appctl_auth.py | 2 +- scripts/appctl_daemon.py | 28 ++++++-- scripts/appctl_engine.py | 6 +- scripts/appctl_router.py | 111 ++++++++++++++++++++++--------- tests/unit/test_appctl_auth.py | 11 +++ tests/unit/test_appctl_router.py | 50 ++++++++++++++ 6 files changed, 167 insertions(+), 41 deletions(-) diff --git a/scripts/appctl_auth.py b/scripts/appctl_auth.py index 7065b24..3d41b7e 100644 --- a/scripts/appctl_auth.py +++ b/scripts/appctl_auth.py @@ -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, diff --git a/scripts/appctl_daemon.py b/scripts/appctl_daemon.py index b720b41..bba84e9 100755 --- a/scripts/appctl_daemon.py +++ b/scripts/appctl_daemon.py @@ -386,13 +386,27 @@ class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler): return # Dispatch operation to OperationalRouter - resp = self.appctl_server.router.dispatch( - request=req, - principal=principal, - transport=transport, - origin=origin, - client=client_header, - ) + try: + resp = self.appctl_server.router.dispatch( + request=req, + principal=principal, + transport=transport, + 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) diff --git a/scripts/appctl_engine.py b/scripts/appctl_engine.py index c03bb7a..af16215 100755 --- a/scripts/appctl_engine.py +++ b/scripts/appctl_engine.py @@ -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)" diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py index 883f10b..50a9764 100644 --- a/scripts/appctl_router.py +++ b/scripts/appctl_router.py @@ -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,26 +622,30 @@ 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 ): - self.audit_logger.log_completed( - 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, - commit_sha=commit_sha, - message=result_data.get( - "message", "Operation completed successfully" - ), - ) + try: + self.audit_logger.log_completed( + 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, + commit_sha=commit_sha, + message=result_data.get( + "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,20 +665,23 @@ class OperationalRouter: operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS ): - 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=getattr(err, "exit_code", 1), - error_code=err.code.value, - message=str(err), - ) + 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=getattr(err, "exit_code", 1), + 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: - cmd_sync_homepage() - except (OSError, ValueError, RuntimeError) as exc: + with self.lock_manager.homepage_sync_lock(): + cmd_sync_homepage() + except (OSError, ValueError, RuntimeError, ConcurrentMutationError) as exc: import sys print(f"Warning: Homepage sync non-fatal error: {exc}", file=sys.stderr) diff --git a/tests/unit/test_appctl_auth.py b/tests/unit/test_appctl_auth.py index 7fc55b7..97c9b15 100644 --- a/tests/unit/test_appctl_auth.py +++ b/tests/unit/test_appctl_auth.py @@ -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], ): diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 4b9dde8..753a436 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -7,6 +7,7 @@ test___ 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