fix(daemon): catch unhandled exceptions, preserve audit trail, and serialize homepage sync

This commit is contained in:
kiskaadee committed 2026-10-31 20:24:35 -05:00
1 parent edca28effc
commit dc70693746
6 files changed
+164 -43

No files matched your search

+1 -1
View File
@@ -310,7 +310,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,
+21 -7
View File
@@ -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)
+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)"
+73 -30
View File
@@ -12,12 +12,15 @@ Implements the single command execution pipeline for homelab-appctl.service:
from __future__ import annotations
import logging
import os
import subprocess
import time
from pathlib import Path
from typing import Any
logger = logging.getLogger("appctl_router")
from appctl_audit import (
AuditLogger,
AuditPersistenceError,
@@ -602,19 +605,22 @@ class OperationalRouter:
# 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",
@@ -631,20 +637,23 @@ class OperationalRouter:
except (RouterValidationError, RouterExecutionError) as err:
duration_ms = int((time.perf_counter() - start_time) * 1000)
if 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,
@@ -654,6 +663,39 @@ 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
@@ -985,13 +1027,14 @@ 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"}
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)
+11
View File
@@ -303,6 +303,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],
):
+53 -4
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
@@ -1147,10 +1148,6 @@ def test_operational_router_workload_list_handles_manifest_error(
assert broken["provenance_status"] == "⚠️ Invalid Manifest"
def test_operational_router_workload_update_succeeds_when_source_ref_is_tag_and_deployment_branch_matches(
tmp_path: Path, admin_principal: Principal, mock_sites_dir: Path
):
@@ -1266,3 +1263,55 @@ deployment:
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