diff --git a/ROADMAP.md b/ROADMAP.md index 8dffc38..5ab6358 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -100,12 +100,12 @@ It describes the implementation trajectory and phased engineering milestones for **Status**: 🎯 **Current / Up Next** * **Objective**: Evolve `appctl` from a collection of local shell scripts into the authoritative platform daemon while enforcing authorization gates from day one. * **Key Deliverables**: - 1. *Daemon Service (`homelab-appctl.service`)*: Systemd daemon exposing one logical API across dual transports: Unix domain socket (`/run/homelab/appctl.sock`) on host and HTTP listener for network clients. - 2. *Mandatory Authorization Gate*: Establish the authentication/authorization middleware interface before exposing mutating routes; reject unauthenticated mutations across both Unix socket and HTTP transports. - 3. *Command-Oriented Operational Router*: Strongly-typed endpoints (`POST /operations/deploy`, `POST /operations/restart`, `POST /operations/pull`, `GET /workloads`, `GET /workloads/{id}/status`, `POST /operations/sync`) invoking `core_manifest.py` and `appctl_engine.py` via internal interfaces. + 1. *Daemon Service (`homelab-appctl.service`)*: Systemd daemon running as dedicated user `homelab-appctl` (`Group = "homelab-operators"`), exposing one logical HTTP/1.1 API across dual transports: Unix domain socket (`/run/homelab/appctl.sock`) on host and loopback HTTP listener (`127.0.0.1:9001`). + 2. *Mandatory Authorization Gate*: Enforce SOPS-projected SHA-256 Bearer tokens (`/run/secrets/appctl/tokens.json`) and 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`) for all mutations, sensitive reads (`workload.config`, `workload.logs`), and HTTP calls; restrict `SO_PEERCRED` on UDS to non-sensitive `homelab-viewer` inspection. + 3. *Command-Oriented Operational Router*: Single canonical command endpoint (`POST /v1/operations` + `GET /v1/health`) invoking `core_manifest.py`, `appctl_engine.py`, `validate_compose_security()`, and pure-Python `.env` assembly with per-target `flock` serialization and revision-consistent `workload.update` execution (unifying CLI and `gitops_dispatcher.py` worker execution). 4. *Thin-Client CLI*: Re-implement `scripts/appctl` as a lightweight dispatch client communicating with the local daemon socket. - 5. *Append-Only Audit Log*: Record every mutating command to `~/.local/state/homelab/appctl/audit.jsonl` with restricted `0600` permissions. Telemetry captures `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, and `result`. -* **Exit Criteria**: Hermetic API test suite passing; unauthenticated mutation attempts rejected across both transports; audit log capturing multi-dimensional telemetry. + 5. *Append-Only Audit Log*: Record every mutating command, sensitive read, and denied request to `/var/log/homelab/appctl/audit.jsonl` with restricted `0600` permissions (`homelab-appctl`) and a fail-closed pre-execution disk guard. Telemetry captures `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, and `result`. +* **Exit Criteria**: Hermetic API test suite passing; unauthenticated and unauthorized mutation attempts rejected across both transports; audit log capturing multi-dimensional telemetry under `homelab-appctl` isolation. --- diff --git a/docs/operations.md b/docs/operations.md index 6171a87..1949b1a 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -51,7 +51,7 @@ docker system prune -a --volumes --filter "until=168h" Homelab Core runs several platform services managed by systemd: ### `homeserver-core.service` (Core Compose Stack) -Manages the lifecycle of Traefik, Authelia, LLDAP, Stalwart, SnappyMail, Homepage, Dozzle, Watchtower, and Diun. +Manages the lifecycle of Traefik, Authelia, LLDAP, Stalwart, Homepage, Dozzle, Watchtower, and Diun. ```bash # Check service status diff --git a/docs/plans/p4-readiness-plan.md b/docs/plans/p4-readiness-plan.md index 5a37c33..f26071c 100644 --- a/docs/plans/p4-readiness-plan.md +++ b/docs/plans/p4-readiness-plan.md @@ -46,10 +46,9 @@ This plan resolves the six architectural prerequisites necessary to implement P4 | :--- | :--- | :--- | :--- | | [`scripts/appctl`](../../scripts/appctl) | Bash | **Active CLI Client** | CLI entry point; secret environment sourcing (`homeserver.env`, `traefik-deployments.env`); resolves metadata via engine; directly runs `docker compose` and `git pull` subprocesses. | | [`scripts/appctl_engine.py`](../../scripts/appctl_engine.py) | Python 3 | **Authoritative Engine** | Domain models (`SitesApp`, `CoreService`); schema v1.0 parsing (`core_manifest.py`); two-axis inspection (`provenance.py`); SSL cert inspection; Homepage compilation; metadata serialization (`resolve`). | -| [`scripts/core_manifest.py`](../../scripts/core_manifest.py) | Python 3 | **Schema Library** | Strongly-typed Manifest dataclasses; transport validation (`https://`, `ssh://`, `git@`); ref semantics classification (`branch`, `tag`, `commit`). | - +| [`scripts/core_manifest.py`](../../scripts/core_manifest.py) | Python 3 | **Schema Library** | Authoritative Pydantic v2 models (`ConfigDict(extra="forbid")`); transport validation (`https://`, `ssh://`, `git@`); ref semantics classification (`branch`, `tag`, `commit`). | | [`scripts/provenance.py`](../../scripts/provenance.py) | Python 3 | **Provenance Library** | Two-axis status engine; local checkout inspection (`git status`, commit SHA); bounded upstream query (`git ls-remote` with 10s timeout). | -| [`scripts/gitops_dispatcher.py`](../../scripts/gitops_dispatcher.py) | Python 3 | **Independent Service** | Webhook listener (port 9000); HMAC validation; flock serialization; independent AST validation; executes its own `docker compose` and `git pull` subprocesses. | +| [`scripts/gitops_dispatcher.py`](../../scripts/gitops_dispatcher.py) | Python 3 | **Webhook Ingress & Queue** | Webhook listener (port 9000); HMAC validation; `deployments.yaml` admission; `.pending.json` commit-superseding queue; Compose AST validator (`validate_compose_security`). | ### B. Command Inventory & Implementation Division @@ -66,8 +65,8 @@ This plan resolves the six architectural prerequisites necessary to implement P4 | `restart` | `appctl restart ` | `scripts/appctl` (Bash) | Mutating (Containers) | Sourced environment variables $\to$ `docker compose restart` (or down/up) $\to$ triggers `appctl sync`. | | `update` | `appctl update ` | `scripts/appctl` (Bash) | Mutating (Git + Containers) | Verifies clean git working tree $\to$ `git pull --ff-only` $\to$ `docker compose pull` $\to$ `docker compose up -d` $\to$ triggers `appctl sync`. | | `pull` | `appctl pull ` | `scripts/appctl` (Bash) | Mutating (Images) | `docker compose pull` $\to$ `docker compose up -d --remove-orphans`. | -| `logs` | `appctl logs [-f]` | `scripts/appctl` (Bash) | Read-Only (Streaming) | Dispatches `docker compose logs -f`. | -| `config` | `appctl config ` | `scripts/appctl` (Bash) | Read-Only | Injects environment $\to$ executes `docker compose config` to view fully evaluated compose AST. | +| `logs` | `appctl logs ` | `scripts/appctl` (Bash) | Read-Only (Sensitive) | Dispatches `docker compose logs`. (Bounded tail output in P4; live streaming deferred to P7.) | +| `config` | `appctl config ` | `scripts/appctl` (Bash) | Read-Only (Sensitive) | Injects environment $\to$ executes `docker compose config` to view fully evaluated compose AST. | ### C. Active Call Sites Across the Repository @@ -76,65 +75,78 @@ This plan resolves the six architectural prerequisites necessary to implement P4 2. **Internal Script Invocation**: - `scripts/appctl` calls `python3 "$ENGINE" resolve "$query"` to set up the Compose environment. - `scripts/appctl` calls `python3 "$ENGINE" sync` after mutating actions (`up`, `down`, `restart`, `update`). -3. **Automated Test Coverage**: - - [`tests/unit/test_appctl_engine.py`](../../tests/unit/test_appctl_engine.py): 12 unit tests exercising `resolve_app`, `get_docker_status`, `check_ssl_cert`, and `cmd_sync_homepage`. - - [`tests/unit/test_core_manifest.py`](../../tests/unit/test_core_manifest.py): 19 unit tests covering schema validation and ref classification. +3. **Automated Test Coverage (124 Passing Tests)**: + - [`tests/unit/test_core_manifest.py`](../../tests/unit/test_core_manifest.py): 24 unit tests covering Pydantic v2 schema validation, extra-field rejection, and ref classification. + - [`tests/unit/test_appctl_engine.py`](../../tests/unit/test_appctl_engine.py): 20 unit tests exercising `resolve_app`, `get_docker_status`, `check_ssl_cert`, and `cmd_sync_homepage`. - [`tests/unit/test_provenance.py`](../../tests/unit/test_provenance.py): 10 unit tests covering two-axis status inspection and timeout handling. - - [`tests/structural/test_repository_structure.py`](../../tests/structural/test_repository_structure.py): Asserts executability and paths of `scripts/appctl` and `scripts/appctl_engine.py`. + - [`tests/security/test_gitops_security.py`](../../tests/security/test_gitops_security.py): 60 security tests covering HMAC verification, `deployments.yaml` containment, Compose AST validation, and worker serialization. + - [`tests/security/test_security_invariants.py`](../../tests/security/test_security_invariants.py): 7 security invariant tests covering `socket-proxy`, `eval` absence, CLI env injection resilience, and platform genericism. + - [`tests/structural/test_repository_structure.py`](../../tests/structural/test_repository_structure.py): 3 structural tests asserting required paths and license preservation. ### D. Architectural Findings & Migration Deductions -1. **V1 Engine is Fully Superseded & V2 Shim Retired**: `scripts/appctl_engine.py` is the single authoritative metadata engine. The `scripts/appctl_engine_v2.py` compatibility shim has been retired. - -2. **Duplicated Operational Logic in GitOps**: `scripts/gitops_dispatcher.py` and `scripts/appctl` maintain **separate, duplicate implementations** of `git pull` and `docker compose up`. This violates Invariant #1 (*Single Operational Truth*). In P4, GitOps webhook handlers must delegate execution to the control-plane daemon via its internal client. -3. **Environment Injection Vulnerability in Bash**: The current Bash CLI constructs shell exports dynamically using `eval "$(python3 ...)"`. The daemon replaces this subprocess string interpolation with in-process, typed dictionary manipulation. +1. **V1 Engine is Fully Superseded & V2 Shim Retired**: `scripts/appctl_engine.py` is the single authoritative metadata engine, and `scripts/core_manifest.py` is migrated to Pydantic v2 (`ADR-0003`). +2. **Duplicated Operational Execution in GitOps (`DEC-04`)**: `scripts/gitops_dispatcher.py` and `scripts/appctl` maintain separate implementations of `git pull` and `docker compose up`, and `gitops_dispatcher.py` currently omits workload environment injection (`SERVICE_DOMAIN`, `CONTAINER_NAME`, `app.yaml` `env:`, `traefik-deployments.env`). In P4, `gitops_dispatcher.py` retains webhook HMAC verification, `deployments.yaml` admission, and the asynchronous `.pending.json` commit-superseding queue, while its worker delegates deployment execution to the daemon's `workload.update` operation over `/run/homelab/appctl.sock` and uses `core_manifest.parse_manifest()`. +3. **Shell `.env` Sourcing & Missing Compose AST Pre-Flight on CLI Path (`DEC-05`)**: While `eval` was removed from `scripts/appctl`, the Bash CLI still runs `source "$APP_DIR/.env"` and `source "$APP_DIR/app.env"` and does not invoke `validate_compose_security()`. The P4 daemon replaces Bash `source` with an inert pure-Python key-value parser (enforcing `ENV_KEY_RE` and `RESERVED_ENV_KEYS`) and runs `validate_compose_security()` before every workload Compose operation. --- -## 2. Command and Error Contract (P4 Prerequisite) +## 2. Command and Error Contract (P4 Prerequisite β€” Locked via `DEC-01` & `DEC-04`) -### A. Canonical Domain Operations +### A. Wire Protocol, Endpoint Surface & Canonical Domain Operations (`DEC-01`) -Every client (local CLI, remote CLI, GitOps dispatcher, and future Operations UI) invokes one of these domain operations across either transport: +1. **HTTP/1.1 Over Both Transports**: Both the local Unix Domain Socket (`/run/homelab/appctl.sock`) and the loopback TCP listener (`127.0.0.1:9001`) speak standard **HTTP/1.1** and traverse a single shared request pipeline (Body Size Limit $\to$ JSON Parse $\to$ Pydantic v2 Validate $\to$ Auth/RBAC Gate $\to$ Target Resolution & Lock $\to$ Pre-Execution Audit $\to$ Execution $\to$ Post-Execution Audit). +2. **Single Canonical Operation Endpoint**: + - `POST /v1/operations`: Dispatches all 12 canonical domain operations (both read-only and mutating). + - `GET /v1/health`: Convenience liveness probe that internally dispatches `platform.health`. + - No multi-route REST aliases (`GET /workloads`, `POST /operations/deploy`, etc.) are exposed in P4, eliminating URL-vs-body ambiguity. +3. **Bounded Non-Streaming Logs**: `workload.logs` is strictly non-streaming in P4 (`tail: StrictInt` bounded `1..1000`, default `100`). Live streaming (`--follow` / SSE) is deferred to Milestone P7. +4. **Payload & Output Bounds**: Maximum HTTP request body size is `64 KiB` (larger bodies are rejected with `400 ERR_VALIDATION_FAILED`). Maximum captured subprocess `stdout`/`stderr` is `256 KiB` per invocation. -``` - β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” - β”‚ Client Request β”‚ - β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β–Ό - β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” - β”‚ Operation Dispatch Router β”‚ - β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ - β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” - β–Ό β–Ό - [ Read-Only Operations ] [ Mutating Operations ] - β€’ workload.list β€’ workload.deploy - β€’ workload.get β€’ workload.stop - β€’ workload.resolve β€’ workload.restart - β€’ workload.config β€’ workload.update - β€’ workload.logs β€’ workload.pull - β€’ platform.ssl β€’ platform.sync_homepage - β€’ platform.health +```text + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Client Request β”‚ + β”‚ POST /v1/operations β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β–Ό + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Operation Dispatch Router β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β–Ό β–Ό + [ Read-Only Operations ] [ Mutating Operations ] + β€’ workload.list (viewer) β€’ workload.deploy (operator / admin*) + β€’ workload.get (viewer) β€’ workload.stop (operator / admin*) + β€’ workload.resolve (viewer) β€’ workload.restart (operator / admin*) + β€’ platform.ssl (viewer) β€’ workload.update (operator / admin*) + β€’ platform.health (viewer) β€’ workload.pull (operator / admin*) + β€’ workload.config (operator / admin* β€” sensitive read) β€’ platform.sync_homepage (operator / admin) + β€’ workload.logs (operator / admin* β€” sensitive read) + (* targeting 'core' or a 'core_service' strictly requires 'homelab-admin') ``` -### B. Typed Request and Response Models (Target Architecture: Pydantic v2 Pipeline) +### B. Typed Request and Response Models (Pydantic v2 Pipeline) -All control plane API requests, responses, error payloads, and workload manifest schemas will be defined and validated through **Pydantic v2** (`pydantic.BaseModel`, `pydantic.Field`, `ConfigDict(extra="forbid", strict=True)`). While the dependency has been integrated into runtime environments, the schema migration and model definitions are the first implementation deliverables of Milestone P4: +All control plane API requests, responses, and error payloads are defined and validated through **Pydantic v2** (`pydantic.BaseModel`, `pydantic.Field`, `ConfigDict(extra="forbid", strict=True)`), joining the existing Pydantic v2 manifest schema in [`scripts/core_manifest.py`](../../scripts/core_manifest.py): -- **Runtime Validation Boundary**: Incoming payloads over both Unix Domain Socket and HTTP endpoints are validated at the transport boundary before reaching the operational router. +- **Runtime Validation Boundary**: Incoming JSON payloads over both Unix Domain Socket and HTTP endpoints are validated at the transport boundary before reaching the operational router. - **Fail-Closed Extra Fields (`extra="forbid"`)**: Rejects any undeclared or unknown fields immediately. -- **Strict Typing vs. Coercion Rules**: - - *Strict Validation*: Operations (`operation`), target identifiers (`target`), boolean flags (`recreate`, `remove_orphans`, `visible`, `auth`), and authentication tokens require strict types (`strict=True` or `StrictStr`, `StrictBool`). Coercion (e.g. converting `"true"` or `1` to `True`, or floats to ints) is strictly forbidden for control plane commands to prevent ambiguous execution. - - *Permitted Coercion / Sanitization*: Only explicitly defined string stripping/normalization (e.g. whitespace trimming) is permitted via field validators. -- **Structured Error Transformation**: Transport handlers intercept `pydantic.ValidationError` and map it to canonical `ERR_VALIDATION_FAILED` (`400 Bad Request`) responses. -- **Information Disclosure Prevention**: Error details must include field names and validation issue descriptions, but must strictly redact and omit raw input values to prevent leaking secrets, credentials, or host filesystem paths. -- **Contract Enforcement**: Manifest definitions in `core_manifest.py` migrate to Pydantic v2 models, guaranteeing uniform schema enforcement across the CLI, daemon, and GitOps engines. +- **Strict Typing vs. Coercion Rules (`strict=True`)**: + - *Strict Validation*: Operations (`operation`), target identifiers (`target`), integer bounds (`tail`), boolean flags (`recreate`, `remove_orphans`, `build`, `fetch`, `core`, `ssl`), and optional strings (`expected_branch`) enforce strict types (`StrictStr`, `StrictBool`, `StrictInt`). Implicit coercion (e.g., `"true"` or `1` to `True`, or floats to ints) is forbidden. + - *Permitted Normalization*: Only explicitly defined string whitespace trimming via field validators is permitted. +- **Operation-Specific Parameters (`DEC-04`)**: + - `workload.deploy`: `recreate: StrictBool = True`, `remove_orphans: StrictBool = True`, `build: StrictBool = False`. + - `workload.update`: `expected_branch: StrictStr | None = None`, `build: StrictBool = False`. Enforces revision-consistent post-pull validation of `app.yaml` (`deployment.branch` and `deployment.actions`, supporting `git_pull`, `compose_pull`, `compose_build`, `compose_up`, `compose_restart`). + - `workload.logs`: `tail: StrictInt = Field(default=100, ge=1, le=1000)`. + - `workload.list`: `fetch: StrictBool = False`, `core: StrictBool = False`, `ssl: StrictBool = False`. + - `workload.get`: `ssl: StrictBool = False`. +- **Information Disclosure Prevention**: Transport handlers intercept `pydantic.ValidationError`, strip raw input values (`e.errors(include_input=False, include_url=False)`), and map violations to `ERR_VALIDATION_FAILED` (`400 Bad Request`). All requests and responses use strict JSON payloads with explicit schema versioning (`version: "1.0"`): ```json -// Example: POST /operations/deploy +// Example: POST /v1/operations // Request: { "version": "1.0", @@ -142,7 +154,8 @@ All requests and responses use strict JSON payloads with explicit schema version "target": "jellyfin", "parameters": { "recreate": true, - "remove_orphans": true + "remove_orphans": true, + "build": false } } @@ -152,136 +165,156 @@ All requests and responses use strict JSON payloads with explicit schema version "status": "success", "operation_id": "op_01JAX71BC98E4", "target": "jellyfin", - "timestamp": "2026-10-13T18:30:00Z", + "timestamp": "2026-10-16T12:00:00Z", "duration_ms": 1420, "result": { - "action": "recreated", - "containers": ["jellyfin"], - "health": "running" + "action": "deployed", + "target_type": "app", + "health": "🟒 Running (1)" } } ``` ### C. Standardized Error Taxonomy -Failures are strongly typed and distinguished at three distinct architectural levels: +Failures are strongly typed and distinguished across six canonical error codes: | Error Classification | HTTP Code | Error Code | Description / Fail-Closed Action | | :--- | :--- | :--- | :--- | -| **Validation Error** | `400 Bad Request` | `ERR_VALIDATION_FAILED` | Request schema violation, invalid target name, malformed `app.yaml`, or Compose AST security violation. | -| **Authentication Error** | `401 Unauthorized` | `ERR_AUTH_REQUIRED` | Missing, expired, or malformed API token / HMAC signature. | -| **Authorization Error** | `403 Forbidden` | `ERR_PERMISSION_DENIED` | Authenticated principal lacks necessary role (`homelab-admin` vs. `homelab-viewer`) for the target operation. | +| **Validation Error** | `400 Bad Request` | `ERR_VALIDATION_FAILED` | Request schema violation, body $>64\text{ KiB}$, invalid target format, malformed `app.yaml`, dirty git working tree on update, post-pull branch mismatch, or Compose AST security violation. | +| **Authentication Error** | `401 Unauthorized` | `ERR_AUTH_REQUIRED` | Missing, unknown, or malformed Bearer token (or unauthenticated UDS caller attempting a token-gated operation). | +| **Authorization Error** | `403 Forbidden` | `ERR_PERMISSION_DENIED` | Authenticated principal lacks required role (e.g., `homelab-viewer` attempting mutation or `config`/`logs`; `homelab-operator` targeting `core`/`core_service` or a workload not in `deployments.yaml`). | | **Target Not Found** | `404 Not Found` | `ERR_TARGET_NOT_FOUND` | Workload target does not exist under `~/Sites` or Core services registry. | -| **State Conflict** | `409 Conflict` | `ERR_CONCURRENT_MUTATION` | Another mutating operation on the target workload is currently holding the operation lock. | -| **Execution Error** | `500 Internal Error`| `ERR_EXECUTION_FAILED` | Docker daemon error, subprocess non-zero exit, or persistent volume failure. | +| **State Conflict** | `409 Conflict` | `ERR_CONCURRENT_MUTATION` | Another mutating operation on the target workload is currently holding the per-target operation lock. | +| **Execution Error** | `500 Internal Error`| `ERR_EXECUTION_FAILED` | Audit log write failure, Docker/Git subprocess non-zero exit, or subprocess timeout expiration. | --- -## 3. Authorization Design (Security Gate) +## 3. Authorization Design (Security Gate β€” Locked via `DEC-02` & `DEC-05`) -### A. The Core Principle: Host Access Does Not Confer Authority +### A. The Core Principle: Host Access Does Not Confer Mutation Authority -Entering the host via SSH establishes Unix access, but **zero operational control plane privileges**. Every mutating request to `homelab-appctl.service` must present authenticated credentials. +Entering the host via SSH establishes Unix access, but **zero operational control plane mutation or secret-inspection privileges**. Every mutating requestβ€”and every sensitive read (`workload.config`, `workload.logs`)β€”to `homelab-appctl.service` must present an authenticated Bearer token. -### B. Principal Identity & Role Mapping +### B. Principal Identity, Role Mapping & Target Scope (`DEC-02`, `DEC-05`) -The platform defines three hierarchical authorization tiers: +The platform enforces three hierarchical authorization tiers: -| Role | Permitted Operations | Typical Principals | +| Role | Permitted Operations & Target Scope | Typical Principals | | :--- | :--- | :--- | -| `homelab-admin` | All operations (including Core platform mutation, daemon reload, secret regeneration). | Break-glass admin token, human interactive operator (`operator`). | -| `homelab-operator` | Workload mutations (`deploy`, `stop`, `restart`, `update`, `pull`, `sync_homepage`). Cannot mutate Core platform infrastructure. | GitOps webhook runner token, automation scripts. | -| `homelab-viewer` | Read-only operations (`list`, `get`, `resolve`, `config`, `logs`, `ssl`, `health`). Zero mutations permitted. | Homepage dashboard status monitor, read-only diagnostic CLI. | +| `homelab-admin` | All operations across **all targets**: `core` stack, individual `core_service` containers (`traefik`, `authelia`, `stalwart`, etc.), and any valid `~/Sites/` directory contained within `SITES_DIR`. | Interactive human operator token (`operator`). | +| `homelab-operator` | Workload mutations (`deploy`, `stop`, `restart`, `update`, `pull`, `sync_homepage`) and sensitive reads (`config`, `logs`) **strictly restricted to workloads registered in [`config/deployments.yaml`](../../config/deployments.yaml)**. Cannot target `core`, `core_service`, or unregistered `~/Sites` directories (`403 ERR_PERMISSION_DENIED`). | GitOps webhook worker token (`gitops-dispatcher`), scoped automation scripts. | +| `homelab-viewer` | Non-sensitive read-only operations (`workload.list`, `workload.get`, `workload.resolve`, `platform.ssl`, `platform.health`). Zero mutations permitted; `workload.config` and `workload.logs` are denied (`403 ERR_PERMISSION_DENIED`). | Local UDS `SO_PEERCRED` operator session fallback, read-only status monitors. | -### C. Transport Authentication Rules +### C. Transport Authentication Rules (P4 vs. P5 Boundary) -1. **Unix Domain Socket (`/run/homelab/appctl.sock`)**: - - Socket ownership: `root:homelab-operators`, file mode `0660`. - - Read-only operations allowed without token *if* the client UID belongs to `homelab-operators`. - - **All mutating operations strictly require a valid user-scoped Bearer token** passed in the request header (`Authorization: Bearer `). -2. **HTTP Network Listener (Local LAN / Traefik)**: - - External Web: Traefik verifies Authelia session and forwards trusted identity headers (`Remote-User`, `Remote-Groups`). Headers are **strictly rejected** unless incoming connection originates from the trusted Docker `proxy-net` gateway. - - Remote CLI / API: Requires user-scoped Bearer token. -3. **GitOps Ingress**: - - Authenticated via HMAC-SHA256 signature (`X-Gitea-Signature` / `X-Hub-Signature-256`) against `/run/secrets/gitops/webhook_secret`. - - Evaluated as an internal caller with `homelab-operator` role, constrained strictly to the target repository declared in [`config/deployments.yaml`](../../config/deployments.yaml). +1. **SOPS-Projected Hashed Token Store (`/run/secrets/appctl/tokens.json`)**: + - Owned by `homelab-appctl` (mode `0400`). + - Stores an array of token descriptors (`token_id`, `identity`, `role`, and 64-char hex `sha256` digest of the bearer secret). + - Incoming `Authorization: Bearer ` headers are hashed with SHA-256 and compared via `hmac.compare_digest`. + - Required for **all mutations**, **all `workload.config` / `workload.logs` calls**, and **all HTTP listener requests**. +2. **Unix Domain Socket (`/run/homelab/appctl.sock`) & `SO_PEERCRED`**: + - Socket ownership: `homelab-appctl:homelab-operators`, file mode `0660`. + - The UDS listener extracts kernel peer credentials (`SO_PEERCRED`: `uid`, `gid`, `pid`) on every connection and records `origin = f"peer_uid_{uid}"`. + - If no `Authorization` header is supplied over UDS and `uid` belongs to an authorized local operator, the request is authenticated as `Principal(identity=f"unix_uid_{uid}", role="homelab-viewer", token_id=None, auth_method="unix_peercred")`. This enables zero-friction local inspection (`appctl list`, `appctl info`, `appctl ssl`) and shell tab-completion (`appctl complete`) while blocking all mutations and secret dumps (`401`/`403`). +3. **HTTP Network Listener (`127.0.0.1:9001`)**: + - Bound strictly to loopback (`127.0.0.1`) in P4 (`APPCTL_HTTP_HOST=127.0.0.1`, `APPCTL_HTTP_PORT=9001`). + - Every `POST /v1/operations` call over HTTP requires a valid Bearer token (`401 ERR_AUTH_REQUIRED` if missing). + - **ForwardAuth Headers Deferred to P5**: Proxy headers (`Remote-User`, `Remote-Groups`) are **ignored and never trusted** in P4. (In P5, ForwardAuth will be introduced with dedicated proxy authentication so workload containers on `proxy-net` cannot spoof headers.) +4. **GitOps Ingress (`homelab-gitops.service` $\to$ Daemon UDS)**: + - `gitops_dispatcher.py` verifies the Gitea webhook HMAC-SHA256 signature against `/run/secrets/gitops/webhook_secret`, admits the push against `config/deployments.yaml`, and enqueues `.pending.json`. + - The serialized background worker invokes `POST /v1/operations` (`operation: "workload.update"`, `parameters: {"expected_branch": branch}`) over `/run/homelab/appctl.sock` authenticating with its `homelab-operator` Bearer token. --- -## 4. Execution & Privilege Boundaries (P4 Prerequisite) +## 4. Execution & Privilege Boundaries (P4 Prerequisite β€” Locked via `DEC-03` & `DEC-05`) -### A. Operational Capability Matrix +### A. Operational Capability Matrix & Timeouts -Each canonical operation is strictly bound to minimal execution permissions, allowable subprocesses, and filesystem boundaries: +Each canonical operation is bound to minimal execution permissions, fixed argument lists (`shell=False`), hard timeouts, and role checks: -| Domain Operation | Subprocess / Tool | Allowed Arguments / API | Required Filesystem Roots | Authority / Role Required | +| Domain Operation | Subprocess / Tool | Allowed Arguments / API | Timeout | Required Role (`Sites` / `Core`) | | :--- | :--- | :--- | :--- | :--- | -| `workload.list` | In-process Python (`provenance.py`) | Read directory metadata; optional `git ls-remote` (10s timeout) | Read: `~/Sites/`, `Core/` | `homelab-viewer` | -| `workload.get` | In-process Python (`provenance.py`, `core_manifest.py`) | Parse `app.yaml`, inspect git status | Read: `~/Sites//` | `homelab-viewer` | -| `workload.resolve` | In-process Python (`appctl_engine.py`) | Name resolution & JSON export | Read: `~/Sites/`, `Core/` | `homelab-viewer` | -| `workload.config` | `/run/current-system/sw/bin/docker` | `compose -f /docker-compose.yml config` | Read: `~/Sites//` | `homelab-viewer` | -| `workload.logs` | `/run/current-system/sw/bin/docker` | `compose -f /docker-compose.yml logs [--tail=N] [--follow]` | Read: `~/Sites//` | `homelab-viewer` | -| `workload.deploy` | `/run/current-system/sw/bin/docker` | `compose -f /docker-compose.yml up -d --remove-orphans` | Read/Write: `~/Sites//`, `~/var/lib/homelab//` | `homelab-operator` | -| `workload.stop` | `/run/current-system/sw/bin/docker` | `compose -f /docker-compose.yml down` | Read/Write: `~/Sites//` | `homelab-operator` | -| `workload.restart`| `/run/current-system/sw/bin/docker` | `compose -f /docker-compose.yml restart` | Read/Write: `~/Sites//` | `homelab-operator` | -| `workload.pull` | `/run/current-system/sw/bin/docker` | `compose -f /docker-compose.yml pull` | Read: `~/Sites//` | `homelab-operator` | -| `workload.update` | `/run/current-system/sw/bin/git`
`/run/current-system/sw/bin/docker` | 1. `-C pull --ff-only`
2. `compose pull`
3. `compose up -d --remove-orphans` | Read/Write: `~/Sites//`, `~/var/lib/homelab//` | `homelab-operator` | -| `platform.sync_homepage` | In-process Python (`appctl_engine.py`) | Internal YAML AST generator | Read: `~/Sites/`
Write: `Core/config/homepage/services.yaml` | `homelab-operator` | -| `platform.core_restart` | `/run/current-system/sw/bin/docker` | `compose -f Core/docker-compose.yml restart [service]` | Read: `Core/` | `homelab-admin` | +| `workload.list` | In-process (`appctl_engine.py`, `provenance.py`) | Scan `~/Sites/`, `git status` (`5s`), optional `git ls-remote` (`10s`), `docker compose ps` (`15s`) | `15s` / cmd | `homelab-viewer` | +| `workload.get` | In-process (`appctl_engine.py`, `core_manifest.py`) | Parse `app.yaml`, inspect git status (`5s`), `git ls-remote` (`10s`), `docker inspect` (`15s`) | `15s` / cmd | `homelab-viewer` | +| `workload.resolve` | In-process (`appctl_engine.py`) | Canonical target resolution & metadata dictionary | In-process | `homelab-viewer` | +| `platform.ssl` | In-process (`appctl_engine.py`) | TLS peer certificate check on port 443 | `3s` / host | `homelab-viewer` | +| `platform.health` | In-process | Daemon liveness, socket/lock/audit readiness check | In-process | `homelab-viewer` | +| `workload.config` | `docker` | `compose -f config` (with secret redaction for non-admin) | `15s` | `homelab-operator` / `homelab-admin` | +| `workload.logs` | `docker` | `compose -f logs --no-color --tail <1..1000>` | `15s` | `homelab-operator` / `homelab-admin` | +| `workload.deploy` | `docker` | Optional `compose -f build` (`if build=True`) $\to$ `compose -f up -d [--remove-orphans]` $\to$ Homepage sync | `300s` | `homelab-operator` / `homelab-admin` | +| `workload.stop` | `docker` | `compose -f down` (or `stop ` for `core_service`) $\to$ Homepage sync | `300s` | `homelab-operator` / `homelab-admin` | +| `workload.restart`| `docker` | `compose -f restart []` $\to$ Homepage sync | `300s` | `homelab-operator` / `homelab-admin` | +| `workload.pull` | `docker` | `compose -f pull []` $\to$ `compose -f up -d --remove-orphans` | `300s` | `homelab-operator` / `homelab-admin` | +| `workload.update` | `git`, `docker` | 1. Clean tree check (`git status --porcelain`, `5s`)
2. `git -C pull --ff-only [origin ]` (`60s`)
3. Re-validate `app.yaml` & `expected_branch` + `validate_compose_security()`
4. Execute declared actions (`compose_pull`, `compose_build`, `compose_up`, `compose_restart`, `300s` each) $\to$ Homepage sync | `60s` (git)
`300s` (docker) | `homelab-operator` / `homelab-admin` | +| `platform.sync_homepage` | In-process (`appctl_engine.py`) | Atomic compile of `Core/config/homepage/services.yaml` under `_homepage_sync.lock` | In-process | `homelab-operator` / `homelab-admin` | -### B. Secret Reference Boundary +### B. Unified Pre-Flight, Environment Assembly & Secret Boundary (`DEC-05`) -1. **Daemon Isolation**: The control plane daemon does **not** ingest master decryption keys (`key.txt`) or decrypt raw SOPS archives. -2. **Ephemeral Secret Projection**: The daemon only accesses runtime projections mounted by NixOS/sops-nix under `/run/secrets/`: - - `/run/secrets/appctl/tokens.json`: Hashed token store for API authentication (mode `0400`, owned by daemon user). - - `/run/secrets/gitops/webhook_secret`: Shared HMAC secret for webhook verification (mode `0400`). - - `/run/secrets/rendered/traefik-deployments.env`: Projected workload secrets referenced during container startup. -3. **No Secret Material in Logs or Audit**: All environment injection is filtered: any environment variable or argument matching `*_KEY`, `*_SECRET`, `*_PASSWORD`, `*_TOKEN`, or `*_HASH` is redacted before logging. +1. **Pre-Flight Validation Gate**: Every workload mutation and `workload.config` call executes in strict order: + - **Path Containment**: Target directory must resolve strictly inside `SITES_DIR.resolve()` (or equal `CORE_DIR.resolve()` for `homelab-admin`). + - **Registry Admission**: If `principal.role == "homelab-operator"`, target must be present in `config/deployments.yaml`. + - **Manifest Validation**: `core_manifest.parse_manifest(app_dir / "app.yaml")` must succeed with zero errors. + - **Compose AST Security Validation**: `validate_compose_security(compose_file, app_dir, app_name=manifest.name)` must pass (blocking `privileged: true`, `cap_add`, `devices`, `security_opt: unconfined`, host namespaces, `/var/run/docker.sock`, top-level `include`, escaping `env_file`, undeclared volumes, and cross-tenant bind mounts). +2. **Inert Pure-Python Environment Assembly (No Shell `source`)**: + - The daemon constructs the subprocess environment dictionary in memory: + 1. Base system `PATH` and `DOCKER_CONFIG`. + 2. Global secret files (`/run/secrets/rendered/homeserver.env`, `/run/secrets/rendered/traefik-deployments.env` with `/run/secrets/*` fallback) parsed via a pure-Python `KEY=VALUE` reader (no shell expansion). + 3. Canonical domain lock (`HOMELAB_DOMAIN` resolved via `HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN`). + 4. Infrastructure defaults (`PROXY_NETWORK=proxy-net`, `CERT_RESOLVER=myresolver`, `DOMAIN_SUFFIX=$HOMELAB_DOMAIN`) and workload identity (`SERVICE_NAME`, `CONTAINER_NAME`, `SERVICE_DOMAIN`, `DOMAIN`). + 5. Validated `manifest.env` dictionary from `app.yaml`. + 6. Optional `$APP_DIR/.env` and `$APP_DIR/app.env` parsed via pure-Python `KEY=VALUE` reader with every key validated against `ENV_KEY_RE` and `RESERVED_ENV_KEYS`. +3. **Secret Isolation & Redaction**: + - The daemon never accesses SOPS master keys (`/etc/ssh/ssh_host_ed25519_key`). + - Any key matching `*_KEY`, `*_SECRET`, `*_PASSWORD`, `*_TOKEN`, `*_PASS`, or `*_HASH` (and any known secret value from `/run/secrets/`) is replaced with `"[REDACTED]"` in audit logs, error responses, and diagnostic messages. -### C. Systemd Unit Sandboxing (`homelab-appctl.service`) +### C. Systemd Unit Sandboxing & Service Identity (`homelab-appctl.service` β€” `DEC-03`) -Following the pattern established in Milestone P2 for `homelab-gitops.service`, the daemon runs with systemd sandboxing: -- `ProtectSystem = "strict"`: Host filesystem is read-only. -- `ProtectHome = "read-only"`: User home is read-only by default. -- `ReadWritePaths`: Explicitly allowlisted writable roots: - - `/home//Sites` (workload definitions and Git checkouts) - - `/home//var/lib/homelab` (workload persistent state roots) - - `/home//Core/config/homepage` (Homepage services.yaml destination) - - `/var/log/homelab/appctl` or `/home//.local/state/homelab/appctl` (audit log directory) - - `/run/homelab` (socket runtime directory) -- `PrivateTmp = true`: Isolated temporary directories. -- `NoNewPrivileges = true`: Disallows privilege escalation. - -### C. Platform Genericism & Domain Decoupling -Per Invariant #8 in `AGENTS.md`, the control plane and all platform components must remain strictly instance-agnostic: -- **No Hardcoded Domains**: Personal domain names must never appear hardcoded in Python modules, NixOS definitions, or default configurations. -- **Canonical Precedence & Dynamic Resolution**: All domain resolutions follow strict, fail-closed precedence: - 1. `HOMELAB_DOMAIN` (Primary platform apex domain) - 2. `DOMAIN_SUFFIX` (Secondary routing suffix fallback) - 3. `DOMAIN` (Legacy environment fallback) - If none are set, the platform fails closed rather than defaulting to hardcoded values. -- **Generic Placeholders & Test Fixtures**: Test fixtures, documentation examples, and schema defaults must use RFC 2606 reserved domains (`example.com`, `example.org`, `example.test`). +- **Dedicated Service Identity**: + - `User = "homelab-appctl"` + - `Group = "homelab-operators"` + - `SupplementaryGroups = [ "docker" ]` +- **Managed Runtime, State & Log Directories**: + - `RuntimeDirectory = "homelab"` (`RuntimeDirectoryMode = "0750"`): Hosts `/run/homelab/appctl.sock` (mode `0660`, `homelab-appctl:homelab-operators`). + - `StateDirectory = "homelab/appctl"` (`StateDirectoryMode = "0700"`): Hosts `/var/lib/homelab/appctl/locks/.lock` and `_homepage_sync.lock`. + - `LogsDirectory = "homelab/appctl"` (`LogsDirectoryMode = "0700"`): Hosts `/var/log/homelab/appctl/audit.jsonl` (mode `0600`, `homelab-appctl:homelab-operators`). +- **Declarative Filesystem Access (`systemd.tmpfiles.rules` POSIX ACLs)**: + - Grants `homelab-appctl` traverse (`x`) on `/home/` and `/home//Core`. + - Applies recursive default POSIX ACLs (`A+`) granting `d:u:homelab-appctl:rwx,u:homelab-appctl:rwx` on `/home//Sites`, `/home//var/lib/homelab`, and `/home//Core/config/homepage` so both `` and `homelab-appctl` can update Git checkouts and write `services.yaml` without permission conflicts. +- **Systemd Hardening**: + - `ProtectSystem = "strict"`, `ProtectHome = "read-only"`, `PrivateTmp = true`, `NoNewPrivileges = true`, `ProtectKernelTunables = true`, `ProtectControlGroups = true`. + - `ReadWritePaths`: `/home//Sites`, `/home//var/lib/homelab`, `/home//Core/config/homepage`, `/var/log/homelab/appctl`, `/var/lib/homelab/appctl`, `/run/homelab`. +### D. Platform Genericism & Domain Decoupling +Per `AGENTS.md` Β§3, all control-plane modules, NixOS definitions, Compose stacks, and tests must remain instance-agnostic: +- Canonical domain precedence: `HOMELAB_DOMAIN` $\to$ `DOMAIN_SUFFIX` $\to$ `DOMAIN` (fails closed if unset). +- Test fixtures and documentation examples use RFC 2606 domains (`example.com`, `example.org`, `example.test`). --- -## 5. Audit Telemetry Semantics (P4 Prerequisite) +## 5. Audit Telemetry & Operational State Semantics (`DEC-03`) -### A. Field Schema (RFC-Compliant JSONL) +### A. Distinction Between Operation Result, Audit Event & Deployment State -Every operation lifecycle event is emitted as a structured JSON object to `audit.jsonl` (mode `0600`): +1. **Operation Result (`OperationResponse`)**: Synchronous HTTP/1.1 response payload returned immediately to the caller. +2. **Audit Event (`/var/log/homelab/appctl/audit.jsonl`)**: Authoritative append-only control-plane security and mutation log. Captures pre-execution (`DISPATCHED`), post-execution (`COMPLETED` / `FAILED`), and admission rejection (`DENIED`) records correlated by `operation_id`, including pre/post `commit_sha` on `workload.update` and `workload.deploy`. +3. **GitOps Status Snapshot (`~/.local/state/homelab/gitops/.status.json`)**: Lightweight latest-run status file written by `gitops_dispatcher.py` worker upon completion for backward-compatible webhook status inspection. (No separate rollback database or `appctl history` command is introduced in P4 v1.) + +### B. Field Schema (RFC-Compliant JSONL) + +Every audited lifecycle event is appended as a single line to `/var/log/homelab/appctl/audit.jsonl` (mode `0600`, overridable via `APPCTL_AUDIT_LOG` in hermetic tests): ```json { - "$schema": "https://json-schema.org/draft/2020-12/schema", "audit_version": "1.0", "event_id": "evt_01JAX73AB190", - "timestamp": "2026-10-13T18:32:05.112Z", + "operation_id": "op_01JAX71BC98E4", + "timestamp": "2026-10-16T12:00:03.112Z", "phase": "COMPLETED", "principal": { "identity": "operator", "role": "homelab-admin", - "token_id": "tok_99fa1b", + "token_id": "tok_admin_01", "auth_method": "bearer_token" }, "action": "workload.update", @@ -290,52 +323,72 @@ Every operation lifecycle event is emitted as a structured JSON object to `audit "origin": "peer_uid_1000", "client": "appctl-cli/2.0", "parameters": { - "recreate": true, - "remove_orphans": true + "expected_branch": null, + "build": false }, "result": { "status": "SUCCESS", "exit_code": 0, "duration_ms": 3210, + "commit_sha": "d4f8a1e", "error_code": null, "message": "Workload updated and reconciled successfully" } } ``` -### B. Event Lifecycle States +### C. Event Lifecycle States & Audited Scope -| Phase | Description | +| Phase | Trigger & Scope | | :--- | :--- | -| `DISPATCHED` | Emitted immediately after authentication and validation pass, before invoking Docker/Git. | -| `COMPLETED` | Emitted when operation terminates cleanly with exit code 0. | -| `FAILED` | Emitted when validation, Docker, or Git execution raises a non-zero exit or exception. | -| `DENIED` | Emitted when authentication fails (`401`) or authorization check fails (`403`). | +| `DISPATCHED` | Written and flushed **before** any subprocess or file mutation executes for all mutating operations (`deploy`, `stop`, `restart`, `pull`, `update`, `sync_homepage`). | +| `COMPLETED` | Written when a mutating operation or sensitive read (`workload.config`, `workload.logs`) terminates cleanly (`exit_code == 0`). | +| `FAILED` | Written when a mutating operation or sensitive read fails during pre-flight validation (`400`) or execution (`500`). | +| `DENIED` | Written when authentication (`401`), RBAC authorization (`403`), or concurrency lock acquisition (`409`) rejects a request. | -### C. Failure Handling & Audit Guarantees +*(Note: High-frequency non-sensitive viewer readsβ€”`list`, `get`, `resolve`, `ssl`, `health`β€”do not emit `COMPLETED` audit records, preventing log bloat during CLI status checks and shell tab-completion.)* -1. **Pre-Execution Write**: Mutating actions log a `DISPATCHED` record before calling external binaries. If the daemon crashes or the host loses power mid-operation, the pending operation is permanently preserved in the audit log. -2. **Fail-Closed Disk Guard**: If writing to `audit.jsonl` fails (e.g. out of disk space, permission error), the daemon **immediately aborts the requested mutation and returns `ERR_EXECUTION_FAILED`**. Unaudited mutations are strictly prohibited. -3. **Audit Log Location & Service Ownership**: - - Primary: `/var/log/homelab/appctl/audit.jsonl` (systemd service root) or `~/.local/state/homelab/appctl/audit.jsonl`. - - Permissions: Mode `0600` owned by `homelab-appctl` service user. +### D. Failure Handling & Explicit Audit Threat Model + +1. **Fail-Closed Pre-Execution Disk Guard**: If writing or flushing the `DISPATCHED` record to `audit.jsonl` fails (`OSError`), the daemon **immediately aborts the mutation and returns `500 ERR_EXECUTION_FAILED`** with zero Docker or Git invocations. +2. **Post-Execution Persistence Failure**: If writing the `COMPLETED`/`FAILED` record fails after subprocess execution, the daemon logs a critical alert to `stderr` (`journald`) and returns `500 ERR_EXECUTION_FAILED`. +3. **Explicit Threat Model**: + - **Protected Boundary**: Running the daemon as `homelab-appctl` with `/var/log/homelab/appctl/audit.jsonl` (`0600`) and `/run/secrets/appctl/tokens.json` (`0400`) enforces an OS user boundary against unprivileged processes and AI coding agents running inside the human operator's SSH session (`` UID). Session processes cannot read `tokens.json`, forge/truncate `audit.jsonl`, or signal the daemon without `sudo`. + - **Out-of-Scope Boundary**: Protection against an actor who possesses host `root` / `sudo` / `docker`-group escalation privileges is out of scope for single-node P4 (as `root` can modify any local file on the host). --- -## 6. P4 Definition of Done & Acceptance Test Matrix +## 6. P4 Implementation Slices (Dependency-Ordered) + +1. **Slice 1 β€” Pydantic v2 API Contracts & Error Sanitizer (`scripts/appctl_contracts.py`)**: + - Strict request/response/error/audit models (`ConfigDict(extra="forbid", strict=True)`), operation parameter schemas, and `ValidationError` $\to$ `400 ERR_VALIDATION_FAILED` sanitizer (`include_input=False`). + - Add `"compose_pull"` to `ALLOWED_ACTIONS` in `scripts/core_manifest.py`. +2. **Slice 2 β€” Append-Only Audit Logger & Per-Target Lock Manager**: + - `AuditLogger` (`DISPATCHED`, `COMPLETED`, `FAILED`, `DENIED`, `0600` enforcement, secret redaction, fail-closed disk guard) and non-blocking `fcntl.flock` manager (`/var/lib/homelab/appctl/locks/.lock` + `_homepage_sync.lock`). +3. **Slice 3 β€” Authentication & 3-Role RBAC Gate**: + - SOPS `tokens.json` SHA-256 authenticator (`hmac.compare_digest`), UDS `SO_PEERCRED` extractor (`unix_peercred` viewer fallback for non-sensitive reads), and role-scoped authorization policy (`homelab-admin` vs `homelab-operator` `deployments.yaml` restriction vs `homelab-viewer`). +4. **Slice 4 β€” Operational Router & Unified Execution Engine**: + - Pure-Python `.env` parser (no shell `source`), mandatory `parse_manifest()` + `validate_compose_security()` pre-flight, revision-consistent `workload.update` (`expected_branch`, dynamic action adoption, `build`), bounded `workload.logs` (`tail`), and atomic Homepage sync. +5. **Slice 5 β€” Dual-Transport HTTP/1.1 Daemon (`scripts/appctl_daemon.py`) & GitOps Cutover**: + - HTTP/1.1 server over UDS (`/run/homelab/appctl.sock`) and TCP (`127.0.0.1:9001`), graceful `SIGTERM`/`SIGINT` cleanup, and rewiring `scripts/gitops_dispatcher.py` to parse manifests via `core_manifest.parse_manifest()` and execute worker deployments through the daemon. +6. **Slice 6 β€” Thin-Client CLI (`scripts/appctl`), NixOS Service & Platform Genericism Cleanup**: + - Re-implement `scripts/appctl` as a thin UDS HTTP client, declare `homelab-appctl.service` (`homelab-appctl:homelab-operators` + POSIX ACLs) in `nixos/modules/homeserver.nix`, scrub remaining hardcoded domain/username literals across `nixos/`, `config/deployments.yaml`, and `docker-compose.yml`, and add `pyright` to `flake.nix` checks and `.githooks/pre-commit`. + +--- + +## 7. P4 Definition of Done & Acceptance Test Matrix Before marking Milestone P4 complete, the following automated regression suite must pass: -### Test Suite Matrix - | Test Suite / Area | Assertion / Invariant Verified | Failure Action | | :--- | :--- | :--- | -| **Transport Parity** | `test_transport_dual_equivalence`: Compare outputs of `appctl list` via Unix socket vs HTTP `GET /workloads`. Assert 100% semantic and data parity. | Reject PR | -| **Unauthenticated Rejection** | `test_auth_missing_token_fails_closed`: `POST /operations/deploy` without `Authorization` header returns `401 Unauthorized` and executes zero subprocesses. | Block Release | -| **RBAC Authorization Enforcement**| `test_rbac_viewer_mutation_denied`: Present valid token with `homelab-viewer` role against `POST /operations/restart`. Assert `403 Forbidden` and zero container restarts. | Block Release | -| **Path Traversal Containment** | `test_path_traversal_rejection`: Submit target `../../etc` or `/var/run`. Assert `ERR_VALIDATION_FAILED` (400) and zero filesystem escape. | Block Release | -| **Truthful Error Reporting** | `test_execution_failure_audit`: Mock failing Docker compose run (exit 1). Assert daemon returns `ERR_EXECUTION_FAILED` (500) and records `phase: FAILED` in audit log. | Reject PR | -| **Audit Persistence Gate** | `test_audit_failure_blocks_mutation`: Mock read-only audit log. Assert mutating command fails closed with zero Docker invocations. | Block Release | -| **Daemon Crash Recovery** | `test_daemon_restart_preserves_state`: Kill and restart `homelab-appctl.service`. Assert running container stacks are undisturbed and desired Git state remains intact. | Reject PR | -| **Existing Invariant Regression** | Run `./scripts/test`: All 121 existing unit, security, structural, and Nix flake sandbox tests pass with 0 regressions. | Block Merge | - +| **Transport Parity** | `test_transport_dual_equivalence`: Compare responses of `POST /v1/operations` (`workload.list`, `workload.get`, errors) over Unix socket vs HTTP `127.0.0.1`. Assert 100% schema and status parity. | Reject PR | +| **Unauthenticated Rejection** | `test_auth_missing_token_fails_closed`: Mutating operations and `workload.config`/`workload.logs` without `Authorization: Bearer` return `401 ERR_AUTH_REQUIRED` on both UDS and HTTP and execute zero subprocesses. | Block Release | +| **UDS Peercred Viewer Scope** | `test_uds_peercred_viewer_boundary`: Tokenless UDS call from operator UID succeeds for `workload.list` (`auth_method: "unix_peercred"`), but fails with `401`/`403` on any mutation or `workload.config`. | Block Release | +| **RBAC & Role-Scoped Resolution**| `test_rbac_role_matrix`: `homelab-viewer` denied (`403`) on all mutations; `homelab-operator` allowed on `deployments.yaml` workloads but denied (`403`) on `core`, `core_service`, and unregistered `~/Sites` dirs; `homelab-admin` allowed on all valid targets. | Block Release | +| **Pre-Flight & `.env` Safety** | `test_daemon_preflight_and_dotenv_safety`: Workload with malicious `.env` (`$(touch ...)`) or prohibited Compose directive (`privileged: true`, `/var/run/docker.sock`) is blocked / parsed inertly with zero shell execution. | Block Release | +| **Concurrency Lock (`409`)** | `test_concurrent_mutation_conflict`: Second concurrent mutation on the same target immediately returns `409 ERR_CONCURRENT_MUTATION` and logs `DENIED`. | Block Release | +| **Truthful Error Reporting** | `test_execution_failure_audit`: Failing or timing-out Docker/Git subprocess returns `500 ERR_EXECUTION_FAILED` and records `phase: FAILED` in `audit.jsonl`. | Reject PR | +| **Audit Persistence Gate** | `test_audit_failure_blocks_mutation`: Unwritable `audit.jsonl` aborts mutating command with `500 ERR_EXECUTION_FAILED` and zero Docker/Git invocations. | Block Release | +| **Daemon Crash Recovery** | `test_daemon_restart_preserves_state`: Clean stop and restart of daemon unlinks/rebinds socket cleanly and leaves running workloads and Git state undisturbed. | Reject PR | +| **Existing Invariant Regression** | Run `./scripts/test`: All 124 existing unit, security, structural, Ruff, Pyright, and Nix flake sandbox checks pass with 0 regressions. | Block Merge | diff --git a/todo.txt b/todo.txt index bb5deab..f354321 100644 --- a/todo.txt +++ b/todo.txt @@ -22,12 +22,11 @@ x 2026-10-15 (B) Scrub hardcoded domain defaults across scripts and tests enforc x 2026-10-15 (A) De-tautologize appctl env injection test to execute scripts/appctl directly with mock docker in tests/security/test_security_invariants.py +test @security 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 -(A) Scaffold asyncio daemon server with Pydantic request/response models supporting dual transports in scripts/appctl_daemon.py +daemon @p4 - -(A) Implement unit and integration tests for dual-transport requests and error handling in tests/unit/test_appctl_daemon.py +test @p4 -(B) Implement command-oriented operational router wiring domain actions to in-process appctl_engine.py methods and fixed subprocess executions +router @p4 -(B) Implement token authentication middleware validating user-scoped Bearer tokens for mutating requests +auth @p4 -(B) Implement append-only audit logger writing structured RFC JSONL records with fail-closed disk guard +audit @p4 -(B) Scrub remaining hardcoded domain references across NixOS modules, Compose stack, and repository documentation +generic @core -(C) Re-implement scripts/appctl as a thin client dispatching JSON requests to the daemon Unix domain socket +cli @p4 -(C) Create NixOS systemd unit module for homelab-appctl.service with strict sandboxing and socket management +nixos @p4 +(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 +(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 +(B) Add comprehensive unit and security test suite for P4 contracts, RBAC, audit guard, concurrency, and dual-transport parity in tests/unit/test_appctl_daemon.py +test @p4 +(C) Re-implement scripts/appctl as a thin UDS HTTP client and declare homelab-appctl.service with POSIX ACLs in nixos/modules/homeserver.nix +cli @p4 +(C) Scrub remaining hardcoded domain and username literals across NixOS modules, Compose stack, and config/deployments.yaml and add pyright to flake.nix checks +generic @core