diff --git a/ROADMAP.md b/ROADMAP.md index 5ab6358..c9ec57a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,34 +1,36 @@ # πŸ—ΊοΈ Homelab Core & Appctl Engineering Roadmap -This document serves as the repository-facing projection of the authoritative **Homelab Architecture Consolidation & Control Plane Roadmap (v5)**. +This document serves as the repository-facing projection of the authoritative **Homelab Architecture Consolidation & Control Plane Roadmap (v6)** and the locked Milestone P4 boundary specification ([`docs/plans/p4-readiness-plan.md`](docs/plans/p4-readiness-plan.md)). It describes the implementation trajectory and phased engineering milestones for transitioning Homelab Core into a unified platform driven by the `appctl` Operational Control Plane. -> **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index (Control Plane Architecture, 3-Tier Provenance Model, and Pydantic v2 Runtime Validation). +> **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index ([ADR-0001: 3-Tier Provenance Model](docs/decisions/0001-3tier-architecture-and-provenance.md), [ADR-0002: Operational Control Plane Architecture](docs/decisions/0002-appctl-control-plane-architecture.md), and [ADR-0003: Pydantic v2 Runtime Validation](docs/decisions/0003-pydantic-v2-runtime-validation.md)). --- ## 🎯 Architectural Invariants Governing Execution 1. **Git is the Authoritative Source of Deployment State**: All workload configurations are versioned in Git. `appctl` reconciles desired Git state into running containers. -2. **One Logical API Across Dual Transports**: The control-plane API is a single logical command-oriented contract. Unix domain socket (`/run/homelab/appctl.sock`) on the host and HTTP for network clients are transport details. -3. **Host Access Does Not Confer Authority**: Entering via SSH does not bypass authentication. Every mutating operation requires an explicit, authenticated user-scoped token. -4. **Separation of Intent from Implementation**: `DeploymentModel` captures implementation-agnostic intent; concrete platform descriptors (`app.yaml` + Compose) are materialized and enforced by `appctl`. -5. **AI Authoring Boundary**: AI agents act strictly as proposal generators (`DeploymentProposal`). Humans approve the intent (`DeploymentModel`). The AI possesses zero execution authority. -6. **Secret Reference Invariant**: Deployment definitions store secret references (`secretKeyRef`), never plaintext material, resolved at runtime via `SecretProvider`. -7. **Clean State Root**: Mutable application runtime data resides strictly under `~/var/lib/homelab//`, isolated from Git repositories. +2. **One Logical API Across Dual Transports (`DEC-01`)**: The control-plane API is a single logical HTTP/1.1 command contract (`POST /v1/operations` + `GET /v1/health`) served identically over Unix domain socket (`/run/homelab/appctl.sock`) and loopback TCP (`127.0.0.1:9001`). +3. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**: Entering via SSH does not bypass authentication. Every mutating operation and sensitive read (`workload.config`, `workload.logs`) requires an explicit Bearer token; tokenless local UDS calls fall back via `SO_PEERCRED` strictly to `homelab-viewer` read-only inspection. +4. **Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)**: `homelab-appctl.service` executes as isolated user `homelab-appctl:homelab-operators` with mode `0600` append-only `/var/log/homelab/appctl/audit.jsonl`. Mutating operations abort immediately (`500 ERR_EXECUTION_FAILED`) if the pre-execution `DISPATCHED` audit write fails. +5. **Unified Execution, Pre-Flight & Pure-Python Environment (`DEC-04`, `DEC-05`)**: Both CLI and GitOps worker paths execute through the daemon, enforcing Pydantic v2 manifest validation, `validate_compose_security()` AST checks, and inert pure-Python `.env` assembly (no shell `source` or `eval`). +6. **Separation of Intent from Implementation**: `DeploymentModel` captures implementation-agnostic intent; concrete platform descriptors (`app.yaml` + Compose) are materialized and enforced by `appctl`. +7. **AI Authoring Boundary**: AI agents act strictly as proposal generators (`DeploymentProposal`). Humans approve the intent (`DeploymentModel`). The AI possesses zero execution authority. +8. **Secret Reference Invariant**: Deployment definitions store secret references (`secretKeyRef`), never plaintext material, resolved at runtime via `SecretProvider`. +9. **Clean State Root**: Mutable application runtime data resides strictly under `~/var/lib/homelab//`, isolated from Git repositories. --- ## πŸ” Current Implementation Baseline vs. Target Architecture -| Architectural Area | Current Implementation Baseline (Milestone P3) | Target Architecture (Roadmap v5) | +| Architectural Area | Current Implementation Baseline (Milestone P3) | Target Architecture (Roadmap v6) | | :--- | :--- | :--- | -| **`appctl` Architecture** | Bash CLI wrapper (`scripts/appctl`) driving local subprocesses (`docker compose`, `git`) and Python engine. | Dedicated daemon service (`homelab-appctl.service`) exposing one logical API over Unix socket and HTTP. | -| **Operational Auth** | Host Unix permissions; sourcing runtime secrets from `/run/secrets/`. | Mandatory auth middleware in daemon (P4 admission gate); LLDAP directory RBAC, user-scoped API tokens, and Authelia ForwardAuth (P5). | -| **Metadata & Schema Engine** | Unified engine (`scripts/appctl_engine.py`) with two-axis provenance and fail-closed Pydantic v2 schema v1.0 parser (`scripts/core_manifest.py`). | Control-plane daemon invokes `core_manifest.py` / `appctl_engine.py` through a stable internal Python interface. | +| **`appctl` Architecture** | Bash CLI wrapper (`scripts/appctl`) driving local subprocesses (`docker compose`, `git`) and Python engine. | Dedicated daemon service (`homelab-appctl.service`, user `homelab-appctl`) exposing `POST /v1/operations` over Unix socket and HTTP. | +| **Operational Auth** | Host Unix permissions; sourcing runtime secrets from `/run/secrets/`. | Mandatory SHA-256 Bearer token + 3-role RBAC + UDS `SO_PEERCRED` viewer fallback (P4); LLDAP directory RBAC & Authelia ForwardAuth (P5). | +| **Metadata & Schema Engine** | Unified engine (`scripts/appctl_engine.py`) with two-axis provenance and fail-closed Pydantic v2 schema v1.0 parser (`scripts/core_manifest.py`). | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | | **Deployment Model** | Direct authoring of `app.yaml` and `docker-compose.yml` in `~/Sites//`. | 5-stage lifecycle (planned in P6): `DeploymentProposal` $\to$ operator-approved `DeploymentModel` in Git $\to$ `appctl` materialization. | -| **GitOps Engine** | Webhook dispatcher (`scripts/gitops_dispatcher.py`) with HMAC-SHA256 auth, Compose AST security validator, and `flock` serialization. | Integrated into control-plane admission, invoking central reconciliation endpoints. | +| **GitOps Engine** | Webhook dispatcher (`scripts/gitops_dispatcher.py`) with HMAC-SHA256 auth, Compose AST security validator, and `flock` serialization. | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | | **Secret Distribution** | Age-encrypted `nixos/secrets.yaml` decrypted by `sops-nix` to tmpfs `/run/secrets/`. | Host secrets remain in `sops-nix`; workload secrets referenced by key and projected via `SecretProvider` (planned in P5). | | **Dashboard** | `appctl sync` compiles `config/homepage/services.yaml` from `app.yaml` manifests. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for management (planned in P7). | @@ -55,7 +57,7 @@ It describes the implementation trajectory and phased engineering milestones for **Status**: βœ… **Completed** * Merged `refactor/appctl-rework` and `main` into a unified architectural baseline (commit `2297cd5`). * Modernized metadata engine with strongly-typed models (`SitesApp`, `CoreService`, `SourceConfig`) and Docker status inspection. -* Formalized the control-plane ADR and Roadmap v5; marked legacy roadmaps as superseded. +* Formalized the control-plane ADR and consolidated roadmap; marked legacy roadmaps as superseded. * Verified test suite and NixOS flake sandbox evaluation. --- diff --git a/docs/decisions/0001-3tier-architecture-and-provenance.md b/docs/decisions/0001-3tier-architecture-and-provenance.md new file mode 100644 index 0000000..018ae75 --- /dev/null +++ b/docs/decisions/0001-3tier-architecture-and-provenance.md @@ -0,0 +1,99 @@ +--- +type: decision +status: accepted +project: homelab-core +date: 2026-09-28 +tags: [architecture, homelab, provenance, gitops, state, kiss] +--- + +# ADR 0001: Homelab 3-Tier Architecture & Deployment Provenance Model + +## Context and Problem Statement + +Homelab Core operates as a dedicated NixOS appliance hosting self-hosted productivity services and independent backend engineering projects. In early platform iterations (v1 through v3), several structural tensions emerged: + +1. **Application & Deployment Coupling**: Custom applications co-located application source trees with host-specific Traefik labels, Docker bridge networks, and host path mounts inside individual Git repositories in `~/Sites/`. +2. **Repository Inflation**: Third-party off-the-shelf applications (`jellyfin`, `stirling`, `snappymail`) required standalone Git repositories simply to store a minimal Compose file and manifest. +3. **Ambiguous Freshness**: Local Git status checks in `~/Sites/` could only report whether deployment descriptors had uncommitted edits, never whether running containers matched current upstream application source code. +4. **Mutable State Entanglement**: Application databases, caches, and runtime state lived inside or adjacent to version-controlled Git working trees (`Core/config/` and `Sites//data`), risking dirty checkouts, accidental secret/state commits, or data loss during branch operations. +5. **Orchestrator Sprawl Risk**: Scaling operational scripts threatened to introduce secondary distributed infrastructure (queues, databases, message brokers) around basic single-node container deployments. + +The central architectural question is: **How should Homelab Core structure application source code, deployment configuration, runtime state, and platform orchestration to maintain strict separation of concerns, verifiable provenance, and linear KISS operations?** + +## Decision Drivers + +* **Clean Separation of Concerns**: Application software projects must be developable, testable, and publishable independently of Homelab Core infrastructure, domains, or bridge networks. +* **Workload Simplicity**: Off-the-shelf third-party applications should not incur standalone source repository overhead. +* **Verifiable Two-Axis Provenance**: Operators must be able to independently verify local deployment configuration freshness (`~/Sites/`) versus upstream software code freshness (`source.url` vs. running container image). +* **KISS Primitives & Minimal Control Paths**: Operational reconciliation must remain bounded, deterministic, and linear without distributed brokers, queues, or deployment databases. +* **Filesystem State Hygiene**: Mutable runtime data must never reside inside version-controlled Git trees. + +## Considered Options + +* **Option 1: Monolithic / Single-Repo Deployment (Status Quo v1–v3)**: Co-locate application source code, Dockerfiles, Compose files, and mutable runtime state inside a single Git repository per application. +* **Option 2: Miniature Cloud Platform**: Introduce message brokers (RabbitMQ/Redis), a deployment state database, multi-environment controllers, and asynchronous rollback daemons. +* **Option 3: Bounded 3-Tier Platform with OCI Provenance Labels & Linear Control Path (Adopted)**: Decouple Software, Deployment, and Platform tiers; connect them via OCI image artifacts carrying source revision labels and content-addressed digests; enforce two-axis provenance inspection, linear reconciliation, and isolated host state roots. + +## Decision Outcome + +Chosen option: **Option 3: Bounded 3-Tier Platform with OCI Provenance Labels & Linear Control Path**, because it resolves source-deployment coupling and provenance ambiguity while retaining a strictly bounded, single-appliance operational footprint. + +### Summary of Architectural Commitments + +1. **3-Tier Separation of Concerns**: + * **Tier 1 β€” Software Layer (Application Repositories)**: Standalone Git repositories owning application source code, tests, Dockerfiles, and CI workflows. Zero Homelab infrastructure coupling. + * **Intermediate Provenance Artifacts**: OCI container images produced by CI act as immutable provenance objects identified by their OCI digest and carrying source commit metadata via the `org.opencontainers.image.revision` label. + * **Tier 2 β€” Deployment Layer (`~/Sites` Workload Plane)**: Declarative catalog in `~/Sites/` owning workload-specific `app.yaml` manifests and `docker-compose.yml` topologies. + * **Tier 3 β€” Platform Layer (Homelab Core Appliance)**: Declarative NixOS host foundation (`~/Core`) owning edge ingress (`traefik`), SSO/directory (`authelia`, `lldap`), mail (`stalwart`), monitoring (`dozzle`, `diun`), and operational controllers (`appctl`, `gitops_dispatcher`). +2. **Two Workload Deployment Classes**: + * **Class A (Source-Backed)**: Declares an explicit upstream `source:` block (`source.url`, `source.ref`) in `app.yaml`; tracks upstream Git revisions against running container OCI labels. + * **Class B (Image-Only)**: Standard third-party workloads omitting `source:`; deployment freshness relies on container registry image tags and content-addressed digests. +3. **Two Operational Inspection Axes (`scripts/provenance.py`)**: + * **Axis 1 (Local Deployment Checkout)**: Evaluates local `~/Sites/` working-tree cleanliness (`βœ“ Synced`, `* Dirty`, `⬆ Ahead`, `⬇ Behind`). + * **Axis 2 (Upstream Software Provenance)**: Independently resolves upstream remote revisions via bounded `git ls-remote` (10-second timeout during `--fetch`) against running container revision labels. +4. **Minimal Linear Reconciliation Path**: + * The deployment lifecycle remains strictly linear: + $$\text{Source Push} \longrightarrow \text{CI Build} \longrightarrow \text{GitOps Ingress} \longrightarrow \text{appctl Reconcile} \longrightarrow \text{Compose Up}$$ + * Secondary message queues, brokers, and deployment databases are rejected. +5. **Isolated Persistent State Root**: + * Mutable application runtime state (databases, caches, uploads, dynamic configs) resides strictly under `~/var/lib/homelab//`, isolated from version-controlled Git repositories. + +## Pros and Cons of the Options + +### Option 1: Monolithic / Single-Repo Deployment +* Good, because it requires only a single Git repository per custom application. +* Bad, because host-specific routing labels and bridge networks leak into application source repositories, preventing clean open-sourcing or reuse. +* Bad, because off-the-shelf tools require artificial wrapper repositories. +* Bad, because a single commit SHA conflates software code revisions with deployment configuration edits. +* Bad, because mutable state co-located in `Sites//data` creates dirty Git trees and risks accidental commits or data loss. + +### Option 2: Miniature Cloud Platform +* Good, because it mirrors enterprise Kubernetes / ArgoCD continuous deployment pipelines. +* Bad, because running distributed brokers, queues, and state databases on a single appliance introduces disproportionate operational overhead and failure modes. +* Bad, because it violates the KISS principle. + +### Option 3: Bounded 3-Tier Platform with OCI Provenance Labels (Adopted) +* Good, because custom software is completely decoupled from homelab infrastructure and remains portable and instance-agnostic. +* Good, because off-the-shelf software incurs zero source repository overhead. +* Good, because two-axis inspection resolves local configuration status and upstream code provenance unambiguously. +* Good, because runtime state is cleanly isolated under `~/var/lib/homelab//`. +* Bad, because custom applications manage source code and Sites deployment manifests as separate concerns. +* Bad, because verifying remote revisions without local clones (`git ls-remote`) evaluates commit equality (`HEAD` match) rather than full commit ancestry distance. + +## Consequences + +### Positive Consequences +* **Independent Software Lifecycle**: Custom applications can be developed, tested, and published without exposing homelab domains, secrets, or network topologies. +* **Precise Diagnostic Truth**: Operators and `appctl` can distinguish between uncommitted local deployment edits (`* Dirty`) and upstream software updates (`git ls-remote`). +* **Zero-Data-Loss State Isolation**: Proven during the Milestone P1 SnappyMail migration, moving persistent runtime data to `~/var/lib/homelab//` keeps Git trees pure and backups deterministic. +* **Operational Restraint**: Preserves a linear, local reconciliation path without distributed state stores. + +### Negative Consequences & Accepted Trade-offs +* **Dual Repositories for Custom Workloads**: Deploying a custom application separates upstream source CI from the `~/Sites/` deployment manifest. +* **Commit Equality Without Ancestry Graph**: Remote `git ls-remote` queries confirm whether the deployed revision matches upstream `HEAD`, without computing commit ahead/behind counts on uncloned source repos. + +## More Information + +* **Architecture Specification**: [`docs/architecture.md`](../architecture.md) +* **Secrets & State Contract**: [`docs/secrets-and-state.md`](../secrets-and-state.md) +* **Governing Roadmap**: [`ROADMAP.md`](../../ROADMAP.md) (Milestones P1 & P3) diff --git a/docs/decisions/0002-appctl-control-plane-architecture.md b/docs/decisions/0002-appctl-control-plane-architecture.md new file mode 100644 index 0000000..7a7f462 --- /dev/null +++ b/docs/decisions/0002-appctl-control-plane-architecture.md @@ -0,0 +1,140 @@ +--- +type: decision +status: accepted +project: homelab-core +date: 2026-10-07 +tags: [architecture, homelab, appctl, control-plane, security, rbac, audit, gitops] +--- + +# ADR 0002: Homelab Operational Control Plane & Deployment Model Architecture + +## Context and Problem Statement + +Homelab Core historically relied on `appctl` as a procedural Bash CLI wrapper (`scripts/appctl`) coupled with a Python metadata helper (`scripts/appctl_engine.py`). Operational commands (`up`, `down`, `restart`, `update`, `logs`, `config`, `sync`) executed as local subprocesses in the operator's shell session, sourcing environment files directly from `/run/secrets/` and `$APP_DIR/.env`. + +As the platform matured and AI coding agents began operating inside developer SSH sessions, this script-based model exposed five architectural and security liabilities: + +1. **Conflated Host & Control Plane Authority**: Entering the server via SSH granted full operational mutation authority. Any unprivileged process or AI coding agent running under the operator's UID could invoke `appctl` to mutate containers, inspect secrets, or alter routing with zero authentication. +2. **Duplicated Execution & Pre-Flight Drift**: The local CLI (`scripts/appctl`) and the GitOps webhook worker (`scripts/gitops_dispatcher.py`) maintained separate implementations of `git pull` and `docker compose`, with the CLI path bypassing Compose AST security validation and sourcing `.env` files via shell `source`. +3. **Absence of Tamper-Evident Auditability**: Operational actions produced only ephemeral terminal output with no centralized, append-only audit log recording principal identity, transport, origin, target revision, and outcome. +4. **Secret Lifecycle Coupling**: Workload secrets were broadly sourced into parent shell environments or coupled to static SOPS rebuilds rather than resolved via scoped references. +5. **Manual Workload Authoring Friction**: Onboarding workloads required handwriting boilerplate descriptors without a structured boundary separating AI-generated proposals (`DeploymentProposal`) from human-approved declarative intent (`DeploymentModel`). + +The central architectural question is: **How should Homelab Core transition `appctl` into an authoritative, fail-closed operational control plane with strict privilege isolation, unified execution, mandatory token authorization, and safe deployment authoring without introducing distributed cloud complexity?** + +## Decision Drivers + +* **Control Plane Centralization**: Exactly one authoritative execution pipeline for all workload and platform operations across CLI, GitOps, and future web clients. +* **Host Access Does Not Confer Mutation Authority**: Entering the host via SSH must not bypass control-plane authentication. Every mutating action and sensitive read requires cryptographic token verification. +* **OS Privilege Isolation**: The control plane daemon, token store, and audit log must be isolated under a dedicated system identity (`homelab-appctl`) inaccessible to unprivileged operator shell processes and AI sessions. +* **Unified Pre-Flight & Inert Environment Assembly**: Eliminate shell `eval` and `source`; enforce Pydantic v2 schema validation ([ADR-0003](0003-pydantic-v2-runtime-validation.md)) and Compose AST security checks before every Compose invocation. +* **Declarative Git Ground Truth & AI Boundary**: Git remains the sole authoritative source of deployment state; AI agents act strictly as upstream proposal generators (`DeploymentProposal`) with zero execution authority. +* **KISS Primitives**: Preserve synchronous, linear execution using local `flock` serialization and HTTP/1.1 without external message brokers or databases. + +## Considered Options + +* **Option 1: Status Quo with Modernized Local CLI**: Modernize `appctl_engine.py` into a type-safe Python CLI while keeping execution in-process inside the caller's SSH session. +* **Option 2: Cloud-Native Micro-Platform (Kubernetes / Nomad / ArgoCD)**: Replace `appctl` and Docker Compose with enterprise cluster orchestration and distributed control loops. +* **Option 3: Authoritative `homelab-appctl.service` Daemon with Single Command Router & Stable Deployment Model (Adopted)**: Evolve `appctl` into an isolated systemd daemon exposing one logical HTTP/1.1 command API (`POST /v1/operations`) across Unix domain socket and TCP, backed by mandatory Bearer token auth, 3-role RBAC, fail-closed audit logging, and a 5-stage `DeploymentModel` lifecycle. + +## Decision Outcome + +Chosen option: **Option 3: Authoritative `homelab-appctl.service` Daemon with Single Command Router & Stable Deployment Model**, because it enforces an OS-level security boundary between operator sessions and platform execution, unifies CLI and GitOps codepaths behind a single fail-closed pipeline, and establishes a clean roadmap for directory-backed identity (P5) and human-gated AI deployment authoring (P6). + +### Summary of Architectural Commitments (Reconciled with Pre-P4 Locked Decisions `DEC-01`–`DEC-05`) + +```text + Clients (CLI / GitOps Worker / Future Web UI) + β”‚ + POST /v1/operations + GET /v1/health + (One Logical HTTP/1.1 Command Contract) + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β–Ό β–Ό + Unix Domain Socket (/run/homelab/appctl.sock) HTTP Listener (127.0.0.1:9001) + mode 0660 (homelab-appctl:homelab-operators) (Loopback in P4) + β”‚ β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β–Ό + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Unified Fail-Closed Pipeline (homelab-appctl)β”‚ + β”‚ 1. Pydantic v2 Validator (extra="forbid", 64K)β”‚ + β”‚ 2. Auth & 3-Role RBAC Gate (Bearer / PeerCred)β”‚ + β”‚ 3. Per-Target flock (/var/lib/homelab/appctl) β”‚ + β”‚ 4. Pre-Exec Audit Disk Guard (DISPATCHED) β”‚ + β”‚ 5. Pre-Flight (Manifest + Compose AST + .env) β”‚ + β”‚ 6. Subprocess Execution (Fixed argv, 256K cap)β”‚ + β”‚ 7. Post-Exec Audit Record (COMPLETED / FAILED)β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +#### 1. One Logical Command API Across Dual Transports (`DEC-01`) +* `appctl` runs as a dedicated systemd daemon (`homelab-appctl.service`) speaking standard **HTTP/1.1** over both a local Unix Domain Socket (`/run/homelab/appctl.sock`) and a TCP listener (`127.0.0.1:9001` in P4). +* All 13 canonical domain operations (`workload.list`, `workload.get`, `workload.resolve`, `platform.ssl`, `platform.health`, `workload.config`, `workload.logs`, `workload.deploy`, `workload.stop`, `workload.restart`, `workload.pull`, `workload.update`, `platform.sync_homepage`) dispatch through a **single canonical endpoint**: `POST /v1/operations` (plus `GET /v1/health` for liveness). Multi-route REST aliases are rejected. +* `scripts/appctl` acts as a thin HTTP/1.1 UDS client with zero local Docker or Git execution logic. + +#### 2. Host Access Does Not Confer Mutation Authority & 3-Role RBAC (`DEC-02`) +* Entering via SSH confers zero control-plane mutation authority. Every mutating operation, every sensitive read (`workload.config`, `workload.logs`), and every HTTP request requires an explicit Bearer token validated via constant-time SHA-256 comparison (`hmac.compare_digest`) against `/run/secrets/appctl/tokens.json` (`0400`). +* **UDS `SO_PEERCRED` Viewer Fallback**: Unauthenticated local Unix socket calls extract kernel peer credentials (`SO_PEERCRED`) and fall back strictly to `homelab-viewer` privileges for non-sensitive reads (`list`, `get`, `resolve`, `ssl`, `health`), preserving zero-friction CLI inspection and shell tab-completion while blocking all mutations and secret dumps (`401`/`403`). +* **3-Role Authorization Hierarchy**: + * `homelab-admin`: Full access across `core`, `core_service`, and all valid `~/Sites/` workloads. + * `homelab-operator`: Mutations and sensitive reads strictly restricted to workloads admitted in `Core/config/deployments.yaml` (used by `gitops-dispatcher`). Denied (`403`) on `core`, `core_service`, and unregistered Sites directories. + * `homelab-viewer`: Non-sensitive read-only operations only. +* *(Milestone P5 expands this gate with LLDAP directory group mapping and authenticated Traefik/Authelia ForwardAuth proxy headers).* + +#### 3. Dedicated Service Identity, OS Isolation & Fail-Closed Audit Guard (`DEC-03`) +* The daemon executes as system user `homelab-appctl` (`Group = "homelab-operators"`, `SupplementaryGroups = [ "docker" ]`), with declarative recursive POSIX ACLs (`systemd.tmpfiles.rules`) granting shared read/write access on `~/Sites`, `~/var/lib/homelab`, and `~/Core/config/homepage`. +* **Append-Only Audit Telemetry (`/var/log/homelab/appctl/audit.jsonl`, mode `0600`)**: Records `DISPATCHED`, `COMPLETED`, `FAILED`, and `DENIED` lifecycle events with `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, `commit_sha`, and secret-redacted `parameters`/`result`. +* **Fail-Closed Disk Guard**: Mutating operations must write and flush a `DISPATCHED` audit record **before** invoking any Docker or Git subprocess. If the audit write fails (`OSError`), the mutation aborts immediately with `500 ERR_EXECUTION_FAILED`. + +#### 4. GitOps Execution Unification (`DEC-04`) +* `scripts/gitops_dispatcher.py` retains webhook HTTP ingress (port 9000), HMAC-SHA256 verification, `config/deployments.yaml` admission, and the commit-superseding `.pending.json` queue. +* The background worker delegates deployment execution to the daemon's `workload.update` operation over `/run/homelab/appctl.sock` using its `homelab-operator` Bearer token, eliminating duplicated `git pull` and `docker compose` execution codepaths. + +#### 5. Unified Pre-Flight & Pure-Python Environment Assembly (`DEC-05`) +* Shell `eval` and `source` are completely eliminated. Subprocess environments are assembled in memory via an inert pure-Python `KEY=VALUE` reader enforcing `ENV_KEY_RE`, `RESERVED_ENV_KEYS`, and canonical domain precedence (`HOMELAB_DOMAIN` $\to$ `DOMAIN_SUFFIX` $\to$ `DOMAIN`). +* Every workload mutation and `workload.config` call enforces path containment, `core_manifest.parse_manifest()`, and `validate_compose_security()` pre-flight inspection before invoking Docker Compose. + +#### 6. Declarative Git Truth, Five-Stage Deployment Model & AI Boundary (P5–P7 Trajectory) +* **Git is Authoritative**: Approved deployment definitions are versioned in Git; `appctl` reconciles desired Git state into running containers. +* **Five-Stage Model Lifecycle (P6)**: + $$\text{Repository} \xrightarrow{\text{Investigation}} \text{Application Profile} \xrightarrow{\text{Proposal}} \text{DeploymentProposal} \xrightarrow{\text{Human Selection}} \text{DeploymentModel (Git)} \xrightarrow{\text{appctl Materialize}} \text{Deployment Definition} \xrightarrow{\text{Reconcile}} \text{Containers}$$ +* **AI Authoring Boundary (P6)**: AI agents act strictly as upstream `DeploymentProposal` generators with zero execution or mutation authority. +* **Secret Reference Invariant (P5)**: Manifests reference secrets by key (`secretKeyRef`) resolved at runtime via `SecretProvider`, never storing plaintext credentials in Git. +* **Client Decoupling (P7)**: Homepage remains a read-only status portal; interactive web management belongs to a dedicated Operations UI client consuming `POST /v1/operations`. + +## Pros and Cons of the Options + +### Option 1: Status Quo with Local CLI Modernization +* Good, because it requires no background daemon or socket listener. +* Bad, because every process running under the operator's SSH UID retains full unauthenticated mutation authority over containers and secrets. +* Bad, because CLI and GitOps execution remain split across separate processes without unified lock management or tamper-evident auditing. + +### Option 2: Cloud-Native Micro-Platform +* Good, because Kubernetes/ArgoCD provide built-in API servers and RBAC. +* Bad, because cluster control planes impose heavy resource and operational complexity disproportionate to a single-node NixOS appliance. + +### Option 3: Authoritative `homelab-appctl.service` Daemon (Adopted) +* Good, because it isolates operational authority, secrets (`/run/secrets/appctl/tokens.json`), and audit logs (`/var/log/homelab/appctl/audit.jsonl`) under `homelab-appctl`. +* Good, because `POST /v1/operations` guarantees 100% contract parity across UDS and HTTP transports. +* Good, because `SO_PEERCRED` viewer fallback preserves ergonomic local read commands (`appctl list`, `appctl info`) while requiring tokens for mutations and secret reads. +* Bad, because it introduces a core systemd daemon and requires provisioning SOPS-managed API tokens for mutating CLI and GitOps operations. + +## Consequences + +### Positive Consequences +* **Defense-in-Depth Against Session Compromise**: Unprivileged scripts or AI coding agents in the operator's shell cannot mutate infrastructure, read `tokens.json`, or alter `audit.jsonl`. +* **Single Execution Truth**: Interactive CLI commands and automated GitOps webhooks execute through the exact same pre-flight validator, lock manager, and environment builder. +* **Deterministic Concurrency**: Per-target non-blocking `flock` locks (`/var/lib/homelab/appctl/locks/.lock`) prevent overlapping mutations (`409 ERR_CONCURRENT_MUTATION`). + +### Negative Consequences & Accepted Trade-offs +* **Daemon Dependency**: Normal operational commands depend on `homelab-appctl.service` availability (emergency host recovery remains possible for human administrators via `sudo`). +* **Token Provisioning**: Mutating CLI invocations require `APPCTL_TOKEN` / token configuration rather than relying on ambient SSH user identity. + +## More Information + +* **P4 Readiness & Boundary Specification**: [`docs/plans/p4-readiness-plan.md`](../plans/p4-readiness-plan.md) +* **Companion ADRs**: + * [ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model](0001-3tier-architecture-and-provenance.md) + * [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md) +* **Governing Roadmap**: [`ROADMAP.md`](../../ROADMAP.md) (Milestones P4–P7) diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 8151774..e60cdde 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -2,7 +2,7 @@ This document serves as the authoritative repository index for Architectural Decision Records (ADRs) governing **Homelab Core** and the **`appctl` Operational Control Plane**. -Repository-level architectural decisions are recorded in `docs/decisions/` using the MADR 4.0 specification. Foundational platform ADRs (0001 and 0002) are summarized inline below alongside full MADR records (0003+). +Repository-level architectural decisions are recorded in `docs/decisions/` using the MADR 4.0 specification (`NNNN-slug.md`). --- @@ -11,15 +11,14 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using | Decision Record | Status | Date | Scope & One-Line Purpose | | :--- | :--- | :--- | :--- | | [**ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. | -| [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](#homelab-operational-control-plane--deployment-model-architecture) | `accepted` | 2026-10-07 | Establishes `appctl` as the central operational control plane daemon, one logical API across dual transports (Unix socket and HTTP), explicit token authentication on host, Git as authoritative deployment state, the 5-stage model lifecycle, AI proposal boundaries, and append-only audit telemetry. | -| [**ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model**](#homelab-3-tier-architecture--deployment-provenance-model) | `accepted` | 2026-09-28 | Establishes 3-tier separation (Software, OCI Artifact, Sites Deployment, Core Platform), two workload classes (Source-Backed vs. Image-Only), isolated state root (`~/var/lib/homelab//`), and two operational inspection axes. | - +| [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and the 5-stage `DeploymentModel` lifecycle. | +| [**ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model**](0001-3tier-architecture-and-provenance.md) | `accepted` | 2026-09-28 | Establishes 3-tier separation (Software, OCI Artifact, Sites Deployment, Core Platform), two workload classes (Source-Backed vs. Image-Only), isolated state root (`~/var/lib/homelab//`), and two operational inspection axes. | --- ## 🧭 Summaries of Governing Decisions -### Centralized Runtime Validation & Serialization via Pydantic v2 +### [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md) * **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md) * **Status**: `accepted` (Active) * **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Milestone P4) @@ -30,27 +29,21 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using 4. **Secret-Safe Error Transformation**: Transport-level conversion of `ValidationError` into standard `ERR_VALIDATION_FAILED` (400) with raw input values redacted. 5. **Dual-Transport Parity**: Identical validated models across Unix domain socket and HTTP transports. -### Homelab Operational Control Plane & Deployment Model Architecture - -* **Decision ID**: `ADR-0002` -* **Status**: `accepted` (Active) -* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v5) +### [ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture](0002-appctl-control-plane-architecture.md) +* **Canonical Document**: [`0002-appctl-control-plane-architecture.md`](0002-appctl-control-plane-architecture.md) +* **Status**: `accepted` (Active β€” Reconciled with Pre-P4 Locked Decisions `DEC-01`–`DEC-05`) +* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v6) * **Core Commitments**: - 1. **Control Plane Daemon**: `appctl` transitions from a collection of local shell scripts into the authoritative platform service (`homelab-appctl.service`). - 2. **One Logical API Across Dual Transports**: Command-oriented operations exposed over a Unix domain socket (`/run/homelab/appctl.sock`) on host and an HTTP listener for network clients. - 3. **Explicit Token Authentication Everywhere**: Host SSH access does not confer appctl authority; every mutating operation requires an explicit, authenticated user-scoped token. - 4. **Git as Authoritative Deployment State**: Approved `DeploymentModels` are committed to Git. `appctl` acts as the reconciliation engine, validating the model, materializing platform descriptors (`app.yaml` + Compose), and reconciling running containers. - 5. **Five-Stage Deployment Model Lifecycle**: Separates factual `ApplicationProfile`, candidate `DeploymentProposal`, validated `DeploymentModel` (in Git), materialized `Deployment Definition`, and runtime `Reconciliation`. - 6. **AI Proposal Boundary**: AI agents act strictly as proposal generators with zero mutation or execution authority. After human approval into a `DeploymentModel`, the AI is completely out of the loop. - 7. **Secret Reference Invariant**: Manifests contain secret references (`secretKeyRef`), never secret material, resolved at runtime via `SecretProvider`. - 8. **Append-Only Audit Log**: Audit entries capture `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, and `result`. + 1. **One Logical Command API Across Dual Transports (`DEC-01`)**: `homelab-appctl.service` exposes `POST /v1/operations` (13 canonical domain operations) and `GET /v1/health` over HTTP/1.1 on `/run/homelab/appctl.sock` and `127.0.0.1:9001`. + 2. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**: Every mutating operation and sensitive read (`workload.config`, `workload.logs`) requires an authenticated SHA-256 Bearer token (`/run/secrets/appctl/tokens.json`); tokenless UDS calls fall back via `SO_PEERCRED` strictly to `homelab-viewer` read-only inspection. + 3. **Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)**: Daemon executes as `homelab-appctl:homelab-operators` with mode `0600` append-only `/var/log/homelab/appctl/audit.jsonl` and a pre-execution `DISPATCHED` disk guard. + 4. **GitOps Worker Unification & Pure-Python Pre-Flight (`DEC-04`, `DEC-05`)**: `gitops_dispatcher.py` worker delegates `workload.update` to the daemon; shell `source`/`eval` are replaced with pure-Python `.env` parsing and mandatory `validate_compose_security()` pre-flight checks. + 5. **Git Truth, Five-Stage Deployment Model & AI Boundary (P5–P7)**: Git remains authoritative deployment state; separates `ApplicationProfile` $\to$ `DeploymentProposal` (AI) $\to$ `DeploymentModel` (human-approved in Git) $\to$ materialized descriptors; resolves workload secrets via `SecretProvider` (`secretKeyRef`). ---- - -### Homelab 3-Tier Architecture & Deployment Provenance Model -* **Decision ID**: `ADR-0001` +### [ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model](0001-3tier-architecture-and-provenance.md) +* **Canonical Document**: [`0001-3tier-architecture-and-provenance.md`](0001-3tier-architecture-and-provenance.md) * **Status**: `accepted` (Active) -* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v5) +* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v6) * **Core Commitments**: 1. **3-Tier Separation of Concerns**: * *Tier 1 (Software Layer)*: Upstream application repositories owning code, tests, and CI. Zero Homelab infrastructure coupling. @@ -67,9 +60,10 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using ## πŸ“œ Superseded Historical Decisions & Lineage -The following historical plans and design iterations have been formally superseded by the active ADRs and Roadmap v5: +The following historical plans and design iterations have been formally superseded by the active ADRs and Roadmap v6: -* **Roadmap v4 & v3** (`architecture-consolidation-roadmap-v4.md`): Superseded by Roadmap v5. -* **appctl-v2 Modernization Plan** (`appctl-engine-v2-refactoring.md`): Scaffolded and absorbed into Roadmap v5 Phases P0 and P3. -* **Smart Selective Deployment Pipeline Plan** (`smart-deployment-pipeline.md`): Absorbed into Roadmap v5 Phase P4 control-plane reconciliation. -* **Architecture Implementation Guide v3** (`architecture-consolidation-implementation-guide-v3.md`): Superseded by Roadmap v5. +* **Roadmap v5 (`architecture-consolidation-roadmap-v5.md`)**: Superseded by Roadmap v6 (`DEC-01`–`DEC-05` pre-P4 boundary lock). +* **Roadmap v4, v3, v2 & v1** (`architecture-consolidation-roadmap-v4.md`): Superseded by Roadmap v5/v6. +* **appctl-v2 Modernization Plan** (`appctl-engine-v2-refactoring.md`): Scaffolded and absorbed into Roadmap Phases P0 and P3. +* **Smart Selective Deployment Pipeline Plan** (`smart-deployment-pipeline.md`): Absorbed into Phase P4 control-plane reconciliation. +* **Architecture Implementation Guide v3 & v2** (`architecture-consolidation-implementation-guide-v3.md`): Superseded by unified Roadmap v4–v6. diff --git a/docs/plans/p4-readiness-plan.md b/docs/plans/p4-readiness-plan.md index f26071c..b10822f 100644 --- a/docs/plans/p4-readiness-plan.md +++ b/docs/plans/p4-readiness-plan.md @@ -2,7 +2,7 @@ **Status**: βœ… **Approved & Locked (Pre-P4 Security Gate Complete; Ready for Daemon Implementation)** **Target Milestone**: [Milestone P4: Appctl Control Plane Daemon & API](../../ROADMAP.md#milestone-p4-appctl-control-plane-daemon--command-oriented-api) -**Governing ADR**: [`homelab-appctl-control-plane-architecture.md`](../decisions/README.md) +**Governing ADR**: [`0002-appctl-control-plane-architecture.md`](../decisions/0002-appctl-control-plane-architecture.md) --- @@ -97,7 +97,7 @@ This plan resolves the six architectural prerequisites necessary to implement P4 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). + - `POST /v1/operations`: Dispatches all 13 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.