Compare commits

..
2 Commits
Author SHA1 Message Date
kiskaadee 55acf00c10 fix(daemon): catch unhandled exceptions, preserve audit trail, and serialize homepage sync
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m0s
2026-10-31 21:38:46 -05:00
kiskaadee c8c79bef89 fix(router): validate deployment branch instead of source ref during post-pull verification 2026-10-31 21:33:59 -05:00
6 changed files with 286 additions and 45 deletions

No files matched your search

+1 -1
View File
@@ -338,7 +338,7 @@ def enforce_rbac(
return return
# Target checks for operations targeting infrastructure # 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( raise AuthorizationError(
f"Role 'homelab-operator' is not permitted to target core service '{target}'", f"Role 'homelab-operator' is not permitted to target core service '{target}'",
code=ErrorCode.ERR_PERMISSION_DENIED, code=ErrorCode.ERR_PERMISSION_DENIED,
+21 -7
View File
@@ -386,13 +386,27 @@ class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
return return
# Dispatch operation to OperationalRouter # Dispatch operation to OperationalRouter
resp = self.appctl_server.router.dispatch( try:
request=req, resp = self.appctl_server.router.dispatch(
principal=principal, request=req,
transport=transport, principal=principal,
origin=origin, transport=transport,
client=client_header, 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 status_code = resp.error.code.http_status if (not resp.success and resp.error) else 200
self._send_operation_response(status_code, resp) 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("") lines.append("")
content = "\n".join(lines).strip() + "\n" 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.write(content)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_services_path, services_yaml_path)
print( print(
f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)" f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)"
+83 -36
View File
@@ -12,6 +12,7 @@ Implements the single command execution pipeline for homelab-appctl.service:
from __future__ import annotations from __future__ import annotations
import logging
import os import os
import subprocess import subprocess
import time import time
@@ -19,6 +20,8 @@ from pathlib import Path
from typing import Any from typing import Any
import yaml import yaml
logger = logging.getLogger("appctl_router")
from appctl_audit import ( from appctl_audit import (
AuditLogger, AuditLogger,
AuditPersistenceError, AuditPersistenceError,
@@ -619,26 +622,30 @@ class OperationalRouter:
duration_ms = int((time.perf_counter() - start_time) * 1000) 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 # Audit COMPLETED for mutating ops and sensitive reads
if ( if (
operation in MUTATING_OPERATIONS operation in MUTATING_OPERATIONS
or operation in SENSITIVE_READ_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS
): ):
self.audit_logger.log_completed( try:
operation_id=op_id, self.audit_logger.log_completed(
principal=principal_audit, operation_id=op_id,
action=operation.value, principal=principal_audit,
target=target, action=operation.value,
transport=transport, target=target,
origin=origin, transport=transport,
client=client, origin=origin,
parameters=request.parameters, client=client,
duration_ms=duration_ms, parameters=request.parameters,
commit_sha=commit_sha, duration_ms=duration_ms,
message=result_data.get( commit_sha=commit_sha,
"message", "Operation completed successfully" 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( return OperationResponse(
version="1.0", version="1.0",
@@ -658,20 +665,23 @@ class OperationalRouter:
operation in MUTATING_OPERATIONS operation in MUTATING_OPERATIONS
or operation in SENSITIVE_READ_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS
): ):
self.audit_logger.log_failed( try:
operation_id=op_id, self.audit_logger.log_failed(
principal=principal_audit, operation_id=op_id,
action=operation.value, principal=principal_audit,
target=target, action=operation.value,
transport=transport, target=target,
origin=origin, transport=transport,
client=client, origin=origin,
parameters=request.parameters, client=client,
duration_ms=duration_ms, parameters=request.parameters,
exit_code=getattr(err, "exit_code", 1), duration_ms=duration_ms,
error_code=err.code.value, exit_code=getattr(err, "exit_code", 1),
message=str(err), 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( return OperationResponse(
version="1.0", version="1.0",
success=False, success=False,
@@ -681,6 +691,42 @@ class OperationalRouter:
duration_ms=duration_ms, duration_ms=duration_ms,
error=OperationError(code=err.code, message=str(err)), 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 # Domain Operation Implementations
@@ -1006,7 +1052,7 @@ class OperationalRouter:
# 2. git pull --ff-only # 2. git pull --ff-only
pull_cmd = ["git", "-C", str(app_dir), "pull", "--ff-only"] pull_cmd = ["git", "-C", str(app_dir), "pull", "--ff-only"]
if params.expected_branch: if params.expected_branch:
pull_cmd.extend(["origin", params.expected_branch]) pull_cmd.extend(["origin", "--", params.expected_branch])
code, pull_out, pull_err = run_bounded_subprocess( code, pull_out, pull_err = run_bounded_subprocess(
pull_cmd, cwd=app_dir, timeout=60.0 pull_cmd, cwd=app_dir, timeout=60.0
) )
@@ -1026,12 +1072,12 @@ class OperationalRouter:
) )
if ( if (
params.expected_branch params.expected_branch
and manifest.source and manifest.deployment
and manifest.source.ref != params.expected_branch and manifest.deployment.branch != params.expected_branch
): ):
raise RouterValidationError( raise RouterValidationError(
f"Post-pull branch mismatch for '{app.name}': expected '{params.expected_branch}', " f"Post-pull branch mismatch for '{app.name}': expected '{params.expected_branch}', "
f"manifest declared '{manifest.source.ref}'" f"manifest declared '{manifest.deployment.branch}'"
) )
declared_actions = manifest.deployment.actions or ["compose_up"] declared_actions = manifest.deployment.actions or ["compose_up"]
@@ -1104,7 +1150,7 @@ class OperationalRouter:
}, commit_sha }, commit_sha
def _op_platform_sync_homepage(self) -> dict[str, Any]: def _op_platform_sync_homepage(self) -> dict[str, Any]:
self._trigger_homepage_sync() cmd_sync_homepage()
return { return {
"action": "sync_homepage", "action": "sync_homepage",
"message": "Homepage dashboard synchronized successfully", "message": "Homepage dashboard synchronized successfully",
@@ -1113,8 +1159,9 @@ class OperationalRouter:
def _trigger_homepage_sync(self) -> None: def _trigger_homepage_sync(self) -> None:
"""Atomic compile of Homepage dashboard services.yaml under _homepage_sync.lock.""" """Atomic compile of Homepage dashboard services.yaml under _homepage_sync.lock."""
try: try:
cmd_sync_homepage() with self.lock_manager.homepage_sync_lock():
except (OSError, ValueError, RuntimeError) as exc: cmd_sync_homepage()
except (OSError, ValueError, RuntimeError, ConcurrentMutationError) as exc:
import sys import sys
print(f"Warning: Homepage sync non-fatal error: {exc}", file=sys.stderr) 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 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( def test_rbac_operator_denied_without_target_on_mutating_or_sensitive_ops(
admitted_workloads: set[str], admitted_workloads: set[str],
): ):
+165
View File
@@ -7,6 +7,7 @@ test_<subject>_<accepts|rejects|enforces>_<condition>
from __future__ import annotations from __future__ import annotations
import json
from pathlib import Path from pathlib import Path
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
@@ -1351,3 +1352,167 @@ def test_parse_dotenv_rejects_reserved_platform_keys(tmp_path: Path):
RouterValidationError, match="Prohibited reserved environment key" RouterValidationError, match="Prohibited reserved environment key"
): ):
parse_dotenv(env_file, validate_keys=True) parse_dotenv(env_file, validate_keys=True)
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
):
"""Ensure workload.update validates deployment.branch (Tier 2) and does not conflate with source.ref (Tier 1) (CR-SS-01)."""
app_dir = mock_sites_dir / "bitetrack"
app_dir.mkdir(parents=True, exist_ok=True)
manifest_content = """
name: "bitetrack"
source:
type: "git"
url: "https://github.com/example/bitetrack.git"
ref: "v2.5.0"
deployment:
strategy: "compose"
branch: "main"
actions:
- "compose_up"
"""
(app_dir / "app.yaml").write_text(manifest_content.strip(), encoding="utf-8")
(app_dir / "docker-compose.yml").write_text("services:\n app:\n image: app:latest\n", encoding="utf-8")
router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_sites_dir,
)
req = OperationRequest.model_validate({
"operation": "workload.update",
"target": "bitetrack",
"parameters": {"expected_branch": "main"},
})
mock_app = MagicMock()
mock_app.name = "bitetrack"
mock_app.dir_path = str(app_dir)
executed_cmds: list[list[str]] = []
def mock_subproc(cmd: list[str], **kwargs):
executed_cmds.append(cmd)
if "status" in cmd:
return 0, "", ""
if "pull" in cmd and "git" in cmd:
return 0, "Fast-forward", ""
if "rev-parse" in cmd:
return 0, "1234567", ""
return 0, "ok", ""
with (
patch("appctl_router.resolve_app", return_value=mock_app),
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
patch("appctl_router.cmd_sync_homepage"),
):
resp = router.dispatch(req, admin_principal)
assert resp.success is True
assert resp.result is not None
pull_calls = [c for c in executed_cmds if "pull" in c and "git" in c]
assert len(pull_calls) == 1
assert pull_calls[0] == ["git", "-C", str(app_dir), "pull", "--ff-only", "origin", "--", "main"]
def test_operational_router_workload_update_rejects_deployment_branch_mismatch_image_only(
tmp_path: Path, admin_principal: Principal, mock_sites_dir: Path
):
"""Ensure workload.update validates deployment.branch for image-only workloads with source=None (CR-SS-01)."""
app_dir = mock_sites_dir / "imageonly"
app_dir.mkdir(parents=True, exist_ok=True)
manifest_content = """
name: "imageonly"
deployment:
strategy: "compose"
branch: "production"
actions:
- "compose_up"
"""
(app_dir / "app.yaml").write_text(manifest_content.strip(), encoding="utf-8")
(app_dir / "docker-compose.yml").write_text("services:\n app:\n image: app:latest\n", encoding="utf-8")
router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_sites_dir,
)
req = OperationRequest.model_validate({
"operation": "workload.update",
"target": "imageonly",
"parameters": {"expected_branch": "main"},
})
mock_app = MagicMock()
mock_app.name = "imageonly"
mock_app.dir_path = str(app_dir)
def mock_subproc(cmd: list[str], **kwargs):
if "status" in cmd:
return 0, "", ""
if "pull" in cmd and "git" in cmd:
return 0, "Fast-forward", ""
if "rev-parse" in cmd:
return 0, "1234567", ""
return 0, "ok", ""
with (
patch("appctl_router.resolve_app", return_value=mock_app),
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
):
resp = router.dispatch(req, admin_principal)
assert resp.success is False
assert resp.error is not None
assert resp.error.code == ErrorCode.ERR_VALIDATION_FAILED
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