Compare commits
2
Commits
5156cf4306
...
55acf00c10
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
55acf00c10 | ||
|
|
c8c79bef89 |
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)"
|
||||
|
||||
@@ -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
|
||||
@@ -1006,7 +1052,7 @@ class OperationalRouter:
|
||||
# 2. git pull --ff-only
|
||||
pull_cmd = ["git", "-C", str(app_dir), "pull", "--ff-only"]
|
||||
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(
|
||||
pull_cmd, cwd=app_dir, timeout=60.0
|
||||
)
|
||||
@@ -1026,12 +1072,12 @@ class OperationalRouter:
|
||||
)
|
||||
if (
|
||||
params.expected_branch
|
||||
and manifest.source
|
||||
and manifest.source.ref != params.expected_branch
|
||||
and manifest.deployment
|
||||
and manifest.deployment.branch != params.expected_branch
|
||||
):
|
||||
raise RouterValidationError(
|
||||
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"]
|
||||
|
||||
@@ -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)
|
||||
@@ -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],
|
||||
):
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1351,3 +1352,167 @@ def test_parse_dotenv_rejects_reserved_platform_keys(tmp_path: Path):
|
||||
RouterValidationError, match="Prohibited reserved environment key"
|
||||
):
|
||||
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
|
||||
Reference in new issue
Block a user