Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8cc06e2470 | ||
|
|
53404914c3 | ||
|
|
194d1bf3ff | ||
|
|
9e30e113a0 | ||
|
|
d092ca17b8 | ||
|
|
8ce74ff520 | ||
|
|
b5a3db6f1b | ||
|
|
e23ff941d8 |
No files matched your search
+11
-1
@@ -21,7 +21,17 @@ else
|
||||
echo "⚠️ [pre-commit] Neither ruff nor nix found; skipping ruff"
|
||||
fi
|
||||
|
||||
# 2. Run Pytest Suite
|
||||
# 2. Run Pyright Type Checker
|
||||
echo " ↳ Checking static types with Pyright..."
|
||||
if command -v pyright >/dev/null 2>&1; then
|
||||
pyright
|
||||
elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then
|
||||
nix develop --command pyright
|
||||
else
|
||||
echo "⚠️ [pre-commit] Neither pyright nor nix found; skipping pyright"
|
||||
fi
|
||||
|
||||
# 3. Run Pytest Suite
|
||||
echo " ↳ Running structural and security test suite with Pytest..."
|
||||
if [ -x ".venv/bin/pytest" ]; then
|
||||
.venv/bin/pytest tests/
|
||||
|
||||
+16
-14
@@ -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/<app>/`, 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/<app>/`, 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/<app>/`. | 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.
|
||||
|
||||
---
|
||||
|
||||
@@ -13,7 +13,7 @@ authentication_backend:
|
||||
address: 'ldap://lldap:3890'
|
||||
timeout: 5s
|
||||
start_tls: false
|
||||
base_dn: 'dc=roadtotech,dc=me'
|
||||
base_dn: '{{ env "LLDAP_LDAP_BASE_DN" "dc=example,dc=test" }}'
|
||||
additional_users_dn: 'ou=people'
|
||||
users_filter: '(&({username_attribute}={input})(objectClass=person))'
|
||||
additional_groups_dn: 'ou=groups'
|
||||
@@ -24,7 +24,7 @@ authentication_backend:
|
||||
display_name: 'displayName'
|
||||
mail: 'mail'
|
||||
group_name: 'cn'
|
||||
user: 'uid=admin,ou=people,dc=roadtotech,dc=me'
|
||||
user: 'uid=admin,ou=people,{{ env "LLDAP_LDAP_BASE_DN" "dc=example,dc=test" }}'
|
||||
|
||||
access_control:
|
||||
default_policy: deny
|
||||
|
||||
+10
-10
@@ -6,48 +6,48 @@
|
||||
schemaVersion: "1.0"
|
||||
repositories:
|
||||
snappymail:
|
||||
path: "/home/kiskaadee/Sites/snappymail"
|
||||
path: "~/Sites/snappymail"
|
||||
aliases:
|
||||
- "homelab-snappymail"
|
||||
- "mail"
|
||||
- "webmail"
|
||||
gitea:
|
||||
path: "/home/kiskaadee/Sites/homelab-gitea"
|
||||
path: "~/Sites/homelab-gitea"
|
||||
aliases:
|
||||
- "homelab-gitea"
|
||||
- "git"
|
||||
jellyfin:
|
||||
path: "/home/kiskaadee/Sites/homelab-jellyfin"
|
||||
path: "~/Sites/homelab-jellyfin"
|
||||
aliases:
|
||||
- "homelab-jellyfin"
|
||||
- "media"
|
||||
docs:
|
||||
path: "/home/kiskaadee/Sites/homelab-doc2site"
|
||||
path: "~/Sites/homelab-doc2site"
|
||||
aliases:
|
||||
- "doc2site"
|
||||
- "homelab-doc2site"
|
||||
courses:
|
||||
path: "/home/kiskaadee/Sites/courses"
|
||||
path: "~/Sites/courses"
|
||||
aliases:
|
||||
- "homelab-courses"
|
||||
bdinvite:
|
||||
path: "/home/kiskaadee/Sites/homelab-bdinvite"
|
||||
path: "~/Sites/homelab-bdinvite"
|
||||
aliases:
|
||||
- "homelab-bdinvite"
|
||||
- "birthday"
|
||||
landing:
|
||||
path: "/home/kiskaadee/Sites/homelab-landing"
|
||||
path: "~/Sites/homelab-landing"
|
||||
aliases:
|
||||
- "homelab-landing"
|
||||
mermaid:
|
||||
path: "/home/kiskaadee/Sites/homelab-mermaid"
|
||||
path: "~/Sites/homelab-mermaid"
|
||||
aliases:
|
||||
- "homelab-mermaid"
|
||||
excalidraw:
|
||||
path: "/home/kiskaadee/Sites/homelab-excalidraw"
|
||||
path: "~/Sites/homelab-excalidraw"
|
||||
aliases:
|
||||
- "homelab-excalidraw"
|
||||
houston:
|
||||
path: "/home/kiskaadee/Sites/homelab-houston"
|
||||
path: "~/Sites/homelab-houston"
|
||||
aliases:
|
||||
- "homelab-houston"
|
||||
@@ -5,7 +5,7 @@
|
||||
- My Projects:
|
||||
- Github:
|
||||
- abbr: GH
|
||||
href: https://github.com/kiskaadee?tab=repositories
|
||||
href: https://github.com
|
||||
|
||||
- Social Media:
|
||||
- Instagram:
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
- Knowledge & Notes:
|
||||
- Docs-Viewer:
|
||||
icon: files.png
|
||||
href: https://docs.roadtotech.me
|
||||
href: https://docs.example.test
|
||||
description: Reactive Obsidian & Markdown Documentation Viewer
|
||||
server: my-docker
|
||||
container: docs
|
||||
- Excalidraw:
|
||||
icon: excalidraw.png
|
||||
href: https://excalidraw.roadtotech.me
|
||||
href: https://excalidraw.example.test
|
||||
description: Collaborative Whiteboarding & Sketching Tool
|
||||
server: my-docker
|
||||
container: excalidraw
|
||||
@@ -18,7 +18,7 @@
|
||||
- Media & Productivity:
|
||||
- Jellyfin:
|
||||
icon: jellyfin.png
|
||||
href: https://jellyfin.roadtotech.me
|
||||
href: https://jellyfin.example.test
|
||||
description: Media Server & Streaming Hub
|
||||
server: my-docker
|
||||
container: jellyfin
|
||||
+5
-5
@@ -106,11 +106,11 @@ services:
|
||||
environment:
|
||||
- TZ=America/Bogota
|
||||
- LLDAP_HTTP_URL=https://users.${DOMAIN}
|
||||
- LLDAP_LDAP_BASE_DN=dc=roadtotech,dc=me
|
||||
- LLDAP_LDAP_BASE_DN=${LLDAP_LDAP_BASE_DN:-dc=example,dc=test}
|
||||
- LLDAP_JWT_SECRET=${LLDAP_JWT_SECRET}
|
||||
- LLDAP_KEY_SEED=${LLDAP_KEY_SEED}
|
||||
- LLDAP_LDAP_USER_PASS=${LLDAP_LDAP_USER_PASS}
|
||||
- LLDAP_LDAP_USER_EMAIL=admin@${DOMAIN:-roadtotech.me}
|
||||
- LLDAP_LDAP_USER_EMAIL=${LLDAP_ADMIN_EMAIL:-admin@${DOMAIN:-example.test}}
|
||||
- LLDAP_DATABASE_URL=sqlite:///data/users.db?mode=rwc
|
||||
volumes:
|
||||
- ./config/lldap/data:/data
|
||||
@@ -222,12 +222,12 @@ services:
|
||||
- DIUN_PROVIDERS_DOCKER_APIVERSION=${DOCKER_API_VERSION:-1.40}
|
||||
- DIUN_NOTIF_MAIL_HOST=stalwart
|
||||
- DIUN_NOTIF_MAIL_PORT=465
|
||||
- DIUN_NOTIF_MAIL_USERNAME=notifier@${DOMAIN:-roadtotech.me}
|
||||
- DIUN_NOTIF_MAIL_USERNAME=${DIUN_NOTIF_MAIL_USERNAME:-notifier@${DOMAIN:-example.test}}
|
||||
- DIUN_NOTIF_MAIL_PASSWORD=${DIUN_SMTP_PASSWORD}
|
||||
- DIUN_NOTIF_MAIL_SSL=true
|
||||
- DIUN_NOTIF_MAIL_INSECURESKIPVERIFY=true
|
||||
- DIUN_NOTIF_MAIL_FROM=notifier@${DOMAIN:-roadtotech.me}
|
||||
- DIUN_NOTIF_MAIL_TO=kiskaadee@${DOMAIN:-roadtotech.me}
|
||||
- DIUN_NOTIF_MAIL_FROM=${DIUN_NOTIF_MAIL_FROM:-notifier@${DOMAIN:-example.test}}
|
||||
- DIUN_NOTIF_MAIL_TO=${DIUN_NOTIF_MAIL_TO:-operator@${DOMAIN:-example.test}}
|
||||
volumes:
|
||||
- ./config/diun:/data
|
||||
networks:
|
||||
|
||||
@@ -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/<app>`.
|
||||
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/<app>` 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/<app>/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/<app>`) 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/<app>` 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/<app>` 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/<app>/`, 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/<app>/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/<app>/`.
|
||||
* 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/<app>/` 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/<app>` 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)
|
||||
@@ -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/<app>` 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/<target>.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)
|
||||
+22
-28
@@ -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/<app>/`), 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/<app>/`), 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.
|
||||
@@ -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.
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
git
|
||||
pythonEnv
|
||||
ruff
|
||||
pyright
|
||||
];
|
||||
} ''
|
||||
mkdir -p $out
|
||||
@@ -59,6 +60,7 @@
|
||||
chmod -R u+w source
|
||||
cd source
|
||||
HOME=/tmp ruff check --no-cache .
|
||||
HOME=/tmp pyright
|
||||
HOME=/tmp pytest -o cache_dir=/tmp/.pytest_cache tests/
|
||||
'';
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# 🌐 Server NixOS Configuration — Turnkey Headless Homelab Appliance
|
||||
# Standalone declarative configuration for the roadtotech.me homelab server.
|
||||
# Standalone declarative configuration for the homelab server.
|
||||
# No Home Manager. No shared desktop modules.
|
||||
# Goal: wipe & restore from any NixOS installation via `nixos-install --flake ~/Core#server`
|
||||
|
||||
@@ -14,6 +14,9 @@
|
||||
./modules/shell.nix # Declarative bash environment for the server
|
||||
];
|
||||
|
||||
# ── Homelab platform settings ────────────────────────────────────────────────
|
||||
homelab.operatorUser = "kiskaadee";
|
||||
|
||||
# ── SOPS secrets configuration ──────────────────────────────────────────────
|
||||
# Set once here to avoid duplicate-option conflicts across submodules
|
||||
sops.defaultSopsFile = ./secrets.yaml;
|
||||
|
||||
@@ -15,7 +15,7 @@ in
|
||||
sops.secrets."dynu/domain" = { };
|
||||
sops.secrets."dynu/password" = { };
|
||||
sops.secrets."system/pdf_decrypt_password" = {
|
||||
owner = "kiskaadee";
|
||||
owner = config.homelab.operatorUser;
|
||||
};
|
||||
|
||||
# Assemble the ddclient config file securely at boot time in /run/secrets/
|
||||
|
||||
+125
-20
@@ -4,8 +4,33 @@
|
||||
{ config, lib, pkgs, ... }:
|
||||
|
||||
{
|
||||
# Define the keys to decrypt from secrets.yaml
|
||||
sops.secrets = lib.genAttrs [
|
||||
# Declarative configuration options for Homelab Core
|
||||
options.homelab = {
|
||||
domain = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "example.test";
|
||||
description = "Canonical domain for homelab services";
|
||||
};
|
||||
operatorUser = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "operator";
|
||||
description = "Primary operator user identity";
|
||||
};
|
||||
coreDir = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "/home/${config.homelab.operatorUser}/Core";
|
||||
description = "Path to Homelab Core repository";
|
||||
};
|
||||
sitesDir = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "/home/${config.homelab.operatorUser}/Sites";
|
||||
description = "Path to Sites directory";
|
||||
};
|
||||
};
|
||||
|
||||
config = {
|
||||
# Define the keys to decrypt from secrets.yaml
|
||||
sops.secrets = lib.genAttrs [
|
||||
"dynu/api_key"
|
||||
"traefik/acme_email"
|
||||
"authelia/session_secret"
|
||||
@@ -18,13 +43,13 @@
|
||||
"brevo/smtp_login"
|
||||
"brevo/smtp_key"
|
||||
"diun/smtp_password"
|
||||
] (name: { owner = "kiskaadee"; });
|
||||
] (name: { owner = config.homelab.operatorUser; });
|
||||
|
||||
# Generate the unified environment file at runtime in /run/secrets/homeserver.env
|
||||
sops.templates."homeserver.env" = {
|
||||
owner = "kiskaadee";
|
||||
owner = config.homelab.operatorUser;
|
||||
content = lib.generators.toKeyValue {} {
|
||||
DOMAIN = "roadtotech.me";
|
||||
DOMAIN = config.homelab.domain;
|
||||
DOCKER_API_VERSION = "1.40";
|
||||
DYNU_API_KEY = config.sops.placeholder."dynu/api_key";
|
||||
ACME_EMAIL = config.sops.placeholder."traefik/acme_email";
|
||||
@@ -53,7 +78,7 @@
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
WorkingDirectory = "/home/kiskaadee/Core";
|
||||
WorkingDirectory = config.homelab.coreDir;
|
||||
ExecStart = "${pkgs.docker-compose}/bin/docker-compose --env-file ${config.sops.templates."homeserver.env".path} up -d --remove-orphans";
|
||||
ExecStop = "${pkgs.docker-compose}/bin/docker-compose down";
|
||||
};
|
||||
@@ -78,24 +103,24 @@
|
||||
|
||||
environment = {
|
||||
GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path;
|
||||
DOCKER_CONFIG = "/home/kiskaadee/.local/state/homelab/docker";
|
||||
DOCKER_CONFIG = "/home/${config.homelab.operatorUser}/.local/state/homelab/docker";
|
||||
};
|
||||
|
||||
serviceConfig = {
|
||||
Type = "simple";
|
||||
User = "kiskaadee";
|
||||
User = config.homelab.operatorUser;
|
||||
SupplementaryGroups = [ "docker" ];
|
||||
WorkingDirectory = "/home/kiskaadee/Core";
|
||||
WorkingDirectory = config.homelab.coreDir;
|
||||
ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [
|
||||
{
|
||||
id = "deploy";
|
||||
execute-command = "/home/kiskaadee/Core/scripts/gitops_dispatcher.py";
|
||||
execute-command = "${config.homelab.coreDir}/scripts/gitops_dispatcher.py";
|
||||
pass-arguments-to-command = [
|
||||
{ source = "raw-request-body"; }
|
||||
{ source = "header"; name = "X-Gitea-Signature"; }
|
||||
{ source = "header"; name = "X-Gitea-Event"; }
|
||||
];
|
||||
command-working-directory = "/home/kiskaadee/Core";
|
||||
command-working-directory = config.homelab.coreDir;
|
||||
response-message = "Deployment payload dispatched successfully.";
|
||||
}
|
||||
])} -port 9000 -verbose";
|
||||
@@ -110,21 +135,101 @@
|
||||
ProtectKernelTunables = true;
|
||||
ProtectControlGroups = true;
|
||||
ReadWritePaths = [
|
||||
"/home/kiskaadee/Sites"
|
||||
"/home/kiskaadee/.local/state/homelab"
|
||||
config.homelab.sitesDir
|
||||
"/home/${config.homelab.operatorUser}/.local/state/homelab"
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
# Declarative Users and Groups for Control Plane Service Identity
|
||||
users.groups.homelab-operators = {};
|
||||
users.users.homelab-appctl = {
|
||||
isSystemUser = true;
|
||||
group = "homelab-operators";
|
||||
extraGroups = [ "docker" ];
|
||||
description = "Homelab appctl control plane daemon service user";
|
||||
};
|
||||
|
||||
# Declarative appctl Control Plane Daemon (Internal HTTP 9001 + UDS /run/homelab/appctl.sock)
|
||||
systemd.services.homelab-appctl = {
|
||||
description = "Homelab appctl Control Plane Daemon";
|
||||
after = [ "network-online.target" "docker.service" ];
|
||||
wants = [ "network-online.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
|
||||
path = with pkgs; [
|
||||
git
|
||||
docker
|
||||
docker-compose
|
||||
(python3.withPackages (ps: with ps; [ pyyaml pydantic ]))
|
||||
coreutils
|
||||
bash
|
||||
openssh
|
||||
];
|
||||
|
||||
environment = {
|
||||
APPCTL_SOCKET_PATH = "/run/homelab/appctl.sock";
|
||||
APPCTL_HTTP_HOST = "127.0.0.1";
|
||||
APPCTL_HTTP_PORT = "9001";
|
||||
APPCTL_AUDIT_LOG = "/var/log/homelab/appctl/audit.jsonl";
|
||||
APPCTL_LOCK_DIR = "/var/lib/homelab/appctl/locks";
|
||||
APPCTL_TOKENS_FILE = "/run/secrets/appctl/tokens.json";
|
||||
SITES_DIR = config.homelab.sitesDir;
|
||||
CORE_DIR = config.homelab.coreDir;
|
||||
HOMELAB_CONFIG_DIR = "/home/${config.homelab.operatorUser}/.config/homelab";
|
||||
HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.coreDir}/config/deployments.yaml";
|
||||
};
|
||||
|
||||
serviceConfig = {
|
||||
Type = "simple";
|
||||
User = "homelab-appctl";
|
||||
Group = "homelab-operators";
|
||||
SupplementaryGroups = [ "docker" ];
|
||||
WorkingDirectory = config.homelab.coreDir;
|
||||
ExecStart = "${(pkgs.python3.withPackages (ps: with ps; [ pyyaml pydantic ]))}/bin/python3 ${config.homelab.coreDir}/scripts/appctl_daemon.py";
|
||||
Restart = "always";
|
||||
RestartSec = "5s";
|
||||
|
||||
RuntimeDirectory = "homelab";
|
||||
RuntimeDirectoryMode = "0750";
|
||||
StateDirectory = "homelab/appctl";
|
||||
StateDirectoryMode = "0700";
|
||||
LogsDirectory = "homelab/appctl";
|
||||
LogsDirectoryMode = "0700";
|
||||
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = "read-only";
|
||||
ProtectKernelTunables = true;
|
||||
ProtectControlGroups = true;
|
||||
ReadWritePaths = [
|
||||
config.homelab.sitesDir
|
||||
"/home/${config.homelab.operatorUser}/var/lib/homelab"
|
||||
"${config.homelab.coreDir}/config/homepage"
|
||||
"/var/log/homelab/appctl"
|
||||
"/var/lib/homelab/appctl"
|
||||
"/run/homelab"
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
# Ensure persistent directories have proper permissions for container runtimes
|
||||
systemd.tmpfiles.rules = [
|
||||
"d /home/kiskaadee/Core/config/stalwart/data 0777 kiskaadee users -"
|
||||
"d /home/kiskaadee/Core/config/stalwart/etc 0777 kiskaadee users -"
|
||||
"d /home/kiskaadee/Sites 0755 kiskaadee users -"
|
||||
"d /home/kiskaadee/.local/state/homelab/gitops 0755 kiskaadee users -"
|
||||
"d /home/kiskaadee/.local/state/homelab/docker 0755 kiskaadee users -"
|
||||
"d ${config.homelab.coreDir}/config/stalwart/data 0777 ${config.homelab.operatorUser} users -"
|
||||
"d ${config.homelab.coreDir}/config/stalwart/etc 0777 ${config.homelab.operatorUser} users -"
|
||||
"d ${config.homelab.sitesDir} 0755 ${config.homelab.operatorUser} users -"
|
||||
"d /home/${config.homelab.operatorUser}/.local/state/homelab/gitops 0755 ${config.homelab.operatorUser} users -"
|
||||
"d /home/${config.homelab.operatorUser}/.local/state/homelab/docker 0755 ${config.homelab.operatorUser} users -"
|
||||
# POSIX ACLs granting homelab-appctl traverse and access to operator sites & homepage config
|
||||
"a+ /home/${config.homelab.operatorUser} - - - - u:homelab-appctl:x"
|
||||
"a+ ${config.homelab.coreDir} - - - - u:homelab-appctl:x"
|
||||
"a+ ${config.homelab.sitesDir} - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
|
||||
"a+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
|
||||
"a+ ${config.homelab.coreDir}/config/homepage - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
|
||||
];
|
||||
|
||||
# Open ports in the firewall for Traefik, Gitea SSH, GitOps Webhook Receiver, and Mail (SMTP, Submission, SMTPS, IMAPS, ManageSieve)
|
||||
networking.firewall.allowedTCPPorts = [ 80 443 2223 9000 25 465 587 993 4190 ];
|
||||
# Open ports in the firewall for Traefik, Gitea SSH, GitOps Webhook Receiver, and Mail (SMTP, Submission, SMTPS, IMAPS, ManageSieve)
|
||||
networking.firewall.allowedTCPPorts = [ 80 443 2223 9000 25 465 587 993 4190 ];
|
||||
};
|
||||
}
|
||||
@@ -15,31 +15,31 @@
|
||||
"postgres/password"
|
||||
"postgres/db"
|
||||
"gitea/runner_token"
|
||||
] (name: { owner = "kiskaadee"; });
|
||||
] (name: { owner = config.homelab.operatorUser; });
|
||||
|
||||
# Generate the unified environment file at runtime in /run/secrets/traefik-deployments.env
|
||||
sops.templates."traefik-deployments.env" = {
|
||||
owner = "kiskaadee";
|
||||
owner = config.homelab.operatorUser;
|
||||
content = lib.generators.toKeyValue {} {
|
||||
# --- Core / Infrastructure Settings ---
|
||||
PROXY_NETWORK = "proxy-net";
|
||||
CERT_RESOLVER = "myresolver";
|
||||
DOMAIN_SUFFIX = "roadtotech.me";
|
||||
DOMAIN_SUFFIX = config.homelab.domain;
|
||||
|
||||
# --- Dashboard & Landing ---
|
||||
DASHBOARD_DOMAIN = "dashboard.roadtotech.me";
|
||||
LANDING_DOMAIN = "roadtotech.me";
|
||||
DASHBOARD_DOMAIN = "dashboard.${config.homelab.domain}";
|
||||
LANDING_DOMAIN = config.homelab.domain;
|
||||
|
||||
# --- Docs ---
|
||||
DOCS_DOMAIN = "docs.roadtotech.me";
|
||||
DOCS_PROJECT_PATH = "/home/kiskaadee/Brain";
|
||||
DOCS_DOMAIN = "docs.${config.homelab.domain}";
|
||||
DOCS_PROJECT_PATH = "/home/${config.homelab.operatorUser}/Brain";
|
||||
|
||||
# --- Excalidraw ---
|
||||
EXCALIDRAW_DOMAIN = "excalidraw.roadtotech.me";
|
||||
EXCALIDRAW_DOMAIN = "excalidraw.${config.homelab.domain}";
|
||||
|
||||
# --- Gitea ---
|
||||
GITEA_DOMAIN = "gitea.roadtotech.me";
|
||||
GITEA_SSH_DOMAIN = "gitea.roadtotech.me";
|
||||
GITEA_DOMAIN = "gitea.${config.homelab.domain}";
|
||||
GITEA_SSH_DOMAIN = "gitea.${config.homelab.domain}";
|
||||
GITEA_SSH_PORT = "2223";
|
||||
GITEA_AUTH_MIDDLEWARE = "https-redirect@docker";
|
||||
GITEA_RUNNER_TOKEN = config.sops.placeholder."gitea/runner_token";
|
||||
@@ -48,7 +48,7 @@
|
||||
JELLYFIN_SERVICE_NAME = "jellyfin";
|
||||
JELLYFIN_CONTAINER_NAME = "jellyfin";
|
||||
JELLYFIN_IMAGE_TAG = "latest";
|
||||
JELLYFIN_DOMAIN = "jellyfin.roadtotech.me";
|
||||
JELLYFIN_DOMAIN = "jellyfin.${config.homelab.domain}";
|
||||
JELLYFIN_TZ = "UTC";
|
||||
JELLYFIN_PUID = "1000";
|
||||
JELLYFIN_PGID = "1000";
|
||||
@@ -60,7 +60,7 @@
|
||||
|
||||
# --- Learning Dashboard ---
|
||||
LEARNING_SERVICE_NAME = "learning-hub";
|
||||
LEARNING_DOMAIN = "learning.roadtotech.me";
|
||||
LEARNING_DOMAIN = "learning.${config.homelab.domain}";
|
||||
LEARNING_APP_PORT = "8000";
|
||||
LEARNING_SOCKET_PROXY_NETWORK = "socket-net";
|
||||
LEARNING_DOCKER_HOST = "tcp://socket-proxy:2375";
|
||||
@@ -68,25 +68,25 @@
|
||||
TURSO_AUTH_TOKEN = config.sops.placeholder."learning/turso_auth_token";
|
||||
|
||||
# --- Mermaid ---
|
||||
MERMAID_DOMAIN = "mermaid.roadtotech.me";
|
||||
MERMAID_DOMAIN = "mermaid.${config.homelab.domain}";
|
||||
MERMAID_SERVICE_NAME = "mermaid";
|
||||
|
||||
# --- Minecraft ---
|
||||
MINECRAFT_DOMAIN = "minecraft.roadtotech.me";
|
||||
MINECRAFT_DOMAIN = "minecraft.${config.homelab.domain}";
|
||||
|
||||
# --- MongoDB ---
|
||||
MONGO_ROOT_USERNAME = config.sops.placeholder."mongo/root_username";
|
||||
MONGO_ROOT_PASSWORD = config.sops.placeholder."mongo/root_password";
|
||||
MONGO_DOMAIN = "mongodb.roadtotech.me";
|
||||
MONGO_DOMAIN = "mongodb.${config.homelab.domain}";
|
||||
|
||||
# --- PostgreSQL ---
|
||||
POSTGRES_USER = config.sops.placeholder."postgres/user";
|
||||
POSTGRES_PASSWORD = config.sops.placeholder."postgres/password";
|
||||
POSTGRES_DB = config.sops.placeholder."postgres/db";
|
||||
POSTGRES_DOMAIN = "pgsql.roadtotech.me";
|
||||
POSTGRES_DOMAIN = "pgsql.${config.homelab.domain}";
|
||||
|
||||
# --- Ollama ---
|
||||
OLLAMA_DOMAIN = "ollama.roadtotech.me";
|
||||
OLLAMA_DOMAIN = "ollama.${config.homelab.domain}";
|
||||
OLLAMA_API_KEY = config.sops.placeholder."ollama/api_key";
|
||||
OLLAMA_REPLICAS = "1";
|
||||
OLLAMA_DATA_VOLUME = "ollama_data";
|
||||
|
||||
@@ -14,3 +14,9 @@ extraPaths = ["scripts"]
|
||||
venvPath = "."
|
||||
venv = ".venv"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
# Automatically adds app modules and script hooks to the sys.venvPath
|
||||
pythonpath = [
|
||||
".",
|
||||
"scripts"
|
||||
]
|
||||
@@ -9,6 +9,14 @@ set -e
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ENGINE="$SCRIPT_DIR/appctl_engine.py"
|
||||
PYTHON_BIN="${PYTHON_BIN:-python3}"
|
||||
SOCKET_PATH="${APPCTL_SOCKET_PATH:-/run/homelab/appctl.sock}"
|
||||
CLI_CLIENT="$SCRIPT_DIR/appctl_cli.py"
|
||||
|
||||
# If daemon Unix domain socket exists, delegate directly to thin client
|
||||
if [ -S "$SOCKET_PATH" ] && [ -f "$CLI_CLIENT" ]; then
|
||||
exec "$PYTHON_BIN" "$CLI_CLIENT" "$@"
|
||||
fi
|
||||
|
||||
ENV_FILE="/run/secrets/rendered/traefik-deployments.env"
|
||||
if [ ! -f "$ENV_FILE" ] && [ -f "/run/secrets/traefik-deployments.env" ]; then
|
||||
ENV_FILE="/run/secrets/traefik-deployments.env"
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
"""
|
||||
appctl_audit.py — Append-Only Audit Logger & Per-Target Lock Manager (P4 Slice 2)
|
||||
|
||||
Governs the audit telemetry and concurrency control for homelab-appctl.service:
|
||||
- Append-only JSONL audit writer adhering to RFC-compliant schema (mode 0600)
|
||||
- Pre-execution DISPATCHED fail-closed disk guard
|
||||
- Sensitive parameter and error redaction (*_KEY, *_SECRET, *_PASSWORD, etc.)
|
||||
- Non-blocking per-target flock context manager raising ConcurrentMutationError (409)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import UTC, datetime
|
||||
from enum import StrEnum
|
||||
from pathlib import Path
|
||||
from types import TracebackType
|
||||
from typing import Annotated, Any, Literal, Self
|
||||
|
||||
from appctl_contracts import StrictModel
|
||||
from pydantic import BeforeValidator, ConfigDict, Field, StrictInt, StrictStr
|
||||
|
||||
DEFAULT_AUDIT_LOG = Path("/var/log/homelab/appctl/audit.jsonl")
|
||||
DEFAULT_LOCK_DIR = Path("/var/lib/homelab/appctl/locks")
|
||||
|
||||
REDACT_KEY_PATTERNS = re.compile(
|
||||
r".*(?:_KEY|_SECRET|_PASSWORD|_TOKEN|_PASS|_HASH)$", re.IGNORECASE
|
||||
)
|
||||
|
||||
|
||||
class AuditPhase(StrEnum):
|
||||
"""Lifecycle phases for control plane audit events."""
|
||||
|
||||
DISPATCHED = "DISPATCHED"
|
||||
COMPLETED = "COMPLETED"
|
||||
FAILED = "FAILED"
|
||||
DENIED = "DENIED"
|
||||
|
||||
|
||||
def _coerce_phase(v: Any) -> Any:
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
return AuditPhase(v)
|
||||
except ValueError:
|
||||
return v
|
||||
return v
|
||||
|
||||
|
||||
FlexibleAuditPhase = Annotated[
|
||||
AuditPhase,
|
||||
BeforeValidator(_coerce_phase),
|
||||
]
|
||||
|
||||
|
||||
class PrincipalAudit(StrictModel):
|
||||
"""Authenticated principal details captured in audit records."""
|
||||
|
||||
identity: StrictStr
|
||||
role: StrictStr
|
||||
token_id: StrictStr | None = None
|
||||
auth_method: StrictStr
|
||||
|
||||
|
||||
class AuditResult(StrictModel):
|
||||
"""Execution outcome details captured in audit records."""
|
||||
|
||||
status: Literal["SUCCESS", "FAILED", "DENIED", "IN_PROGRESS"]
|
||||
exit_code: StrictInt | None = None
|
||||
duration_ms: StrictInt | None = None
|
||||
commit_sha: StrictStr | None = None
|
||||
error_code: StrictStr | None = None
|
||||
message: StrictStr | None = None
|
||||
|
||||
|
||||
class AuditEvent(StrictModel):
|
||||
"""RFC-compliant single-line JSONL audit event model (ADR-0002 / DEC-03)."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
audit_version: Literal["1.0"] = "1.0"
|
||||
event_id: StrictStr
|
||||
operation_id: StrictStr
|
||||
timestamp: StrictStr
|
||||
phase: FlexibleAuditPhase
|
||||
principal: PrincipalAudit
|
||||
action: StrictStr
|
||||
target: StrictStr | None = None
|
||||
transport: StrictStr
|
||||
origin: StrictStr
|
||||
client: StrictStr
|
||||
parameters: dict[str, Any] = Field(default_factory=dict)
|
||||
result: AuditResult | None = None
|
||||
|
||||
|
||||
class AuditPersistenceError(Exception):
|
||||
"""Raised when an audit record cannot be persisted or flushed to disk."""
|
||||
|
||||
|
||||
class ConcurrentMutationError(Exception):
|
||||
"""Raised when a per-target operation lock cannot be acquired (409 Conflict)."""
|
||||
|
||||
def __init__(self, target: str, message: str | None = None) -> None:
|
||||
self.target = target
|
||||
msg = message or f"Operation on target '{target}' is locked by a concurrent task."
|
||||
super().__init__(msg)
|
||||
|
||||
|
||||
def redact_sensitive_data(val: Any) -> Any:
|
||||
"""
|
||||
Recursively redact values whose dictionary keys match sensitive patterns
|
||||
(*_KEY, *_SECRET, *_PASSWORD, *_TOKEN, *_PASS, *_HASH).
|
||||
"""
|
||||
if isinstance(val, dict):
|
||||
return {
|
||||
k: "[REDACTED]" if REDACT_KEY_PATTERNS.match(str(k)) else redact_sensitive_data(v)
|
||||
for k, v in val.items()
|
||||
}
|
||||
if isinstance(val, list):
|
||||
return [redact_sensitive_data(v) for v in val]
|
||||
return val
|
||||
|
||||
|
||||
def generate_event_id() -> str:
|
||||
"""Generate a unique event identifier."""
|
||||
return f"evt_{secrets.token_hex(6)}"
|
||||
|
||||
|
||||
def generate_operation_id() -> str:
|
||||
"""Generate a unique operation identifier."""
|
||||
return f"op_{secrets.token_hex(6)}"
|
||||
|
||||
|
||||
def current_iso_timestamp() -> str:
|
||||
"""Current UTC timestamp formatted as ISO 8601 with millisecond precision."""
|
||||
now = datetime.now(UTC)
|
||||
return now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
|
||||
|
||||
|
||||
class AuditLogger:
|
||||
"""
|
||||
Append-only thread-safe audit logger writing single-line JSONL records.
|
||||
Enforces mode 0600 on the log file and provides a fail-closed pre-execution
|
||||
DISPATCHED disk guard.
|
||||
"""
|
||||
|
||||
def __init__(self, log_path: Path | str | None = None) -> None:
|
||||
if log_path is not None:
|
||||
self.log_path = Path(log_path)
|
||||
elif "APPCTL_AUDIT_LOG" in os.environ:
|
||||
self.log_path = Path(os.environ["APPCTL_AUDIT_LOG"])
|
||||
else:
|
||||
self.log_path = DEFAULT_AUDIT_LOG
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def _ensure_log_file(self) -> None:
|
||||
"""Ensure parent directories exist and file is initialized with mode 0600."""
|
||||
self.log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not self.log_path.exists():
|
||||
fd = os.open(
|
||||
self.log_path,
|
||||
os.O_WRONLY | os.O_CREAT | os.O_APPEND,
|
||||
0o600,
|
||||
)
|
||||
os.close(fd)
|
||||
|
||||
def emit_event(self, event: AuditEvent) -> None:
|
||||
"""
|
||||
Append an audit event as a single JSON line to the audit log.
|
||||
Flushes and fsyncs to ensure durability. Raises AuditPersistenceError on failure.
|
||||
"""
|
||||
with self._lock:
|
||||
try:
|
||||
self._ensure_log_file()
|
||||
line = event.model_dump_json() + "\n"
|
||||
fd = os.open(
|
||||
self.log_path,
|
||||
os.O_WRONLY | os.O_APPEND,
|
||||
0o600,
|
||||
)
|
||||
try:
|
||||
os.write(fd, line.encode("utf-8"))
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
except OSError as err:
|
||||
raise AuditPersistenceError(
|
||||
f"Failed to persist audit event '{event.event_id}': {err}"
|
||||
) from err
|
||||
|
||||
def log_dispatched(
|
||||
self,
|
||||
operation_id: str,
|
||||
principal: PrincipalAudit,
|
||||
action: str,
|
||||
target: str | None,
|
||||
transport: str,
|
||||
origin: str,
|
||||
client: str,
|
||||
parameters: dict[str, Any],
|
||||
) -> AuditEvent:
|
||||
"""
|
||||
Fail-closed pre-execution disk guard: logs DISPATCHED phase before any
|
||||
subprocess or filesystem mutation begins. Raises AuditPersistenceError if disk write fails.
|
||||
"""
|
||||
clean_params = redact_sensitive_data(parameters)
|
||||
event = AuditEvent(
|
||||
event_id=generate_event_id(),
|
||||
operation_id=operation_id,
|
||||
timestamp=current_iso_timestamp(),
|
||||
phase=AuditPhase.DISPATCHED,
|
||||
principal=principal,
|
||||
action=action,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=clean_params,
|
||||
result=AuditResult(status="IN_PROGRESS"),
|
||||
)
|
||||
self.emit_event(event)
|
||||
return event
|
||||
|
||||
def log_completed(
|
||||
self,
|
||||
operation_id: str,
|
||||
principal: PrincipalAudit,
|
||||
action: str,
|
||||
target: str | None,
|
||||
transport: str,
|
||||
origin: str,
|
||||
client: str,
|
||||
parameters: dict[str, Any],
|
||||
duration_ms: int,
|
||||
commit_sha: str | None = None,
|
||||
message: str | None = None,
|
||||
) -> AuditEvent:
|
||||
"""Log COMPLETED phase upon clean operation termination."""
|
||||
clean_params = redact_sensitive_data(parameters)
|
||||
event = AuditEvent(
|
||||
event_id=generate_event_id(),
|
||||
operation_id=operation_id,
|
||||
timestamp=current_iso_timestamp(),
|
||||
phase=AuditPhase.COMPLETED,
|
||||
principal=principal,
|
||||
action=action,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=clean_params,
|
||||
result=AuditResult(
|
||||
status="SUCCESS",
|
||||
exit_code=0,
|
||||
duration_ms=duration_ms,
|
||||
commit_sha=commit_sha,
|
||||
error_code=None,
|
||||
message=message or "Operation completed successfully",
|
||||
),
|
||||
)
|
||||
self.emit_event(event)
|
||||
return event
|
||||
|
||||
def log_failed(
|
||||
self,
|
||||
operation_id: str,
|
||||
principal: PrincipalAudit,
|
||||
action: str,
|
||||
target: str | None,
|
||||
transport: str,
|
||||
origin: str,
|
||||
client: str,
|
||||
parameters: dict[str, Any],
|
||||
duration_ms: int | None = None,
|
||||
exit_code: int | None = None,
|
||||
error_code: str | None = None,
|
||||
message: str | None = None,
|
||||
) -> AuditEvent:
|
||||
"""Log FAILED phase when validation or execution fails."""
|
||||
clean_params = redact_sensitive_data(parameters)
|
||||
clean_msg = redact_sensitive_data(message) if message else None
|
||||
event = AuditEvent(
|
||||
event_id=generate_event_id(),
|
||||
operation_id=operation_id,
|
||||
timestamp=current_iso_timestamp(),
|
||||
phase=AuditPhase.FAILED,
|
||||
principal=principal,
|
||||
action=action,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=clean_params,
|
||||
result=AuditResult(
|
||||
status="FAILED",
|
||||
exit_code=exit_code,
|
||||
duration_ms=duration_ms,
|
||||
error_code=error_code,
|
||||
message=clean_msg,
|
||||
),
|
||||
)
|
||||
self.emit_event(event)
|
||||
return event
|
||||
|
||||
def log_denied(
|
||||
self,
|
||||
operation_id: str,
|
||||
principal: PrincipalAudit,
|
||||
action: str,
|
||||
target: str | None,
|
||||
transport: str,
|
||||
origin: str,
|
||||
client: str,
|
||||
parameters: dict[str, Any],
|
||||
error_code: str,
|
||||
message: str,
|
||||
) -> AuditEvent:
|
||||
"""Log DENIED phase when authentication, RBAC, or concurrency lock rejects request."""
|
||||
clean_params = redact_sensitive_data(parameters)
|
||||
event = AuditEvent(
|
||||
event_id=generate_event_id(),
|
||||
operation_id=operation_id,
|
||||
timestamp=current_iso_timestamp(),
|
||||
phase=AuditPhase.DENIED,
|
||||
principal=principal,
|
||||
action=action,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=clean_params,
|
||||
result=AuditResult(
|
||||
status="DENIED",
|
||||
error_code=error_code,
|
||||
message=message,
|
||||
),
|
||||
)
|
||||
self.emit_event(event)
|
||||
return event
|
||||
|
||||
|
||||
class TargetLock:
|
||||
"""Context manager acquiring a non-blocking per-target flock."""
|
||||
|
||||
def __init__(self, lock_path: Path, target: str) -> None:
|
||||
self.lock_path = lock_path
|
||||
self.target = target
|
||||
self._fd: int | None = None
|
||||
|
||||
def __enter__(self) -> Self:
|
||||
self.lock_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd = os.open(
|
||||
self.lock_path,
|
||||
os.O_RDWR | os.O_CREAT,
|
||||
0o600,
|
||||
)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except (BlockingIOError, OSError) as err:
|
||||
os.close(fd)
|
||||
raise ConcurrentMutationError(self.target) from err
|
||||
self._fd = fd
|
||||
return self
|
||||
|
||||
def __exit__(
|
||||
self,
|
||||
exc_type: type[BaseException] | None,
|
||||
exc_val: BaseException | None,
|
||||
exc_tb: TracebackType | None,
|
||||
) -> None:
|
||||
if self._fd is not None:
|
||||
try:
|
||||
fcntl.flock(self._fd, fcntl.LOCK_UN)
|
||||
finally:
|
||||
os.close(self._fd)
|
||||
self._fd = None
|
||||
|
||||
|
||||
class TargetLockManager:
|
||||
"""Manages operational per-target locks under /var/lib/homelab/appctl/locks."""
|
||||
|
||||
def __init__(self, lock_dir: Path | str | None = None) -> None:
|
||||
if lock_dir is not None:
|
||||
self.lock_dir = Path(lock_dir)
|
||||
elif "APPCTL_LOCK_DIR" in os.environ:
|
||||
self.lock_dir = Path(os.environ["APPCTL_LOCK_DIR"])
|
||||
else:
|
||||
self.lock_dir = DEFAULT_LOCK_DIR
|
||||
|
||||
def lock_target(self, target: str) -> TargetLock:
|
||||
"""Return a non-blocking flock context manager for a workload target."""
|
||||
clean_target = re.sub(r"[^a-zA-Z0-9._-]", "_", target)
|
||||
lock_path = self.lock_dir / f"{clean_target}.lock"
|
||||
return TargetLock(lock_path, target)
|
||||
|
||||
def homepage_sync_lock(self) -> TargetLock:
|
||||
"""Return a non-blocking flock context manager for homepage compilation."""
|
||||
lock_path = self.lock_dir / "_homepage_sync.lock"
|
||||
return TargetLock(lock_path, "_homepage_sync")
|
||||
@@ -0,0 +1,360 @@
|
||||
"""
|
||||
appctl_auth.py — Authentication & 3-Role RBAC Policy Enforcement (P4 Slice 3)
|
||||
|
||||
Implements the zero-trust authorization pipeline for homelab-appctl.service:
|
||||
- SOPS-managed SHA-256 Bearer token store loader (mode 0400 check, constant-time compare)
|
||||
- Unix domain socket SO_PEERCRED fallback to homelab-viewer for zero-friction local reads
|
||||
- Mandatory Bearer tokens for all network (HTTP) operations and all mutations / sensitive reads
|
||||
- 3-role RBAC enforcement (homelab-admin, homelab-operator, homelab-viewer)
|
||||
- Workload scope gating against config/deployments.yaml for homelab-operator
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
from enum import StrEnum
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from appctl_contracts import (
|
||||
ErrorCode,
|
||||
OperationType,
|
||||
StrictModel,
|
||||
)
|
||||
from pydantic import BeforeValidator, ConfigDict, Field, StrictStr
|
||||
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
yaml = None # type: ignore[assignment]
|
||||
|
||||
DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json")
|
||||
DEFAULT_DEPLOYMENTS_FILE = Path(__file__).resolve().parent.parent / "config" / "deployments.yaml"
|
||||
|
||||
CORE_TARGETS: frozenset[str] = frozenset({
|
||||
"core",
|
||||
"traefik",
|
||||
"authelia",
|
||||
"lldap",
|
||||
"stalwart",
|
||||
"dozzle",
|
||||
"socket-proxy",
|
||||
"homepage",
|
||||
"diun",
|
||||
"watchtower",
|
||||
})
|
||||
|
||||
SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_CONFIG,
|
||||
OperationType.WORKLOAD_LOGS,
|
||||
})
|
||||
|
||||
MUTATING_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_STOP,
|
||||
OperationType.WORKLOAD_RESTART,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_PULL,
|
||||
OperationType.PLATFORM_SYNC_HOMEPAGE,
|
||||
})
|
||||
|
||||
READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_LIST,
|
||||
OperationType.WORKLOAD_GET,
|
||||
OperationType.WORKLOAD_RESOLVE,
|
||||
OperationType.PLATFORM_SSL,
|
||||
OperationType.PLATFORM_HEALTH,
|
||||
})
|
||||
|
||||
|
||||
class Role(StrEnum):
|
||||
"""Hierarchical authorization roles for homelab-appctl.service."""
|
||||
|
||||
ADMIN = "homelab-admin"
|
||||
OPERATOR = "homelab-operator"
|
||||
VIEWER = "homelab-viewer"
|
||||
|
||||
|
||||
def _coerce_role(v: Any) -> Any:
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
return Role(v)
|
||||
except ValueError:
|
||||
return v
|
||||
return v
|
||||
|
||||
|
||||
FlexibleRole = Annotated[
|
||||
Role,
|
||||
BeforeValidator(_coerce_role),
|
||||
]
|
||||
|
||||
|
||||
class Principal(StrictModel):
|
||||
"""Authenticated caller identity and operational role."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
identity: StrictStr
|
||||
role: FlexibleRole
|
||||
token_id: StrictStr | None = None
|
||||
auth_method: Literal["bearer_token", "unix_peercred"]
|
||||
|
||||
|
||||
class TokenDescriptor(StrictModel):
|
||||
"""Internal model for token entries in SOPS tokens.json store."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
token_id: StrictStr
|
||||
identity: StrictStr
|
||||
role: FlexibleRole
|
||||
sha256: Annotated[StrictStr, Field(pattern=r"^[0-9a-fA-F]{64}$")]
|
||||
|
||||
|
||||
class AuthenticationError(Exception):
|
||||
"""Raised when authentication fails (401 Unauthorized)."""
|
||||
|
||||
def __init__(self, message: str = "Authentication required", code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.http_status = 401
|
||||
|
||||
|
||||
class AuthorizationError(Exception):
|
||||
"""Raised when an authenticated principal lacks required role or scope (403 Forbidden)."""
|
||||
|
||||
def __init__(self, message: str = "Permission denied", code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.http_status = 403
|
||||
|
||||
|
||||
class TokenStore:
|
||||
"""Loads and validates SHA-256 Bearer tokens from a mode 0400 store."""
|
||||
|
||||
def __init__(self, tokens_path: Path | str | None = None) -> None:
|
||||
if tokens_path is not None:
|
||||
self.tokens_path = Path(tokens_path)
|
||||
elif "APPCTL_TOKENS_FILE" in os.environ:
|
||||
self.tokens_path = Path(os.environ["APPCTL_TOKENS_FILE"])
|
||||
else:
|
||||
self.tokens_path = DEFAULT_TOKENS_FILE
|
||||
|
||||
def _verify_permissions(self) -> None:
|
||||
"""Enforce strict 0400 file mode: readable only by owner, no write/exec, no group/world."""
|
||||
if not self.tokens_path.is_file():
|
||||
raise AuthenticationError(
|
||||
f"Token store '{self.tokens_path}' not found",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
# Check permissions: reject if group/world readable or writable (must be 0400)
|
||||
mode = stat.S_IMODE(self.tokens_path.stat().st_mode)
|
||||
if (mode & 0o077) != 0 or (mode & 0o200) != 0:
|
||||
raise AuthenticationError(
|
||||
f"Token store '{self.tokens_path}' has insecure mode {oct(mode)}; mode 0400 required",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
|
||||
def load_tokens(self) -> list[TokenDescriptor]:
|
||||
"""Load and parse token descriptors from the token store."""
|
||||
self._verify_permissions()
|
||||
try:
|
||||
content = self.tokens_path.read_text(encoding="utf-8")
|
||||
data = json.loads(content)
|
||||
if not isinstance(data, list):
|
||||
raise TypeError("Tokens payload must be an array of token descriptors")
|
||||
return [TokenDescriptor.model_validate(item) for item in data]
|
||||
except (OSError, json.JSONDecodeError, ValueError, TypeError) as err:
|
||||
raise AuthenticationError(
|
||||
f"Failed to load token store '{self.tokens_path}': {err}",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
) from err
|
||||
|
||||
def authenticate_bearer(self, secret: str) -> Principal:
|
||||
"""
|
||||
Hash secret with SHA-256 and look up against stored token descriptors using
|
||||
constant-time hmac.compare_digest.
|
||||
"""
|
||||
if not secret:
|
||||
raise AuthenticationError("Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED)
|
||||
|
||||
secret_hash = hashlib.sha256(secret.encode("utf-8")).hexdigest()
|
||||
tokens = self.load_tokens()
|
||||
|
||||
for token in tokens:
|
||||
if hmac.compare_digest(secret_hash, token.sha256):
|
||||
return Principal(
|
||||
identity=token.identity,
|
||||
role=token.role,
|
||||
token_id=token.token_id,
|
||||
auth_method="bearer_token",
|
||||
)
|
||||
|
||||
raise AuthenticationError("Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED)
|
||||
|
||||
|
||||
def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[str]:
|
||||
"""
|
||||
Load admitted repository names and aliases from config/deployments.yaml.
|
||||
Fails closed (empty set) if registry is missing or malformed.
|
||||
"""
|
||||
if deployments_path is not None:
|
||||
reg_file = Path(deployments_path)
|
||||
elif "HOMELAB_DEPLOYMENTS_FILE" in os.environ:
|
||||
reg_file = Path(os.environ["HOMELAB_DEPLOYMENTS_FILE"])
|
||||
else:
|
||||
reg_file = DEFAULT_DEPLOYMENTS_FILE
|
||||
|
||||
if not reg_file.is_file():
|
||||
return set()
|
||||
|
||||
yaml_errors = (yaml.YAMLError,) if yaml is not None else ()
|
||||
try:
|
||||
content = reg_file.read_text(encoding="utf-8")
|
||||
if yaml is not None:
|
||||
data = yaml.safe_load(content)
|
||||
else:
|
||||
data = json.loads(content)
|
||||
if not isinstance(data, dict):
|
||||
return set()
|
||||
|
||||
admitted: set[str] = set()
|
||||
repos = data.get("repositories", {})
|
||||
if isinstance(repos, dict):
|
||||
for name, entry in repos.items():
|
||||
admitted.add(name)
|
||||
if isinstance(entry, dict):
|
||||
aliases = entry.get("aliases", [])
|
||||
if isinstance(aliases, list):
|
||||
for alias in aliases:
|
||||
if isinstance(alias, str) and alias.strip():
|
||||
admitted.add(alias.strip())
|
||||
return admitted
|
||||
except (OSError, UnicodeDecodeError, ValueError, json.JSONDecodeError, *yaml_errors):
|
||||
return set()
|
||||
|
||||
|
||||
def authenticate_request(
|
||||
transport: Literal["unix_socket", "http"],
|
||||
auth_header: str | None,
|
||||
peer_uid: int | None = None,
|
||||
token_store: TokenStore | None = None,
|
||||
) -> Principal:
|
||||
"""
|
||||
Authenticate an incoming request across transports:
|
||||
- If Authorization header present: parses Bearer secret and verifies against TokenStore.
|
||||
- If Authorization header missing over HTTP: fails closed with 401 ERR_AUTH_REQUIRED.
|
||||
- If Authorization header missing over Unix socket: falls back to homelab-viewer with peer_uid.
|
||||
"""
|
||||
store = token_store or TokenStore()
|
||||
|
||||
if auth_header is not None:
|
||||
header_val = auth_header.strip()
|
||||
if not header_val.startswith("Bearer "):
|
||||
raise AuthenticationError(
|
||||
"Malformed Authorization header: must start with 'Bearer '",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
secret = header_val[7:].strip()
|
||||
if not secret:
|
||||
raise AuthenticationError(
|
||||
"Missing token secret in Authorization header",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
return store.authenticate_bearer(secret)
|
||||
|
||||
# Missing Authorization header
|
||||
if transport == "unix_socket":
|
||||
if peer_uid is not None:
|
||||
return Principal(
|
||||
identity=f"unix_uid_{peer_uid}",
|
||||
role=Role.VIEWER,
|
||||
token_id=None,
|
||||
auth_method="unix_peercred",
|
||||
)
|
||||
raise AuthenticationError(
|
||||
"Missing peer credentials over Unix socket",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
|
||||
# HTTP transport requires Bearer token strictly
|
||||
raise AuthenticationError(
|
||||
"Bearer token required over network transport",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
|
||||
|
||||
def enforce_rbac(
|
||||
principal: Principal,
|
||||
operation: OperationType,
|
||||
target: str | None = None,
|
||||
admitted_workloads: set[str] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Enforce 3-role RBAC policy (homelab-admin, homelab-operator, homelab-viewer).
|
||||
Raises AuthorizationError (403) on violation.
|
||||
"""
|
||||
# 1. homelab-admin has unrestricted access across all operations and targets
|
||||
if principal.role == Role.ADMIN:
|
||||
return
|
||||
|
||||
# 2. homelab-operator:
|
||||
if principal.role == Role.OPERATOR:
|
||||
# Platform homepage sync allowed
|
||||
if operation == OperationType.PLATFORM_SYNC_HOMEPAGE:
|
||||
return
|
||||
|
||||
# Target checks for operations targeting infrastructure
|
||||
if target is not None and (target in CORE_TARGETS or target == "core"):
|
||||
raise AuthorizationError(
|
||||
f"Role 'homelab-operator' is not permitted to target core service '{target}'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
|
||||
# Non-sensitive reads are permitted
|
||||
if operation in READ_ONLY_OPERATIONS:
|
||||
return
|
||||
|
||||
# Sensitive reads and mutations must target an admitted workload from deployments.yaml
|
||||
if operation in SENSITIVE_OPERATIONS or operation in MUTATING_OPERATIONS:
|
||||
if not target:
|
||||
raise AuthorizationError(
|
||||
f"Operation '{operation.value}' requires an explicit workload target",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
registry = (
|
||||
admitted_workloads
|
||||
if admitted_workloads is not None
|
||||
else load_admitted_workloads()
|
||||
)
|
||||
if target not in registry:
|
||||
raise AuthorizationError(
|
||||
f"Target '{target}' is not registered in deployments.yaml for role 'homelab-operator'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
return
|
||||
|
||||
# 3. homelab-viewer:
|
||||
if principal.role == Role.VIEWER:
|
||||
if operation in MUTATING_OPERATIONS:
|
||||
raise AuthorizationError(
|
||||
f"Role 'homelab-viewer' is not permitted to execute mutating operation '{operation.value}'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
if operation in SENSITIVE_OPERATIONS:
|
||||
raise AuthorizationError(
|
||||
f"Role 'homelab-viewer' is not permitted to access sensitive operation '{operation.value}'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
if operation in READ_ONLY_OPERATIONS:
|
||||
return
|
||||
|
||||
raise AuthorizationError(
|
||||
f"Operation '{operation.value}' denied for role '{principal.role.value}'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
Executable
+260
@@ -0,0 +1,260 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
appctl_cli.py — Thin HTTP/1.1 Unix Domain Socket Client for homelab-appctl
|
||||
|
||||
Dispatches CLI commands to the control plane daemon over /run/homelab/appctl.sock.
|
||||
Supports local peercred viewer fallback, Bearer token authentication, and formatted output.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from appctl_contracts import (
|
||||
OperationRequest,
|
||||
OperationResponse,
|
||||
OperationType,
|
||||
)
|
||||
from appctl_daemon import (
|
||||
DEFAULT_SOCKET_PATH,
|
||||
send_daemon_request,
|
||||
)
|
||||
|
||||
|
||||
def resolve_token(cli_token: str | None = None) -> str | None:
|
||||
"""Resolve Bearer token from CLI flag, environment, or user token files."""
|
||||
if cli_token:
|
||||
return cli_token.strip()
|
||||
|
||||
if "APPCTL_TOKEN" in os.environ:
|
||||
return os.environ["APPCTL_TOKEN"].strip()
|
||||
|
||||
token_candidates = [
|
||||
Path.home() / ".config/homelab/token",
|
||||
Path("/run/secrets/appctl/token"),
|
||||
]
|
||||
for path in token_candidates:
|
||||
if path.is_file():
|
||||
try:
|
||||
return path.read_text(encoding="utf-8").strip()
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def format_response(resp: OperationResponse, raw_json: bool = False) -> str:
|
||||
"""Format an OperationResponse for human-friendly terminal display or JSON output."""
|
||||
if raw_json:
|
||||
return resp.model_dump_json(indent=2, exclude_none=True)
|
||||
|
||||
if not resp.success:
|
||||
err_msg = resp.error.message if resp.error else "Unknown error"
|
||||
code = f" [{resp.error.code.value}]" if resp.error else ""
|
||||
return f"❌ Error{code}: {err_msg}"
|
||||
|
||||
# If the engine produced terminal output (e.g. logs, compose config, status table), show it
|
||||
if resp.output:
|
||||
return resp.output
|
||||
|
||||
if resp.result:
|
||||
if "message" in resp.result and len(resp.result) <= 3:
|
||||
return f"✨ {resp.result['message']}"
|
||||
return json.dumps(resp.result, indent=2)
|
||||
|
||||
return f"✨ Operation '{resp.operation}' succeeded."
|
||||
|
||||
|
||||
def run_cli(argv: list[str] | None = None) -> int:
|
||||
"""Main CLI command parser and dispatcher."""
|
||||
common_parser = argparse.ArgumentParser(add_help=False)
|
||||
common_parser.add_argument(
|
||||
"--socket",
|
||||
type=Path,
|
||||
default=None,
|
||||
help="Path to appctl Unix domain socket",
|
||||
)
|
||||
common_parser.add_argument(
|
||||
"--token",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Bearer token secret (overrides APPCTL_TOKEN and token files)",
|
||||
)
|
||||
common_parser.add_argument(
|
||||
"--json",
|
||||
action="store_true",
|
||||
help="Output raw JSON response",
|
||||
)
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="appctl",
|
||||
description="Homelab Unified Control Plane Client",
|
||||
parents=[common_parser],
|
||||
)
|
||||
|
||||
subparsers = parser.add_subparsers(dest="command", help="Operational commands")
|
||||
|
||||
# list / status
|
||||
list_p = subparsers.add_parser("list", aliases=["status"], parents=[common_parser], help="List workloads")
|
||||
list_p.add_argument("--core", action="store_true", help="Include core platform services")
|
||||
list_p.add_argument("--fetch", action="store_true", help="Fetch remote git revisions")
|
||||
list_p.add_argument("--ssl", action="store_true", help="Check SSL certificate status")
|
||||
|
||||
# info
|
||||
info_p = subparsers.add_parser("info", parents=[common_parser], help="Get workload metadata")
|
||||
info_p.add_argument("target", help="Workload name")
|
||||
info_p.add_argument("--ssl", action="store_true", help="Check SSL certificate status")
|
||||
|
||||
# ssl
|
||||
ssl_p = subparsers.add_parser("ssl", parents=[common_parser], help="Inspect platform SSL certificates")
|
||||
ssl_p.add_argument("target", nargs="?", default=None, help="Target workload or platform")
|
||||
|
||||
# health
|
||||
subparsers.add_parser("health", parents=[common_parser], help="Check control plane daemon health")
|
||||
|
||||
# up / deploy
|
||||
up_p = subparsers.add_parser("up", aliases=["deploy"], parents=[common_parser], help="Deploy workload")
|
||||
up_p.add_argument("target", help="Workload or core target")
|
||||
up_p.add_argument("--build", action="store_true", help="Rebuild container images")
|
||||
|
||||
# down / stop
|
||||
down_p = subparsers.add_parser("down", aliases=["stop"], parents=[common_parser], help="Stop workload")
|
||||
down_p.add_argument("target", help="Workload or core target")
|
||||
|
||||
# restart
|
||||
restart_p = subparsers.add_parser("restart", parents=[common_parser], help="Restart workload")
|
||||
restart_p.add_argument("target", help="Workload or core target")
|
||||
|
||||
# update
|
||||
update_p = subparsers.add_parser("update", parents=[common_parser], help="Update workload revision")
|
||||
update_p.add_argument("target", help="Workload target")
|
||||
update_p.add_argument("--branch", default=None, help="Expected git branch")
|
||||
|
||||
# pull
|
||||
pull_p = subparsers.add_parser("pull", parents=[common_parser], help="Pull workload images")
|
||||
pull_p.add_argument("target", help="Workload target")
|
||||
|
||||
# logs
|
||||
logs_p = subparsers.add_parser("logs", parents=[common_parser], help="View workload logs")
|
||||
logs_p.add_argument("target", help="Workload target")
|
||||
logs_p.add_argument("--tail", type=int, default=100, help="Number of log lines")
|
||||
|
||||
# config
|
||||
config_p = subparsers.add_parser("config", parents=[common_parser], help="View workload compose config")
|
||||
config_p.add_argument("target", help="Workload target")
|
||||
|
||||
# sync
|
||||
subparsers.add_parser("sync", parents=[common_parser], help="Synchronize Homepage services.yaml")
|
||||
|
||||
parsed, _ = parser.parse_known_args(argv)
|
||||
|
||||
if not parsed.command:
|
||||
parser.print_help()
|
||||
return 1
|
||||
|
||||
token = resolve_token(parsed.token)
|
||||
socket_path = parsed.socket or Path(os.environ.get("APPCTL_SOCKET_PATH", DEFAULT_SOCKET_PATH))
|
||||
|
||||
# Map command to OperationRequest
|
||||
op_req: OperationRequest
|
||||
cmd = parsed.command
|
||||
|
||||
if cmd in ("list", "status"):
|
||||
params: dict[str, Any] = {
|
||||
"core": getattr(parsed, "core", False),
|
||||
"fetch": getattr(parsed, "fetch", False),
|
||||
"ssl": getattr(parsed, "ssl", False),
|
||||
}
|
||||
op_req = OperationRequest(operation=OperationType.WORKLOAD_LIST, parameters=params)
|
||||
elif cmd == "info":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_GET,
|
||||
target=parsed.target,
|
||||
parameters={"ssl": getattr(parsed, "ssl", False)},
|
||||
)
|
||||
elif cmd == "ssl":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.PLATFORM_SSL,
|
||||
target=parsed.target,
|
||||
)
|
||||
elif cmd == "health":
|
||||
op_req = OperationRequest(operation=OperationType.PLATFORM_HEALTH)
|
||||
elif cmd in ("up", "deploy"):
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_DEPLOY,
|
||||
target=parsed.target,
|
||||
parameters={"build": getattr(parsed, "build", False)},
|
||||
)
|
||||
elif cmd in ("down", "stop"):
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_STOP,
|
||||
target=parsed.target,
|
||||
)
|
||||
elif cmd == "restart":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_RESTART,
|
||||
target=parsed.target,
|
||||
)
|
||||
elif cmd == "update":
|
||||
params = {}
|
||||
if getattr(parsed, "branch", None):
|
||||
params["expected_branch"] = parsed.branch
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_UPDATE,
|
||||
target=parsed.target,
|
||||
parameters=params,
|
||||
)
|
||||
elif cmd == "pull":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_PULL,
|
||||
target=parsed.target,
|
||||
)
|
||||
elif cmd == "logs":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_LOGS,
|
||||
target=parsed.target,
|
||||
parameters={"tail": getattr(parsed, "tail", 100)},
|
||||
)
|
||||
elif cmd == "config":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_CONFIG,
|
||||
target=parsed.target,
|
||||
)
|
||||
elif cmd == "sync":
|
||||
op_req = OperationRequest(operation=OperationType.PLATFORM_SYNC_HOMEPAGE)
|
||||
else:
|
||||
print(f"❌ Unknown command '{cmd}'", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
try:
|
||||
resp = send_daemon_request(
|
||||
endpoint=socket_path,
|
||||
operation_request=op_req,
|
||||
token=token,
|
||||
timeout=330.0,
|
||||
)
|
||||
print(format_response(resp, raw_json=parsed.json))
|
||||
return 0 if resp.success else 1
|
||||
except FileNotFoundError:
|
||||
print(f"❌ Error: appctl daemon socket not found at {socket_path}", file=sys.stderr)
|
||||
return 1
|
||||
except ConnectionRefusedError:
|
||||
print(f"❌ Error: appctl daemon is not accepting connections at {socket_path}", file=sys.stderr)
|
||||
return 1
|
||||
except (
|
||||
OSError,
|
||||
json.JSONDecodeError,
|
||||
TimeoutError,
|
||||
ValueError,
|
||||
) as e:
|
||||
print(f"❌ Error: Failed to communicate with appctl daemon: {e}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(run_cli())
|
||||
@@ -0,0 +1,328 @@
|
||||
"""
|
||||
appctl_contracts.py — Authoritative Control Plane API Contracts & Schema Validation
|
||||
|
||||
Defines the wire protocol and Pydantic v2 domain schemas for homelab-appctl.service:
|
||||
- Canonical 13 domain operations (workload.*, platform.*)
|
||||
- Fail-closed strict typing (ConfigDict(extra="forbid", strict=True))
|
||||
- Operation-specific parameter models (DeployParams, UpdateParams, LogsParams, ListParams, GetParams)
|
||||
- Closed 6-code error taxonomy mapped to HTTP/1.1 semantics
|
||||
- Information-disclosure-preventing error sanitizer (stripping input and url)
|
||||
- Dual-transport request/response models
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import StrEnum
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from pydantic import (
|
||||
AliasChoices,
|
||||
BaseModel,
|
||||
BeforeValidator,
|
||||
ConfigDict,
|
||||
Field,
|
||||
StrictBool,
|
||||
StrictInt,
|
||||
StrictStr,
|
||||
ValidationError,
|
||||
field_validator,
|
||||
model_validator,
|
||||
)
|
||||
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
"""Base model propagating strict validation across all control plane models — ADR-0003."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
|
||||
class OperationType(StrEnum):
|
||||
"""The 13 canonical domain operations exposed by homelab-appctl.service."""
|
||||
|
||||
# Read-Only Operations
|
||||
WORKLOAD_LIST = "workload.list"
|
||||
WORKLOAD_GET = "workload.get"
|
||||
WORKLOAD_RESOLVE = "workload.resolve"
|
||||
PLATFORM_SSL = "platform.ssl"
|
||||
PLATFORM_HEALTH = "platform.health"
|
||||
WORKLOAD_CONFIG = "workload.config"
|
||||
WORKLOAD_LOGS = "workload.logs"
|
||||
|
||||
# Mutating Operations
|
||||
WORKLOAD_DEPLOY = "workload.deploy"
|
||||
WORKLOAD_STOP = "workload.stop"
|
||||
WORKLOAD_RESTART = "workload.restart"
|
||||
WORKLOAD_UPDATE = "workload.update"
|
||||
WORKLOAD_PULL = "workload.pull"
|
||||
PLATFORM_SYNC_HOMEPAGE = "platform.sync_homepage"
|
||||
|
||||
|
||||
# Backward-compatibility alias
|
||||
WorkloadAction = OperationType
|
||||
CanonicalOperation = OperationType
|
||||
|
||||
MUTATING_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_STOP,
|
||||
OperationType.WORKLOAD_RESTART,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_PULL,
|
||||
OperationType.PLATFORM_SYNC_HOMEPAGE,
|
||||
})
|
||||
|
||||
READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_LIST,
|
||||
OperationType.WORKLOAD_GET,
|
||||
OperationType.WORKLOAD_RESOLVE,
|
||||
OperationType.PLATFORM_SSL,
|
||||
OperationType.PLATFORM_HEALTH,
|
||||
OperationType.WORKLOAD_CONFIG,
|
||||
OperationType.WORKLOAD_LOGS,
|
||||
})
|
||||
|
||||
SENSITIVE_READ_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_CONFIG,
|
||||
OperationType.WORKLOAD_LOGS,
|
||||
})
|
||||
|
||||
TARGET_REQUIRED_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_GET,
|
||||
OperationType.WORKLOAD_RESOLVE,
|
||||
OperationType.WORKLOAD_CONFIG,
|
||||
OperationType.WORKLOAD_LOGS,
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_STOP,
|
||||
OperationType.WORKLOAD_RESTART,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_PULL,
|
||||
})
|
||||
|
||||
|
||||
def _coerce_operation(v: Any) -> Any:
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
return OperationType(v)
|
||||
except ValueError:
|
||||
return v
|
||||
return v
|
||||
|
||||
|
||||
FlexibleOperationType = Annotated[
|
||||
OperationType,
|
||||
BeforeValidator(_coerce_operation),
|
||||
]
|
||||
FlexibleWorkloadAction = FlexibleOperationType
|
||||
|
||||
|
||||
class ErrorCode(StrEnum):
|
||||
"""Canonical 6-code error taxonomy for homelab-appctl.service."""
|
||||
|
||||
ERR_VALIDATION_FAILED = "ERR_VALIDATION_FAILED"
|
||||
ERR_AUTH_REQUIRED = "ERR_AUTH_REQUIRED"
|
||||
ERR_PERMISSION_DENIED = "ERR_PERMISSION_DENIED"
|
||||
ERR_TARGET_NOT_FOUND = "ERR_TARGET_NOT_FOUND"
|
||||
ERR_CONCURRENT_MUTATION = "ERR_CONCURRENT_MUTATION"
|
||||
ERR_EXECUTION_FAILED = "ERR_EXECUTION_FAILED"
|
||||
|
||||
@property
|
||||
def http_status(self) -> int:
|
||||
return ERROR_HTTP_STATUS[self]
|
||||
|
||||
|
||||
ERROR_HTTP_STATUS: dict[ErrorCode, int] = {
|
||||
ErrorCode.ERR_VALIDATION_FAILED: 400,
|
||||
ErrorCode.ERR_AUTH_REQUIRED: 401,
|
||||
ErrorCode.ERR_PERMISSION_DENIED: 403,
|
||||
ErrorCode.ERR_TARGET_NOT_FOUND: 404,
|
||||
ErrorCode.ERR_CONCURRENT_MUTATION: 409,
|
||||
ErrorCode.ERR_EXECUTION_FAILED: 500,
|
||||
}
|
||||
|
||||
|
||||
def _coerce_error_code(v: Any) -> Any:
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
return ErrorCode(v)
|
||||
except ValueError:
|
||||
return v
|
||||
return v
|
||||
|
||||
|
||||
FlexibleErrorCode = Annotated[
|
||||
ErrorCode,
|
||||
BeforeValidator(_coerce_error_code),
|
||||
]
|
||||
|
||||
|
||||
class DeployParams(StrictModel):
|
||||
"""Parameters for workload.deploy."""
|
||||
|
||||
recreate: StrictBool = True
|
||||
remove_orphans: StrictBool = True
|
||||
build: StrictBool = False
|
||||
|
||||
|
||||
class UpdateParams(StrictModel):
|
||||
"""Parameters for workload.update."""
|
||||
|
||||
expected_branch: Annotated[StrictStr, Field(min_length=1)] | None = None
|
||||
build: StrictBool = False
|
||||
|
||||
|
||||
class LogsParams(StrictModel):
|
||||
"""Parameters for workload.logs."""
|
||||
|
||||
tail: StrictInt = Field(default=100, ge=1, le=1000)
|
||||
|
||||
|
||||
class ListParams(StrictModel):
|
||||
"""Parameters for workload.list."""
|
||||
|
||||
fetch: StrictBool = False
|
||||
core: StrictBool = False
|
||||
ssl: StrictBool = False
|
||||
|
||||
|
||||
class GetParams(StrictModel):
|
||||
"""Parameters for workload.get."""
|
||||
|
||||
ssl: StrictBool = False
|
||||
|
||||
|
||||
class EmptyParams(StrictModel):
|
||||
"""Parameters model for operations that accept no arguments."""
|
||||
|
||||
|
||||
OPERATION_PARAMS_MAP: dict[OperationType, type[StrictModel]] = {
|
||||
OperationType.WORKLOAD_DEPLOY: DeployParams,
|
||||
OperationType.WORKLOAD_UPDATE: UpdateParams,
|
||||
OperationType.WORKLOAD_LOGS: LogsParams,
|
||||
OperationType.WORKLOAD_LIST: ListParams,
|
||||
OperationType.WORKLOAD_GET: GetParams,
|
||||
OperationType.WORKLOAD_STOP: EmptyParams,
|
||||
OperationType.WORKLOAD_RESTART: EmptyParams,
|
||||
OperationType.WORKLOAD_PULL: EmptyParams,
|
||||
OperationType.WORKLOAD_RESOLVE: EmptyParams,
|
||||
OperationType.PLATFORM_SSL: EmptyParams,
|
||||
OperationType.PLATFORM_HEALTH: EmptyParams,
|
||||
OperationType.WORKLOAD_CONFIG: EmptyParams,
|
||||
OperationType.PLATFORM_SYNC_HOMEPAGE: EmptyParams,
|
||||
}
|
||||
|
||||
|
||||
class OperationError(StrictModel):
|
||||
"""Standardized error payload returned in failed OperationResponse payloads."""
|
||||
|
||||
code: FlexibleErrorCode
|
||||
message: StrictStr
|
||||
details: list[dict[str, Any]] | None = None
|
||||
|
||||
|
||||
def sanitize_validation_error(exc: ValidationError) -> OperationError:
|
||||
"""
|
||||
Format and sanitize a Pydantic ValidationError into an OperationError with ERR_VALIDATION_FAILED,
|
||||
stripping raw user input and documentation URLs to prevent information disclosure.
|
||||
"""
|
||||
raw_details = exc.errors(include_input=False, include_url=False)
|
||||
clean_details: list[dict[str, Any]] = []
|
||||
for d in raw_details:
|
||||
clean_details.append({
|
||||
"type": d.get("type"),
|
||||
"loc": list(d.get("loc", ())),
|
||||
"msg": d.get("msg"),
|
||||
})
|
||||
return OperationError(
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message="Request payload validation failed",
|
||||
details=clean_details,
|
||||
)
|
||||
|
||||
|
||||
class OperationRequest(StrictModel):
|
||||
"""Defines the body requirements of an HTTP/1.1 operation request."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True, populate_by_name=True)
|
||||
|
||||
version: Literal["1.0"] = "1.0"
|
||||
operation: FlexibleOperationType = Field(
|
||||
validation_alias=AliasChoices("operation", "action")
|
||||
)
|
||||
target: Annotated[StrictStr, Field(min_length=1)] | None = None
|
||||
parameters: dict[str, Any] = Field(
|
||||
default_factory=dict,
|
||||
validation_alias=AliasChoices("parameters", "params"),
|
||||
)
|
||||
|
||||
@property
|
||||
def action(self) -> OperationType:
|
||||
return self.operation
|
||||
|
||||
@property
|
||||
def params(self) -> dict[str, Any]:
|
||||
return self.parameters
|
||||
|
||||
@field_validator("parameters", mode="before")
|
||||
@classmethod
|
||||
def _coerce_parameters(cls, v: Any) -> Any:
|
||||
if isinstance(v, BaseModel):
|
||||
return v.model_dump()
|
||||
return v
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_request(self) -> OperationRequest:
|
||||
if self.operation in TARGET_REQUIRED_OPERATIONS and not self.target:
|
||||
raise ValueError(f"Operation '{self.operation.value}' requires a non-empty target")
|
||||
param_model = OPERATION_PARAMS_MAP.get(self.operation, EmptyParams)
|
||||
param_model.model_validate(self.parameters)
|
||||
return self
|
||||
|
||||
def parse_parameters(self) -> StrictModel:
|
||||
"""Parse and return the typed parameter model for this operation."""
|
||||
param_model = OPERATION_PARAMS_MAP.get(self.operation, EmptyParams)
|
||||
return param_model.model_validate(self.parameters)
|
||||
|
||||
|
||||
class OperationResponse(StrictModel):
|
||||
"""Defines the standard response payload for control plane operations."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True, populate_by_name=True)
|
||||
|
||||
version: Literal["1.0"] = "1.0"
|
||||
success: StrictBool | None = None
|
||||
status: Literal["success", "error"] | None = None
|
||||
operation_id: StrictStr = Field(min_length=1)
|
||||
operation: FlexibleOperationType | StrictStr | None = Field(
|
||||
default=None,
|
||||
validation_alias=AliasChoices("operation", "action"),
|
||||
)
|
||||
target: StrictStr | None = None
|
||||
output: StrictStr = ""
|
||||
result: dict[str, Any] | None = None
|
||||
error: OperationError | None = None
|
||||
timestamp: StrictStr | None = None
|
||||
duration_ms: StrictInt | None = None
|
||||
|
||||
@property
|
||||
def action(self) -> OperationType | str | None:
|
||||
return self.operation
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_consistency(self) -> OperationResponse:
|
||||
if self.success is None and self.status is None:
|
||||
raise ValueError("Either 'success' or 'status' must be provided")
|
||||
if self.success is None and self.status is not None:
|
||||
self.success = self.status == "success"
|
||||
elif self.status is None and self.success is not None:
|
||||
self.status = "success" if self.success else "error"
|
||||
elif (
|
||||
self.success is not None
|
||||
and self.status is not None
|
||||
and (self.status == "success") != self.success
|
||||
):
|
||||
raise ValueError("'status' and 'success' must agree")
|
||||
|
||||
if self.success and self.error is not None:
|
||||
raise ValueError("Successful operation cannot contain an error")
|
||||
if not self.success and self.error is None:
|
||||
raise ValueError("Failed operation must contain an error")
|
||||
return self
|
||||
Executable
+585
@@ -0,0 +1,585 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
appctl_daemon.py — Dual-Transport HTTP/1.1 Control Plane Daemon for Homelab
|
||||
|
||||
Implements Milestone P4 Control Plane Daemon:
|
||||
- Multi-threaded Unix domain socket listener (/run/homelab/appctl.sock, mode 0660)
|
||||
- Multi-threaded loopback HTTP listener (127.0.0.1:9001)
|
||||
- Bounded 64 KiB request body enforcement
|
||||
- Endpoints: GET /v1/health, POST /v1/operations
|
||||
- Linux SO_PEERCRED credential extraction on UDS transport
|
||||
- Bearer token authentication + RBAC gating + append-only audit logging
|
||||
- Pure-Python Unix domain socket HTTP client helper
|
||||
- Graceful SIGINT and SIGTERM shutdown unlinking socket file
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import http.server
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import socketserver
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from appctl_audit import (
|
||||
AuditLogger,
|
||||
PrincipalAudit,
|
||||
TargetLockManager,
|
||||
current_iso_timestamp,
|
||||
generate_operation_id,
|
||||
)
|
||||
from appctl_auth import (
|
||||
AuthenticationError,
|
||||
TokenStore,
|
||||
authenticate_request,
|
||||
)
|
||||
from appctl_contracts import (
|
||||
ErrorCode,
|
||||
OperationError,
|
||||
OperationRequest,
|
||||
OperationResponse,
|
||||
OperationType,
|
||||
sanitize_validation_error,
|
||||
)
|
||||
from appctl_router import OperationalRouter
|
||||
from pydantic import ValidationError
|
||||
|
||||
logger = logging.getLogger("appctl_daemon")
|
||||
|
||||
CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent))
|
||||
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
|
||||
DEPLOYMENTS_FILE = Path(
|
||||
os.environ.get("HOMELAB_DEPLOYMENTS_FILE", CORE_DIR / "config" / "deployments.yaml")
|
||||
)
|
||||
|
||||
DEFAULT_SOCKET_PATH = Path(
|
||||
os.environ.get("APPCTL_SOCKET_PATH", "/run/homelab/appctl.sock")
|
||||
)
|
||||
DEFAULT_HTTP_HOST = os.environ.get("APPCTL_HTTP_HOST", "127.0.0.1")
|
||||
DEFAULT_HTTP_PORT = int(os.environ.get("APPCTL_HTTP_PORT", "9001"))
|
||||
MAX_REQUEST_BODY = 64 * 1024 # 64 KiB
|
||||
|
||||
|
||||
def extract_peer_credentials(sock: socket.socket) -> tuple[int, int, int] | None:
|
||||
"""
|
||||
Extract (pid, uid, gid) from a connected Unix domain socket on Linux via SO_PEERCRED.
|
||||
Returns None if unsupported or on error.
|
||||
"""
|
||||
try:
|
||||
so_peercred = getattr(socket, "SO_PEERCRED", 17)
|
||||
creds = sock.getsockopt(socket.SOL_SOCKET, so_peercred, struct.calcsize("3i"))
|
||||
pid, uid, gid = struct.unpack("3i", creds)
|
||||
return pid, uid, gid
|
||||
except (OSError, struct.error, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
class UnixHTTPConnection(http.client.HTTPConnection):
|
||||
"""HTTP client connection over a local Unix domain socket."""
|
||||
|
||||
def __init__(self, socket_path: str, timeout: float = 30.0) -> None:
|
||||
super().__init__("localhost", timeout=timeout)
|
||||
self.socket_path = socket_path
|
||||
|
||||
def connect(self) -> None:
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
if self.timeout is not None:
|
||||
sock.settimeout(self.timeout)
|
||||
sock.connect(self.socket_path)
|
||||
self.sock = sock
|
||||
|
||||
|
||||
def send_daemon_request(
|
||||
endpoint: str | Path,
|
||||
operation_request: OperationRequest | dict[str, Any],
|
||||
token: str | None = None,
|
||||
timeout: float = 30.0,
|
||||
) -> OperationResponse:
|
||||
"""
|
||||
Client helper to send an OperationRequest over UDS or HTTP to the daemon.
|
||||
Accepts:
|
||||
- Path object or path ending in .sock -> UnixHTTPConnection
|
||||
- URL starting with http:// or host:port -> standard HTTPConnection
|
||||
"""
|
||||
if isinstance(operation_request, OperationRequest):
|
||||
req_body = operation_request.model_dump_json(exclude_none=True)
|
||||
elif isinstance(operation_request, dict):
|
||||
req_body = json.dumps(operation_request)
|
||||
else:
|
||||
raise TypeError("operation_request must be OperationRequest or dict")
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Host": "localhost",
|
||||
}
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
|
||||
is_unix = False
|
||||
endpoint_str = str(endpoint)
|
||||
|
||||
if (
|
||||
isinstance(endpoint, Path)
|
||||
or endpoint_str.endswith(".sock")
|
||||
or ("/" in endpoint_str and not endpoint_str.startswith("http"))
|
||||
):
|
||||
is_unix = True
|
||||
|
||||
if is_unix:
|
||||
conn = UnixHTTPConnection(endpoint_str, timeout=timeout)
|
||||
else:
|
||||
if endpoint_str.startswith(("http://", "https://")):
|
||||
parsed = urlparse(endpoint_str)
|
||||
host = parsed.hostname or "127.0.0.1"
|
||||
port = parsed.port or (443 if parsed.scheme == "https" else 80)
|
||||
elif ":" in endpoint_str:
|
||||
host, port_str = endpoint_str.split(":", 1)
|
||||
port = int(port_str)
|
||||
else:
|
||||
host = endpoint_str
|
||||
port = DEFAULT_HTTP_PORT
|
||||
conn = http.client.HTTPConnection(host, port, timeout=timeout)
|
||||
|
||||
try:
|
||||
conn.request("POST", "/v1/operations", body=req_body.encode("utf-8"), headers=headers)
|
||||
res = conn.getresponse()
|
||||
resp_data = res.read().decode("utf-8")
|
||||
parsed_json = json.loads(resp_data)
|
||||
return OperationResponse.model_validate(parsed_json)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
|
||||
"""
|
||||
HTTP/1.1 request handler for appctl control plane operations.
|
||||
Supports both UDS and loopback TCP listeners.
|
||||
"""
|
||||
|
||||
server_version = "AppctlDaemon/1.0"
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
@property
|
||||
def appctl_server(self) -> ThreadingUnixStreamServer | ThreadingHTTPServer:
|
||||
return cast("ThreadingUnixStreamServer | ThreadingHTTPServer", self.server)
|
||||
|
||||
def address_string(self) -> str:
|
||||
"""Safely format client address avoiding slow DNS lookups or UDS unpack errors."""
|
||||
client_addr = self.client_address
|
||||
if isinstance(client_addr, tuple) and len(client_addr) >= 2:
|
||||
return f"{client_addr[0]}:{client_addr[1]}"
|
||||
if isinstance(client_addr, str) and client_addr:
|
||||
return client_addr
|
||||
return "unix_socket"
|
||||
|
||||
def log_message(self, format: str, *args: Any) -> None:
|
||||
"""Forward access logs to Python standard logger."""
|
||||
logger.info("%s - %s", self.address_string(), format % args)
|
||||
|
||||
def _send_json(self, status_code: int, data: dict[str, Any] | str) -> None:
|
||||
"""Send formatted JSON HTTP response."""
|
||||
body_bytes = data.encode("utf-8") if isinstance(data, str) else json.dumps(data, indent=2).encode("utf-8")
|
||||
self.send_response(status_code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body_bytes)))
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
self.wfile.write(body_bytes)
|
||||
|
||||
def _send_operation_response(self, status_code: int, response: OperationResponse) -> None:
|
||||
"""Serialize and send an OperationResponse payload."""
|
||||
payload_str = response.model_dump_json(exclude_none=True)
|
||||
self._send_json(status_code, payload_str)
|
||||
|
||||
def _send_operation_error(
|
||||
self,
|
||||
status_code: int,
|
||||
error: OperationError,
|
||||
operation: Any = None,
|
||||
target: str | None = None,
|
||||
op_id: str | None = None,
|
||||
) -> None:
|
||||
"""Send standardized OperationResponse representing a failure."""
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=False,
|
||||
status="error",
|
||||
operation_id=op_id or generate_operation_id(),
|
||||
operation=operation if isinstance(operation, (OperationType, str)) else None,
|
||||
target=target if isinstance(target, str) else None,
|
||||
error=error,
|
||||
timestamp=current_iso_timestamp(),
|
||||
)
|
||||
self._send_operation_response(status_code, resp)
|
||||
|
||||
def _send_error_response(
|
||||
self,
|
||||
status_code: int,
|
||||
code: ErrorCode,
|
||||
message: str,
|
||||
details: list[dict[str, Any]] | None = None,
|
||||
op_id: str | None = None,
|
||||
operation: Any = None,
|
||||
target: str | None = None,
|
||||
) -> None:
|
||||
"""Send structured error response with canonical error code."""
|
||||
error = OperationError(code=code, message=message, details=details)
|
||||
self._send_operation_error(
|
||||
status_code=status_code,
|
||||
error=error,
|
||||
operation=operation,
|
||||
target=target,
|
||||
op_id=op_id,
|
||||
)
|
||||
|
||||
def do_GET(self) -> None:
|
||||
"""Handle health check endpoint."""
|
||||
if self.path in ("/v1/health", "/health"):
|
||||
health = self.appctl_server.daemon_instance.get_health_status()
|
||||
self._send_json(200, health)
|
||||
return
|
||||
|
||||
self._send_error_response(
|
||||
status_code=404,
|
||||
code=ErrorCode.ERR_TARGET_NOT_FOUND,
|
||||
message=f"Endpoint '{self.path}' not found",
|
||||
)
|
||||
|
||||
def do_POST(self) -> None:
|
||||
"""Handle operational dispatch requests."""
|
||||
if self.path != "/v1/operations":
|
||||
self._send_error_response(
|
||||
status_code=404,
|
||||
code=ErrorCode.ERR_TARGET_NOT_FOUND,
|
||||
message=f"Endpoint '{self.path}' not found. Supported endpoint: POST /v1/operations",
|
||||
)
|
||||
return
|
||||
|
||||
cl_header = self.headers.get("Content-Length")
|
||||
if cl_header is None:
|
||||
self._send_error_response(
|
||||
status_code=400,
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message="Missing Content-Length header",
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
content_length = int(cl_header.strip())
|
||||
except ValueError:
|
||||
self._send_error_response(
|
||||
status_code=400,
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message="Malformed Content-Length header",
|
||||
)
|
||||
return
|
||||
|
||||
if content_length < 0:
|
||||
self._send_error_response(
|
||||
status_code=400,
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message="Content-Length cannot be negative",
|
||||
)
|
||||
return
|
||||
|
||||
if content_length > MAX_REQUEST_BODY:
|
||||
self._send_error_response(
|
||||
status_code=400,
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message=f"Request body ({content_length} bytes) exceeds limit of {MAX_REQUEST_BODY} bytes",
|
||||
)
|
||||
return
|
||||
|
||||
raw_body = self.rfile.read(content_length)
|
||||
|
||||
try:
|
||||
body_dict = json.loads(raw_body.decode("utf-8"))
|
||||
except (json.JSONDecodeError, UnicodeDecodeError) as e:
|
||||
self._send_error_response(
|
||||
status_code=400,
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message=f"Invalid JSON payload: {e}",
|
||||
)
|
||||
return
|
||||
|
||||
if not isinstance(body_dict, dict):
|
||||
self._send_error_response(
|
||||
status_code=400,
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message="Payload root must be a JSON object mapping",
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
req = OperationRequest.model_validate(body_dict)
|
||||
except ValidationError as exc:
|
||||
sanitized = sanitize_validation_error(exc)
|
||||
self._send_operation_error(
|
||||
status_code=400,
|
||||
error=sanitized,
|
||||
operation=body_dict.get("operation") or body_dict.get("action"),
|
||||
target=body_dict.get("target"),
|
||||
)
|
||||
return
|
||||
|
||||
# Determine transport scheme and peer credentials
|
||||
is_unix = getattr(self.connection, "family", None) == socket.AF_UNIX
|
||||
transport = "unix_socket" if is_unix else "http"
|
||||
peer_uid: int | None = None
|
||||
|
||||
if is_unix:
|
||||
creds = extract_peer_credentials(self.connection)
|
||||
if creds is not None:
|
||||
_, peer_uid, _ = creds
|
||||
origin = f"peer_uid_{peer_uid}" if peer_uid is not None else "unix_socket"
|
||||
else:
|
||||
origin = self.address_string()
|
||||
|
||||
client_header = self.headers.get("User-Agent", "appctl-client/1.0")
|
||||
auth_header = self.headers.get("Authorization")
|
||||
|
||||
# Authenticate principal
|
||||
try:
|
||||
principal = authenticate_request(
|
||||
auth_header=auth_header,
|
||||
transport=transport,
|
||||
peer_uid=peer_uid,
|
||||
token_store=self.appctl_server.token_store,
|
||||
)
|
||||
except AuthenticationError as auth_err:
|
||||
op_id = generate_operation_id()
|
||||
auth_msg = str(auth_err)
|
||||
self.appctl_server.audit_logger.log_denied(
|
||||
operation_id=op_id,
|
||||
principal=PrincipalAudit(
|
||||
identity=f"peer_uid_{peer_uid}" if peer_uid is not None else "unknown",
|
||||
role="homelab-viewer" if is_unix else "unknown",
|
||||
token_id=None,
|
||||
auth_method="unix_peercred" if is_unix and auth_header is None else "bearer_token",
|
||||
),
|
||||
action=req.operation.value,
|
||||
target=req.target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client_header,
|
||||
parameters=req.parameters,
|
||||
error_code=auth_err.code.value,
|
||||
message=auth_msg,
|
||||
)
|
||||
self._send_operation_error(
|
||||
status_code=auth_err.code.http_status,
|
||||
error=OperationError(code=auth_err.code, message=auth_msg),
|
||||
operation=req.operation,
|
||||
target=req.target,
|
||||
op_id=op_id,
|
||||
)
|
||||
return
|
||||
|
||||
# Dispatch operation to OperationalRouter
|
||||
resp = self.appctl_server.router.dispatch(
|
||||
request=req,
|
||||
principal=principal,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client_header,
|
||||
)
|
||||
|
||||
status_code = resp.error.code.http_status if (not resp.success and resp.error) else 200
|
||||
self._send_operation_response(status_code, resp)
|
||||
|
||||
|
||||
class ThreadingUnixStreamServer(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
|
||||
"""Multi-threaded Unix Domain Socket HTTP server."""
|
||||
|
||||
daemon_threads = True
|
||||
allow_reuse_address = True
|
||||
|
||||
router: OperationalRouter
|
||||
token_store: TokenStore
|
||||
audit_logger: AuditLogger
|
||||
daemon_instance: AppctlDaemon
|
||||
|
||||
|
||||
class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
|
||||
"""Multi-threaded TCP Loopback HTTP server."""
|
||||
|
||||
daemon_threads = True
|
||||
allow_reuse_address = True
|
||||
|
||||
router: OperationalRouter
|
||||
token_store: TokenStore
|
||||
audit_logger: AuditLogger
|
||||
daemon_instance: AppctlDaemon
|
||||
|
||||
|
||||
class AppctlDaemon:
|
||||
"""
|
||||
Control Plane Daemon managing dual-transport operational listeners (UDS + TCP).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
router: OperationalRouter | None = None,
|
||||
token_store: TokenStore | None = None,
|
||||
audit_logger: AuditLogger | None = None,
|
||||
lock_manager: TargetLockManager | None = None,
|
||||
socket_path: Path | str | None = None,
|
||||
http_host: str | None = None,
|
||||
http_port: int | None = None,
|
||||
sites_dir: Path | str | None = None,
|
||||
core_dir: Path | str | None = None,
|
||||
deployments_file: Path | str | None = None,
|
||||
) -> None:
|
||||
self.socket_path = Path(socket_path or os.environ.get("APPCTL_SOCKET_PATH", DEFAULT_SOCKET_PATH))
|
||||
self.http_host = str(http_host or os.environ.get("APPCTL_HTTP_HOST", DEFAULT_HTTP_HOST))
|
||||
self.http_port = int(http_port or os.environ.get("APPCTL_HTTP_PORT", str(DEFAULT_HTTP_PORT)))
|
||||
|
||||
self.audit_logger = audit_logger or AuditLogger()
|
||||
self.token_store = token_store or TokenStore()
|
||||
self.lock_manager = lock_manager or TargetLockManager()
|
||||
|
||||
self.router = router or OperationalRouter(
|
||||
audit_logger=self.audit_logger,
|
||||
lock_manager=self.lock_manager,
|
||||
sites_dir=sites_dir or SITES_DIR,
|
||||
core_dir=core_dir or CORE_DIR,
|
||||
)
|
||||
|
||||
self.uds_server: ThreadingUnixStreamServer | None = None
|
||||
self.tcp_server: ThreadingHTTPServer | None = None
|
||||
self.uds_thread: threading.Thread | None = None
|
||||
self.tcp_thread: threading.Thread | None = None
|
||||
|
||||
self.running = False
|
||||
self.start_time: float = 0.0
|
||||
|
||||
def start(self) -> None:
|
||||
"""Bind both transports and start listener worker threads."""
|
||||
if self.running:
|
||||
return
|
||||
|
||||
self.start_time = time.time()
|
||||
|
||||
# 1. Prepare and bind UDS listener
|
||||
self.socket_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if self.socket_path.exists() or self.socket_path.is_socket():
|
||||
self.socket_path.unlink(missing_ok=True)
|
||||
|
||||
self.uds_server = ThreadingUnixStreamServer(str(self.socket_path), AppctlHTTPHandler)
|
||||
self.uds_server.router = self.router
|
||||
self.uds_server.token_store = self.token_store
|
||||
self.uds_server.audit_logger = self.audit_logger
|
||||
self.uds_server.daemon_instance = self
|
||||
|
||||
try:
|
||||
os.chmod(self.socket_path, 0o660)
|
||||
except OSError as e:
|
||||
logger.warning("Could not set mode 0660 on socket %s: %e", self.socket_path, e)
|
||||
|
||||
# 2. Prepare and bind TCP listener
|
||||
self.tcp_server = ThreadingHTTPServer((self.http_host, self.http_port), AppctlHTTPHandler)
|
||||
self.tcp_server.router = self.router
|
||||
self.tcp_server.token_store = self.token_store
|
||||
self.tcp_server.audit_logger = self.audit_logger
|
||||
self.tcp_server.daemon_instance = self
|
||||
|
||||
# 3. Start listener threads
|
||||
self.uds_thread = threading.Thread(target=self.uds_server.serve_forever, daemon=True, name="uds-listener")
|
||||
self.uds_thread.start()
|
||||
|
||||
self.tcp_thread = threading.Thread(target=self.tcp_server.serve_forever, daemon=True, name="tcp-listener")
|
||||
self.tcp_thread.start()
|
||||
|
||||
self.running = True
|
||||
logger.info(
|
||||
"appctl daemon started: UDS=%s, HTTP=%s:%d",
|
||||
self.socket_path,
|
||||
self.http_host,
|
||||
self.http_port,
|
||||
)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Gracefully shut down both transport servers and unlink socket."""
|
||||
if not self.running:
|
||||
return
|
||||
|
||||
self.running = False
|
||||
logger.info("Shutting down appctl daemon...")
|
||||
|
||||
if self.uds_server:
|
||||
self.uds_server.shutdown()
|
||||
self.uds_server.server_close()
|
||||
self.uds_server = None
|
||||
|
||||
if self.socket_path.exists() or self.socket_path.is_socket():
|
||||
self.socket_path.unlink(missing_ok=True)
|
||||
|
||||
if self.tcp_server:
|
||||
self.tcp_server.shutdown()
|
||||
self.tcp_server.server_close()
|
||||
self.tcp_server = None
|
||||
|
||||
if self.uds_thread and self.uds_thread.is_alive():
|
||||
self.uds_thread.join(timeout=2.0)
|
||||
self.uds_thread = None
|
||||
|
||||
if self.tcp_thread and self.tcp_thread.is_alive():
|
||||
self.tcp_thread.join(timeout=2.0)
|
||||
self.tcp_thread = None
|
||||
|
||||
logger.info("appctl daemon shut down successfully.")
|
||||
|
||||
def get_health_status(self) -> dict[str, Any]:
|
||||
"""Produce non-sensitive health metadata."""
|
||||
uptime = round(time.time() - self.start_time, 2) if self.running else 0.0
|
||||
return {
|
||||
"status": "healthy" if self.running else "stopped",
|
||||
"version": "1.0",
|
||||
"uptime_seconds": uptime,
|
||||
"transports": {
|
||||
"unix_socket": str(self.socket_path),
|
||||
"http_loopback": f"{self.http_host}:{self.http_port}",
|
||||
},
|
||||
"timestamp": current_iso_timestamp(),
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""CLI entrypoint for running the daemon."""
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] [appctl-daemon] %(message)s",
|
||||
handlers=[logging.StreamHandler(sys.stdout)],
|
||||
)
|
||||
|
||||
daemon = AppctlDaemon()
|
||||
|
||||
def handle_signal(sig: int, _frame: Any) -> None:
|
||||
logger.info("Received signal %d, stopping daemon...", sig)
|
||||
daemon.stop()
|
||||
sys.exit(0)
|
||||
|
||||
signal.signal(signal.SIGINT, handle_signal)
|
||||
signal.signal(signal.SIGTERM, handle_signal)
|
||||
|
||||
daemon.start()
|
||||
|
||||
try:
|
||||
while daemon.running:
|
||||
time.sleep(1.0)
|
||||
except KeyboardInterrupt:
|
||||
daemon.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,840 @@
|
||||
"""
|
||||
appctl_router.py — Operational Router & Unified Execution Engine (P4 Slice 4)
|
||||
|
||||
Implements the single command execution pipeline for homelab-appctl.service:
|
||||
- Pure-Python inert .env loader (enforcing ENV_KEY_RE, RESERVED_ENV_KEYS, zero shell evaluation)
|
||||
- Canonical domain precedence resolution (HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN)
|
||||
- Mandatory pre-flight validation (Path containment, parse_manifest, validate_compose_security)
|
||||
- Bounded subprocess execution engine (fixed argv, shell=False, 256 KiB output cap, hard timeouts)
|
||||
- Revision-consistent workload.update (clean tree check, git pull, post-pull validation, declared action execution)
|
||||
- Synchronous atomic Homepage compilation under _homepage_sync.lock
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from appctl_audit import (
|
||||
AuditLogger,
|
||||
AuditPersistenceError,
|
||||
ConcurrentMutationError,
|
||||
PrincipalAudit,
|
||||
TargetLockManager,
|
||||
current_iso_timestamp,
|
||||
generate_operation_id,
|
||||
redact_sensitive_data,
|
||||
)
|
||||
from appctl_auth import (
|
||||
AuthorizationError,
|
||||
Principal,
|
||||
Role,
|
||||
enforce_rbac,
|
||||
load_admitted_workloads,
|
||||
)
|
||||
from appctl_contracts import (
|
||||
MUTATING_OPERATIONS,
|
||||
SENSITIVE_READ_OPERATIONS,
|
||||
TARGET_REQUIRED_OPERATIONS,
|
||||
DeployParams,
|
||||
ErrorCode,
|
||||
GetParams,
|
||||
ListParams,
|
||||
LogsParams,
|
||||
OperationError,
|
||||
OperationRequest,
|
||||
OperationResponse,
|
||||
OperationType,
|
||||
UpdateParams,
|
||||
)
|
||||
from appctl_engine import (
|
||||
CORE_DIR as ENGINE_CORE_DIR,
|
||||
)
|
||||
from appctl_engine import (
|
||||
HOMELAB_DOMAIN as ENGINE_HOMELAB_DOMAIN,
|
||||
)
|
||||
from appctl_engine import (
|
||||
SITES_DIR as ENGINE_SITES_DIR,
|
||||
)
|
||||
from appctl_engine import (
|
||||
check_ssl_cert,
|
||||
cmd_sync_homepage,
|
||||
get_sites_apps,
|
||||
resolve_app,
|
||||
)
|
||||
from core_manifest import (
|
||||
ENV_KEY_RE,
|
||||
RESERVED_ENV_KEYS,
|
||||
Manifest,
|
||||
ManifestValidationError,
|
||||
parse_manifest,
|
||||
)
|
||||
from gitops_dispatcher import validate_compose_security
|
||||
|
||||
MAX_OUTPUT_BYTES = 256 * 1024 # 256 KiB cap per invocation
|
||||
|
||||
|
||||
class RouterValidationError(Exception):
|
||||
"""Raised when request payload or pre-flight validation fails (400 Bad Request)."""
|
||||
|
||||
def __init__(self, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.code = ErrorCode.ERR_VALIDATION_FAILED
|
||||
self.http_status = 400
|
||||
|
||||
|
||||
class RouterExecutionError(Exception):
|
||||
"""Raised when a subprocess or internal operation fails (500 Internal Error)."""
|
||||
|
||||
def __init__(self, message: str, exit_code: int = 1) -> None:
|
||||
super().__init__(message)
|
||||
self.code = ErrorCode.ERR_EXECUTION_FAILED
|
||||
self.exit_code = exit_code
|
||||
self.http_status = 500
|
||||
|
||||
|
||||
def parse_dotenv(path: Path, validate_keys: bool = True) -> dict[str, str]:
|
||||
"""
|
||||
Pure-Python inert KEY=VALUE parser.
|
||||
Never invokes a shell or evaluates variables. Enforces ENV_KEY_RE and RESERVED_ENV_KEYS.
|
||||
"""
|
||||
if not path.is_file():
|
||||
return {}
|
||||
|
||||
env: dict[str, str] = {}
|
||||
content = path.read_text(encoding="utf-8", errors="replace")
|
||||
for line_num, raw_line in enumerate(content.splitlines(), start=1):
|
||||
line = raw_line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if "=" not in line:
|
||||
continue
|
||||
key, val = line.split("=", 1)
|
||||
key = key.strip()
|
||||
val = val.strip()
|
||||
|
||||
# Strip optional surrounding single or double quotes
|
||||
if len(val) >= 2 and (
|
||||
(val.startswith('"') and val.endswith('"'))
|
||||
or (val.startswith("'") and val.endswith("'"))
|
||||
):
|
||||
val = val[1:-1]
|
||||
|
||||
if validate_keys:
|
||||
if not ENV_KEY_RE.match(key):
|
||||
raise RouterValidationError(
|
||||
f"Prohibited environment key syntax in {path.name}:{line_num}: '{key}'"
|
||||
)
|
||||
if key in RESERVED_ENV_KEYS:
|
||||
raise RouterValidationError(
|
||||
f"Prohibited reserved environment key in {path.name}:{line_num}: '{key}'"
|
||||
)
|
||||
env[key] = val
|
||||
return env
|
||||
|
||||
|
||||
def resolve_canonical_domain() -> str:
|
||||
"""Resolve canonical platform domain: HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN (fails closed)."""
|
||||
domain = (
|
||||
os.environ.get("HOMELAB_DOMAIN")
|
||||
or os.environ.get("DOMAIN_SUFFIX")
|
||||
or os.environ.get("DOMAIN")
|
||||
or ENGINE_HOMELAB_DOMAIN
|
||||
)
|
||||
if not domain or not domain.strip():
|
||||
raise RouterValidationError(
|
||||
"Canonical domain is unset: HOMELAB_DOMAIN, DOMAIN_SUFFIX, or DOMAIN must be configured."
|
||||
)
|
||||
return domain.strip()
|
||||
|
||||
|
||||
def assemble_workload_env(
|
||||
app_dir: Path,
|
||||
manifest: Manifest | None,
|
||||
app_name: str,
|
||||
) -> dict[str, str]:
|
||||
"""
|
||||
Assemble the 6-layer in-memory execution environment for Docker Compose subprocesses:
|
||||
1. Base PATH and DOCKER_CONFIG
|
||||
2. Global rendered secrets (homeserver.env, traefik-deployments.env)
|
||||
3. Canonical domain lock
|
||||
4. Infrastructure defaults (PROXY_NETWORK, CERT_RESOLVER, SERVICE_NAME, DOMAIN)
|
||||
5. Validated manifest.env from app.yaml
|
||||
6. Workload .env and app.env files parsed inertly
|
||||
"""
|
||||
env: dict[str, str] = {
|
||||
"PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"),
|
||||
}
|
||||
if "DOCKER_CONFIG" in os.environ:
|
||||
env["DOCKER_CONFIG"] = os.environ["DOCKER_CONFIG"]
|
||||
|
||||
# Layer 2: Global secrets from /run/secrets/rendered/ or /run/secrets/
|
||||
secrets_candidates = [
|
||||
Path("/run/secrets/rendered/homeserver.env"),
|
||||
Path("/run/secrets/homeserver.env"),
|
||||
Path("/run/secrets/rendered/traefik-deployments.env"),
|
||||
Path("/run/secrets/traefik-deployments.env"),
|
||||
]
|
||||
if "HOMESERVER_ENV_FILE" in os.environ:
|
||||
secrets_candidates.insert(0, Path(os.environ["HOMESERVER_ENV_FILE"]))
|
||||
|
||||
for sec_path in secrets_candidates:
|
||||
if sec_path.is_file():
|
||||
env.update(parse_dotenv(sec_path, validate_keys=False))
|
||||
|
||||
# Layer 3 & 4: Domain & Infrastructure defaults
|
||||
domain = resolve_canonical_domain()
|
||||
env["HOMELAB_DOMAIN"] = domain
|
||||
env["DOMAIN_SUFFIX"] = domain
|
||||
env["DOMAIN"] = domain
|
||||
env["PROXY_NETWORK"] = os.environ.get("PROXY_NETWORK", "proxy-net")
|
||||
env["CERT_RESOLVER"] = os.environ.get("CERT_RESOLVER", "myresolver")
|
||||
env["SERVICE_NAME"] = app_name
|
||||
env["CONTAINER_NAME"] = app_name
|
||||
env["SERVICE_DOMAIN"] = f"{app_name}.{domain}"
|
||||
|
||||
# Layer 5: Validated manifest env
|
||||
if manifest and manifest.env:
|
||||
env.update(manifest.env)
|
||||
|
||||
# Layer 6: Workload-scoped .env and app.env
|
||||
for local_env in [app_dir / ".env", app_dir / "app.env"]:
|
||||
if local_env.is_file():
|
||||
env.update(parse_dotenv(local_env, validate_keys=True))
|
||||
|
||||
return env
|
||||
|
||||
|
||||
def run_bounded_subprocess(
|
||||
cmd: list[str],
|
||||
cwd: Path | str | None = None,
|
||||
env: dict[str, str] | None = None,
|
||||
timeout: float = 300.0,
|
||||
) -> tuple[int, str, str]:
|
||||
"""
|
||||
Execute subprocess with fixed argv (shell=False), hard timeout, and 256 KiB output cap.
|
||||
Returns (exit_code, stdout_str, stderr_str).
|
||||
"""
|
||||
proc = subprocess.Popen(
|
||||
cmd,
|
||||
cwd=str(cwd) if cwd else None,
|
||||
env=env,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
shell=False,
|
||||
)
|
||||
try:
|
||||
raw_stdout, raw_stderr = proc.communicate(timeout=timeout)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
proc.kill()
|
||||
proc.communicate()
|
||||
raise RouterExecutionError(
|
||||
f"Command '{' '.join(cmd)}' timed out after {timeout} seconds",
|
||||
exit_code=124,
|
||||
) from exc
|
||||
|
||||
# Enforce 256 KiB cap on output
|
||||
stdout_str = raw_stdout[:MAX_OUTPUT_BYTES].decode("utf-8", errors="replace")
|
||||
if len(raw_stdout) > MAX_OUTPUT_BYTES:
|
||||
stdout_str += "\n[TRUNCATED: Output exceeded 256 KiB limit]"
|
||||
|
||||
stderr_str = raw_stderr[:MAX_OUTPUT_BYTES].decode("utf-8", errors="replace")
|
||||
if len(raw_stderr) > MAX_OUTPUT_BYTES:
|
||||
stderr_str += "\n[TRUNCATED: Stderr exceeded 256 KiB limit]"
|
||||
|
||||
return proc.returncode, stdout_str, stderr_str
|
||||
|
||||
|
||||
def validate_workload_preflight(
|
||||
app_dir: Path,
|
||||
allowed_root: Path,
|
||||
app_name: str | None = None,
|
||||
) -> tuple[Manifest, Path]:
|
||||
"""
|
||||
Enforce strict pre-flight gate:
|
||||
1. Target directory must be contained within allowed_root.
|
||||
2. app.yaml must parse cleanly via core_manifest.parse_manifest().
|
||||
3. docker-compose.yml must pass validate_compose_security().
|
||||
"""
|
||||
app_dir_resolved = app_dir.resolve()
|
||||
allowed_root_resolved = allowed_root.resolve()
|
||||
if not (
|
||||
app_dir_resolved == allowed_root_resolved
|
||||
or app_dir_resolved.is_relative_to(allowed_root_resolved)
|
||||
):
|
||||
raise RouterValidationError(
|
||||
f"Path traversal rejected: '{app_dir}' is outside '{allowed_root}'"
|
||||
)
|
||||
|
||||
manifest_file = app_dir / "app.yaml"
|
||||
if not manifest_file.is_file():
|
||||
raise RouterValidationError(f"Workload manifest not found at '{manifest_file}'")
|
||||
|
||||
try:
|
||||
manifest = parse_manifest(manifest_file)
|
||||
except ManifestValidationError as err:
|
||||
raise RouterValidationError(f"Workload manifest validation failed: {err}") from err
|
||||
|
||||
effective_name = app_name or manifest.name
|
||||
compose_file = app_dir / "docker-compose.yml"
|
||||
if compose_file.exists():
|
||||
ok, reason = validate_compose_security(
|
||||
compose_file=compose_file,
|
||||
allowed_root=app_dir,
|
||||
app_name=effective_name,
|
||||
)
|
||||
if not ok:
|
||||
raise RouterValidationError(
|
||||
f"Compose AST security validation failed for '{effective_name}': {reason}"
|
||||
)
|
||||
|
||||
return manifest, compose_file
|
||||
|
||||
|
||||
class OperationalRouter:
|
||||
"""Executes validated domain operations according to P4 boundaries and contracts."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
audit_logger: AuditLogger | None = None,
|
||||
lock_manager: TargetLockManager | None = None,
|
||||
sites_dir: Path | str | None = None,
|
||||
core_dir: Path | str | None = None,
|
||||
) -> None:
|
||||
self.audit_logger = audit_logger or AuditLogger()
|
||||
self.lock_manager = lock_manager or TargetLockManager()
|
||||
self.sites_dir = Path(sites_dir or ENGINE_SITES_DIR)
|
||||
self.core_dir = Path(core_dir or ENGINE_CORE_DIR)
|
||||
|
||||
def dispatch(
|
||||
self,
|
||||
request: OperationRequest,
|
||||
principal: Principal,
|
||||
transport: str = "unix_socket",
|
||||
origin: str = "peer_uid_1000",
|
||||
client: str = "appctl-cli/2.0",
|
||||
) -> OperationResponse:
|
||||
"""Single entrypoint dispatching all 13 canonical domain operations."""
|
||||
op_id = generate_operation_id()
|
||||
start_time = time.perf_counter()
|
||||
target = request.target
|
||||
operation = request.operation
|
||||
admitted = load_admitted_workloads()
|
||||
principal_audit = PrincipalAudit(
|
||||
identity=principal.identity,
|
||||
role=principal.role.value,
|
||||
token_id=principal.token_id,
|
||||
auth_method=principal.auth_method,
|
||||
)
|
||||
|
||||
# 1. RBAC Gate
|
||||
try:
|
||||
enforce_rbac(
|
||||
principal=principal,
|
||||
operation=operation,
|
||||
target=target,
|
||||
admitted_workloads=admitted,
|
||||
)
|
||||
except AuthorizationError as err:
|
||||
self.audit_logger.log_denied(
|
||||
operation_id=op_id,
|
||||
principal=principal_audit,
|
||||
action=operation.value,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=request.parameters,
|
||||
error_code=err.code.value,
|
||||
message=str(err),
|
||||
)
|
||||
return OperationResponse(
|
||||
version="1.0",
|
||||
success=False,
|
||||
operation_id=op_id,
|
||||
operation=operation,
|
||||
target=target,
|
||||
error=OperationError(code=err.code, message=str(err)),
|
||||
)
|
||||
|
||||
# 2. Target Resolution (for operations requiring target)
|
||||
resolved_app = None
|
||||
if operation in TARGET_REQUIRED_OPERATIONS:
|
||||
if not target:
|
||||
return OperationResponse(
|
||||
version="1.0",
|
||||
success=False,
|
||||
operation_id=op_id,
|
||||
operation=operation,
|
||||
target=target,
|
||||
error=OperationError(
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message=f"Operation '{operation.value}' requires a non-empty target",
|
||||
),
|
||||
)
|
||||
resolved_app = resolve_app(target, sites_dir=str(self.sites_dir))
|
||||
if not resolved_app:
|
||||
return OperationResponse(
|
||||
version="1.0",
|
||||
success=False,
|
||||
operation_id=op_id,
|
||||
operation=operation,
|
||||
target=target,
|
||||
error=OperationError(
|
||||
code=ErrorCode.ERR_TARGET_NOT_FOUND,
|
||||
message=f"Workload or core target '{target}' not found",
|
||||
),
|
||||
)
|
||||
|
||||
# 3. Concurrency Lock & Pre-Execution Audit (Mutating Operations)
|
||||
if operation in MUTATING_OPERATIONS:
|
||||
lock_ctx = (
|
||||
self.lock_manager.homepage_sync_lock()
|
||||
if operation == OperationType.PLATFORM_SYNC_HOMEPAGE
|
||||
else self.lock_manager.lock_target(target or "_unknown")
|
||||
)
|
||||
try:
|
||||
with lock_ctx:
|
||||
# Fail-closed pre-execution DISPATCHED audit guard
|
||||
try:
|
||||
self.audit_logger.log_dispatched(
|
||||
operation_id=op_id,
|
||||
principal=principal_audit,
|
||||
action=operation.value,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=request.parameters,
|
||||
)
|
||||
except AuditPersistenceError as audit_err:
|
||||
return OperationResponse(
|
||||
version="1.0",
|
||||
success=False,
|
||||
operation_id=op_id,
|
||||
operation=operation,
|
||||
target=target,
|
||||
error=OperationError(
|
||||
code=ErrorCode.ERR_EXECUTION_FAILED,
|
||||
message=f"Pre-execution audit guard failed: {audit_err}",
|
||||
),
|
||||
)
|
||||
|
||||
# Execute Mutation
|
||||
return self._execute_operation(
|
||||
request=request,
|
||||
principal=principal,
|
||||
principal_audit=principal_audit,
|
||||
resolved_app=resolved_app,
|
||||
op_id=op_id,
|
||||
start_time=start_time,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
)
|
||||
except ConcurrentMutationError as lock_err:
|
||||
self.audit_logger.log_denied(
|
||||
operation_id=op_id,
|
||||
principal=principal_audit,
|
||||
action=operation.value,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=request.parameters,
|
||||
error_code=ErrorCode.ERR_CONCURRENT_MUTATION.value,
|
||||
message=str(lock_err),
|
||||
)
|
||||
return OperationResponse(
|
||||
version="1.0",
|
||||
success=False,
|
||||
operation_id=op_id,
|
||||
operation=operation,
|
||||
target=target,
|
||||
error=OperationError(
|
||||
code=ErrorCode.ERR_CONCURRENT_MUTATION,
|
||||
message=str(lock_err),
|
||||
),
|
||||
)
|
||||
|
||||
# 4. Read-Only Operations (no concurrency lock required)
|
||||
return self._execute_operation(
|
||||
request=request,
|
||||
principal=principal,
|
||||
principal_audit=principal_audit,
|
||||
resolved_app=resolved_app,
|
||||
op_id=op_id,
|
||||
start_time=start_time,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
)
|
||||
|
||||
def _execute_operation(
|
||||
self,
|
||||
request: OperationRequest,
|
||||
principal: Principal,
|
||||
principal_audit: PrincipalAudit,
|
||||
resolved_app: Any,
|
||||
op_id: str,
|
||||
start_time: float,
|
||||
transport: str,
|
||||
origin: str,
|
||||
client: str,
|
||||
) -> OperationResponse:
|
||||
"""Route to specific operation handler with post-execution audit logging."""
|
||||
operation = request.operation
|
||||
target = request.target
|
||||
commit_sha: str | None = None
|
||||
duration_ms = 0
|
||||
|
||||
try:
|
||||
if operation == OperationType.WORKLOAD_LIST:
|
||||
result_data = self._op_workload_list(request)
|
||||
elif operation == OperationType.WORKLOAD_GET:
|
||||
result_data = self._op_workload_get(request, resolved_app)
|
||||
elif operation == OperationType.WORKLOAD_RESOLVE:
|
||||
result_data = self._op_workload_resolve(resolved_app)
|
||||
elif operation == OperationType.PLATFORM_SSL:
|
||||
result_data = self._op_platform_ssl(target)
|
||||
elif operation == OperationType.PLATFORM_HEALTH:
|
||||
result_data = self._op_platform_health()
|
||||
elif operation == OperationType.WORKLOAD_CONFIG:
|
||||
result_data = self._op_workload_config(resolved_app, principal)
|
||||
elif operation == OperationType.WORKLOAD_LOGS:
|
||||
result_data = self._op_workload_logs(request, resolved_app)
|
||||
elif operation == OperationType.WORKLOAD_DEPLOY:
|
||||
result_data = self._op_workload_deploy(request, resolved_app)
|
||||
elif operation == OperationType.WORKLOAD_STOP:
|
||||
result_data = self._op_workload_stop(resolved_app)
|
||||
elif operation == OperationType.WORKLOAD_RESTART:
|
||||
result_data = self._op_workload_restart(resolved_app)
|
||||
elif operation == OperationType.WORKLOAD_PULL:
|
||||
result_data = self._op_workload_pull(resolved_app)
|
||||
elif operation == OperationType.WORKLOAD_UPDATE:
|
||||
result_data, commit_sha = self._op_workload_update(request, resolved_app)
|
||||
elif operation == OperationType.PLATFORM_SYNC_HOMEPAGE:
|
||||
result_data = self._op_platform_sync_homepage()
|
||||
else:
|
||||
raise RouterValidationError(f"Unsupported operation: {operation.value}")
|
||||
|
||||
duration_ms = int((time.perf_counter() - start_time) * 1000)
|
||||
|
||||
# Audit COMPLETED for mutating ops and sensitive reads
|
||||
if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS:
|
||||
self.audit_logger.log_completed(
|
||||
operation_id=op_id,
|
||||
principal=principal_audit,
|
||||
action=operation.value,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=request.parameters,
|
||||
duration_ms=duration_ms,
|
||||
commit_sha=commit_sha,
|
||||
message=result_data.get("message", "Operation completed successfully"),
|
||||
)
|
||||
|
||||
return OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id=op_id,
|
||||
operation=operation,
|
||||
target=target,
|
||||
result=result_data,
|
||||
output=result_data.get("output", ""),
|
||||
duration_ms=duration_ms,
|
||||
timestamp=current_iso_timestamp(),
|
||||
)
|
||||
|
||||
except (RouterValidationError, RouterExecutionError) as err:
|
||||
duration_ms = int((time.perf_counter() - start_time) * 1000)
|
||||
if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS:
|
||||
self.audit_logger.log_failed(
|
||||
operation_id=op_id,
|
||||
principal=principal_audit,
|
||||
action=operation.value,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=request.parameters,
|
||||
duration_ms=duration_ms,
|
||||
exit_code=getattr(err, "exit_code", 1),
|
||||
error_code=err.code.value,
|
||||
message=str(err),
|
||||
)
|
||||
return OperationResponse(
|
||||
version="1.0",
|
||||
success=False,
|
||||
operation_id=op_id,
|
||||
operation=operation,
|
||||
target=target,
|
||||
duration_ms=duration_ms,
|
||||
error=OperationError(code=err.code, message=str(err)),
|
||||
)
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# Domain Operation Implementations
|
||||
# -----------------------------------------------------------------------
|
||||
|
||||
def _op_workload_list(self, request: OperationRequest) -> dict[str, Any]:
|
||||
params = request.parse_parameters()
|
||||
assert isinstance(params, ListParams)
|
||||
apps = get_sites_apps(sites_dir=str(self.sites_dir))
|
||||
apps_data = [a.to_dict() for a in apps]
|
||||
return {
|
||||
"total": len(apps_data),
|
||||
"workloads": apps_data,
|
||||
"message": f"Found {len(apps_data)} workloads",
|
||||
}
|
||||
|
||||
def _op_workload_get(self, request: OperationRequest, app: Any) -> dict[str, Any]:
|
||||
params = request.parse_parameters()
|
||||
assert isinstance(params, GetParams)
|
||||
data = app.to_dict()
|
||||
return {"workload": data, "message": f"Retrieved metadata for {app.name}"}
|
||||
|
||||
def _op_workload_resolve(self, app: Any) -> dict[str, Any]:
|
||||
return {"workload": app.to_dict(), "message": f"Resolved target to {app.name}"}
|
||||
|
||||
def _op_platform_ssl(self, target: str | None) -> dict[str, Any]:
|
||||
domain = target or resolve_canonical_domain()
|
||||
try:
|
||||
cert_info = check_ssl_cert(domain)
|
||||
return {"ssl": cert_info, "message": f"SSL certificate inspected for {domain}"}
|
||||
except Exception as err:
|
||||
raise RouterExecutionError(f"SSL inspection failed for '{domain}': {err}") from err
|
||||
|
||||
def _op_platform_health(self) -> dict[str, Any]:
|
||||
return {
|
||||
"status": "healthy",
|
||||
"audit_log": str(self.audit_logger.log_path),
|
||||
"lock_dir": str(self.lock_manager.lock_dir),
|
||||
"message": "Control plane daemon healthy",
|
||||
}
|
||||
|
||||
def _op_workload_config(self, app: Any, principal: Principal) -> dict[str, Any]:
|
||||
app_dir = Path(app.dir_path)
|
||||
manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name)
|
||||
env = assemble_workload_env(app_dir, manifest, app.name)
|
||||
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "config"]
|
||||
code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose config failed: {stderr}", exit_code=code)
|
||||
|
||||
config_output = stdout
|
||||
if principal.role != Role.ADMIN:
|
||||
# Redact secrets for non-admin callers
|
||||
config_output = redact_sensitive_data(config_output)
|
||||
|
||||
return {"output": config_output, "message": "Evaluated compose configuration"}
|
||||
|
||||
def _op_workload_logs(self, request: OperationRequest, app: Any) -> dict[str, Any]:
|
||||
params = request.parse_parameters()
|
||||
assert isinstance(params, LogsParams)
|
||||
app_dir = Path(app.dir_path)
|
||||
manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name)
|
||||
env = assemble_workload_env(app_dir, manifest, app.name)
|
||||
|
||||
cmd = [
|
||||
"docker",
|
||||
"compose",
|
||||
"-f",
|
||||
str(compose_file),
|
||||
"logs",
|
||||
"--no-color",
|
||||
"--tail",
|
||||
str(params.tail),
|
||||
]
|
||||
code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose logs failed: {stderr}", exit_code=code)
|
||||
|
||||
return {"output": stdout, "tail": params.tail, "message": f"Tail {params.tail} logs"}
|
||||
|
||||
def _op_workload_deploy(self, request: OperationRequest, app: Any) -> dict[str, Any]:
|
||||
params = request.parse_parameters()
|
||||
assert isinstance(params, DeployParams)
|
||||
app_dir = Path(app.dir_path)
|
||||
manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name)
|
||||
env = assemble_workload_env(app_dir, manifest, app.name)
|
||||
|
||||
# Optional build
|
||||
if params.build:
|
||||
build_cmd = ["docker", "compose", "-f", str(compose_file), "build"]
|
||||
code, out, err = run_bounded_subprocess(build_cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose build failed: {err}", exit_code=code)
|
||||
|
||||
# Deploy up
|
||||
up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d"]
|
||||
if params.remove_orphans:
|
||||
up_cmd.append("--remove-orphans")
|
||||
|
||||
code, out, err = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose up failed: {err}", exit_code=code)
|
||||
|
||||
# Trigger Homepage sync
|
||||
self._trigger_homepage_sync()
|
||||
|
||||
return {
|
||||
"output": out,
|
||||
"action": "deployed",
|
||||
"message": f"Workload '{app.name}' deployed successfully",
|
||||
}
|
||||
|
||||
def _op_workload_stop(self, app: Any) -> dict[str, Any]:
|
||||
app_dir = Path(app.dir_path)
|
||||
manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name)
|
||||
env = assemble_workload_env(app_dir, manifest, app.name)
|
||||
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "down"]
|
||||
code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose down failed: {err}", exit_code=code)
|
||||
|
||||
self._trigger_homepage_sync()
|
||||
return {"output": out, "action": "stopped", "message": f"Workload '{app.name}' stopped"}
|
||||
|
||||
def _op_workload_restart(self, app: Any) -> dict[str, Any]:
|
||||
app_dir = Path(app.dir_path)
|
||||
manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name)
|
||||
env = assemble_workload_env(app_dir, manifest, app.name)
|
||||
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "restart"]
|
||||
code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose restart failed: {err}", exit_code=code)
|
||||
|
||||
self._trigger_homepage_sync()
|
||||
return {"output": out, "action": "restarted", "message": f"Workload '{app.name}' restarted"}
|
||||
|
||||
def _op_workload_pull(self, app: Any) -> dict[str, Any]:
|
||||
app_dir = Path(app.dir_path)
|
||||
manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name)
|
||||
env = assemble_workload_env(app_dir, manifest, app.name)
|
||||
|
||||
pull_cmd = ["docker", "compose", "-f", str(compose_file), "pull"]
|
||||
code, _, err = run_bounded_subprocess(pull_cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose pull failed: {err}", exit_code=code)
|
||||
|
||||
up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"]
|
||||
code, out_up, err_up = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose up failed after pull: {err_up}", exit_code=code)
|
||||
|
||||
self._trigger_homepage_sync()
|
||||
return {"output": out_up, "action": "pulled", "message": f"Workload '{app.name}' pulled and updated"}
|
||||
|
||||
def _op_workload_update(
|
||||
self, request: OperationRequest, app: Any
|
||||
) -> tuple[dict[str, Any], str | None]:
|
||||
"""
|
||||
Revision-consistent workload update pipeline (DEC-04):
|
||||
1. Clean working tree check (git status --porcelain, 5s)
|
||||
2. git pull --ff-only (60s)
|
||||
3. Post-pull re-validation of app.yaml & expected_branch & compose security
|
||||
4. Execute declared actions (compose_pull, compose_build, compose_up, compose_restart)
|
||||
5. Homepage sync
|
||||
"""
|
||||
params = request.parse_parameters()
|
||||
assert isinstance(params, UpdateParams)
|
||||
app_dir = Path(app.dir_path)
|
||||
|
||||
# 1. Clean working tree check
|
||||
code, status_out, _ = run_bounded_subprocess(
|
||||
["git", "-C", str(app_dir), "status", "--porcelain"],
|
||||
cwd=app_dir,
|
||||
timeout=5.0,
|
||||
)
|
||||
if code != 0 or status_out.strip():
|
||||
raise RouterValidationError(
|
||||
f"Workload '{app.name}' has uncommitted changes in git working tree; update aborted."
|
||||
)
|
||||
|
||||
# 2. git pull --ff-only
|
||||
pull_cmd = ["git", "-C", str(app_dir), "pull", "--ff-only"]
|
||||
if params.expected_branch:
|
||||
pull_cmd.extend(["origin", params.expected_branch])
|
||||
code, pull_out, pull_err = run_bounded_subprocess(
|
||||
pull_cmd, cwd=app_dir, timeout=60.0
|
||||
)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"git pull failed for '{app.name}': {pull_err}", exit_code=code)
|
||||
|
||||
# 3. Post-pull re-validation of manifest and expected_branch
|
||||
manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name)
|
||||
if (
|
||||
params.expected_branch
|
||||
and manifest.source
|
||||
and manifest.source.ref != params.expected_branch
|
||||
):
|
||||
raise RouterValidationError(
|
||||
f"Post-pull branch mismatch for '{app.name}': expected '{params.expected_branch}', "
|
||||
f"manifest declared '{manifest.source.ref}'"
|
||||
)
|
||||
|
||||
# 4. Execute declared actions from manifest
|
||||
env = assemble_workload_env(app_dir, manifest, app.name)
|
||||
declared_actions = manifest.deployment.actions or ["compose_up"]
|
||||
output_log = [f"git: {pull_out.strip()}"]
|
||||
|
||||
for action in declared_actions:
|
||||
if action == "git_pull":
|
||||
continue # already executed in step 2
|
||||
elif action == "compose_pull":
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "pull"]
|
||||
elif action == "compose_build" or (params.build and action == "compose_up"):
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "build"]
|
||||
elif action == "compose_up":
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"]
|
||||
elif action == "compose_restart":
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "restart"]
|
||||
else:
|
||||
continue
|
||||
|
||||
code, act_out, act_err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(
|
||||
f"Action '{action}' failed during workload.update for '{app.name}': {act_err}",
|
||||
exit_code=code,
|
||||
)
|
||||
output_log.append(f"{action}: {act_out.strip()}")
|
||||
|
||||
# 5. Extract current commit SHA
|
||||
_, sha_out, _ = run_bounded_subprocess(
|
||||
["git", "-C", str(app_dir), "rev-parse", "--short", "HEAD"],
|
||||
cwd=app_dir,
|
||||
timeout=5.0,
|
||||
)
|
||||
commit_sha = sha_out.strip() or None
|
||||
|
||||
# 6. Trigger Homepage sync
|
||||
self._trigger_homepage_sync()
|
||||
|
||||
return {
|
||||
"output": "\n".join(output_log),
|
||||
"commit_sha": commit_sha,
|
||||
"actions": declared_actions,
|
||||
"message": f"Workload '{app.name}' updated and reconciled successfully",
|
||||
}, commit_sha
|
||||
|
||||
def _op_platform_sync_homepage(self) -> dict[str, Any]:
|
||||
self._trigger_homepage_sync()
|
||||
return {"action": "sync_homepage", "message": "Homepage dashboard synchronized successfully"}
|
||||
|
||||
def _trigger_homepage_sync(self) -> None:
|
||||
"""Atomic compile of Homepage dashboard services.yaml under _homepage_sync.lock."""
|
||||
try:
|
||||
cmd_sync_homepage()
|
||||
except (OSError, ValueError, RuntimeError) as exc:
|
||||
import sys
|
||||
print(f"Warning: Homepage sync non-fatal error: {exc}", file=sys.stderr)
|
||||
@@ -75,7 +75,7 @@ RESERVED_ENV_KEYS = {
|
||||
}
|
||||
|
||||
ALLOWED_STRATEGIES = {"compose"}
|
||||
ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"}
|
||||
ALLOWED_ACTIONS = {"git_pull", "compose_pull", "compose_up", "compose_build", "compose_restart"}
|
||||
|
||||
|
||||
def validate_transport(url: str) -> tuple[TransportScheme, str]:
|
||||
@@ -260,7 +260,7 @@ class DeploymentConfig(BaseModel):
|
||||
act_str = str(act).strip().lower()
|
||||
if act_str not in ALLOWED_ACTIONS:
|
||||
raise ManifestValidationError(
|
||||
f"Prohibited deployment action '{act_str}'. Allowed: {sorted(ALLOWED_ACTIONS)}"
|
||||
f"Unsupported deployment action '{act_str}' (Prohibited deployment action '{act_str}'). Allowed: {sorted(ALLOWED_ACTIONS)}"
|
||||
)
|
||||
actions.append(act_str)
|
||||
if not actions:
|
||||
|
||||
+108
-12
@@ -12,6 +12,7 @@ import datetime
|
||||
import fcntl
|
||||
import hashlib
|
||||
import hmac
|
||||
import http.client
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -19,6 +20,16 @@ import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from appctl_contracts import OperationRequest, OperationType
|
||||
from core_manifest import (
|
||||
ALLOWED_ACTIONS,
|
||||
ALLOWED_STRATEGIES,
|
||||
ManifestValidationError,
|
||||
parse_manifest,
|
||||
)
|
||||
from pydantic import ValidationError
|
||||
|
||||
try:
|
||||
import yaml
|
||||
@@ -39,6 +50,12 @@ DEFAULT_SECRET_PATH = Path(
|
||||
STATE_DIR = Path(
|
||||
os.environ.get("GITOPS_STATE_DIR", Path.home() / ".local/state/homelab/gitops")
|
||||
)
|
||||
DEFAULT_APPCTL_SOCKET_PATH = Path(
|
||||
os.environ.get("APPCTL_SOCKET_PATH", "/run/homelab/appctl.sock")
|
||||
)
|
||||
DEFAULT_APPCTL_TOKEN_PATH = Path(
|
||||
os.environ.get("GITOPS_APPCTL_TOKEN_FILE", "/run/secrets/gitops/appctl_token")
|
||||
)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
@@ -48,6 +65,70 @@ logging.basicConfig(
|
||||
logger = logging.getLogger("gitops_dispatcher")
|
||||
|
||||
|
||||
def load_appctl_token(token_file: Path | None = None) -> str | None:
|
||||
"""
|
||||
Load Bearer token for appctl daemon communication from environment or secrets file.
|
||||
"""
|
||||
if "GITOPS_APPCTL_TOKEN" in os.environ:
|
||||
return os.environ["GITOPS_APPCTL_TOKEN"].strip()
|
||||
path = token_file or DEFAULT_APPCTL_TOKEN_PATH
|
||||
if path.is_file():
|
||||
try:
|
||||
return path.read_text(encoding="utf-8").strip()
|
||||
except OSError as e:
|
||||
logger.error(f"Failed to read appctl token from {path}: {e}")
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def execute_deployment_via_daemon(
|
||||
target: str,
|
||||
branch: str,
|
||||
socket_path: Path | str | None = None,
|
||||
token: str | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Execute deployment by delegating workload.update to appctl daemon over UDS.
|
||||
"""
|
||||
sock = Path(socket_path or DEFAULT_APPCTL_SOCKET_PATH)
|
||||
auth_token = token or load_appctl_token()
|
||||
logger.info(
|
||||
f"Delegating workload.update for '{target}' to daemon at {sock} (branch: {branch})"
|
||||
)
|
||||
from appctl_daemon import send_daemon_request
|
||||
|
||||
try:
|
||||
req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_UPDATE,
|
||||
target=target,
|
||||
parameters={"expected_branch": branch},
|
||||
)
|
||||
resp = send_daemon_request(
|
||||
endpoint=sock,
|
||||
operation_request=req,
|
||||
token=auth_token,
|
||||
timeout=330.0,
|
||||
)
|
||||
if resp.success:
|
||||
logger.info(f"✨ Deployment of '{target}' via daemon completed successfully.")
|
||||
return True
|
||||
err_msg = resp.error.message if resp.error else "Unknown daemon error"
|
||||
logger.error(f"❌ Deployment of '{target}' via daemon failed: {err_msg}")
|
||||
return False
|
||||
except (
|
||||
OSError,
|
||||
http.client.HTTPException,
|
||||
json.JSONDecodeError,
|
||||
ValidationError,
|
||||
TimeoutError,
|
||||
KeyError,
|
||||
TypeError,
|
||||
ValueError,
|
||||
) as e:
|
||||
logger.error(f"❌ Failed to communicate with appctl daemon at {sock}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def load_webhook_secret(secret_file: Path | None = None) -> bytes:
|
||||
"""
|
||||
Load webhook shared secret from projected secret file or environment.
|
||||
@@ -204,7 +285,11 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
|
||||
raw_path = entry.get("path")
|
||||
if not raw_path:
|
||||
continue
|
||||
p = Path(raw_path).expanduser().resolve()
|
||||
if raw_path.startswith("~/Sites/") or raw_path == "~/Sites":
|
||||
sub = raw_path[len("~/Sites"):].lstrip("/")
|
||||
p = (SITES_DIR / sub).resolve() if sub else SITES_DIR.resolve()
|
||||
else:
|
||||
p = Path(raw_path).expanduser().resolve()
|
||||
# Enforce strict containment strictly inside SITES_DIR
|
||||
if SITES_DIR.is_dir() and p.is_relative_to(SITES_DIR.resolve()):
|
||||
mapping[reg_name] = p
|
||||
@@ -322,8 +407,6 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
|
||||
return target_dir, deployment_config
|
||||
|
||||
|
||||
ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"}
|
||||
ALLOWED_STRATEGIES = {"compose"}
|
||||
|
||||
|
||||
PROHIBITED_HOST_NAMESPACES = {"host"}
|
||||
@@ -630,6 +713,15 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
||||
)
|
||||
return True
|
||||
|
||||
daemon_sock = Path(os.environ.get("APPCTL_SOCKET_PATH", DEFAULT_APPCTL_SOCKET_PATH))
|
||||
if daemon_sock.is_socket():
|
||||
canonical_app_name = target_dir.name.removeprefix("homelab-")
|
||||
return execute_deployment_via_daemon(
|
||||
target=canonical_app_name,
|
||||
branch=expected_branch,
|
||||
socket_path=daemon_sock,
|
||||
)
|
||||
|
||||
canonical_app_name = target_dir.name.removeprefix("homelab-")
|
||||
manifest_file = target_dir / "app.yaml"
|
||||
if manifest_file.is_file():
|
||||
@@ -903,22 +995,26 @@ def admit_deployment(
|
||||
|
||||
# 4. Manifest & Strategy Validation
|
||||
manifest_file = target_dir / "app.yaml"
|
||||
manifest = {}
|
||||
manifest: dict[str, Any] = {}
|
||||
if manifest_file.is_file():
|
||||
try:
|
||||
manifest_text = manifest_file.read_text(encoding="utf-8")
|
||||
manifest = (
|
||||
yaml.safe_load(manifest_text)
|
||||
if yaml
|
||||
else parse_yaml_simple(manifest_text)
|
||||
) or {}
|
||||
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
||||
parsed_manifest = parse_manifest(manifest_file)
|
||||
manifest = parsed_manifest.model_dump()
|
||||
except ManifestValidationError as e:
|
||||
return (
|
||||
False,
|
||||
None,
|
||||
{},
|
||||
pushed_branch,
|
||||
f"Failed to parse manifest {manifest_file}: {e}",
|
||||
f"Manifest validation error: {e}",
|
||||
)
|
||||
except OSError as e:
|
||||
return (
|
||||
False,
|
||||
None,
|
||||
{},
|
||||
pushed_branch,
|
||||
f"Failed to read manifest {manifest_file}: {e}",
|
||||
)
|
||||
|
||||
valid, err_msg = validate_manifest_deployment(manifest)
|
||||
|
||||
@@ -180,13 +180,20 @@ exit 0
|
||||
def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests():
|
||||
"""Ensure personal domains and operator usernames are absent from scripts, tests, and documentation."""
|
||||
forbidden = ["roadtotech.me", "kiskaadee"]
|
||||
root_dirs = [CORE_ROOT / "scripts", CORE_ROOT / "tests", CORE_ROOT / "docs"]
|
||||
root_dirs = [
|
||||
CORE_ROOT / "scripts",
|
||||
CORE_ROOT / "tests",
|
||||
CORE_ROOT / "docs",
|
||||
CORE_ROOT / "nixos" / "modules",
|
||||
CORE_ROOT / "config",
|
||||
]
|
||||
root_files = [
|
||||
CORE_ROOT / "README.md",
|
||||
CORE_ROOT / "ROADMAP.md",
|
||||
CORE_ROOT / "AGENTS.md",
|
||||
CORE_ROOT / "SECURITY.md",
|
||||
CORE_ROOT / "flake.nix",
|
||||
CORE_ROOT / "docker-compose.yml",
|
||||
]
|
||||
violations = []
|
||||
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
"""
|
||||
tests/unit/test_appctl_audit.py — Unit Tests for Audit Logger & Concurrency Lock (P4 Slice 2)
|
||||
|
||||
Behavior-driven test naming convention:
|
||||
test_<subject>_<accepts|rejects|enforces>_<condition>
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from appctl_audit import (
|
||||
AuditEvent,
|
||||
AuditLogger,
|
||||
AuditPersistenceError,
|
||||
AuditPhase,
|
||||
ConcurrentMutationError,
|
||||
PrincipalAudit,
|
||||
TargetLockManager,
|
||||
redact_sensitive_data,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_audit_file(tmp_path: Path) -> Path:
|
||||
return tmp_path / "audit" / "audit.jsonl"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_lock_dir(tmp_path: Path) -> Path:
|
||||
lock_dir = tmp_path / "locks"
|
||||
lock_dir.mkdir(parents=True, exist_ok=True)
|
||||
return lock_dir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_principal() -> PrincipalAudit:
|
||||
return PrincipalAudit(
|
||||
identity="operator",
|
||||
role="homelab-admin",
|
||||
token_id="tok_admin_01",
|
||||
auth_method="bearer_token",
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# File Permissions & Initialization
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_audit_logger_enforces_0600_permissions_on_creation(
|
||||
temp_audit_file: Path, sample_principal: PrincipalAudit
|
||||
):
|
||||
logger = AuditLogger(temp_audit_file)
|
||||
logger.log_dispatched(
|
||||
operation_id="op_100",
|
||||
principal=sample_principal,
|
||||
action="workload.deploy",
|
||||
target="snappymail",
|
||||
transport="unix_socket",
|
||||
origin="peer_uid_1000",
|
||||
client="appctl-cli/2.0",
|
||||
parameters={"recreate": True},
|
||||
)
|
||||
|
||||
assert temp_audit_file.exists()
|
||||
mode = stat.S_IMODE(temp_audit_file.stat().st_mode)
|
||||
assert mode == 0o600
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Audit Phases & RFC JSONL Schema
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_audit_logger_writes_valid_jsonl_lifecycle(
|
||||
temp_audit_file: Path, sample_principal: PrincipalAudit
|
||||
):
|
||||
logger = AuditLogger(temp_audit_file)
|
||||
|
||||
# 1. DISPATCHED
|
||||
evt_disp = logger.log_dispatched(
|
||||
operation_id="op_101",
|
||||
principal=sample_principal,
|
||||
action="workload.update",
|
||||
target="jellyfin",
|
||||
transport="http",
|
||||
origin="127.0.0.1:48291",
|
||||
client="gitops-dispatcher/1.0",
|
||||
parameters={"expected_branch": "main", "build": False},
|
||||
)
|
||||
assert evt_disp.phase == AuditPhase.DISPATCHED
|
||||
assert evt_disp.result is not None
|
||||
assert evt_disp.result.status == "IN_PROGRESS"
|
||||
|
||||
# 2. COMPLETED
|
||||
evt_comp = logger.log_completed(
|
||||
operation_id="op_101",
|
||||
principal=sample_principal,
|
||||
action="workload.update",
|
||||
target="jellyfin",
|
||||
transport="http",
|
||||
origin="127.0.0.1:48291",
|
||||
client="gitops-dispatcher/1.0",
|
||||
parameters={"expected_branch": "main", "build": False},
|
||||
duration_ms=1450,
|
||||
commit_sha="a1b2c3d",
|
||||
message="Workload updated and reconciled successfully",
|
||||
)
|
||||
assert evt_comp.phase == AuditPhase.COMPLETED
|
||||
assert evt_comp.result is not None
|
||||
assert evt_comp.result.status == "SUCCESS"
|
||||
assert evt_comp.result.exit_code == 0
|
||||
assert evt_comp.result.commit_sha == "a1b2c3d"
|
||||
|
||||
# Read and validate JSONL file contents
|
||||
lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines()
|
||||
assert len(lines) == 2
|
||||
|
||||
parsed_disp = AuditEvent.model_validate(json.loads(lines[0]))
|
||||
assert parsed_disp.phase == AuditPhase.DISPATCHED
|
||||
assert parsed_disp.operation_id == "op_101"
|
||||
|
||||
parsed_comp = AuditEvent.model_validate(json.loads(lines[1]))
|
||||
assert parsed_comp.phase == AuditPhase.COMPLETED
|
||||
assert parsed_comp.operation_id == "op_101"
|
||||
|
||||
|
||||
def test_audit_logger_writes_failed_event(
|
||||
temp_audit_file: Path, sample_principal: PrincipalAudit
|
||||
):
|
||||
logger = AuditLogger(temp_audit_file)
|
||||
logger.log_failed(
|
||||
operation_id="op_102",
|
||||
principal=sample_principal,
|
||||
action="workload.deploy",
|
||||
target="jellyfin",
|
||||
transport="unix_socket",
|
||||
origin="peer_uid_1000",
|
||||
client="appctl-cli/2.0",
|
||||
parameters={"recreate": True},
|
||||
duration_ms=320,
|
||||
exit_code=1,
|
||||
error_code="ERR_EXECUTION_FAILED",
|
||||
message="Docker compose failed with exit code 1",
|
||||
)
|
||||
|
||||
lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines()
|
||||
assert len(lines) == 1
|
||||
event = AuditEvent.model_validate(json.loads(lines[0]))
|
||||
assert event.phase == AuditPhase.FAILED
|
||||
assert event.result is not None
|
||||
assert event.result.status == "FAILED"
|
||||
assert event.result.exit_code == 1
|
||||
assert event.result.error_code == "ERR_EXECUTION_FAILED"
|
||||
|
||||
|
||||
def test_audit_logger_writes_denied_event(
|
||||
temp_audit_file: Path, sample_principal: PrincipalAudit
|
||||
):
|
||||
logger = AuditLogger(temp_audit_file)
|
||||
logger.log_denied(
|
||||
operation_id="op_103",
|
||||
principal=sample_principal,
|
||||
action="workload.config",
|
||||
target="core",
|
||||
transport="http",
|
||||
origin="127.0.0.1:49000",
|
||||
client="curl/8.1",
|
||||
parameters={},
|
||||
error_code="ERR_PERMISSION_DENIED",
|
||||
message="Role homelab-operator cannot target core stack",
|
||||
)
|
||||
|
||||
lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines()
|
||||
assert len(lines) == 1
|
||||
event = AuditEvent.model_validate(json.loads(lines[0]))
|
||||
assert event.phase == AuditPhase.DENIED
|
||||
assert event.result is not None
|
||||
assert event.result.status == "DENIED"
|
||||
assert event.result.error_code == "ERR_PERMISSION_DENIED"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Secret Redaction
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_redact_sensitive_data_masks_secret_keys():
|
||||
raw_params = {
|
||||
"API_KEY": "supersecretkey123",
|
||||
"WEBHOOK_SECRET": "whsec_9999",
|
||||
"db_password": "mypassword",
|
||||
"AUTH_TOKEN": "tok_12345",
|
||||
"SSH_KEY": "ssh-ed25519 AAA...",
|
||||
"PASSWORD_HASH": "$2b$12$...",
|
||||
"recreate": True,
|
||||
"nested": {
|
||||
"SECRET_PASS": "pass123",
|
||||
"normal_config": "enabled",
|
||||
"list_items": [
|
||||
{"ITEM_SECRET": "leak", "id": 1},
|
||||
"safe_string",
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
redacted = redact_sensitive_data(raw_params)
|
||||
assert redacted["API_KEY"] == "[REDACTED]"
|
||||
assert redacted["WEBHOOK_SECRET"] == "[REDACTED]"
|
||||
assert redacted["db_password"] == "[REDACTED]"
|
||||
assert redacted["AUTH_TOKEN"] == "[REDACTED]"
|
||||
assert redacted["SSH_KEY"] == "[REDACTED]"
|
||||
assert redacted["PASSWORD_HASH"] == "[REDACTED]"
|
||||
assert redacted["recreate"] is True
|
||||
assert redacted["nested"]["SECRET_PASS"] == "[REDACTED]"
|
||||
assert redacted["nested"]["normal_config"] == "enabled"
|
||||
assert redacted["nested"]["list_items"][0]["ITEM_SECRET"] == "[REDACTED]"
|
||||
assert redacted["nested"]["list_items"][0]["id"] == 1
|
||||
assert redacted["nested"]["list_items"][1] == "safe_string"
|
||||
|
||||
|
||||
def test_audit_logger_automatically_redacts_sensitive_parameters(
|
||||
temp_audit_file: Path, sample_principal: PrincipalAudit
|
||||
):
|
||||
logger = AuditLogger(temp_audit_file)
|
||||
logger.log_dispatched(
|
||||
operation_id="op_104",
|
||||
principal=sample_principal,
|
||||
action="workload.deploy",
|
||||
target="vaultwarden",
|
||||
transport="unix_socket",
|
||||
origin="peer_uid_1000",
|
||||
client="appctl-cli/2.0",
|
||||
parameters={"ADMIN_TOKEN": "super_token_leak", "recreate": True},
|
||||
)
|
||||
|
||||
content = temp_audit_file.read_text(encoding="utf-8")
|
||||
assert "super_token_leak" not in content
|
||||
assert "[REDACTED]" in content
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pre-Execution Fail-Closed Disk Guard
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_audit_logger_fails_closed_when_audit_log_unwritable(
|
||||
tmp_path: Path, sample_principal: PrincipalAudit
|
||||
):
|
||||
read_only_dir = tmp_path / "readonly_audit"
|
||||
read_only_dir.mkdir(parents=True, exist_ok=True)
|
||||
unwritable_file = read_only_dir / "audit.jsonl"
|
||||
unwritable_file.touch(mode=0o400)
|
||||
os.chmod(unwritable_file, 0o400)
|
||||
|
||||
# In addition, make directory read-only
|
||||
os.chmod(read_only_dir, 0o500)
|
||||
|
||||
try:
|
||||
logger = AuditLogger(unwritable_file)
|
||||
with pytest.raises(AuditPersistenceError) as exc_info:
|
||||
logger.log_dispatched(
|
||||
operation_id="op_105",
|
||||
principal=sample_principal,
|
||||
action="workload.deploy",
|
||||
target="jellyfin",
|
||||
transport="unix_socket",
|
||||
origin="peer_uid_1000",
|
||||
client="appctl-cli/2.0",
|
||||
parameters={"recreate": True},
|
||||
)
|
||||
assert "Failed to persist audit event" in str(exc_info.value)
|
||||
finally:
|
||||
os.chmod(read_only_dir, 0o700)
|
||||
os.chmod(unwritable_file, 0o600)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Concurrency & Non-Blocking Flock Manager
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_target_lock_manager_acquires_and_releases_lock(temp_lock_dir: Path):
|
||||
manager = TargetLockManager(temp_lock_dir)
|
||||
|
||||
with manager.lock_target("snappymail") as lock:
|
||||
assert lock.target == "snappymail"
|
||||
assert lock.lock_path.exists()
|
||||
# Verify mode 0600 on lock file
|
||||
assert stat.S_IMODE(lock.lock_path.stat().st_mode) == 0o600
|
||||
|
||||
# Lock can be re-acquired immediately after release
|
||||
with manager.lock_target("snappymail"):
|
||||
pass
|
||||
|
||||
|
||||
def test_target_lock_manager_rejects_concurrent_mutation(temp_lock_dir: Path):
|
||||
manager = TargetLockManager(temp_lock_dir)
|
||||
|
||||
with (
|
||||
manager.lock_target("jellyfin"),
|
||||
pytest.raises(ConcurrentMutationError) as exc_info,
|
||||
manager.lock_target("jellyfin"),
|
||||
):
|
||||
pass
|
||||
|
||||
assert exc_info.value.target == "jellyfin"
|
||||
assert "locked by a concurrent task" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_target_lock_manager_permits_independent_targets_concurrently(
|
||||
temp_lock_dir: Path,
|
||||
):
|
||||
manager = TargetLockManager(temp_lock_dir)
|
||||
|
||||
with manager.lock_target("app1"), manager.lock_target("app2"):
|
||||
pass
|
||||
|
||||
|
||||
def test_homepage_sync_lock_acquires_designated_file(temp_lock_dir: Path):
|
||||
manager = TargetLockManager(temp_lock_dir)
|
||||
|
||||
with (
|
||||
manager.homepage_sync_lock() as lock,
|
||||
pytest.raises(ConcurrentMutationError) as exc_info,
|
||||
manager.homepage_sync_lock(),
|
||||
):
|
||||
pass
|
||||
|
||||
assert lock.lock_path.name == "_homepage_sync.lock"
|
||||
assert exc_info.value.target == "_homepage_sync"
|
||||
@@ -0,0 +1,326 @@
|
||||
"""
|
||||
tests/unit/test_appctl_auth.py — Unit Tests for Authentication & 3-Role RBAC (P4 Slice 3)
|
||||
|
||||
Behavior-driven test naming convention:
|
||||
test_<subject>_<accepts|rejects|enforces>_<condition>
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from appctl_auth import (
|
||||
AuthenticationError,
|
||||
AuthorizationError,
|
||||
Principal,
|
||||
Role,
|
||||
TokenStore,
|
||||
authenticate_request,
|
||||
enforce_rbac,
|
||||
load_admitted_workloads,
|
||||
)
|
||||
from appctl_contracts import ErrorCode, OperationType
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def secret_tokens() -> dict[str, str]:
|
||||
return {
|
||||
"admin_secret": "sec_admin_9876543210abcdef",
|
||||
"operator_secret": "sec_operator_1234567890abcdef",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_tokens_file(tmp_path: Path, secret_tokens: dict[str, str]) -> Path:
|
||||
tokens_path = tmp_path / "tokens.json"
|
||||
admin_hash = hashlib.sha256(secret_tokens["admin_secret"].encode("utf-8")).hexdigest()
|
||||
op_hash = hashlib.sha256(secret_tokens["operator_secret"].encode("utf-8")).hexdigest()
|
||||
|
||||
data = [
|
||||
{
|
||||
"token_id": "tok_admin_01",
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"sha256": admin_hash,
|
||||
},
|
||||
{
|
||||
"token_id": "tok_gitops_01",
|
||||
"identity": "gitops-dispatcher",
|
||||
"role": "homelab-operator",
|
||||
"sha256": op_hash,
|
||||
},
|
||||
]
|
||||
tokens_path.write_text(json.dumps(data), encoding="utf-8")
|
||||
os.chmod(tokens_path, 0o400)
|
||||
return tokens_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admitted_workloads() -> set[str]:
|
||||
return {"snappymail", "mail", "webmail", "jellyfin", "media", "docs"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TokenStore & Strict Permissions (0400)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_token_store_accepts_valid_0400_store(temp_tokens_file: Path):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
tokens = store.load_tokens()
|
||||
assert len(tokens) == 2
|
||||
assert tokens[0].role == Role.ADMIN
|
||||
assert tokens[1].role == Role.OPERATOR
|
||||
|
||||
|
||||
def test_token_store_rejects_insecure_file_permissions(tmp_path: Path):
|
||||
bad_tokens_file = tmp_path / "insecure_tokens.json"
|
||||
bad_tokens_file.write_text("[]", encoding="utf-8")
|
||||
|
||||
# Insecure modes: 0644, 0600, 0777
|
||||
for insecure_mode in [0o644, 0o600, 0o777, 0o444]:
|
||||
os.chmod(bad_tokens_file, insecure_mode)
|
||||
store = TokenStore(bad_tokens_file)
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
store.load_tokens()
|
||||
assert "mode 0400 required" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||
|
||||
|
||||
def test_token_store_rejects_missing_file(tmp_path: Path):
|
||||
missing_file = tmp_path / "nonexistent.json"
|
||||
store = TokenStore(missing_file)
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
store.load_tokens()
|
||||
assert "not found" in str(exc_info.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bearer Token Authentication
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_token_store_authenticates_valid_bearer_secrets(
|
||||
temp_tokens_file: Path, secret_tokens: dict[str, str]
|
||||
):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
p_admin = store.authenticate_bearer(secret_tokens["admin_secret"])
|
||||
assert p_admin.identity == "operator"
|
||||
assert p_admin.role == Role.ADMIN
|
||||
assert p_admin.token_id == "tok_admin_01"
|
||||
assert p_admin.auth_method == "bearer_token"
|
||||
|
||||
p_op = store.authenticate_bearer(secret_tokens["operator_secret"])
|
||||
assert p_op.identity == "gitops-dispatcher"
|
||||
assert p_op.role == Role.OPERATOR
|
||||
assert p_op.token_id == "tok_gitops_01"
|
||||
|
||||
|
||||
def test_token_store_rejects_invalid_bearer_secret(temp_tokens_file: Path):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
store.authenticate_bearer("wrong_secret_token_123")
|
||||
assert "Invalid or unknown Bearer token" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||
|
||||
|
||||
def test_token_store_rejects_empty_bearer_secret(temp_tokens_file: Path):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
store.authenticate_bearer("")
|
||||
assert "Empty Bearer token provided" in str(exc_info.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Transport Authentication Rules (HTTP vs. Unix Domain Socket)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_authenticate_request_over_http_requires_valid_bearer(
|
||||
temp_tokens_file: Path, secret_tokens: dict[str, str]
|
||||
):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
# Valid Bearer token
|
||||
auth_header = f"Bearer {secret_tokens['admin_secret']}"
|
||||
p = authenticate_request("http", auth_header, token_store=store)
|
||||
assert p.role == Role.ADMIN
|
||||
|
||||
# Missing Authorization header -> 401
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
authenticate_request("http", None, token_store=store)
|
||||
assert "Bearer token required over network transport" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||
|
||||
# Malformed Authorization header -> 401
|
||||
with pytest.raises(AuthenticationError):
|
||||
authenticate_request("http", "Basic dXNlcjpwYXNz", token_store=store)
|
||||
|
||||
|
||||
def test_authenticate_request_over_uds_falls_back_to_viewer(
|
||||
temp_tokens_file: Path, secret_tokens: dict[str, str]
|
||||
):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
# Missing Authorization header over UDS with peer_uid=1000
|
||||
p = authenticate_request("unix_socket", None, peer_uid=1000, token_store=store)
|
||||
assert p.identity == "unix_uid_1000"
|
||||
assert p.role == Role.VIEWER
|
||||
assert p.token_id is None
|
||||
assert p.auth_method == "unix_peercred"
|
||||
|
||||
# Explicit Bearer token over UDS confers full privileges
|
||||
auth_header = f"Bearer {secret_tokens['admin_secret']}"
|
||||
p_admin = authenticate_request("unix_socket", auth_header, peer_uid=1000, token_store=store)
|
||||
assert p_admin.role == Role.ADMIN
|
||||
assert p_admin.auth_method == "bearer_token"
|
||||
|
||||
|
||||
def test_authenticate_request_over_uds_rejects_missing_peer_uid():
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
authenticate_request("unix_socket", None, peer_uid=None)
|
||||
assert "Missing peer credentials" in str(exc_info.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Deployments Registry Scope Loader
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_load_admitted_workloads_parses_names_and_aliases(tmp_path: Path):
|
||||
deploy_file = tmp_path / "deployments.yaml"
|
||||
deploy_file.write_text("""
|
||||
schemaVersion: "1.0"
|
||||
repositories:
|
||||
snappymail:
|
||||
path: "/home/operator/Sites/snappymail"
|
||||
aliases:
|
||||
- "mail"
|
||||
- "webmail"
|
||||
jellyfin:
|
||||
path: "/home/operator/Sites/homelab-jellyfin"
|
||||
aliases:
|
||||
- "media"
|
||||
""", encoding="utf-8")
|
||||
|
||||
admitted = load_admitted_workloads(deploy_file)
|
||||
assert "snappymail" in admitted
|
||||
assert "mail" in admitted
|
||||
assert "webmail" in admitted
|
||||
assert "jellyfin" in admitted
|
||||
assert "media" in admitted
|
||||
assert "unknown_app" not in admitted
|
||||
|
||||
|
||||
def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path):
|
||||
admitted = load_admitted_workloads(tmp_path / "missing.yaml")
|
||||
assert admitted == set()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# RBAC Policy Matrix Enforcement
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_rbac_admin_permitted_across_all_operations_and_targets(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
admin = Principal(identity="admin_user", role=Role.ADMIN, auth_method="bearer_token")
|
||||
|
||||
# Mutations across Core and Sites
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "traefik", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_CONFIG, "core", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_LOGS, "traefik", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_LIST, None, admitted_workloads)
|
||||
|
||||
|
||||
def test_rbac_operator_permitted_on_admitted_workloads(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
|
||||
# Permitted on admitted workload
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_UPDATE, "mail", admitted_workloads)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_LOGS, "docs", admitted_workloads)
|
||||
enforce_rbac(operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_LIST, None, admitted_workloads)
|
||||
|
||||
|
||||
def test_rbac_operator_denied_on_core_targets(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
|
||||
# Targeting "core" stack
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads)
|
||||
assert "not permitted to target core service 'core'" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
# Targeting core services (traefik, stalwart, etc.)
|
||||
for core_svc in ["traefik", "authelia", "stalwart", "socket-proxy"]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads)
|
||||
assert f"not permitted to target core service '{core_svc}'" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_rbac_operator_denied_on_unregistered_workload(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unregistered_app", admitted_workloads)
|
||||
assert "not registered in deployments.yaml" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_viewer_permitted_only_on_non_sensitive_reads():
|
||||
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
|
||||
|
||||
# Permitted reads
|
||||
enforce_rbac(viewer, OperationType.WORKLOAD_LIST, None)
|
||||
enforce_rbac(viewer, OperationType.WORKLOAD_GET, "snappymail")
|
||||
enforce_rbac(viewer, OperationType.WORKLOAD_RESOLVE, "snappymail")
|
||||
enforce_rbac(viewer, OperationType.PLATFORM_SSL, "snappymail")
|
||||
enforce_rbac(viewer, OperationType.PLATFORM_HEALTH, None)
|
||||
|
||||
|
||||
def test_rbac_viewer_denied_on_mutations():
|
||||
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
|
||||
|
||||
mutations = [
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_STOP,
|
||||
OperationType.WORKLOAD_RESTART,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_PULL,
|
||||
OperationType.PLATFORM_SYNC_HOMEPAGE,
|
||||
]
|
||||
for mut in mutations:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(viewer, mut, "snappymail")
|
||||
assert "not permitted to execute mutating operation" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_viewer_denied_on_sensitive_reads():
|
||||
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
|
||||
|
||||
for sens_op in [OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(viewer, sens_op, "snappymail")
|
||||
assert "not permitted to access sensitive operation" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
test_appctl_cli.py — Unit Tests for Thin UDS Client (scripts/appctl_cli.py)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from appctl_cli import format_response, resolve_token, run_cli
|
||||
from appctl_contracts import (
|
||||
ErrorCode,
|
||||
OperationError,
|
||||
OperationRequest,
|
||||
OperationResponse,
|
||||
OperationType,
|
||||
)
|
||||
|
||||
|
||||
def test_cli_token_resolution(tmp_path: Path, monkeypatch):
|
||||
"""Ensure token resolution checks CLI flag, environment, and config file."""
|
||||
# 1. Direct CLI argument precedence
|
||||
assert resolve_token("explicit-secret") == "explicit-secret"
|
||||
|
||||
# 2. Environment variable precedence
|
||||
monkeypatch.setenv("APPCTL_TOKEN", "env-secret")
|
||||
assert resolve_token(None) == "env-secret"
|
||||
|
||||
# 3. File fallback
|
||||
monkeypatch.delenv("APPCTL_TOKEN", raising=False)
|
||||
cfg_token = tmp_path / "token"
|
||||
cfg_token.write_text("file-secret\n", encoding="utf-8")
|
||||
with patch("pathlib.Path.home", return_value=tmp_path):
|
||||
dot_config = tmp_path / ".config" / "homelab"
|
||||
dot_config.mkdir(parents=True)
|
||||
(dot_config / "token").write_text("user-file-secret\n", encoding="utf-8")
|
||||
assert resolve_token(None) == "user-file-secret"
|
||||
|
||||
|
||||
def test_cli_format_response_success_and_error():
|
||||
"""Ensure response formatter produces human-friendly strings and JSON."""
|
||||
success_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_123",
|
||||
operation=OperationType.WORKLOAD_DEPLOY,
|
||||
output="Container started successfully",
|
||||
)
|
||||
formatted = format_response(success_resp, raw_json=False)
|
||||
assert "Container started successfully" in formatted
|
||||
|
||||
raw_json = format_response(success_resp, raw_json=True)
|
||||
assert '"operation": "workload.deploy"' in raw_json
|
||||
assert '"success": true' in raw_json
|
||||
|
||||
error_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=False,
|
||||
operation_id="op_456",
|
||||
operation=OperationType.WORKLOAD_DEPLOY,
|
||||
error=OperationError(code=ErrorCode.ERR_PERMISSION_DENIED, message="Forbidden"),
|
||||
)
|
||||
formatted_err = format_response(error_resp, raw_json=False)
|
||||
assert "❌ Error [ERR_PERMISSION_DENIED]: Forbidden" in formatted_err
|
||||
|
||||
|
||||
def test_cli_dispatches_list_command():
|
||||
"""Ensure appctl list dispatches OperationRequest(workload.list)."""
|
||||
mock_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_001",
|
||||
operation=OperationType.WORKLOAD_LIST,
|
||||
output="NAME STATUS\ndocs running\n",
|
||||
)
|
||||
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
|
||||
ret = run_cli(["list", "--core"])
|
||||
assert ret == 0
|
||||
assert mock_send.call_count == 1
|
||||
req: OperationRequest = mock_send.call_args[1]["operation_request"]
|
||||
assert req.operation == OperationType.WORKLOAD_LIST
|
||||
assert req.parameters["core"] is True
|
||||
assert "NAME STATUS" in mock_stdout.getvalue()
|
||||
|
||||
|
||||
def test_cli_dispatches_mutation_command():
|
||||
"""Ensure appctl up <target> dispatches OperationRequest(workload.deploy)."""
|
||||
mock_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_002",
|
||||
operation=OperationType.WORKLOAD_DEPLOY,
|
||||
target="jellyfin",
|
||||
result={"action": "deployed", "message": "Workload deployed"},
|
||||
)
|
||||
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
|
||||
ret = run_cli(["up", "jellyfin", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
assert mock_send.call_count == 1
|
||||
assert mock_send.call_args[1]["token"] == "tok_secret"
|
||||
req: OperationRequest = mock_send.call_args[1]["operation_request"]
|
||||
assert req.operation == OperationType.WORKLOAD_DEPLOY
|
||||
assert req.target == "jellyfin"
|
||||
assert "Workload deployed" in mock_stdout.getvalue()
|
||||
|
||||
|
||||
def test_cli_handles_missing_socket():
|
||||
"""Ensure friendly stderr message when socket is absent."""
|
||||
with patch("appctl_cli.send_daemon_request", side_effect=FileNotFoundError), patch("sys.stderr", new_callable=io.StringIO) as mock_stderr:
|
||||
ret = run_cli(["list", "--socket", "/nonexistent/appctl.sock"])
|
||||
assert ret == 1
|
||||
assert "socket not found" in mock_stderr.getvalue()
|
||||
@@ -0,0 +1,657 @@
|
||||
"""
|
||||
tests/unit/test_appctl_contracts.py — Unit Tests for Control Plane API Contracts (P4 Slice 1)
|
||||
|
||||
Behavior-driven test naming convention:
|
||||
test_<subject>_<accepts|rejects>_<condition>
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from appctl_contracts import (
|
||||
MUTATING_OPERATIONS,
|
||||
READ_ONLY_OPERATIONS,
|
||||
TARGET_REQUIRED_OPERATIONS,
|
||||
DeployParams,
|
||||
EmptyParams,
|
||||
ErrorCode,
|
||||
GetParams,
|
||||
ListParams,
|
||||
LogsParams,
|
||||
OperationError,
|
||||
OperationRequest,
|
||||
OperationResponse,
|
||||
OperationType,
|
||||
UpdateParams,
|
||||
sanitize_validation_error,
|
||||
)
|
||||
from core_manifest import ALLOWED_ACTIONS, Manifest
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def get_validation_error_locs(data: dict) -> list[str | int]:
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationRequest.model_validate(data)
|
||||
return [err["loc"][0] for err in exc_info.value.errors()]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Canonical 13 Operations
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_operation_type_contains_exactly_13_canonical_operations():
|
||||
assert len(OperationType) == 13
|
||||
expected = {
|
||||
"workload.list",
|
||||
"workload.get",
|
||||
"workload.resolve",
|
||||
"platform.ssl",
|
||||
"platform.health",
|
||||
"workload.config",
|
||||
"workload.logs",
|
||||
"workload.deploy",
|
||||
"workload.stop",
|
||||
"workload.restart",
|
||||
"workload.update",
|
||||
"workload.pull",
|
||||
"platform.sync_homepage",
|
||||
}
|
||||
assert {op.value for op in OperationType} == expected
|
||||
|
||||
|
||||
def test_operation_sets_partition_canonical_operations():
|
||||
assert MUTATING_OPERATIONS | READ_ONLY_OPERATIONS == set(OperationType)
|
||||
assert MUTATING_OPERATIONS.isdisjoint(READ_ONLY_OPERATIONS)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("op", list(OperationType))
|
||||
def test_operation_request_accepts_all_canonical_operations(op: OperationType):
|
||||
target = "jellyfin" if op in TARGET_REQUIRED_OPERATIONS else None
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": op.value,
|
||||
"target": target,
|
||||
"parameters": {},
|
||||
}
|
||||
validated = OperationRequest.model_validate(request)
|
||||
assert validated.operation == op
|
||||
assert validated.action == op
|
||||
|
||||
|
||||
def test_operation_request_rejects_unknown_operation():
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": "workload.unknown_action",
|
||||
"target": "jellyfin",
|
||||
"parameters": {},
|
||||
}
|
||||
locs = get_validation_error_locs(request)
|
||||
assert "operation" in locs
|
||||
|
||||
|
||||
def test_operation_request_rejects_empty_operation():
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": "",
|
||||
"target": "jellyfin",
|
||||
"parameters": {},
|
||||
}
|
||||
locs = get_validation_error_locs(request)
|
||||
assert "operation" in locs
|
||||
|
||||
|
||||
def test_operation_request_rejects_non_string_operation():
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": 12345,
|
||||
"target": "jellyfin",
|
||||
"parameters": {},
|
||||
}
|
||||
locs = get_validation_error_locs(request)
|
||||
assert "operation" in locs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Version "1.0"
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_operation_request_accepts_default_and_explicit_version_1_0():
|
||||
# Explicit "1.0"
|
||||
r1 = OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "platform.health",
|
||||
})
|
||||
assert r1.version == "1.0"
|
||||
|
||||
# Default "1.0"
|
||||
r2 = OperationRequest.model_validate({
|
||||
"operation": "platform.health",
|
||||
})
|
||||
assert r2.version == "1.0"
|
||||
|
||||
|
||||
def test_operation_request_rejects_non_1_0_version():
|
||||
for bad_ver in ["2.0", "0.9", "1.1", ""]:
|
||||
request = {
|
||||
"version": bad_ver,
|
||||
"operation": "platform.health",
|
||||
}
|
||||
locs = get_validation_error_locs(request)
|
||||
assert "version" in locs
|
||||
|
||||
|
||||
def test_operation_request_rejects_numeric_version():
|
||||
request = {
|
||||
"version": 1.0,
|
||||
"operation": "platform.health",
|
||||
}
|
||||
locs = get_validation_error_locs(request)
|
||||
assert "version" in locs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Target Validation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_operation_request_rejects_empty_target():
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": "workload.deploy",
|
||||
"target": "",
|
||||
"parameters": {},
|
||||
}
|
||||
locs = get_validation_error_locs(request)
|
||||
assert "target" in locs
|
||||
|
||||
|
||||
@pytest.mark.parametrize("op", list(TARGET_REQUIRED_OPERATIONS))
|
||||
def test_operation_request_rejects_missing_target_when_required(op: OperationType):
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": op.value,
|
||||
"target": None,
|
||||
"parameters": {},
|
||||
}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationRequest.model_validate(request)
|
||||
assert "requires a non-empty target" in str(exc_info.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("op", [
|
||||
OperationType.WORKLOAD_LIST,
|
||||
OperationType.PLATFORM_HEALTH,
|
||||
OperationType.PLATFORM_SYNC_HOMEPAGE,
|
||||
])
|
||||
def test_operation_request_accepts_missing_target_when_optional(op: OperationType):
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": op.value,
|
||||
"parameters": {},
|
||||
}
|
||||
validated = OperationRequest.model_validate(request)
|
||||
assert validated.target is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Parameter Models & Bounds Validation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_deploy_params_defaults_and_explicit_bounds():
|
||||
# Defaults
|
||||
p_default = DeployParams()
|
||||
assert p_default.recreate is True
|
||||
assert p_default.remove_orphans is True
|
||||
assert p_default.build is False
|
||||
|
||||
# Explicit
|
||||
p_custom = DeployParams(recreate=False, remove_orphans=False, build=True)
|
||||
assert p_custom.recreate is False
|
||||
assert p_custom.remove_orphans is False
|
||||
assert p_custom.build is True
|
||||
|
||||
|
||||
def test_deploy_params_rejects_non_strict_types():
|
||||
for bad_bool in ["true", "false", 1, 0, None, [True]]:
|
||||
with pytest.raises(ValidationError):
|
||||
DeployParams(recreate=bad_bool) # type: ignore[arg-type]
|
||||
with pytest.raises(ValidationError):
|
||||
DeployParams(remove_orphans=bad_bool) # type: ignore[arg-type]
|
||||
with pytest.raises(ValidationError):
|
||||
DeployParams(build=bad_bool) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_deploy_params_rejects_extra_fields():
|
||||
with pytest.raises(ValidationError):
|
||||
DeployParams.model_validate({"recreate": True, "unexpected": "extra"})
|
||||
|
||||
|
||||
def test_update_params_defaults_and_explicit():
|
||||
# Defaults
|
||||
p_default = UpdateParams()
|
||||
assert p_default.expected_branch is None
|
||||
assert p_default.build is False
|
||||
|
||||
# Explicit
|
||||
p_custom = UpdateParams(expected_branch="main", build=True)
|
||||
assert p_custom.expected_branch == "main"
|
||||
assert p_custom.build is True
|
||||
|
||||
|
||||
def test_update_params_rejects_empty_branch_and_non_strict_types():
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(expected_branch="") # min_length=1
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(expected_branch=123) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(build="true") # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams.model_validate({"build": False, "extra": "prohibited"})
|
||||
|
||||
|
||||
def test_logs_params_defaults_and_bounds():
|
||||
# Default
|
||||
p_default = LogsParams()
|
||||
assert p_default.tail == 100
|
||||
|
||||
# Bounds
|
||||
assert LogsParams(tail=1).tail == 1
|
||||
assert LogsParams(tail=1000).tail == 1000
|
||||
assert LogsParams(tail=500).tail == 500
|
||||
|
||||
# Below minimum
|
||||
with pytest.raises(ValidationError):
|
||||
LogsParams(tail=0)
|
||||
|
||||
# Above maximum
|
||||
with pytest.raises(ValidationError):
|
||||
LogsParams(tail=1001)
|
||||
|
||||
# Non-strict integer (string / float)
|
||||
with pytest.raises(ValidationError):
|
||||
LogsParams(tail="100") # type: ignore[arg-type]
|
||||
with pytest.raises(ValidationError):
|
||||
LogsParams(tail=100.5) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
LogsParams.model_validate({"tail": 50, "follow": True})
|
||||
|
||||
|
||||
def test_list_params_defaults_and_explicit():
|
||||
p_default = ListParams()
|
||||
assert p_default.fetch is False
|
||||
assert p_default.core is False
|
||||
assert p_default.ssl is False
|
||||
|
||||
p_custom = ListParams(fetch=True, core=True, ssl=True)
|
||||
assert p_custom.fetch is True
|
||||
assert p_custom.core is True
|
||||
assert p_custom.ssl is True
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
ListParams(fetch="yes") # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
ListParams.model_validate({"fetch": False, "extra": 1})
|
||||
|
||||
|
||||
def test_get_params_defaults_and_explicit():
|
||||
p_default = GetParams()
|
||||
assert p_default.ssl is False
|
||||
|
||||
p_custom = GetParams(ssl=True)
|
||||
assert p_custom.ssl is True
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
GetParams(ssl="true") # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_empty_params_rejects_extra_fields():
|
||||
p = EmptyParams()
|
||||
assert p.model_dump() == {}
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
EmptyParams.model_validate({"any_field": "disallowed"})
|
||||
|
||||
|
||||
def test_operation_request_validates_and_parses_operation_specific_params():
|
||||
# Deploy
|
||||
req_deploy = OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
"parameters": {"recreate": True, "build": True},
|
||||
})
|
||||
params = req_deploy.parse_parameters()
|
||||
assert isinstance(params, DeployParams)
|
||||
assert params.build is True
|
||||
|
||||
# Logs
|
||||
req_logs = OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "workload.logs",
|
||||
"target": "snappymail",
|
||||
"parameters": {"tail": 250},
|
||||
})
|
||||
log_params = req_logs.parse_parameters()
|
||||
assert isinstance(log_params, LogsParams)
|
||||
assert log_params.tail == 250
|
||||
|
||||
# Stop (accepts EmptyParams)
|
||||
req_stop = OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "workload.stop",
|
||||
"target": "snappymail",
|
||||
"parameters": {},
|
||||
})
|
||||
assert isinstance(req_stop.parse_parameters(), EmptyParams)
|
||||
|
||||
|
||||
def test_operation_request_rejects_invalid_params_for_operation():
|
||||
# Deploy with bad tail
|
||||
with pytest.raises(ValidationError):
|
||||
OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
"parameters": {"tail": 50}, # Deploy does not accept tail
|
||||
})
|
||||
|
||||
# Logs with out-of-bounds tail
|
||||
with pytest.raises(ValidationError):
|
||||
OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "workload.logs",
|
||||
"target": "snappymail",
|
||||
"parameters": {"tail": 9999},
|
||||
})
|
||||
|
||||
# Stop with extra params
|
||||
with pytest.raises(ValidationError):
|
||||
OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "workload.stop",
|
||||
"target": "snappymail",
|
||||
"parameters": {"force": True},
|
||||
})
|
||||
|
||||
|
||||
def test_operation_request_rejects_extra_top_level_fields():
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": "platform.health",
|
||||
"prohibited_extra": "attack",
|
||||
}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationRequest.model_validate(request)
|
||||
assert "extra_forbidden" in [e["type"] for e in exc_info.value.errors()]
|
||||
|
||||
|
||||
def test_operation_request_backward_compatibility_aliases():
|
||||
# Accepts 'action' alias for 'operation', and 'params' alias for 'parameters'
|
||||
request = {
|
||||
"action": "workload.deploy",
|
||||
"target": "jellyfin",
|
||||
"params": {"recreate": True},
|
||||
}
|
||||
validated = OperationRequest.model_validate(request)
|
||||
assert validated.operation == OperationType.WORKLOAD_DEPLOY
|
||||
assert validated.action == OperationType.WORKLOAD_DEPLOY
|
||||
assert validated.parameters == {"recreate": True}
|
||||
assert validated.params == {"recreate": True}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Closed 6-Code Error Taxonomy
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_error_code_taxonomy_contains_exactly_6_canonical_codes():
|
||||
assert len(ErrorCode) == 6
|
||||
expected_codes = {
|
||||
"ERR_VALIDATION_FAILED",
|
||||
"ERR_AUTH_REQUIRED",
|
||||
"ERR_PERMISSION_DENIED",
|
||||
"ERR_TARGET_NOT_FOUND",
|
||||
"ERR_CONCURRENT_MUTATION",
|
||||
"ERR_EXECUTION_FAILED",
|
||||
}
|
||||
assert {code.value for code in ErrorCode} == expected_codes
|
||||
|
||||
|
||||
def test_error_code_http_status_mapping():
|
||||
assert ErrorCode.ERR_VALIDATION_FAILED.http_status == 400
|
||||
assert ErrorCode.ERR_AUTH_REQUIRED.http_status == 401
|
||||
assert ErrorCode.ERR_PERMISSION_DENIED.http_status == 403
|
||||
assert ErrorCode.ERR_TARGET_NOT_FOUND.http_status == 404
|
||||
assert ErrorCode.ERR_CONCURRENT_MUTATION.http_status == 409
|
||||
assert ErrorCode.ERR_EXECUTION_FAILED.http_status == 500
|
||||
|
||||
|
||||
def test_operation_error_accepts_valid_error_code():
|
||||
err = OperationError(
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
message="Bearer token required",
|
||||
)
|
||||
assert err.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||
assert err.message == "Bearer token required"
|
||||
assert err.details is None
|
||||
|
||||
|
||||
def test_operation_error_accepts_string_error_code_coercion():
|
||||
err = OperationError.model_validate({
|
||||
"code": "ERR_CONCURRENT_MUTATION",
|
||||
"message": "Operation locked by concurrent task",
|
||||
})
|
||||
assert err.code == ErrorCode.ERR_CONCURRENT_MUTATION
|
||||
|
||||
|
||||
def test_operation_error_rejects_invalid_error_code():
|
||||
with pytest.raises(ValidationError):
|
||||
OperationError.model_validate({
|
||||
"code": "ERR_CUSTOM_CODE",
|
||||
"message": "Invalid code",
|
||||
})
|
||||
|
||||
|
||||
def test_operation_error_rejects_extra_fields():
|
||||
with pytest.raises(ValidationError):
|
||||
OperationError.model_validate({
|
||||
"code": "ERR_VALIDATION_FAILED",
|
||||
"message": "Failed",
|
||||
"secret_leak": "value",
|
||||
})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Error Sanitizer (Information Disclosure Prevention)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_sanitize_validation_error_strips_input_and_url():
|
||||
# Create a model with secret value that fails validation
|
||||
class SecretPayload(BaseModel):
|
||||
token: str = "default"
|
||||
|
||||
try:
|
||||
LogsParams.model_validate({
|
||||
"tail": "SUPER_SECRET_TOKEN_DO_NOT_LEAK",
|
||||
})
|
||||
except ValidationError as exc:
|
||||
op_err = sanitize_validation_error(exc)
|
||||
|
||||
assert op_err.code == ErrorCode.ERR_VALIDATION_FAILED
|
||||
assert op_err.message == "Request payload validation failed"
|
||||
assert op_err.details is not None
|
||||
assert len(op_err.details) > 0
|
||||
|
||||
# Ensure neither input nor url appears in any details dictionary
|
||||
for detail in op_err.details:
|
||||
assert "input" not in detail
|
||||
assert "url" not in detail
|
||||
assert "SUPER_SECRET_TOKEN_DO_NOT_LEAK" not in str(detail)
|
||||
assert "loc" in detail
|
||||
assert "msg" in detail
|
||||
assert "type" in detail
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OperationResponse Consistency & Edge Cases
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_operation_response_accepts_success_without_error():
|
||||
response_data = {
|
||||
"version": "1.0",
|
||||
"success": True,
|
||||
"operation_id": "op_123",
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
"output": "Snappymail deployment complete",
|
||||
}
|
||||
validated = OperationResponse.model_validate(response_data)
|
||||
assert validated.success is True
|
||||
assert validated.status == "success"
|
||||
assert validated.error is None
|
||||
assert validated.operation == OperationType.WORKLOAD_DEPLOY
|
||||
assert validated.action == OperationType.WORKLOAD_DEPLOY
|
||||
assert validated.operation_id == "op_123"
|
||||
|
||||
|
||||
def test_operation_response_accepts_status_field_reconciliation():
|
||||
# Pass 'status': 'success' without 'success'
|
||||
r1 = OperationResponse.model_validate({
|
||||
"version": "1.0",
|
||||
"status": "success",
|
||||
"operation_id": "op_123",
|
||||
"operation": "platform.health",
|
||||
})
|
||||
assert r1.success is True
|
||||
assert r1.status == "success"
|
||||
|
||||
# Pass 'status': 'error' without 'success'
|
||||
r2 = OperationResponse.model_validate({
|
||||
"version": "1.0",
|
||||
"status": "error",
|
||||
"operation_id": "op_124",
|
||||
"operation": "platform.health",
|
||||
"error": {
|
||||
"code": "ERR_EXECUTION_FAILED",
|
||||
"message": "Health probe failed",
|
||||
},
|
||||
})
|
||||
assert r2.success is False
|
||||
assert r2.status == "error"
|
||||
|
||||
|
||||
def test_operation_response_accepts_failure_with_nested_error():
|
||||
response_data = {
|
||||
"version": "1.0",
|
||||
"success": False,
|
||||
"operation_id": "op_456",
|
||||
"operation": "workload.deploy",
|
||||
"target": "capybara",
|
||||
"error": {
|
||||
"code": "ERR_TARGET_NOT_FOUND",
|
||||
"message": "Workload `capybara` does not exist",
|
||||
},
|
||||
}
|
||||
validated = OperationResponse.model_validate(response_data)
|
||||
assert validated.success is False
|
||||
assert validated.target == "capybara"
|
||||
assert validated.operation_id == "op_456"
|
||||
assert validated.operation == OperationType.WORKLOAD_DEPLOY
|
||||
assert isinstance(validated.error, OperationError)
|
||||
assert validated.error.code == ErrorCode.ERR_TARGET_NOT_FOUND
|
||||
assert validated.error.message == "Workload `capybara` does not exist"
|
||||
|
||||
|
||||
def test_operation_response_rejects_success_with_error():
|
||||
response_data = {
|
||||
"version": "1.0",
|
||||
"success": True,
|
||||
"operation": "workload.deploy",
|
||||
"target": "microservice1",
|
||||
"operation_id": "op_124",
|
||||
"error": {
|
||||
"code": "ERR_VALIDATION_FAILED",
|
||||
"message": "This error should not appear on success response",
|
||||
},
|
||||
}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationResponse.model_validate(response_data)
|
||||
assert "cannot contain an error" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_operation_response_rejects_failure_without_error():
|
||||
response_data = {
|
||||
"version": "1.0",
|
||||
"success": False,
|
||||
"operation": "workload.deploy",
|
||||
"target": "microservice2",
|
||||
"operation_id": "op_125",
|
||||
}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationResponse.model_validate(response_data)
|
||||
assert "must contain an error" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_operation_response_rejects_inconsistent_status_and_success():
|
||||
response_data = {
|
||||
"version": "1.0",
|
||||
"success": True,
|
||||
"status": "error",
|
||||
"operation": "platform.health",
|
||||
"operation_id": "op_126",
|
||||
}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationResponse.model_validate(response_data)
|
||||
assert "'status' and 'success' must agree" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_operation_response_rejects_extra_fields():
|
||||
response_data = {
|
||||
"version": "1.0",
|
||||
"success": True,
|
||||
"operation": "platform.health",
|
||||
"operation_id": "op_127",
|
||||
"unauthorized_field": "data",
|
||||
}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationResponse.model_validate(response_data)
|
||||
assert "extra_forbidden" in [e["type"] for e in exc_info.value.errors()]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Core Manifest compose_pull Action
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_core_manifest_allows_compose_pull_action():
|
||||
assert "compose_pull" in ALLOWED_ACTIONS
|
||||
|
||||
valid_manifest = {
|
||||
"schema_version": "1.0",
|
||||
"name": "snappymail",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/example/snappymail.git",
|
||||
"ref": "main",
|
||||
},
|
||||
"deployment": {
|
||||
"strategy": "compose",
|
||||
"actions": ["git_pull", "compose_pull", "compose_up"],
|
||||
},
|
||||
}
|
||||
parsed = Manifest.model_validate(valid_manifest)
|
||||
assert parsed.deployment.actions == ["git_pull", "compose_pull", "compose_up"]
|
||||
@@ -0,0 +1,527 @@
|
||||
"""
|
||||
test_appctl_daemon.py — Unit and Integration Test Suite for Milestone P4 Daemon
|
||||
|
||||
Asserts:
|
||||
- Dual-transport equivalence between UDS (/run/homelab/appctl.sock) and TCP (127.0.0.1:9001)
|
||||
- 64 KiB request body limit enforcement (400 ERR_VALIDATION_FAILED)
|
||||
- Health check route GET /v1/health
|
||||
- Unauthenticated rejection fails closed (401 ERR_AUTH_REQUIRED)
|
||||
- UDS SO_PEERCRED viewer fallback boundary
|
||||
- 3-role RBAC enforcement across daemon transports
|
||||
- Pre-flight and inert dotenv safety through daemon
|
||||
- Concurrency conflict (409 ERR_CONCURRENT_MUTATION)
|
||||
- Truthful execution failure reporting (500 ERR_EXECUTION_FAILED)
|
||||
- Fail-closed pre-execution audit guard
|
||||
- Daemon restart socket unlinking and clean rebinding
|
||||
- gitops_dispatcher delegation to daemon UDS
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import socket
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import gitops_dispatcher
|
||||
import pytest
|
||||
from appctl_audit import AuditLogger, TargetLockManager
|
||||
from appctl_auth import Role, TokenDescriptor, TokenStore
|
||||
from appctl_contracts import ErrorCode, OperationRequest, OperationType
|
||||
from appctl_daemon import (
|
||||
AppctlDaemon,
|
||||
UnixHTTPConnection,
|
||||
send_daemon_request,
|
||||
)
|
||||
from appctl_router import OperationalRouter
|
||||
|
||||
ADMIN_SECRET = "secret-admin-key-789"
|
||||
OPERATOR_SECRET = "secret-operator-key-456"
|
||||
|
||||
ADMIN_HASH = hashlib.sha256(ADMIN_SECRET.encode()).hexdigest()
|
||||
OPERATOR_HASH = hashlib.sha256(OPERATOR_SECRET.encode()).hexdigest()
|
||||
|
||||
|
||||
def get_free_port() -> int:
|
||||
"""Find an available TCP port on loopback."""
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def daemon_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
|
||||
"""
|
||||
Spins up an isolated AppctlDaemon instance with:
|
||||
- Dedicated UDS socket in tmp_path
|
||||
- Dynamic loopback TCP port
|
||||
- Mock Sites directory with admitted 'docs' and unregistered 'rogue' workloads
|
||||
- Valid 0400 tokens store with admin and operator tokens
|
||||
- Valid 0600 audit log file
|
||||
"""
|
||||
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
|
||||
socket_path = tmp_path / "appctl.sock"
|
||||
http_port = get_free_port()
|
||||
http_host = "127.0.0.1"
|
||||
|
||||
# Tokens store
|
||||
tokens_file = tmp_path / "tokens.json"
|
||||
tokens_data = [
|
||||
TokenDescriptor(
|
||||
token_id="tok_admin",
|
||||
identity="operator",
|
||||
role=Role.ADMIN,
|
||||
sha256=ADMIN_HASH,
|
||||
).model_dump(),
|
||||
TokenDescriptor(
|
||||
token_id="tok_gitops",
|
||||
identity="gitops-dispatcher",
|
||||
role=Role.OPERATOR,
|
||||
sha256=OPERATOR_HASH,
|
||||
).model_dump(),
|
||||
]
|
||||
tokens_file.write_text(json.dumps(tokens_data), encoding="utf-8")
|
||||
tokens_file.chmod(0o400)
|
||||
token_store = TokenStore(tokens_file)
|
||||
|
||||
# Audit log
|
||||
audit_file = tmp_path / "audit.jsonl"
|
||||
audit_file.touch()
|
||||
audit_file.chmod(0o600)
|
||||
audit_logger = AuditLogger(audit_file)
|
||||
|
||||
# Locks
|
||||
lock_dir = tmp_path / "locks"
|
||||
lock_dir.mkdir()
|
||||
lock_manager = TargetLockManager(lock_dir)
|
||||
|
||||
# Workloads
|
||||
sites_dir = tmp_path / "Sites"
|
||||
sites_dir.mkdir()
|
||||
core_dir = tmp_path / "Core"
|
||||
core_dir.mkdir()
|
||||
|
||||
# Admitted workload: docs
|
||||
docs_dir = sites_dir / "docs"
|
||||
docs_dir.mkdir()
|
||||
(docs_dir / "app.yaml").write_text(
|
||||
"name: docs\n"
|
||||
"domain: docs\n"
|
||||
"deployment:\n"
|
||||
" branch: main\n"
|
||||
" actions:\n"
|
||||
" - compose_up\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
(docs_dir / "docker-compose.yml").write_text(
|
||||
"services:\n"
|
||||
" web:\n"
|
||||
" image: nginx:alpine\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
# Unregistered workload: rogue
|
||||
rogue_dir = sites_dir / "rogue"
|
||||
rogue_dir.mkdir()
|
||||
(rogue_dir / "app.yaml").write_text(
|
||||
"name: rogue\n"
|
||||
"deployment:\n"
|
||||
" branch: main\n"
|
||||
" actions:\n"
|
||||
" - compose_up\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
(rogue_dir / "docker-compose.yml").write_text(
|
||||
"services:\n"
|
||||
" web:\n"
|
||||
" image: alpine:latest\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
# deployments.yaml
|
||||
deployments_file = tmp_path / "deployments.yaml"
|
||||
deployments_file.write_text(
|
||||
'schemaVersion: "1.0"\n'
|
||||
"repositories:\n"
|
||||
" docs:\n"
|
||||
f' path: "{docs_dir}"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
router = OperationalRouter(
|
||||
audit_logger=audit_logger,
|
||||
lock_manager=lock_manager,
|
||||
sites_dir=sites_dir,
|
||||
core_dir=core_dir,
|
||||
)
|
||||
|
||||
daemon = AppctlDaemon(
|
||||
router=router,
|
||||
token_store=token_store,
|
||||
audit_logger=audit_logger,
|
||||
lock_manager=lock_manager,
|
||||
socket_path=socket_path,
|
||||
http_host=http_host,
|
||||
http_port=http_port,
|
||||
sites_dir=sites_dir,
|
||||
core_dir=core_dir,
|
||||
deployments_file=deployments_file,
|
||||
)
|
||||
|
||||
daemon.start()
|
||||
|
||||
class Context:
|
||||
def __init__(self):
|
||||
self.daemon = daemon
|
||||
self.socket_path = socket_path
|
||||
self.http_url = f"http://{http_host}:{http_port}"
|
||||
self.sites_dir = sites_dir
|
||||
self.core_dir = core_dir
|
||||
self.audit_file = audit_file
|
||||
self.deployments_file = deployments_file
|
||||
self.docs_dir = docs_dir
|
||||
self.rogue_dir = rogue_dir
|
||||
|
||||
ctx = Context()
|
||||
try:
|
||||
yield ctx
|
||||
finally:
|
||||
daemon.stop()
|
||||
|
||||
|
||||
def test_health_endpoint(daemon_env):
|
||||
"""GET /v1/health returns HTTP 200 with health metadata over UDS and TCP."""
|
||||
# Over UDS
|
||||
conn_uds = UnixHTTPConnection(str(daemon_env.socket_path))
|
||||
conn_uds.request("GET", "/v1/health")
|
||||
res_uds = conn_uds.getresponse()
|
||||
assert res_uds.status == 200
|
||||
data_uds = json.loads(res_uds.read().decode())
|
||||
assert data_uds["status"] == "healthy"
|
||||
assert data_uds["version"] == "1.0"
|
||||
assert "uptime_seconds" in data_uds
|
||||
conn_uds.close()
|
||||
|
||||
# Over TCP
|
||||
import http.client
|
||||
conn_tcp = http.client.HTTPConnection("127.0.0.1", daemon_env.daemon.http_port)
|
||||
conn_tcp.request("GET", "/v1/health")
|
||||
res_tcp = conn_tcp.getresponse()
|
||||
assert res_tcp.status == 200
|
||||
data_tcp = json.loads(res_tcp.read().decode())
|
||||
assert data_tcp["status"] == "healthy"
|
||||
assert data_tcp["version"] == "1.0"
|
||||
conn_tcp.close()
|
||||
|
||||
|
||||
def test_transport_dual_equivalence(daemon_env):
|
||||
"""
|
||||
Compare responses of POST /v1/operations over Unix socket vs HTTP 127.0.0.1.
|
||||
Asserts 100% schema and status parity.
|
||||
"""
|
||||
list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST)
|
||||
|
||||
# 1. Successful query with admin token
|
||||
resp_uds = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=list_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
resp_http = send_daemon_request(
|
||||
endpoint=daemon_env.http_url,
|
||||
operation_request=list_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
|
||||
assert resp_uds.success is True
|
||||
assert resp_http.success is True
|
||||
assert resp_uds.status == resp_http.status
|
||||
assert resp_uds.operation == resp_http.operation
|
||||
assert resp_uds.version == resp_http.version
|
||||
assert resp_uds.result == resp_http.result
|
||||
|
||||
# 2. Error case parity (404 target not found)
|
||||
get_req = OperationRequest(operation=OperationType.WORKLOAD_GET, target="nonexistent")
|
||||
err_uds = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=get_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
err_http = send_daemon_request(
|
||||
endpoint=daemon_env.http_url,
|
||||
operation_request=get_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
|
||||
assert err_uds.success is False
|
||||
assert err_http.success is False
|
||||
assert err_uds.error is not None and err_http.error is not None
|
||||
assert err_uds.error.code == ErrorCode.ERR_TARGET_NOT_FOUND
|
||||
assert err_http.error.code == ErrorCode.ERR_TARGET_NOT_FOUND
|
||||
assert err_uds.error.code.http_status == 404
|
||||
assert err_http.error.code.http_status == 404
|
||||
|
||||
|
||||
def test_request_body_size_limit(daemon_env):
|
||||
"""Requests exceeding 64 KiB are rejected with 400 ERR_VALIDATION_FAILED."""
|
||||
oversized_data = {"version": "1.0", "operation": "workload.list", "padding": "x" * (65 * 1024)}
|
||||
body_str = json.dumps(oversized_data)
|
||||
|
||||
conn = UnixHTTPConnection(str(daemon_env.socket_path))
|
||||
headers = {"Content-Type": "application/json", "Host": "localhost"}
|
||||
conn.request("POST", "/v1/operations", body=body_str, headers=headers)
|
||||
res = conn.getresponse()
|
||||
assert res.status == 400
|
||||
data = json.loads(res.read().decode())
|
||||
assert data["status"] == "error"
|
||||
assert data["error"]["code"] == ErrorCode.ERR_VALIDATION_FAILED.value
|
||||
assert "exceeds limit" in data["error"]["message"]
|
||||
conn.close()
|
||||
|
||||
|
||||
def test_auth_missing_token_fails_closed(daemon_env):
|
||||
"""
|
||||
Mutating operations and sensitive reads without Bearer token return 401 ERR_AUTH_REQUIRED
|
||||
and execute zero subprocesses.
|
||||
"""
|
||||
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
|
||||
with patch("subprocess.run") as mock_subproc:
|
||||
# Over HTTP without token
|
||||
resp_http = send_daemon_request(
|
||||
endpoint=daemon_env.http_url,
|
||||
operation_request=deploy_req,
|
||||
token=None,
|
||||
)
|
||||
assert resp_http.success is False
|
||||
assert resp_http.error is not None
|
||||
assert resp_http.error.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||
assert resp_http.error.code.http_status == 401
|
||||
assert mock_subproc.call_count == 0
|
||||
|
||||
# Over UDS without token (deploy is mutating, peercred viewer fallback must be rejected)
|
||||
resp_uds = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=None,
|
||||
)
|
||||
assert resp_uds.success is False
|
||||
assert resp_uds.error is not None
|
||||
assert resp_uds.error.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
assert resp_uds.error.code.http_status == 403
|
||||
assert mock_subproc.call_count == 0
|
||||
|
||||
|
||||
def test_uds_peercred_viewer_boundary(daemon_env):
|
||||
"""
|
||||
Tokenless UDS call from operator UID succeeds for workload.list (auth_method: unix_peercred),
|
||||
but fails with 403 on mutation or sensitive reads.
|
||||
"""
|
||||
# Read-only query over UDS without token succeeds as viewer
|
||||
list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST)
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=list_req,
|
||||
token=None,
|
||||
)
|
||||
assert resp.success is True
|
||||
assert resp.result is not None
|
||||
assert "workloads" in resp.result
|
||||
|
||||
# Sensitive read (workload.config) without token fails
|
||||
config_req = OperationRequest(operation=OperationType.WORKLOAD_CONFIG, target="docs")
|
||||
resp_cfg = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=config_req,
|
||||
token=None,
|
||||
)
|
||||
assert resp_cfg.success is False
|
||||
assert resp_cfg.error is not None
|
||||
assert resp_cfg.error.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
assert resp_cfg.error.code.http_status == 403
|
||||
|
||||
|
||||
def test_rbac_role_matrix(daemon_env):
|
||||
"""
|
||||
homelab-operator allowed on deployments.yaml workloads but denied on unregistered workloads;
|
||||
homelab-admin allowed on all valid targets.
|
||||
"""
|
||||
deploy_registered = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
deploy_unregistered = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="rogue")
|
||||
|
||||
with patch("appctl_router.run_bounded_subprocess") as mock_subproc, patch("appctl_router.OperationalRouter._trigger_homepage_sync"):
|
||||
mock_subproc.return_value = (0, "Container docs created", "")
|
||||
|
||||
# Operator on registered target -> SUCCESS
|
||||
resp_op_reg = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_registered,
|
||||
token=OPERATOR_SECRET,
|
||||
)
|
||||
assert resp_op_reg.success is True
|
||||
assert resp_op_reg.result is not None
|
||||
assert resp_op_reg.result["action"] == "deployed"
|
||||
|
||||
# Operator on unregistered target -> 403 ERR_PERMISSION_DENIED
|
||||
resp_op_unreg = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_unregistered,
|
||||
token=OPERATOR_SECRET,
|
||||
)
|
||||
assert resp_op_unreg.success is False
|
||||
assert resp_op_unreg.error is not None
|
||||
assert resp_op_unreg.error.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
assert resp_op_unreg.error.code.http_status == 403
|
||||
|
||||
# Admin on unregistered target -> SUCCESS
|
||||
resp_adm_unreg = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_unregistered,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
assert resp_adm_unreg.success is True
|
||||
assert resp_adm_unreg.result is not None
|
||||
assert resp_adm_unreg.result["action"] == "deployed"
|
||||
|
||||
|
||||
def test_daemon_preflight_and_dotenv_safety(daemon_env):
|
||||
"""
|
||||
Workload with prohibited Compose directive (privileged: true) is blocked by Compose AST
|
||||
pre-flight before any subprocess runs.
|
||||
"""
|
||||
bad_compose = daemon_env.docs_dir / "docker-compose.yml"
|
||||
bad_compose.write_text(
|
||||
"services:\n"
|
||||
" web:\n"
|
||||
" image: nginx\n"
|
||||
" privileged: true\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
|
||||
with patch("subprocess.run") as mock_subproc:
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_VALIDATION_FAILED
|
||||
assert resp.error.code.http_status == 400
|
||||
assert "privileged: true" in resp.error.message
|
||||
assert mock_subproc.call_count == 0
|
||||
|
||||
|
||||
def test_concurrent_mutation_conflict(daemon_env):
|
||||
"""
|
||||
Second concurrent mutation on the same target returns 409 ERR_CONCURRENT_MUTATION.
|
||||
"""
|
||||
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
|
||||
# Manually hold lock on target
|
||||
lock_ctx = daemon_env.daemon.lock_manager.lock_target("docs")
|
||||
with lock_ctx:
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_CONCURRENT_MUTATION
|
||||
assert resp.error.code.http_status == 409
|
||||
|
||||
|
||||
def test_execution_failure_audit(daemon_env):
|
||||
"""
|
||||
Failing Docker subprocess returns 500 ERR_EXECUTION_FAILED and records phase: FAILED.
|
||||
"""
|
||||
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
|
||||
with patch("appctl_router.run_bounded_subprocess") as mock_subproc:
|
||||
mock_subproc.return_value = (1, "", "Error: docker daemon not reachable")
|
||||
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED
|
||||
assert resp.error.code.http_status == 500
|
||||
|
||||
# Verify audit.jsonl contains FAILED event
|
||||
lines = [json.loads(line) for line in daemon_env.audit_file.read_text().splitlines() if line.strip()]
|
||||
failed_events = [ev for ev in lines if ev.get("phase") == "FAILED"]
|
||||
assert len(failed_events) >= 1
|
||||
assert failed_events[-1]["target"] == "docs"
|
||||
assert failed_events[-1]["result"]["error_code"] == ErrorCode.ERR_EXECUTION_FAILED.value
|
||||
|
||||
|
||||
def test_audit_failure_blocks_mutation(daemon_env):
|
||||
"""
|
||||
Unwritable audit.jsonl aborts mutating command with 500 ERR_EXECUTION_FAILED
|
||||
and zero Docker invocations.
|
||||
"""
|
||||
daemon_env.audit_file.chmod(0o400)
|
||||
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
|
||||
with patch("subprocess.run") as mock_subproc:
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED
|
||||
assert resp.error.code.http_status == 500
|
||||
assert mock_subproc.call_count == 0
|
||||
|
||||
# Restore write permission for teardown
|
||||
daemon_env.audit_file.chmod(0o600)
|
||||
|
||||
|
||||
def test_daemon_restart_preserves_state(daemon_env):
|
||||
"""
|
||||
Clean stop and restart of daemon unlinks and rebinds socket cleanly.
|
||||
"""
|
||||
daemon_env.daemon.stop()
|
||||
assert not daemon_env.socket_path.exists()
|
||||
|
||||
# Restart
|
||||
daemon_env.daemon.start()
|
||||
assert daemon_env.socket_path.is_socket()
|
||||
|
||||
# Re-verify communication
|
||||
list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST)
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=list_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
assert resp.success is True
|
||||
|
||||
|
||||
def test_gitops_dispatcher_delegates_to_daemon(daemon_env, monkeypatch):
|
||||
"""
|
||||
When daemon socket is active, gitops_dispatcher calls daemon over UDS with Bearer token.
|
||||
"""
|
||||
monkeypatch.setattr(gitops_dispatcher, "DEFAULT_APPCTL_SOCKET_PATH", daemon_env.socket_path)
|
||||
monkeypatch.setenv("GITOPS_APPCTL_TOKEN", OPERATOR_SECRET)
|
||||
monkeypatch.setenv("APPCTL_SOCKET_PATH", str(daemon_env.socket_path))
|
||||
|
||||
with patch.object(daemon_env.daemon.router, "_op_workload_update") as mock_update:
|
||||
mock_update.return_value = ({"action": "updated", "message": "Updated via daemon"}, "sha12345")
|
||||
|
||||
success = gitops_dispatcher.execute_deployment(
|
||||
target_dir=daemon_env.docs_dir,
|
||||
deployment_config={"branch": "main", "actions": ["git_pull", "compose_up"]},
|
||||
branch="main",
|
||||
)
|
||||
assert success is True
|
||||
assert mock_update.call_count == 1
|
||||
@@ -83,7 +83,7 @@ def test_manifest_data_overrides_default_values(app_factory: AppFactory):
|
||||
dir_name="homelab-custom",
|
||||
manifest_yaml="""
|
||||
name: custom-app
|
||||
domain: custom.roadtotech.local
|
||||
domain: custom.example.test
|
||||
auth: false
|
||||
visible: false
|
||||
networks:
|
||||
@@ -95,7 +95,7 @@ def test_manifest_data_overrides_default_values(app_factory: AppFactory):
|
||||
app = engine.resolve_app("custom-app", apps)
|
||||
|
||||
assert app is not None
|
||||
assert app.domain == "custom.roadtotech.local"
|
||||
assert app.domain == "custom.example.test"
|
||||
assert app.auth is False
|
||||
assert app.networks == ["custom-net"]
|
||||
|
||||
|
||||
@@ -0,0 +1,511 @@
|
||||
"""
|
||||
tests/unit/test_appctl_router.py — Unit Tests for Operational Router & Execution Engine (P4 Slice 4)
|
||||
|
||||
Behavior-driven test naming convention:
|
||||
test_<subject>_<accepts|rejects|enforces>_<condition>
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from appctl_audit import AuditLogger, TargetLockManager
|
||||
from appctl_auth import Principal, Role
|
||||
from appctl_contracts import ErrorCode, OperationRequest
|
||||
from appctl_router import (
|
||||
MAX_OUTPUT_BYTES,
|
||||
OperationalRouter,
|
||||
RouterExecutionError,
|
||||
RouterValidationError,
|
||||
assemble_workload_env,
|
||||
parse_dotenv,
|
||||
resolve_canonical_domain,
|
||||
run_bounded_subprocess,
|
||||
validate_workload_preflight,
|
||||
)
|
||||
from core_manifest import parse_manifest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def set_test_domain(monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_sites_dir(tmp_path: Path) -> Path:
|
||||
sites = tmp_path / "Sites"
|
||||
sites.mkdir(parents=True, exist_ok=True)
|
||||
return sites
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_core_dir(tmp_path: Path) -> Path:
|
||||
core = tmp_path / "Core"
|
||||
core.mkdir(parents=True, exist_ok=True)
|
||||
return core
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_workload_dir(mock_sites_dir: Path) -> Path:
|
||||
app_dir = mock_sites_dir / "snappymail"
|
||||
app_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
manifest_content = """
|
||||
schema_version: "1.0"
|
||||
name: "snappymail"
|
||||
source:
|
||||
type: "git"
|
||||
url: "https://github.com/example/snappymail.git"
|
||||
ref: "main"
|
||||
deployment:
|
||||
strategy: "compose"
|
||||
actions:
|
||||
- "git_pull"
|
||||
- "compose_pull"
|
||||
- "compose_up"
|
||||
env:
|
||||
WORKLOAD_CUSTOM_VAR: "custom_value"
|
||||
"""
|
||||
(app_dir / "app.yaml").write_text(manifest_content.strip(), encoding="utf-8")
|
||||
|
||||
compose_content = """
|
||||
services:
|
||||
webmail:
|
||||
image: "snappymail:latest"
|
||||
container_name: "snappymail"
|
||||
restart: "unless-stopped"
|
||||
"""
|
||||
(app_dir / "docker-compose.yml").write_text(compose_content.strip(), encoding="utf-8")
|
||||
return app_dir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_principal() -> Principal:
|
||||
return Principal(identity="operator", role=Role.ADMIN, auth_method="bearer_token")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def operator_principal() -> Principal:
|
||||
return Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def viewer_principal() -> Principal:
|
||||
return Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pure-Python Inert Dotenv Parser
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_parse_dotenv_parses_valid_key_values(tmp_path: Path):
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text("""
|
||||
# Comment line
|
||||
APP_PORT=8080
|
||||
APP_HOST="127.0.0.1"
|
||||
SINGLE_QUOTE='single_val'
|
||||
EMPTY_VAL=
|
||||
WITH_EQUALS=key=value=more
|
||||
""", encoding="utf-8")
|
||||
|
||||
parsed = parse_dotenv(env_file)
|
||||
assert parsed["APP_PORT"] == "8080"
|
||||
assert parsed["APP_HOST"] == "127.0.0.1"
|
||||
assert parsed["SINGLE_QUOTE"] == "single_val"
|
||||
assert parsed["EMPTY_VAL"] == ""
|
||||
assert parsed["WITH_EQUALS"] == "key=value=more"
|
||||
|
||||
|
||||
def test_parse_dotenv_preserves_shell_injection_as_inert_literals(tmp_path: Path):
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text("""
|
||||
INJECTION_ONE=$(touch /tmp/pwned)
|
||||
INJECTION_TWO=`cat /etc/passwd`
|
||||
VARIABLE_REF=$HOMELAB_DOMAIN
|
||||
""", encoding="utf-8")
|
||||
|
||||
parsed = parse_dotenv(env_file)
|
||||
assert parsed["INJECTION_ONE"] == "$(touch /tmp/pwned)"
|
||||
assert parsed["INJECTION_TWO"] == "`cat /etc/passwd`"
|
||||
assert parsed["VARIABLE_REF"] == "$HOMELAB_DOMAIN"
|
||||
assert not Path("/tmp/pwned").exists()
|
||||
|
||||
|
||||
def test_parse_dotenv_rejects_invalid_key_syntax(tmp_path: Path):
|
||||
bad_keys = ["APP-PORT=80", "123NUM=val", "KEY WITH SPACES=val", "@INVALID=1"]
|
||||
for bad in bad_keys:
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text(bad, encoding="utf-8")
|
||||
with pytest.raises(RouterValidationError) as exc_info:
|
||||
parse_dotenv(env_file)
|
||||
assert "Prohibited environment key syntax" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_parse_dotenv_rejects_reserved_environment_keys(tmp_path: Path):
|
||||
for reserved in ["PATH=foo", "LD_PRELOAD=bar", "SHELL=/bin/bash", "USER=root"]:
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text(reserved, encoding="utf-8")
|
||||
with pytest.raises(RouterValidationError) as exc_info:
|
||||
parse_dotenv(env_file)
|
||||
assert "Prohibited reserved environment key" in str(exc_info.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Canonical Domain Resolution & Environment Assembly
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_resolve_canonical_domain_precedence(monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.setenv("HOMELAB_DOMAIN", "domain-a.test")
|
||||
monkeypatch.setenv("DOMAIN_SUFFIX", "domain-b.test")
|
||||
monkeypatch.setenv("DOMAIN", "domain-c.test")
|
||||
assert resolve_canonical_domain() == "domain-a.test"
|
||||
|
||||
monkeypatch.delenv("HOMELAB_DOMAIN")
|
||||
assert resolve_canonical_domain() == "domain-b.test"
|
||||
|
||||
monkeypatch.delenv("DOMAIN_SUFFIX")
|
||||
assert resolve_canonical_domain() == "domain-c.test"
|
||||
|
||||
|
||||
def test_assemble_workload_env_constructs_6_layer_environment(
|
||||
mock_workload_dir: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
|
||||
manifest = parse_manifest(mock_workload_dir / "app.yaml")
|
||||
|
||||
# Add local .env
|
||||
(mock_workload_dir / ".env").write_text("LOCAL_ENV_VAR=local_val\n", encoding="utf-8")
|
||||
|
||||
env = assemble_workload_env(mock_workload_dir, manifest, "snappymail")
|
||||
|
||||
# Layer 1
|
||||
assert "PATH" in env
|
||||
# Layer 3 & 4
|
||||
assert env["HOMELAB_DOMAIN"] == "example.test"
|
||||
assert env["SERVICE_NAME"] == "snappymail"
|
||||
assert env["SERVICE_DOMAIN"] == "snappymail.example.test"
|
||||
assert env["PROXY_NETWORK"] == "proxy-net"
|
||||
# Layer 5 (manifest env)
|
||||
assert env["WORKLOAD_CUSTOM_VAR"] == "custom_value"
|
||||
# Layer 6 (.env)
|
||||
assert env["LOCAL_ENV_VAR"] == "local_val"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bounded Subprocess Execution Engine
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_run_bounded_subprocess_executes_valid_command():
|
||||
code, out, err = run_bounded_subprocess(["echo", "hello world"])
|
||||
assert code == 0
|
||||
assert out.strip() == "hello world"
|
||||
assert err == ""
|
||||
|
||||
|
||||
def test_run_bounded_subprocess_enforces_256_kib_cap():
|
||||
# Produce > 256 KiB of output
|
||||
python_cmd = [
|
||||
"python3",
|
||||
"-c",
|
||||
f"import sys; sys.stdout.write('A' * ({MAX_OUTPUT_BYTES} + 1024))",
|
||||
]
|
||||
code, out, _ = run_bounded_subprocess(python_cmd)
|
||||
assert code == 0
|
||||
assert len(out.encode("utf-8")) <= MAX_OUTPUT_BYTES + 200
|
||||
assert "[TRUNCATED: Output exceeded 256 KiB limit]" in out
|
||||
|
||||
|
||||
def test_run_bounded_subprocess_times_out():
|
||||
cmd = ["sleep", "2"]
|
||||
with pytest.raises(RouterExecutionError) as exc_info:
|
||||
run_bounded_subprocess(cmd, timeout=0.1)
|
||||
assert "timed out after 0.1 seconds" in str(exc_info.value)
|
||||
assert exc_info.value.exit_code == 124
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Workload Pre-Flight Gate
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_validate_workload_preflight_accepts_valid_workload(
|
||||
mock_workload_dir: Path, mock_sites_dir: Path
|
||||
):
|
||||
manifest, compose_file = validate_workload_preflight(
|
||||
mock_workload_dir, mock_sites_dir, "snappymail"
|
||||
)
|
||||
assert manifest.name == "snappymail"
|
||||
assert compose_file.exists()
|
||||
|
||||
|
||||
def test_validate_workload_preflight_rejects_path_traversal(
|
||||
mock_sites_dir: Path, tmp_path: Path
|
||||
):
|
||||
outside_dir = tmp_path / "outside_dir"
|
||||
outside_dir.mkdir(parents=True, exist_ok=True)
|
||||
with pytest.raises(RouterValidationError) as exc_info:
|
||||
validate_workload_preflight(outside_dir, mock_sites_dir)
|
||||
assert "Path traversal rejected" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_validate_workload_preflight_rejects_prohibited_compose_security(
|
||||
mock_workload_dir: Path, mock_sites_dir: Path
|
||||
):
|
||||
# Inject privileged: true into docker-compose.yml
|
||||
bad_compose = """
|
||||
services:
|
||||
webmail:
|
||||
image: "snappymail:latest"
|
||||
privileged: true
|
||||
"""
|
||||
(mock_workload_dir / "docker-compose.yml").write_text(bad_compose, encoding="utf-8")
|
||||
|
||||
with pytest.raises(RouterValidationError) as exc_info:
|
||||
validate_workload_preflight(mock_workload_dir, mock_sites_dir, "snappymail")
|
||||
assert "Compose AST security validation failed" in str(exc_info.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Operational Router Dispatch Pipeline
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_operational_router_dispatches_platform_health(tmp_path: Path, admin_principal: Principal):
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
)
|
||||
req = OperationRequest.model_validate({"operation": "platform.health"})
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
assert resp.success is True
|
||||
assert resp.result is not None
|
||||
assert resp.result["status"] == "healthy"
|
||||
|
||||
|
||||
def test_operational_router_dispatches_platform_sync_homepage(
|
||||
tmp_path: Path, admin_principal: Principal
|
||||
):
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
)
|
||||
req = OperationRequest.model_validate({"operation": "platform.sync_homepage"})
|
||||
with patch("appctl_router.cmd_sync_homepage") as mock_sync:
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
assert resp.success is True
|
||||
mock_sync.assert_called_once()
|
||||
|
||||
|
||||
def test_operational_router_enforces_rbac_denial(
|
||||
tmp_path: Path, viewer_principal: Principal
|
||||
):
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
})
|
||||
resp = router.dispatch(req, viewer_principal)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_operational_router_rejects_non_existent_target(
|
||||
tmp_path: Path, admin_principal: Principal
|
||||
):
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "workload.get",
|
||||
"target": "nonexistent_workload_999",
|
||||
})
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_TARGET_NOT_FOUND
|
||||
|
||||
|
||||
def test_operational_router_rejects_concurrent_mutation(
|
||||
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
|
||||
):
|
||||
lock_mgr = TargetLockManager(tmp_path / "locks")
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=lock_mgr,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
})
|
||||
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "snappymail"
|
||||
mock_app.dir_path = str(mock_workload_dir)
|
||||
|
||||
# Hold the lock on snappymail
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
lock_mgr.lock_target("snappymail"),
|
||||
):
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_CONCURRENT_MUTATION
|
||||
|
||||
|
||||
def test_operational_router_dispatches_workload_deploy(
|
||||
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
|
||||
):
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_workload_dir.parent,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
"parameters": {"recreate": True, "remove_orphans": True, "build": False},
|
||||
})
|
||||
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "snappymail"
|
||||
mock_app.dir_path = str(mock_workload_dir)
|
||||
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
patch("appctl_router.run_bounded_subprocess", return_value=(0, "Container started", "")) as mock_run,
|
||||
patch("appctl_router.cmd_sync_homepage"),
|
||||
):
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
assert resp.success is True
|
||||
assert resp.result is not None
|
||||
assert resp.result["action"] == "deployed"
|
||||
mock_run.assert_called_once()
|
||||
assert "up" in mock_run.call_args[0][0]
|
||||
|
||||
|
||||
def test_operational_router_workload_update_rejects_dirty_git_tree(
|
||||
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
|
||||
):
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_workload_dir.parent,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "workload.update",
|
||||
"target": "snappymail",
|
||||
})
|
||||
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "snappymail"
|
||||
mock_app.dir_path = str(mock_workload_dir)
|
||||
|
||||
# Simulate dirty working tree from git status --porcelain
|
||||
def mock_subproc(cmd: list[str], **kwargs):
|
||||
if "status" in cmd:
|
||||
return 0, " M app.yaml\n", ""
|
||||
return 0, "", ""
|
||||
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
|
||||
):
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_VALIDATION_FAILED
|
||||
assert "uncommitted changes" in resp.error.message
|
||||
|
||||
|
||||
def test_operational_router_workload_update_rejects_branch_mismatch(
|
||||
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
|
||||
):
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_workload_dir.parent,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "workload.update",
|
||||
"target": "snappymail",
|
||||
"parameters": {"expected_branch": "feature/branch"},
|
||||
})
|
||||
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "snappymail"
|
||||
mock_app.dir_path = str(mock_workload_dir)
|
||||
|
||||
def mock_subproc(cmd: list[str], **kwargs):
|
||||
if "status" in cmd:
|
||||
return 0, "", ""
|
||||
if "pull" in cmd:
|
||||
return 0, "Fast-forward", ""
|
||||
if "rev-parse" in cmd:
|
||||
return 0, "1234567", ""
|
||||
return 0, "", ""
|
||||
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
|
||||
):
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_VALIDATION_FAILED
|
||||
assert "Post-pull branch mismatch" in resp.error.message
|
||||
|
||||
|
||||
def test_operational_router_workload_update_succeeds_on_clean_tree(
|
||||
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
|
||||
):
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_workload_dir.parent,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "workload.update",
|
||||
"target": "snappymail",
|
||||
"parameters": {"expected_branch": "main"},
|
||||
})
|
||||
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "snappymail"
|
||||
mock_app.dir_path = str(mock_workload_dir)
|
||||
|
||||
executed_commands: list[list[str]] = []
|
||||
|
||||
def mock_subproc(cmd: list[str], **kwargs):
|
||||
executed_commands.append(cmd)
|
||||
if "status" in cmd:
|
||||
return 0, "", ""
|
||||
if "pull" in cmd:
|
||||
return 0, "Updating 1111..2222\nFast-forward", ""
|
||||
if "rev-parse" in cmd:
|
||||
return 0, "a1b2c3d", ""
|
||||
return 0, "success", ""
|
||||
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
|
||||
patch("appctl_router.cmd_sync_homepage"),
|
||||
):
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
assert resp.success is True
|
||||
assert resp.result is not None
|
||||
assert resp.result["commit_sha"] == "a1b2c3d"
|
||||
# Verify git pull was called with expected branch
|
||||
pull_calls = [c for c in executed_commands if "pull" in c]
|
||||
assert len(pull_calls) == 2 # git pull and docker compose pull
|
||||
@@ -22,11 +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) 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
|
||||
x 2026-10-19 (A) Implement strict Pydantic v2 API contracts, error sanitizer, and compose_pull action in scripts/appctl_contracts.py and scripts/core_manifest.py +contracts @p4
|
||||
x 2026-10-19 (A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4
|
||||
x 2026-10-19 (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
|
||||
x 2026-10-19 (B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4
|
||||
x 2026-10-19 (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
|
||||
x 2026-10-19 (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
|
||||
x 2026-10-19 (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
|
||||
x 2026-10-19 (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
|
||||
Reference in new issue
Block a user