diff --git a/scripts/appctl_audit.py b/scripts/appctl_audit.py new file mode 100644 index 0000000..635afe1 --- /dev/null +++ b/scripts/appctl_audit.py @@ -0,0 +1,402 @@ +""" +appctl_audit.py — Append-Only Audit Logger & Per-Target Lock Manager (P4 Slice 2) + +Governs the audit telemetry and concurrency control for homelab-appctl.service: +- Append-only JSONL audit writer adhering to RFC-compliant schema (mode 0600) +- Pre-execution DISPATCHED fail-closed disk guard +- Sensitive parameter and error redaction (*_KEY, *_SECRET, *_PASSWORD, etc.) +- Non-blocking per-target flock context manager raising ConcurrentMutationError (409) +""" + +from __future__ import annotations + +import fcntl +import os +import re +import secrets +import threading +from datetime import UTC, datetime +from enum import StrEnum +from pathlib import Path +from types import TracebackType +from typing import Annotated, Any, Literal, Self + +from appctl_contracts import StrictModel +from pydantic import BeforeValidator, ConfigDict, Field, StrictInt, StrictStr + +DEFAULT_AUDIT_LOG = Path("/var/log/homelab/appctl/audit.jsonl") +DEFAULT_LOCK_DIR = Path("/var/lib/homelab/appctl/locks") + +REDACT_KEY_PATTERNS = re.compile( + r".*(?:_KEY|_SECRET|_PASSWORD|_TOKEN|_PASS|_HASH)$", re.IGNORECASE +) + + +class AuditPhase(StrEnum): + """Lifecycle phases for control plane audit events.""" + + DISPATCHED = "DISPATCHED" + COMPLETED = "COMPLETED" + FAILED = "FAILED" + DENIED = "DENIED" + + +def _coerce_phase(v: Any) -> Any: + if isinstance(v, str): + try: + return AuditPhase(v) + except ValueError: + return v + return v + + +FlexibleAuditPhase = Annotated[ + AuditPhase, + BeforeValidator(_coerce_phase), +] + + +class PrincipalAudit(StrictModel): + """Authenticated principal details captured in audit records.""" + + identity: StrictStr + role: StrictStr + token_id: StrictStr | None = None + auth_method: StrictStr + + +class AuditResult(StrictModel): + """Execution outcome details captured in audit records.""" + + status: Literal["SUCCESS", "FAILED", "DENIED", "IN_PROGRESS"] + exit_code: StrictInt | None = None + duration_ms: StrictInt | None = None + commit_sha: StrictStr | None = None + error_code: StrictStr | None = None + message: StrictStr | None = None + + +class AuditEvent(StrictModel): + """RFC-compliant single-line JSONL audit event model (ADR-0002 / DEC-03).""" + + model_config = ConfigDict(extra="forbid", strict=True) + + audit_version: Literal["1.0"] = "1.0" + event_id: StrictStr + operation_id: StrictStr + timestamp: StrictStr + phase: FlexibleAuditPhase + principal: PrincipalAudit + action: StrictStr + target: StrictStr | None = None + transport: StrictStr + origin: StrictStr + client: StrictStr + parameters: dict[str, Any] = Field(default_factory=dict) + result: AuditResult | None = None + + +class AuditPersistenceError(Exception): + """Raised when an audit record cannot be persisted or flushed to disk.""" + + +class ConcurrentMutationError(Exception): + """Raised when a per-target operation lock cannot be acquired (409 Conflict).""" + + def __init__(self, target: str, message: str | None = None) -> None: + self.target = target + msg = message or f"Operation on target '{target}' is locked by a concurrent task." + super().__init__(msg) + + +def redact_sensitive_data(val: Any) -> Any: + """ + Recursively redact values whose dictionary keys match sensitive patterns + (*_KEY, *_SECRET, *_PASSWORD, *_TOKEN, *_PASS, *_HASH). + """ + if isinstance(val, dict): + return { + k: "[REDACTED]" if REDACT_KEY_PATTERNS.match(str(k)) else redact_sensitive_data(v) + for k, v in val.items() + } + if isinstance(val, list): + return [redact_sensitive_data(v) for v in val] + return val + + +def generate_event_id() -> str: + """Generate a unique event identifier.""" + return f"evt_{secrets.token_hex(6)}" + + +def generate_operation_id() -> str: + """Generate a unique operation identifier.""" + return f"op_{secrets.token_hex(6)}" + + +def current_iso_timestamp() -> str: + """Current UTC timestamp formatted as ISO 8601 with millisecond precision.""" + now = datetime.now(UTC) + return now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" + + +class AuditLogger: + """ + Append-only thread-safe audit logger writing single-line JSONL records. + Enforces mode 0600 on the log file and provides a fail-closed pre-execution + DISPATCHED disk guard. + """ + + def __init__(self, log_path: Path | str | None = None) -> None: + if log_path is not None: + self.log_path = Path(log_path) + elif "APPCTL_AUDIT_LOG" in os.environ: + self.log_path = Path(os.environ["APPCTL_AUDIT_LOG"]) + else: + self.log_path = DEFAULT_AUDIT_LOG + self._lock = threading.Lock() + + def _ensure_log_file(self) -> None: + """Ensure parent directories exist and file is initialized with mode 0600.""" + self.log_path.parent.mkdir(parents=True, exist_ok=True) + if not self.log_path.exists(): + fd = os.open( + self.log_path, + os.O_WRONLY | os.O_CREAT | os.O_APPEND, + 0o600, + ) + os.close(fd) + + def emit_event(self, event: AuditEvent) -> None: + """ + Append an audit event as a single JSON line to the audit log. + Flushes and fsyncs to ensure durability. Raises AuditPersistenceError on failure. + """ + with self._lock: + try: + self._ensure_log_file() + line = event.model_dump_json() + "\n" + fd = os.open( + self.log_path, + os.O_WRONLY | os.O_APPEND, + 0o600, + ) + try: + os.write(fd, line.encode("utf-8")) + os.fsync(fd) + finally: + os.close(fd) + except OSError as err: + raise AuditPersistenceError( + f"Failed to persist audit event '{event.event_id}': {err}" + ) from err + + def log_dispatched( + self, + operation_id: str, + principal: PrincipalAudit, + action: str, + target: str | None, + transport: str, + origin: str, + client: str, + parameters: dict[str, Any], + ) -> AuditEvent: + """ + Fail-closed pre-execution disk guard: logs DISPATCHED phase before any + subprocess or filesystem mutation begins. Raises AuditPersistenceError if disk write fails. + """ + clean_params = redact_sensitive_data(parameters) + event = AuditEvent( + event_id=generate_event_id(), + operation_id=operation_id, + timestamp=current_iso_timestamp(), + phase=AuditPhase.DISPATCHED, + principal=principal, + action=action, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=clean_params, + result=AuditResult(status="IN_PROGRESS"), + ) + self.emit_event(event) + return event + + def log_completed( + self, + operation_id: str, + principal: PrincipalAudit, + action: str, + target: str | None, + transport: str, + origin: str, + client: str, + parameters: dict[str, Any], + duration_ms: int, + commit_sha: str | None = None, + message: str | None = None, + ) -> AuditEvent: + """Log COMPLETED phase upon clean operation termination.""" + clean_params = redact_sensitive_data(parameters) + event = AuditEvent( + event_id=generate_event_id(), + operation_id=operation_id, + timestamp=current_iso_timestamp(), + phase=AuditPhase.COMPLETED, + principal=principal, + action=action, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=clean_params, + result=AuditResult( + status="SUCCESS", + exit_code=0, + duration_ms=duration_ms, + commit_sha=commit_sha, + error_code=None, + message=message or "Operation completed successfully", + ), + ) + self.emit_event(event) + return event + + def log_failed( + self, + operation_id: str, + principal: PrincipalAudit, + action: str, + target: str | None, + transport: str, + origin: str, + client: str, + parameters: dict[str, Any], + duration_ms: int | None = None, + exit_code: int | None = None, + error_code: str | None = None, + message: str | None = None, + ) -> AuditEvent: + """Log FAILED phase when validation or execution fails.""" + clean_params = redact_sensitive_data(parameters) + clean_msg = redact_sensitive_data(message) if message else None + event = AuditEvent( + event_id=generate_event_id(), + operation_id=operation_id, + timestamp=current_iso_timestamp(), + phase=AuditPhase.FAILED, + principal=principal, + action=action, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=clean_params, + result=AuditResult( + status="FAILED", + exit_code=exit_code, + duration_ms=duration_ms, + error_code=error_code, + message=clean_msg, + ), + ) + self.emit_event(event) + return event + + def log_denied( + self, + operation_id: str, + principal: PrincipalAudit, + action: str, + target: str | None, + transport: str, + origin: str, + client: str, + parameters: dict[str, Any], + error_code: str, + message: str, + ) -> AuditEvent: + """Log DENIED phase when authentication, RBAC, or concurrency lock rejects request.""" + clean_params = redact_sensitive_data(parameters) + event = AuditEvent( + event_id=generate_event_id(), + operation_id=operation_id, + timestamp=current_iso_timestamp(), + phase=AuditPhase.DENIED, + principal=principal, + action=action, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=clean_params, + result=AuditResult( + status="DENIED", + error_code=error_code, + message=message, + ), + ) + self.emit_event(event) + return event + + +class TargetLock: + """Context manager acquiring a non-blocking per-target flock.""" + + def __init__(self, lock_path: Path, target: str) -> None: + self.lock_path = lock_path + self.target = target + self._fd: int | None = None + + def __enter__(self) -> Self: + self.lock_path.parent.mkdir(parents=True, exist_ok=True) + fd = os.open( + self.lock_path, + os.O_RDWR | os.O_CREAT, + 0o600, + ) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except (BlockingIOError, OSError) as err: + os.close(fd) + raise ConcurrentMutationError(self.target) from err + self._fd = fd + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self._fd is not None: + try: + fcntl.flock(self._fd, fcntl.LOCK_UN) + finally: + os.close(self._fd) + self._fd = None + + +class TargetLockManager: + """Manages operational per-target locks under /var/lib/homelab/appctl/locks.""" + + def __init__(self, lock_dir: Path | str | None = None) -> None: + if lock_dir is not None: + self.lock_dir = Path(lock_dir) + elif "APPCTL_LOCK_DIR" in os.environ: + self.lock_dir = Path(os.environ["APPCTL_LOCK_DIR"]) + else: + self.lock_dir = DEFAULT_LOCK_DIR + + def lock_target(self, target: str) -> TargetLock: + """Return a non-blocking flock context manager for a workload target.""" + clean_target = re.sub(r"[^a-zA-Z0-9._-]", "_", target) + lock_path = self.lock_dir / f"{clean_target}.lock" + return TargetLock(lock_path, target) + + def homepage_sync_lock(self) -> TargetLock: + """Return a non-blocking flock context manager for homepage compilation.""" + lock_path = self.lock_dir / "_homepage_sync.lock" + return TargetLock(lock_path, "_homepage_sync") diff --git a/tests/unit/test_appctl_audit.py b/tests/unit/test_appctl_audit.py new file mode 100644 index 0000000..ce69250 --- /dev/null +++ b/tests/unit/test_appctl_audit.py @@ -0,0 +1,336 @@ +""" +tests/unit/test_appctl_audit.py — Unit Tests for Audit Logger & Concurrency Lock (P4 Slice 2) + +Behavior-driven test naming convention: +test___ +""" + +from __future__ import annotations + +import json +import os +import stat +from pathlib import Path + +import pytest +from appctl_audit import ( + AuditEvent, + AuditLogger, + AuditPersistenceError, + AuditPhase, + ConcurrentMutationError, + PrincipalAudit, + TargetLockManager, + redact_sensitive_data, +) + + +@pytest.fixture +def temp_audit_file(tmp_path: Path) -> Path: + return tmp_path / "audit" / "audit.jsonl" + + +@pytest.fixture +def temp_lock_dir(tmp_path: Path) -> Path: + lock_dir = tmp_path / "locks" + lock_dir.mkdir(parents=True, exist_ok=True) + return lock_dir + + +@pytest.fixture +def sample_principal() -> PrincipalAudit: + return PrincipalAudit( + identity="operator", + role="homelab-admin", + token_id="tok_admin_01", + auth_method="bearer_token", + ) + + +# --------------------------------------------------------------------------- +# File Permissions & Initialization +# --------------------------------------------------------------------------- + + +def test_audit_logger_enforces_0600_permissions_on_creation( + temp_audit_file: Path, sample_principal: PrincipalAudit +): + logger = AuditLogger(temp_audit_file) + logger.log_dispatched( + operation_id="op_100", + principal=sample_principal, + action="workload.deploy", + target="snappymail", + transport="unix_socket", + origin="peer_uid_1000", + client="appctl-cli/2.0", + parameters={"recreate": True}, + ) + + assert temp_audit_file.exists() + mode = stat.S_IMODE(temp_audit_file.stat().st_mode) + assert mode == 0o600 + + +# --------------------------------------------------------------------------- +# Audit Phases & RFC JSONL Schema +# --------------------------------------------------------------------------- + + +def test_audit_logger_writes_valid_jsonl_lifecycle( + temp_audit_file: Path, sample_principal: PrincipalAudit +): + logger = AuditLogger(temp_audit_file) + + # 1. DISPATCHED + evt_disp = logger.log_dispatched( + operation_id="op_101", + principal=sample_principal, + action="workload.update", + target="jellyfin", + transport="http", + origin="127.0.0.1:48291", + client="gitops-dispatcher/1.0", + parameters={"expected_branch": "main", "build": False}, + ) + assert evt_disp.phase == AuditPhase.DISPATCHED + assert evt_disp.result is not None + assert evt_disp.result.status == "IN_PROGRESS" + + # 2. COMPLETED + evt_comp = logger.log_completed( + operation_id="op_101", + principal=sample_principal, + action="workload.update", + target="jellyfin", + transport="http", + origin="127.0.0.1:48291", + client="gitops-dispatcher/1.0", + parameters={"expected_branch": "main", "build": False}, + duration_ms=1450, + commit_sha="a1b2c3d", + message="Workload updated and reconciled successfully", + ) + assert evt_comp.phase == AuditPhase.COMPLETED + assert evt_comp.result is not None + assert evt_comp.result.status == "SUCCESS" + assert evt_comp.result.exit_code == 0 + assert evt_comp.result.commit_sha == "a1b2c3d" + + # Read and validate JSONL file contents + lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines() + assert len(lines) == 2 + + parsed_disp = AuditEvent.model_validate(json.loads(lines[0])) + assert parsed_disp.phase == AuditPhase.DISPATCHED + assert parsed_disp.operation_id == "op_101" + + parsed_comp = AuditEvent.model_validate(json.loads(lines[1])) + assert parsed_comp.phase == AuditPhase.COMPLETED + assert parsed_comp.operation_id == "op_101" + + +def test_audit_logger_writes_failed_event( + temp_audit_file: Path, sample_principal: PrincipalAudit +): + logger = AuditLogger(temp_audit_file) + logger.log_failed( + operation_id="op_102", + principal=sample_principal, + action="workload.deploy", + target="jellyfin", + transport="unix_socket", + origin="peer_uid_1000", + client="appctl-cli/2.0", + parameters={"recreate": True}, + duration_ms=320, + exit_code=1, + error_code="ERR_EXECUTION_FAILED", + message="Docker compose failed with exit code 1", + ) + + lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines() + assert len(lines) == 1 + event = AuditEvent.model_validate(json.loads(lines[0])) + assert event.phase == AuditPhase.FAILED + assert event.result is not None + assert event.result.status == "FAILED" + assert event.result.exit_code == 1 + assert event.result.error_code == "ERR_EXECUTION_FAILED" + + +def test_audit_logger_writes_denied_event( + temp_audit_file: Path, sample_principal: PrincipalAudit +): + logger = AuditLogger(temp_audit_file) + logger.log_denied( + operation_id="op_103", + principal=sample_principal, + action="workload.config", + target="core", + transport="http", + origin="127.0.0.1:49000", + client="curl/8.1", + parameters={}, + error_code="ERR_PERMISSION_DENIED", + message="Role homelab-operator cannot target core stack", + ) + + lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines() + assert len(lines) == 1 + event = AuditEvent.model_validate(json.loads(lines[0])) + assert event.phase == AuditPhase.DENIED + assert event.result is not None + assert event.result.status == "DENIED" + assert event.result.error_code == "ERR_PERMISSION_DENIED" + + +# --------------------------------------------------------------------------- +# Secret Redaction +# --------------------------------------------------------------------------- + + +def test_redact_sensitive_data_masks_secret_keys(): + raw_params = { + "API_KEY": "supersecretkey123", + "WEBHOOK_SECRET": "whsec_9999", + "db_password": "mypassword", + "AUTH_TOKEN": "tok_12345", + "SSH_KEY": "ssh-ed25519 AAA...", + "PASSWORD_HASH": "$2b$12$...", + "recreate": True, + "nested": { + "SECRET_PASS": "pass123", + "normal_config": "enabled", + "list_items": [ + {"ITEM_SECRET": "leak", "id": 1}, + "safe_string", + ], + }, + } + + redacted = redact_sensitive_data(raw_params) + assert redacted["API_KEY"] == "[REDACTED]" + assert redacted["WEBHOOK_SECRET"] == "[REDACTED]" + assert redacted["db_password"] == "[REDACTED]" + assert redacted["AUTH_TOKEN"] == "[REDACTED]" + assert redacted["SSH_KEY"] == "[REDACTED]" + assert redacted["PASSWORD_HASH"] == "[REDACTED]" + assert redacted["recreate"] is True + assert redacted["nested"]["SECRET_PASS"] == "[REDACTED]" + assert redacted["nested"]["normal_config"] == "enabled" + assert redacted["nested"]["list_items"][0]["ITEM_SECRET"] == "[REDACTED]" + assert redacted["nested"]["list_items"][0]["id"] == 1 + assert redacted["nested"]["list_items"][1] == "safe_string" + + +def test_audit_logger_automatically_redacts_sensitive_parameters( + temp_audit_file: Path, sample_principal: PrincipalAudit +): + logger = AuditLogger(temp_audit_file) + logger.log_dispatched( + operation_id="op_104", + principal=sample_principal, + action="workload.deploy", + target="vaultwarden", + transport="unix_socket", + origin="peer_uid_1000", + client="appctl-cli/2.0", + parameters={"ADMIN_TOKEN": "super_token_leak", "recreate": True}, + ) + + content = temp_audit_file.read_text(encoding="utf-8") + assert "super_token_leak" not in content + assert "[REDACTED]" in content + + +# --------------------------------------------------------------------------- +# Pre-Execution Fail-Closed Disk Guard +# --------------------------------------------------------------------------- + + +def test_audit_logger_fails_closed_when_audit_log_unwritable( + tmp_path: Path, sample_principal: PrincipalAudit +): + read_only_dir = tmp_path / "readonly_audit" + read_only_dir.mkdir(parents=True, exist_ok=True) + unwritable_file = read_only_dir / "audit.jsonl" + unwritable_file.touch(mode=0o400) + os.chmod(unwritable_file, 0o400) + + # In addition, make directory read-only + os.chmod(read_only_dir, 0o500) + + try: + logger = AuditLogger(unwritable_file) + with pytest.raises(AuditPersistenceError) as exc_info: + logger.log_dispatched( + operation_id="op_105", + principal=sample_principal, + action="workload.deploy", + target="jellyfin", + transport="unix_socket", + origin="peer_uid_1000", + client="appctl-cli/2.0", + parameters={"recreate": True}, + ) + assert "Failed to persist audit event" in str(exc_info.value) + finally: + os.chmod(read_only_dir, 0o700) + os.chmod(unwritable_file, 0o600) + + +# --------------------------------------------------------------------------- +# Concurrency & Non-Blocking Flock Manager +# --------------------------------------------------------------------------- + + +def test_target_lock_manager_acquires_and_releases_lock(temp_lock_dir: Path): + manager = TargetLockManager(temp_lock_dir) + + with manager.lock_target("snappymail") as lock: + assert lock.target == "snappymail" + assert lock.lock_path.exists() + # Verify mode 0600 on lock file + assert stat.S_IMODE(lock.lock_path.stat().st_mode) == 0o600 + + # Lock can be re-acquired immediately after release + with manager.lock_target("snappymail"): + pass + + +def test_target_lock_manager_rejects_concurrent_mutation(temp_lock_dir: Path): + manager = TargetLockManager(temp_lock_dir) + + with ( + manager.lock_target("jellyfin"), + pytest.raises(ConcurrentMutationError) as exc_info, + manager.lock_target("jellyfin"), + ): + pass + + assert exc_info.value.target == "jellyfin" + assert "locked by a concurrent task" in str(exc_info.value) + + +def test_target_lock_manager_permits_independent_targets_concurrently( + temp_lock_dir: Path, +): + manager = TargetLockManager(temp_lock_dir) + + with manager.lock_target("app1"), manager.lock_target("app2"): + pass + + +def test_homepage_sync_lock_acquires_designated_file(temp_lock_dir: Path): + manager = TargetLockManager(temp_lock_dir) + + with ( + manager.homepage_sync_lock() as lock, + pytest.raises(ConcurrentMutationError) as exc_info, + manager.homepage_sync_lock(), + ): + pass + + assert lock.lock_path.name == "_homepage_sync.lock" + assert exc_info.value.target == "_homepage_sync" diff --git a/todo.txt b/todo.txt index 2963a01..e461507 100644 --- a/todo.txt +++ b/todo.txt @@ -23,7 +23,7 @@ x 2026-10-15 (A) De-tautologize appctl env injection test to execute scripts/app x 2026-10-15 (A) Clarify Pydantic v2 target architecture, strict typing rules, and domain precedence in docs/plans/p4-readiness-plan.md +docs @p4-gate x 2026-10-15 (A) Migrate core_manifest.py to Pydantic v2 models for strict type validation and serialization +manifest @schema x 2026-10-19 (A) Implement strict Pydantic v2 API contracts, error sanitizer, and compose_pull action in scripts/appctl_contracts.py and scripts/core_manifest.py +contracts @p4 -(A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4 +x 2026-10-19 (A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4 (A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4 (B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4 (B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) and wire gitops_dispatcher.py worker to daemon in scripts/appctl_daemon.py +daemon @p4