Compare commits
86
Commits
c86103a14b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e341ea6d8 | ||
|
|
49cded6122 | ||
|
|
90f3ca930c | ||
|
|
47d059ee8d | ||
|
|
a966244f08 | ||
|
|
ef42bfc801 | ||
|
|
6ba45961ae | ||
|
|
1eed45c301 | ||
|
|
1a8e3b5eae | ||
|
|
c9f3108805 | ||
|
|
4f40668536 | ||
|
|
ce969f4678 | ||
|
|
e807a90017 | ||
|
|
37d529848a | ||
|
|
f326b11986 | ||
|
|
8f3b98344a | ||
|
|
92333b017c | ||
|
|
131e5d75a1 | ||
|
|
158bbb0eed | ||
|
|
c104c69fbc | ||
|
|
11aaf6038b | ||
|
|
648dd49c82 | ||
|
|
365801a169 | ||
|
|
7d4cfe1c04 | ||
|
|
9306dae56b | ||
|
|
c337914fb3 | ||
|
|
df7c1f5292 | ||
|
|
33fda26dc1 | ||
|
|
f0db802f72 | ||
|
|
514409939d | ||
|
|
a5826e0e74 | ||
|
|
cdd2d562c3 | ||
|
|
2df95648d4 | ||
|
|
9d7114b547 | ||
|
|
9ac44d0baa | ||
|
|
88f8bace04 | ||
|
|
2882dc99b5 | ||
|
|
2b89ff44c3 | ||
|
|
99bda8740f | ||
|
|
de02b19861 | ||
|
|
99e9c130c0 | ||
|
|
9c9127b833 | ||
|
|
76df30747d | ||
|
|
c034afd0f8 | ||
|
|
af82d4b26d | ||
|
|
b7b19ad7f1 | ||
|
|
1fea9024f1 | ||
|
|
4622392ca5 | ||
|
|
c740ed8c71 | ||
|
|
55acf00c10 | ||
|
|
c8c79bef89 | ||
|
|
5156cf4306 | ||
|
|
5dfebac35c | ||
|
|
d0213d7209 | ||
|
|
178a0c8990 | ||
|
|
03c8fdcf8e | ||
|
|
3ba8e2b51d | ||
|
|
4f1a63160b | ||
|
|
e2dbc97b0e | ||
|
|
caa8140cd3 | ||
|
|
eb02543fa6 | ||
|
|
24508f8d92 | ||
|
|
8ad48a49db | ||
|
|
f631d5627c | ||
|
|
021c01171b | ||
|
|
7c1b9b75c5 | ||
|
|
c86faa8397 | ||
|
|
dae99af189 | ||
|
|
8da559381f | ||
|
|
ce7ffa8c46 | ||
|
|
3230e08bf9 | ||
|
|
b6ec909bb6 | ||
|
|
25e79898af | ||
|
|
528bd0d4bc | ||
|
|
2668dcc5a8 | ||
|
|
0b5ba58ecf | ||
|
|
154cde272b | ||
|
|
8cc06e2470 | ||
|
|
53404914c3 | ||
|
|
194d1bf3ff | ||
|
|
9e30e113a0 | ||
|
|
d092ca17b8 | ||
|
|
8ce74ff520 | ||
|
|
b5a3db6f1b | ||
|
|
e23ff941d8 | ||
|
|
dc880928a9 |
No files matched your search
@@ -9,8 +9,6 @@ on:
|
||||
jobs:
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: nixery.dev/shell/coreutils/git/nix/nodejs:latest
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
+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/
|
||||
|
||||
@@ -6,6 +6,7 @@ backup.zip
|
||||
.envrc
|
||||
.direnv
|
||||
.venv
|
||||
nixos/instance.nix
|
||||
|
||||
# SSL / ACME Certificates & Keys
|
||||
config/letsencrypt/*
|
||||
@@ -40,13 +41,20 @@ config/homepage/custom.js
|
||||
Thumbs.db
|
||||
.vscode/
|
||||
.idea/
|
||||
.worktrees/
|
||||
|
||||
# Python & Testing Caches
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
mutants/
|
||||
.mutmut-cache/
|
||||
|
||||
# Local Bootstrap & Operational Scripts
|
||||
scripts/bootstrap_lldap_users.py
|
||||
scripts/bootstrap_*.py
|
||||
!scripts/bootstrap_token.py
|
||||
|
||||
# Worktrees & Slices
|
||||
.worktrees/
|
||||
@@ -1,13 +1,13 @@
|
||||
# Homelab Core — Agent Guidelines
|
||||
# Canopy NixOS Core — Agent Guidelines
|
||||
|
||||
## 1. Project Overview & Architectural Boundaries
|
||||
|
||||
**Homelab Core** defines the declarative NixOS host foundation, shared platform infrastructure services, security boundaries, and the `appctl` operational control plane. Independent application workloads live in `~/Sites/<app>` and integrate through declarative `app.yaml` manifests and workload-scoped Docker Compose files.
|
||||
**Canopy NixOS Core** (`canopy-homelab/nixos-core`) defines the declarative NixOS host foundation, shared platform infrastructure services, security boundaries, and the `appctl` operational control plane for the **Canopy** ecosystem. Independent application workloads live in `~/Workloads/<app>` and integrate through declarative `app.yaml` manifests and workload-scoped Docker Compose files.
|
||||
|
||||
### Core vs. `~/Sites` Ownership
|
||||
- **Core owns**: NixOS host configuration, shared platform services (edge ingress, SSO/LDAP, mail, log/update monitors), platform-level ports and security policy, and orchestration/deployment mechanics.
|
||||
- **`~/Sites` owns**: Independently deployed application workloads, workload-specific `docker-compose.yml` topologies, and workload intent (`app.yaml`).
|
||||
- **Boundary Rule**: Never hardcode *workload-specific* domains, ports, containers, environment variables, or deployment policies in Core (`scripts/appctl*`, GitOps, or Core `docker-compose.yml`), and never move Core platform services into `~/Sites`. When ownership is ambiguous, consult [`docs/architecture.md`](docs/architecture.md) before changing the boundary.
|
||||
### Core vs. `~/Workloads` Ownership
|
||||
- **Core owns**: NixOS host configuration (`nixos/instance.example.nix` template for `/etc/nixos/homelab-instance.nix`), shared platform services (edge ingress, SSO/LDAP, mail, log/update monitors), platform-level ports and security policy (including `homelab.workloadGrants` -> `/etc/homelab/grants.json`), and orchestration/deployment mechanics (`appctl`, `gitops_dispatcher.py`, `workload_grants.py`).
|
||||
- **`~/Workloads` owns**: Independently deployed application workloads, workload-specific `docker-compose.yml` topologies, workload intent (`app.yaml`), and `deployments.yaml`.
|
||||
- **Boundary Rule**: Never hardcode *workload-specific* domains, ports, containers, environment variables, or deployment policies in Core (`scripts/appctl*`, GitOps, or Core `docker-compose.yml`), and never move Core platform services into `~/Workloads`. When ownership is ambiguous, consult [`docs/architecture.md`](docs/architecture.md) before changing the boundary.
|
||||
|
||||
### Context Discovery Hierarchy
|
||||
Before proposing or implementing changes, establish context in this order:
|
||||
@@ -27,7 +27,7 @@ Every implementation step must close with the automated verification gate before
|
||||
|
||||
```bash
|
||||
# Full verification gate: Ruff + Pyright + Pytest (124+ tests) + nix flake check + NixOS drv eval
|
||||
./scripts/test
|
||||
./scripts/run-tests
|
||||
|
||||
# Targeted fast iteration commands (inside direnv / nix develop, or via .venv)
|
||||
ruff check .
|
||||
@@ -67,7 +67,7 @@ docker compose config -q
|
||||
1. **Workload Manifests (`app.yaml`)**: Describe declarative workload identity, routing metadata, and deployment intent only. Never introduce arbitrary command execution, host filesystem paths, privileged flags, or Docker control capabilities into `app.yaml`.
|
||||
2. **GitOps Trust Boundary (`scripts/gitops_dispatcher.py`)**:
|
||||
- Webhook admission requires cryptographic authentication (HMAC-SHA256).
|
||||
- Repository identity and filesystem paths must be resolved strictly through trusted Core configuration (`config/deployments.yaml`)—never directly from webhook payloads.
|
||||
- Repository identity and filesystem paths must be resolved strictly through the trusted workloads registry (`~/Workloads/deployments.yaml` or `HOMELAB_DEPLOYMENTS_FILE`, templated by `config/deployments.yaml`)—never directly from webhook payloads.
|
||||
- Execution must remain allowlisted, serialized (`flock`), pre-validated by the Compose AST security checker, and free of shell interpolation (`shell=False`, no `eval`).
|
||||
3. **Docker & Privilege Isolation**:
|
||||
- `socket-proxy` is the **only** service permitted to mount `/var/run/docker.sock` (strictly `:ro`, read-only API capabilities only; `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`).
|
||||
@@ -89,3 +89,10 @@ docker compose config -q
|
||||
- Never run destructive Git commands (`reset --hard`, `restore`, `clean -fd`, `push --force`) without explicit user confirmation.
|
||||
- Stage atomic changes and use Conventional Commits (`feat`, `fix`, `refactor`, `test`, `docs`, `chore`), waiting for user approval before committing.
|
||||
- Preserve [The Unlicense](UNLICENSE) across the repository.
|
||||
|
||||
### Organization Planning Sync Contract
|
||||
- **Ecosystem Hub**: Master roadmap and cross-repo plans live in `canopy-homelab/.profile` (`ROADMAP.md`, `docs/plans/`, `todo.txt`).
|
||||
- **Organization Kanban Board**: **Canopy Platform** (`https://gitea.<domain>/canopy-homelab/-/projects/7`, Project ID: `7`).
|
||||
- **Column IDs (Deep Signal)**: `Backlog` -> `30` (default), `Ready` -> `31`, `Work in Progress` -> `32`, `Review` -> `33`, `Completed` -> `34`.
|
||||
- **Mirror Policy**: Primary sovereign Gitea forge (`canopy-homelab/nixos-core`); GitHub (`canopy-homelab/nixos-core`) is an automated `sync_on_commit` push mirror.
|
||||
- **Re-sync Trigger**: Re-run `/gitea-plan` on scope shifts or before decomposing the next rolling milestone (P5/P6/P7).
|
||||
@@ -1,15 +1,15 @@
|
||||
# Homelab Core
|
||||
# Canopy — NixOS Core (`canopy-homelab/nixos-core`)
|
||||
|
||||
**Homelab Core** is the declarative NixOS host foundation, shared platform infrastructure stack, and `appctl` operational control plane for a self-hosted homelab appliance.
|
||||
**Canopy NixOS Core** is the declarative NixOS host foundation, shared platform infrastructure stack, and `appctl` operational control plane for the **Canopy** self-hosted homelab ecosystem.
|
||||
|
||||
It is designed around a strict two-tier boundary:
|
||||
1. **Homelab Core (this repository)**: Owns NixOS operating system configuration, edge TLS ingress, SSO/LDAP directory identity, mail routing, read-only Docker socket isolation, and orchestration/deployment mechanics.
|
||||
2. **Workload Repositories (`~/Sites/<app>`)**: Independently deployed application stacks that integrate with Core through self-describing `app.yaml` manifests and workload-scoped `docker-compose.yml` definitions.
|
||||
1. **Canopy NixOS Core (`canopy-homelab/nixos-core`, this repository)**: Owns NixOS operating system configuration, edge TLS ingress, SSO/LDAP directory identity, mail routing, read-only Docker socket isolation, and orchestration/deployment mechanics.
|
||||
2. **Canopy Workloads (`~/Workloads/<app>`, e.g. `<user>/canopy-workloads`)**: Independently deployed application stacks that integrate with Core through self-describing `app.yaml` manifests and workload-scoped `docker-compose.yml` definitions.
|
||||
|
||||
All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime.
|
||||
|
||||
> [!NOTE]
|
||||
> **Current Implementation Baseline vs. Target Architecture**: This README documents the **currently implemented CLI and runtime baseline (Milestone P3)**. Under [Milestone P4 in `ROADMAP.md`](ROADMAP.md), `appctl` is transitioning from a host CLI orchestrator into a dedicated daemon service (`homelab-appctl.service`) exposing a unified logical API across local Unix socket and HTTP transports. See [`ROADMAP.md`](ROADMAP.md) for the full baseline-to-target matrix.
|
||||
> **Milestone P4 Control Plane Architecture**: Under [Milestone P4 in `ROADMAP.md`](ROADMAP.md), `appctl` operates as an operational control plane daemon service (`homelab-appctl.service`) exposing a unified logical API across a local Unix Domain Socket (`/run/homelab/appctl.sock`) and loopback HTTP (`127.0.0.1:9001`). The thin `appctl` CLI delegates commands to this daemon with automatic `SO_PEERCRED` identity inspection and token-based RBAC. See [`docs/appctl.md`](docs/appctl.md) and [`ROADMAP.md`](ROADMAP.md) for details.
|
||||
|
||||
---
|
||||
|
||||
@@ -35,7 +35,7 @@ All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_
|
||||
├───────────────────────────────┤
|
||||
│ • Core Services (Homepage, │
|
||||
│ Dozzle, Stalwart, etc.) │
|
||||
│ • Workload Apps (~/Sites/*) │
|
||||
│ • Workload Apps (~/Workloads/*) │
|
||||
└───────────────┬───────────────┘
|
||||
│ (Read-Only API via TCP:2375)
|
||||
▼
|
||||
@@ -49,8 +49,10 @@ All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_
|
||||
▲
|
||||
│ (Host Orchestration & CD)
|
||||
┌───────────────┴───────────────┐
|
||||
│ Host Control Plane Baseline │
|
||||
│ • appctl CLI + Engine │
|
||||
│ Host Control Plane (P4) │
|
||||
│ • thin appctl CLI │
|
||||
│ • homelab-appctl.service │
|
||||
│ (UDS / HTTP daemon) │
|
||||
│ • homelab-gitops.service │
|
||||
└───────────────────────────────┘
|
||||
```
|
||||
@@ -79,21 +81,29 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran
|
||||
.
|
||||
├── flake.nix # NixOS host configuration, devShell (.venv symlink), and CI checks
|
||||
├── docker-compose.yml # Core platform service stack
|
||||
├── nixos/ # Declarative NixOS modules, systemd units, and SOPS secret wiring
|
||||
├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml)
|
||||
├── nixos/ # Declarative NixOS modules, systemd units, SOPS secret wiring & instance.example.nix
|
||||
├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml template)
|
||||
├── scripts/
|
||||
│ ├── appctl # Operational CLI entrypoint and Compose environment orchestrator
|
||||
│ ├── appctl_engine.py # Discovery, two-axis provenance, TLS inspection, and Homepage sync engine
|
||||
│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for workload app.yaml
|
||||
│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST security validation
|
||||
│ └── test # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks)
|
||||
│ ├── appctl # Thin operational CLI delegating to control plane daemon
|
||||
│ ├── appctl_daemon.py # Async HTTP/UDS daemon server (homelab-appctl.service)
|
||||
│ ├── appctl_router.py # Operational router, locking, RBAC & dispatch
|
||||
│ ├── appctl_auth.py # SO_PEERCRED & Bearer token RBAC authentication
|
||||
│ ├── appctl_audit.py # Append-only fail-closed structured audit logger
|
||||
│ ├── appctl_contracts.py # Pydantic v2 schemas for daemon RPC requests & responses
|
||||
│ ├── appctl_cli.py # Unified CLI client with dual transport fallbacks
|
||||
│ ├── appctl_engine.py # Discovery, two-axis provenance, TLS inspection, and Homepage sync
|
||||
│ ├── bootstrap_token.py # Operator Bearer token provisioning helper
|
||||
│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for app.yaml
|
||||
│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST validation
|
||||
│ ├── workload_grants.py # Fail-closed Pydantic v2 loader for /etc/homelab/grants.json
|
||||
│ └── run-tests # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks)
|
||||
├── tests/ # Unit, structural, and security invariant test suites
|
||||
└── docs/ # Architecture references, operational runbooks, and MADR decisions
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quickstart & Operations (Current CLI Baseline)
|
||||
## Quickstart & Operations (Control Plane Daemon & CLI)
|
||||
|
||||
### Development & Verification
|
||||
|
||||
@@ -101,7 +111,7 @@ Entering the directory via `direnv` (`use flake`) or `nix develop` provisions th
|
||||
|
||||
```bash
|
||||
# Run full automated verification (Ruff + Pyright + Pytest + nix flake check + NixOS drv eval)
|
||||
./scripts/test
|
||||
./scripts/run-tests
|
||||
|
||||
# Run individual checks directly
|
||||
ruff check .
|
||||
@@ -111,7 +121,12 @@ pyright
|
||||
|
||||
### Workload Management (`appctl` CLI)
|
||||
|
||||
The thin `appctl` CLI connects directly to `homelab-appctl.service` via Unix Domain Socket (`/run/homelab/appctl.sock`) or loopback HTTP (`127.0.0.1:9876`). Local operators in `homelab-operators` or `wheel` receive read-only viewer access via kernel `SO_PEERCRED` without tokens, while mutating actions consume Bearer tokens from `~/.config/homelab/token`:
|
||||
|
||||
```bash
|
||||
# Check daemon health status
|
||||
appctl health
|
||||
|
||||
# List all workloads with container health and local Git checkout status
|
||||
appctl list
|
||||
|
||||
@@ -121,7 +136,7 @@ appctl list --fetch --ssl --core
|
||||
# Inspect detailed manifest, provenance, and container diagnostics for a workload
|
||||
appctl info <service>
|
||||
|
||||
# Manage workload or Core service lifecycle (executes docker compose locally in the current baseline)
|
||||
# Manage workload or Core service lifecycle (dispatched via homelab-appctl daemon)
|
||||
appctl up <service|core>
|
||||
appctl down <service|core>
|
||||
appctl restart <service|core>
|
||||
@@ -136,11 +151,12 @@ appctl sync
|
||||
### Host System Management
|
||||
|
||||
```bash
|
||||
# Rebuild and activate the NixOS host configuration
|
||||
sudo nixos-rebuild switch --flake .#server
|
||||
# Rebuild and activate the NixOS host configuration (or use the 'nix-switch' alias)
|
||||
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
|
||||
|
||||
# Inspect platform systemd units
|
||||
systemctl status homeserver-core.service
|
||||
systemctl status homelab-appctl.service
|
||||
systemctl status homelab-gitops.service
|
||||
systemctl status dynu-monitor.service
|
||||
```
|
||||
@@ -151,7 +167,7 @@ systemctl status dynu-monitor.service
|
||||
|
||||
| Document | Scope |
|
||||
| :--- | :--- |
|
||||
| [**`docs/architecture.md`**](docs/architecture.md) | Runtime layers, network segmentation, and Core / `~/Sites` boundaries. |
|
||||
| [**`docs/architecture.md`**](docs/architecture.md) | Runtime layers, network segmentation, and Core / `~/Workloads` boundaries. |
|
||||
| [**`docs/decisions/README.md`**](docs/decisions/README.md) | Architecture Decision Records (MADR 4.0) governing platform evolution. |
|
||||
| [**`ROADMAP.md`**](ROADMAP.md) | Phased engineering milestones (P0–P7) and baseline-to-target architecture matrix. |
|
||||
| [**`docs/appctl.md`**](docs/appctl.md) | Current `appctl` CLI commands, resolution hierarchy, and `app.yaml` schema v1.0 contract. |
|
||||
|
||||
+35
-32
@@ -1,36 +1,38 @@
|
||||
# 🗺️ Homelab Core & Appctl Engineering Roadmap
|
||||
# 🗺️ Canopy — NixOS 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 **Canopy 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.
|
||||
It describes the implementation trajectory and phased engineering milestones for evolving the **Canopy** platform (`canopy-homelab/nixos-core`) around a unified `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), [ADR-0003: Pydantic v2 Runtime Validation](docs/decisions/0003-pydantic-v2-runtime-validation.md), [ADR-0004: Unified ~/Workloads Monorepo](docs/decisions/0004-unified-workloads-monorepo.md), and [ADR-0005: Host-Granted Workload Capabilities](docs/decisions/0005-workload-capability-grants.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**: Declarative manifests (`app.yaml` + Compose) versioned in Git capture workload intent and platform descriptors, materialized and enforced deterministically by `appctl`.
|
||||
7. **AI Authoring Boundary & External MCP Gateway**: AI agents operate externally as proposal generators via client-side Model Context Protocol (MCP) tool integrations. Humans approve intent before any mutation is applied in Git. The server appliance hosts zero autonomous agent loops or on-server compilers.
|
||||
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 P4) | 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. |
|
||||
| **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. |
|
||||
| **`appctl` Architecture** | Dedicated daemon service (`homelab-appctl.service`, user `homelab-appctl`) exposing `POST /v1/operations` over Unix socket and loopback HTTP, with thin-client CLI (`scripts/appctl_cli.py`). | Expand with Operations UI and external ForwardAuth integration (P5–P7). |
|
||||
| **Operational Auth** | Mandatory SHA-256 Bearer token + 3-role RBAC + UDS `SO_PEERCRED` viewer fallback (`/run/secrets/appctl/tokens.json`). | LLDAP directory RBAC & Authelia ForwardAuth (P5). |
|
||||
| **Metadata & Schema Engine** | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | Standardized JSON-RPC Model Context Protocol tools over Pydantic v2 schemas (P6). |
|
||||
| **Deployment Model** | Authoritative declarative Git state (`app.yaml`, `docker-compose.yml`, `deployments.yaml`) in `~/Workloads/<app>/`, bounded by `homelab.workloadGrants` (`/etc/homelab/grants.json`). | Standardized JSON-RPC MCP tools (`P6`) and Operations UI (`P7`). |
|
||||
| **GitOps Engine** | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | Unified continuous deployment worker driven by Git webhooks delegating to control plane daemon (P4 baseline consolidated). |
|
||||
| **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). |
|
||||
| **Dashboard** | `appctl sync` compiles `config/homepage/services.yaml` from `app.yaml` manifests under `_homepage_sync.lock`. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for management (planned in P7). |
|
||||
|
||||
---
|
||||
|
||||
@@ -42,9 +44,10 @@ It describes the implementation trajectory and phased engineering milestones for
|
||||
| **P1** | **Mail Topology Realignment** | Topology & State | ✅ **Completed** | Re-homed Stalwart to the dedicated `smtp.` subdomain; migrated SnappyMail to `~/Sites/snappymail` with zero data loss. |
|
||||
| **P2** | **GitOps Hardening** | Ingress Security | ✅ **Completed** | Authoritative Core repository registry (`deployments.yaml`), Compose AST security validator, systemd sandboxing. |
|
||||
| **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0 with Pydantic v2 fail-closed models (`core_manifest.py`), two-axis status inspection, unified `appctl_engine.py`. |
|
||||
| **P4** | **Control Plane Daemon** | API & Dispatch | 🎯 **Current / Up Next** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. |
|
||||
| **P5** | **Identity & Secrets** | Auth & Providers | ⏳ **Planned** | LLDAP RBAC group mapping, Authelia ForwardAuth header integration, user-scoped token lifecycle, `SecretProvider` reference resolution. |
|
||||
| **P6** | **Deployment Model & AI**| Intent Authoring | ⏳ **Planned** | Capability catalog, `DeploymentProposal` $\to$ `DeploymentModel` compiler, Git commit pipeline. |
|
||||
| **P4** | **Control Plane Daemon** | API & Dispatch | ✅ **Completed** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. |
|
||||
| **P4.5** | **Workloads Contract & Agent Readiness** | Monorepo & Grants | ✅ **Completed** *(in `nixos-core`)* | `~/Workloads/deployments.yaml` decoupling, read-only `agents` SSH user, `homelab.workloadGrants` (`ADR-0005`), `nixos/instance.example.nix`, and `:host` CI runner workflow. |
|
||||
| **P5** | **Identity & Secrets** | Auth & Providers | 🎯 **Current / Up Next** | LLDAP RBAC group mapping, Authelia ForwardAuth header integration, user-scoped token lifecycle, `SecretProvider` reference resolution. |
|
||||
| **P6** | **Homelab MCP Gateway** | Protocol Integration | ⏳ **Planned** | Standardized JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`), client-side human-in-the-loop approvals, deprecation of on-server AI proposal compilers. |
|
||||
| **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. |
|
||||
|
||||
---
|
||||
@@ -55,7 +58,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.
|
||||
|
||||
---
|
||||
@@ -97,7 +100,7 @@ It describes the implementation trajectory and phased engineering milestones for
|
||||
---
|
||||
|
||||
### Milestone P4: Appctl Control Plane Daemon & Command-Oriented API
|
||||
**Status**: 🎯 **Current / Up Next**
|
||||
**Status**: ✅ **Completed**
|
||||
* **Objective**: Evolve `appctl` from a collection of local shell scripts into the authoritative platform daemon while enforcing authorization gates from day one.
|
||||
* **Key Deliverables**:
|
||||
1. *Daemon Service (`homelab-appctl.service`)*: Systemd daemon running as dedicated user `homelab-appctl` (`Group = "homelab-operators"`), exposing one logical HTTP/1.1 API across dual transports: Unix domain socket (`/run/homelab/appctl.sock`) on host and loopback HTTP listener (`127.0.0.1:9001`).
|
||||
@@ -120,15 +123,15 @@ It describes the implementation trajectory and phased engineering milestones for
|
||||
|
||||
---
|
||||
|
||||
### Milestone P6: Homelab Deployment Model & AI Authoring Workflow
|
||||
**Status**: ⏳ **Planned**
|
||||
* **Objective**: Enable safe, human-reviewed workload authoring from upstream repositories.
|
||||
### Milestone P6: Homelab MCP Gateway (Protocol Tool Integration)
|
||||
**Status**: ⏳ **Planned** *(Amended: Deprecated on-server `DeploymentProposal` compiler in favor of decoupled Model Context Protocol gateway)*
|
||||
* **Objective**: Expose `appctl` control plane capabilities over standardized JSON-RPC Model Context Protocol (MCP) tools for external AI assistants (Antigravity, Claude Code, Cursor) without running unverified autonomous agents on the appliance host.
|
||||
* **Key Deliverables**:
|
||||
1. *Platform Capability Catalog*: Machine-readable specification of Core capabilities and security invariants.
|
||||
2. *DeploymentProposal Schema*: Candidate model format produced by AI discovery workflows.
|
||||
3. *DeploymentModel Git Pipeline*: Operator approves proposal into a `DeploymentModel`; the model is committed to the version-controlled deployment repository (Git).
|
||||
4. *Materialization & Reconciliation*: `appctl` validates the committed model, provisions state roots, compiles platform descriptors (`app.yaml` + Compose), and reconciles running containers.
|
||||
* **Exit Criteria**: Human approval gate strictly enforced; AI possesses zero execution authority; generated workloads conform to all Core invariants.
|
||||
1. *Protocol Tool Gateway*: Standardized MCP server wrapping deterministic `appctl` operations (`appctl_status`, `appctl_logs`, `appctl_deploy`, `appctl_audit`) over JSON-RPC.
|
||||
2. *Client-Side Human-in-the-Loop Confirmation*: Native IDE/client confirmation gating for all mutating tools before execution.
|
||||
3. *Deprecate On-Server AI Proposal Compiler*: Remove requirements for server-side `DeploymentProposal` $\to$ `DeploymentModel` pipelines; desired state remains standard Git-tracked declarative YAML (`app.yaml` + Compose).
|
||||
4. *Schema & Tool Security Guards*: Strict Pydantic parameter validation on incoming MCP tool calls matching `appctl_contracts.py`.
|
||||
* **Exit Criteria**: External AI clients successfully query status, inspect logs, and request deployments through MCP with strict confirmation gates; Core boundaries remain 100% deterministic with zero autonomous agent code on the host.
|
||||
|
||||
---
|
||||
|
||||
@@ -136,7 +139,7 @@ It describes the implementation trajectory and phased engineering milestones for
|
||||
**Status**: ⏳ **Planned**
|
||||
* **Objective**: Deliver a unified web-based management experience without coupling the control plane to specific frontend engines.
|
||||
* **Key Deliverables**:
|
||||
1. *Operations UI Client*: Dedicated lightweight web client consuming the `appctl` API for proposal review, approval, real-time log streaming, and API token management.
|
||||
1. *Operations UI Client*: Dedicated lightweight web client consuming the `appctl` API for workload inspection, deployment management, real-time log streaming, and API token management.
|
||||
2. *Homepage Status Integration*: Homepage consumes live status widgets from `appctl` live endpoints or compiled service maps.
|
||||
* **Exit Criteria**: End-to-end browser and CLI deployment verification; Homepage accurately reflecting live container health.
|
||||
|
||||
@@ -146,5 +149,5 @@ It describes the implementation trajectory and phased engineering milestones for
|
||||
|
||||
Progress across milestones is governed by explicit verification criteria:
|
||||
* **Behavioral Invariant Coverage**: All defined domain, authorization, deployment, and security invariants must have automated regression tests.
|
||||
* **Pre-Merge Validation**: Every commit must pass `./scripts/test` (Ruff linter + Pytest suite + Nix flake check).
|
||||
* **Pre-Merge Validation**: Every commit must pass `./scripts/run-tests` (Ruff linter + Pytest suite + Nix flake check).
|
||||
* **Zero Production Regressions**: Platform migrations must include verified pre-flight snapshots, state parity proofs, and documented rollback runbooks.
|
||||
+15
-3
@@ -1,6 +1,6 @@
|
||||
# 🛡️ Homelab Core — Security Controls & Hardening
|
||||
# 🛡️ Canopy NixOS Core — Security Controls & Hardening
|
||||
|
||||
This document outlines the security controls, container isolation rules, and operational boundaries implemented in **Homelab Core**.
|
||||
This document outlines the security controls, container isolation rules, and operational boundaries implemented in **Canopy NixOS Core** (`canopy-homelab/nixos-core`).
|
||||
|
||||
---
|
||||
|
||||
@@ -31,6 +31,15 @@ This document outlines the security controls, container isolation rules, and ope
|
||||
* Secrets are stored encrypted in `nixos/secrets.yaml` using Age keys derived from the host SSH key (`/etc/ssh/ssh_host_ed25519_key`).
|
||||
* Decrypted secrets reside in RAM-backed ephemeral filesystems (`/run/secrets/`, `/run/credentials/`) and are not committed to unencrypted persistent files.
|
||||
|
||||
### F. Operational Control Plane Security (`homelab-appctl.service`)
|
||||
* **Transport Isolation**: Daemon listens on a restricted Unix Domain Socket (`/run/homelab/appctl.sock`, mode `0660`, group `homelab-operators`) and loopback HTTP (`127.0.0.1:9876`). It never binds to public interfaces.
|
||||
* **Authentication & RBAC**:
|
||||
- **UDS Peer Credential Identification**: Local connections inspect kernel peer credentials (`SO_PEERCRED`). Callers in `homelab-operators` or `wheel` receive read-only viewer privileges automatically without requiring secrets on disk.
|
||||
- **Cryptographic Bearer Tokens**: Mutating actions require Bearer tokens defined in SOPS (`/run/secrets/appctl/tokens.json`). Tokens are validated using `hmac.compare_digest` against SHA-256 digests.
|
||||
- **Three-Tier RBAC**: Granular role enforcement distinguishes read-only inspectors (`viewer`), workload managers (`operator`), and core platform administrators (`admin`).
|
||||
* **Per-Target Concurrency Control (`flock`)**: Non-blocking file locks (`/run/lock/homelab/<target>.lock`) serialize mutating actions per workload, returning HTTP 409 Conflict if an operation is already in flight.
|
||||
* **Fail-Closed Structured Audit Logging**: Every operational command is appended synchronously to a tamper-evident audit log (`/var/log/homelab/appctl/audit.jsonl`, mode `0600`). If disk writing fails, the daemon fails closed and rejects the request.
|
||||
|
||||
---
|
||||
|
||||
## 2. Threat Model & Operational Considerations
|
||||
@@ -54,6 +63,9 @@ This document outlines the security controls, container isolation rules, and ope
|
||||
- [x] User identities managed in LLDAP (`users.${HOMELAB_DOMAIN}`).
|
||||
- [x] `socket-proxy` configured with `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`.
|
||||
- [x] Webhook HMAC signature verification active on port 9000.
|
||||
- [x] Invariant test runner (`./scripts/test`) passing on changes.
|
||||
- [x] Invariant test runner (`./scripts/run-tests`) passing on changes.
|
||||
- [x] `config/letsencrypt/acme.json` permissions set to `0600`.
|
||||
- [x] Host firewall ports restricted to declared services in `nixos/modules/homeserver.nix`.
|
||||
- [x] Control plane daemon (`homelab-appctl.service`) isolated to UDS (`0660`) and loopback HTTP.
|
||||
- [x] Operational audit log (`/var/log/homelab/appctl/audit.jsonl`) append-only with strict `0600` permissions.
|
||||
- [x] Control plane mutation endpoints enforce per-target `flock` and SHA-256 Bearer tokens.
|
||||
@@ -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" }}'
|
||||
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" }}'
|
||||
|
||||
access_control:
|
||||
default_policy: deny
|
||||
|
||||
+12
-47
@@ -1,53 +1,18 @@
|
||||
# Core Authoritative Repository Identity Registry
|
||||
# Governs admitted continuous deployment targets for GitOps webhook execution.
|
||||
# Example Repository Identity Registry Template
|
||||
# Live production deployments are configured in ~/Workloads/deployments.yaml
|
||||
# (or overridden via the HOMELAB_DEPLOYMENTS_FILE environment variable).
|
||||
#
|
||||
# Owns: repository identity, canonical filesystem path, and aliases.
|
||||
# Enforces: strict path containment within ~/Sites.
|
||||
# Enforces: strict path containment within ~/Workloads (WORKLOADS_DIR).
|
||||
|
||||
schemaVersion: "1.0"
|
||||
repositories:
|
||||
snappymail:
|
||||
path: "/home/kiskaadee/Sites/snappymail"
|
||||
example-app:
|
||||
path: "~/Workloads/example-app"
|
||||
aliases:
|
||||
- "homelab-snappymail"
|
||||
- "mail"
|
||||
- "webmail"
|
||||
gitea:
|
||||
path: "/home/kiskaadee/Sites/homelab-gitea"
|
||||
- "example"
|
||||
- "homelab-example"
|
||||
example-docs:
|
||||
path: "~/Workloads/example-docs"
|
||||
aliases:
|
||||
- "homelab-gitea"
|
||||
- "git"
|
||||
jellyfin:
|
||||
path: "/home/kiskaadee/Sites/homelab-jellyfin"
|
||||
aliases:
|
||||
- "homelab-jellyfin"
|
||||
- "media"
|
||||
docs:
|
||||
path: "/home/kiskaadee/Sites/homelab-doc2site"
|
||||
aliases:
|
||||
- "doc2site"
|
||||
- "homelab-doc2site"
|
||||
courses:
|
||||
path: "/home/kiskaadee/Sites/courses"
|
||||
aliases:
|
||||
- "homelab-courses"
|
||||
bdinvite:
|
||||
path: "/home/kiskaadee/Sites/homelab-bdinvite"
|
||||
aliases:
|
||||
- "homelab-bdinvite"
|
||||
- "birthday"
|
||||
landing:
|
||||
path: "/home/kiskaadee/Sites/homelab-landing"
|
||||
aliases:
|
||||
- "homelab-landing"
|
||||
mermaid:
|
||||
path: "/home/kiskaadee/Sites/homelab-mermaid"
|
||||
aliases:
|
||||
- "homelab-mermaid"
|
||||
excalidraw:
|
||||
path: "/home/kiskaadee/Sites/homelab-excalidraw"
|
||||
aliases:
|
||||
- "homelab-excalidraw"
|
||||
houston:
|
||||
path: "/home/kiskaadee/Sites/homelab-houston"
|
||||
aliases:
|
||||
- "homelab-houston"
|
||||
- "docs"
|
||||
@@ -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
|
||||
+15
-7
@@ -3,6 +3,8 @@ services:
|
||||
image: tecnativa/docker-socket-proxy
|
||||
container_name: socket-proxy
|
||||
restart: always
|
||||
ports:
|
||||
- "127.0.0.1:2375:2375"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
environment:
|
||||
@@ -42,7 +44,7 @@ services:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
environment:
|
||||
- DYNU_API_KEY=${DYNU_API_KEY}
|
||||
- CF_DNS_API_TOKEN=${CF_DNS_API_TOKEN}
|
||||
- DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40}
|
||||
command:
|
||||
- "--log.level=INFO"
|
||||
@@ -59,7 +61,7 @@ services:
|
||||
- "--entrypoints.websecure.http.tls.domains[0].sans=*.${DOMAIN}"
|
||||
# SSL Setup
|
||||
- "--certificatesresolvers.myresolver.acme.dnschallenge=true"
|
||||
- "--certificatesresolvers.myresolver.acme.dnschallenge.provider=dynu"
|
||||
- "--certificatesresolvers.myresolver.acme.dnschallenge.provider=cloudflare"
|
||||
- "--certificatesresolvers.myresolver.acme.email=${ACME_EMAIL}"
|
||||
- "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"
|
||||
volumes:
|
||||
@@ -79,6 +81,11 @@ services:
|
||||
- "traefik.http.middlewares.authelia-auth.forwardauth.trustForwardHeader=true"
|
||||
- "traefik.http.middlewares.authelia-auth.forwardauth.authResponseHeaders=Remote-User,Remote-Groups,Remote-Email,Remote-Name"
|
||||
|
||||
# Middleware: Public Rate Limit (mitigates scraper/crawler bursts on public routes)
|
||||
- "traefik.http.middlewares.public-ratelimit.ratelimit.average=20"
|
||||
- "traefik.http.middlewares.public-ratelimit.ratelimit.burst=40"
|
||||
- "traefik.http.middlewares.public-ratelimit.ratelimit.period=1s"
|
||||
|
||||
# Dashboard - Public (HTTPS)
|
||||
- "traefik.http.routers.traefik-dash.rule=Host(`traefik.${DOMAIN}`)"
|
||||
- "traefik.http.routers.traefik-dash.entrypoints=websecure"
|
||||
@@ -106,11 +113,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
|
||||
@@ -142,6 +149,7 @@ services:
|
||||
- ./config/authelia:/config
|
||||
environment:
|
||||
- DOMAIN=${DOMAIN}
|
||||
- LLDAP_LDAP_BASE_DN=${LLDAP_LDAP_BASE_DN}
|
||||
- AUTHELIA_SESSION_SECRET=${AUTHELIA_SESSION_SECRET}
|
||||
- AUTHELIA_STORAGE_ENCRYPTION_KEY=${AUTHELIA_STORAGE_ENCRYPTION_KEY}
|
||||
- AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET=${AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET}
|
||||
@@ -222,12 +230,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:
|
||||
|
||||
+156
-49
@@ -3,49 +3,142 @@
|
||||
The `appctl` tool is the command-line orchestrator and metadata engine for the **Homelab Core** platform. It coordinates interactions between independent workload repositories in `~/Sites` and platform services in `~/Core`.
|
||||
|
||||
> [!NOTE]
|
||||
> **Implementation Reference**: This document serves as the **current implementation manual (Milestone P3)** for the `appctl` Bash CLI wrapper (`scripts/appctl`), metadata/provenance engine (`scripts/appctl_engine.py`), and Pydantic v2 manifest parser (`scripts/core_manifest.py`).
|
||||
> For the platform's planned Milestone P4 control-plane daemon transition and phased engineering roadmap, see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md).
|
||||
> **Implementation Reference**: This document serves as the **current implementation manual (Milestone P4)** for the `appctl` Operational Control Plane Daemon (`scripts/appctl_daemon.py`), Operational Router (`scripts/appctl_router.py`), Thin-Client CLI (`scripts/appctl`, `scripts/appctl_cli.py`), metadata/provenance engine (`scripts/appctl_engine.py`), and Pydantic v2 manifest parser (`scripts/core_manifest.py`).
|
||||
> For the platform's phased engineering roadmap, see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md).
|
||||
|
||||
---
|
||||
|
||||
## 1. How `appctl` Works
|
||||
|
||||
`appctl` consists of three cooperating modules in `scripts/`:
|
||||
1. **[`scripts/appctl`](../scripts/appctl)** (Bash CLI wrapper): Parses CLI arguments, sources runtime secret templates, injects validated workload environment variables, dispatches `docker compose` commands, and provides shell autocompletions.
|
||||
2. **[`scripts/appctl_engine.py`](../scripts/appctl_engine.py)** (Discovery, Provenance & TLS Engine): Scans `~/Sites/*`, evaluates **two-axis status** (local deployment checkout state vs. upstream software provenance), inspects live container health and TLS certificates, and compiles the Homepage dashboard configuration.
|
||||
3. **[`scripts/core_manifest.py`](../scripts/core_manifest.py)** (Schema v1.0 Parser & Validator): Enforces fail-closed Pydantic v2 validation (`ConfigDict(extra="forbid")`) on `app.yaml` manifests, validates upstream Git transport schemes (`https://`, `ssh://`, `git@`), classifies reference mutability (branch, tag, commit SHA), and blocks reserved host environment keys (`PATH`, `LD_PRELOAD`, `IFS`, `CORE_DIR`, `SITES_DIR`, etc.).
|
||||
Under Milestone P4, `appctl` operates as a centralized operational control plane daemon (`homelab-appctl.service`, running as isolated user `homelab-appctl:homelab-operators`) backed by cooperating modules in `scripts/`:
|
||||
|
||||
1. **[`scripts/appctl`](../scripts/appctl) & [`scripts/appctl_cli.py`](../scripts/appctl_cli.py)** (Thin-Client CLI): Dispatches operational commands over the Unix domain socket (`/run/homelab/appctl.sock`) using HTTP/1.1 (`POST /v1/operations`), resolves operator Bearer tokens (`--token`, `APPCTL_TOKEN`, `~/.config/homelab/token`), renders human-readable tables, and fast-paths local shell autocompletions (`complete`, `completion`, `resolve`).
|
||||
2. **[`scripts/appctl_daemon.py`](../scripts/appctl_daemon.py) & [`scripts/appctl_contracts.py`](../scripts/appctl_contracts.py)** (Dual-Transport Control Plane Server & Contracts): Serves a single logical HTTP/1.1 API (`POST /v1/operations` + `GET /v1/health`) identically across `/run/homelab/appctl.sock` (mode `0660`) and loopback TCP (`127.0.0.1:9001`), enforcing 64 KiB request caps and strict Pydantic v2 contracts (`ConfigDict(extra="forbid", strict=True)`).
|
||||
3. **[`scripts/appctl_auth.py`](../scripts/appctl_auth.py) & [`scripts/appctl_audit.py`](../scripts/appctl_audit.py)** (Zero-Trust Auth, 3-Role RBAC & Fail-Closed Audit Guard): Verifies SHA-256 Bearer tokens against `/run/secrets/appctl/tokens.json` (mode `0400`) using `hmac.compare_digest`, maps tokenless local UDS `SO_PEERCRED` callers strictly to `homelab-viewer` (non-sensitive read-only inspection), enforces `homelab-admin` / `homelab-operator` / `homelab-viewer` RBAC, serializes mutations via per-target `fcntl.flock`, and writes append-only audit records to `/var/log/homelab/appctl/audit.jsonl` (mode `0600`) before any mutation executes.
|
||||
4. **[`scripts/appctl_router.py`](../scripts/appctl_router.py)** (Operational Router & Unified Execution Engine): Enforces pre-flight path containment, `core_manifest.parse_manifest()`, and `validate_compose_security()` AST checks; assembles the 6-layer execution environment in pure Python (zero shell `source` or `eval`); and runs bounded `git` and `docker compose` subprocesses (`shell=False`, 256 KiB output cap, hard timeouts).
|
||||
5. **[`scripts/appctl_engine.py`](../scripts/appctl_engine.py) & [`scripts/core_manifest.py`](../scripts/core_manifest.py)** (Discovery, Provenance & Schema v1.0 Validator): Scans `~/Sites/*`, evaluates **two-axis status** (local deployment checkout state vs. upstream software provenance), inspects live container health and TLS certificates, validates `app.yaml` manifests, and atomically compiles the Homepage dashboard configuration under `_homepage_sync.lock`.
|
||||
|
||||
```text
|
||||
┌───────────────────────────────┐
|
||||
│ appctl <command> │
|
||||
└───────────────┬───────────────┘
|
||||
│
|
||||
┌──────────────────────────┐ ┌──────────────────────────┐
|
||||
│ appctl <cmd> (CLI) │ │ homelab-gitops.service │
|
||||
└────────────┬─────────────┘ └────────────┬─────────────┘
|
||||
│ UDS (/run/homelab/appctl.sock) │ Bearer Token (homelab-operator)
|
||||
└─────────────────┬─────────────────┘
|
||||
▼
|
||||
┌───────────────────────────┐
|
||||
│ setup_app_env() │
|
||||
└─────────────┬─────────────┘
|
||||
│
|
||||
┌──────────────────────────┴──────────────────────────┐
|
||||
▼ ▼
|
||||
[ appctl_engine.py resolve ] [ Source Secrets ]
|
||||
• Parses app.yaml via core_manifest.py /run/secrets/traefik-deployments.env
|
||||
• Fails closed on manifest_error /run/secrets/homeserver.env
|
||||
│ │
|
||||
└──────────────────────────┬──────────────────────────┘
|
||||
┌────────────────────────────────────────────────┐
|
||||
│ homelab-appctl.service (appctl_daemon.py) │
|
||||
│ • POST /v1/operations & GET /v1/health │
|
||||
│ • Auth: SHA-256 tokens.json + SO_PEERCRED │
|
||||
│ • RBAC: admin / operator / viewer │
|
||||
└────────────────────────┬───────────────────────┘
|
||||
▼
|
||||
┌─────────────────────────────┐
|
||||
│ Injected Compose Context │
|
||||
│ • PROXY_NETWORK │
|
||||
│ • SERVICE_DOMAIN / DOMAIN │
|
||||
│ • CONTAINER_NAME │
|
||||
│ • Validated manifest env │
|
||||
└──────────────┬──────────────┘
|
||||
┌────────────────────────────────────────────────┐
|
||||
│ OperationalRouter (appctl_router.py) │
|
||||
│ • Per-target flock + Fail-closed DISPATCHED │
|
||||
│ audit write (/var/log/homelab/appctl/...) │
|
||||
│ • Pre-flight: parse_manifest() + Compose AST │
|
||||
│ • Pure-Python 6-layer .env assembly │
|
||||
└────────────────────────┬───────────────────────┘
|
||||
▼
|
||||
┌─────────────────────────────┐
|
||||
│ docker compose <subcommand> │
|
||||
└─────────────────────────────┘
|
||||
┌────────────────────────────────────────────────┐
|
||||
│ Bounded Subprocess Engine (shell=False) │
|
||||
│ • git status / pull --ff-only │
|
||||
│ • docker compose -f <file> <subcommand> │
|
||||
└────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Operator Admin Token Bootstrapping & Rotation
|
||||
|
||||
`appctl` implements zero-trust authorization across three roles: `homelab-admin`, `homelab-operator`, and `homelab-viewer`. Local Unix domain socket (`/run/homelab/appctl.sock`) callers without a token are granted `homelab-viewer` privileges via `SO_PEERCRED` for non-sensitive read-only commands (e.g., `appctl list`, `appctl status`, `appctl ssl`).
|
||||
|
||||
Sensitive inspection (e.g., `appctl config <workload>` which renders secrets in Compose definitions) and all mutating operations (e.g., `appctl up`, `appctl restart`, `appctl update`) require an authenticated Bearer token.
|
||||
|
||||
#### Role of `~/.config/homelab/token`
|
||||
The thin CLI client resolves Bearer tokens in the following order of precedence:
|
||||
1. Direct CLI flag: `--token <secret>`
|
||||
2. Environment variable: `APPCTL_TOKEN`
|
||||
3. Local operator token file: `~/.config/homelab/token` (mode `0600`)
|
||||
4. System service token file: `/run/secrets/appctl/token`
|
||||
|
||||
The standard operator setup stores a 256-bit hex Bearer token with mode `0600` in `~/.config/homelab/token`.
|
||||
|
||||
#### Generating a Token (`scripts/bootstrap_token.py`)
|
||||
To generate an operator token and its matching SHA-256 descriptor:
|
||||
|
||||
```bash
|
||||
python3 scripts/bootstrap_token.py
|
||||
```
|
||||
|
||||
This utility:
|
||||
1. Generates a cryptographically secure 256-bit token (`secrets.token_hex(32)`).
|
||||
2. Computes the SHA-256 digest: `hashlib.sha256(raw_token.encode("utf-8")).hexdigest()`.
|
||||
3. Ensures `~/.config/homelab` exists with mode `0700`.
|
||||
4. Writes the raw Bearer token to `~/.config/homelab/token` with mode `0600`.
|
||||
5. Outputs the JSON descriptor matching `TokenDescriptor` in `scripts/appctl_auth.py`:
|
||||
|
||||
```json
|
||||
{
|
||||
"token_id": "operator-admin",
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"sha256": "4a12...<64-hex-sha256>"
|
||||
}
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> The raw secret is **never** printed to stdout or stderr. Only the descriptor snippet (containing the SHA-256 digest) is output. To print only the JSON snippet for automation or piping, pass `--print-json`.
|
||||
|
||||
#### Registering the Descriptor in SOPS
|
||||
Insert the generated JSON descriptor into your encrypted SOPS secrets store (`nixos/secrets.yaml`):
|
||||
|
||||
```bash
|
||||
sops nixos/secrets.yaml
|
||||
```
|
||||
|
||||
Under `appctl.tokens_json`, add the entry to the JSON list:
|
||||
```yaml
|
||||
appctl:
|
||||
tokens_json: |
|
||||
[
|
||||
{
|
||||
"token_id": "operator-admin",
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"sha256": "<64-hex-sha256>"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
Save and exit your editor (SOPS will re-encrypt the file), then project the updated secrets:
|
||||
```bash
|
||||
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
|
||||
```
|
||||
This updates `/run/secrets/appctl/tokens.json` (owned by `homelab-appctl:homelab-operators`, mode `0400`), which `homelab-appctl.service` consumes.
|
||||
|
||||
#### Verifying Token Authentication
|
||||
Verify permissions using both unauthenticated and authenticated queries:
|
||||
|
||||
1. **Viewer Inspection** (succeeds without token via `SO_PEERCRED`):
|
||||
```bash
|
||||
appctl health
|
||||
# Output: OK (homelab-appctl.service operational)
|
||||
```
|
||||
|
||||
2. **Admin-Gated Operation** (requires `homelab-admin` Bearer token):
|
||||
```bash
|
||||
appctl config docs
|
||||
# Renders the resolved Compose YAML with injected secrets
|
||||
```
|
||||
If the token is missing or mismatched, `appctl` returns `401 Unauthorized` or `403 Forbidden` with `ERR_PERMISSION_DENIED`.
|
||||
|
||||
#### Token Rotation Workflow
|
||||
To rotate an operator token:
|
||||
1. Run `python3 scripts/bootstrap_token.py --force --token-id "operator-admin-$(date +%Y%m%d)"`.
|
||||
2. Open `sops nixos/secrets.yaml` and add the new descriptor to `appctl.tokens_json`. Keep the old entry temporarily if multiple sessions share it, or replace it immediately.
|
||||
3. Run `sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure` to apply the updated token store.
|
||||
4. Verify CLI operations (`appctl config docs`).
|
||||
5. Remove the deprecated token descriptor from `nixos/secrets.yaml` and re-run `nixos-rebuild switch`.
|
||||
|
||||
---
|
||||
|
||||
## 2. CLI Command Reference
|
||||
@@ -100,11 +193,13 @@ appctl info docs --ssl
|
||||
|
||||
### Lifecycle Management
|
||||
|
||||
#### `appctl up <service|core>`
|
||||
#### `appctl up <service|core> [--build] [--no-cache]`
|
||||
Starts the specified service stack in detached mode (`--remove-orphans`).
|
||||
* For a workload in `~/Sites`: starts containers and triggers `appctl sync`.
|
||||
* For `core`: starts the entire Core Compose stack using `/run/secrets/homeserver.env`.
|
||||
* For an individual Core service (e.g., `appctl up traefik`): starts that specific container.
|
||||
* When `--build` is passed: invokes `docker compose build --pull` prior to deployment. The `--pull` flag guarantees base images in Dockerfile `FROM` lines are refreshed from remote registries.
|
||||
* When `--no-cache` is passed: `--build` is implied (`build: True`) and `docker compose build --pull --no-cache` is executed, forcing a clean rebuild without cached layers.
|
||||
|
||||
#### `appctl down <service|core>`
|
||||
Stops and removes containers defined in the target's Compose file (or stops the targeted Core container).
|
||||
@@ -115,19 +210,31 @@ Restarts the target stack or individual container:
|
||||
* `appctl restart core`: Restarts all Core Compose services.
|
||||
* `appctl restart traefik`: Restarts only the Traefik container.
|
||||
|
||||
#### `appctl update <service|core>`
|
||||
Performs a sequential update workflow:
|
||||
#### `appctl update <service> [--branch <branch>] [--build] [--no-cache]`
|
||||
Performs a sequential, revision-consistent update workflow for a Sites workload stack:
|
||||
1. Verifies that the local Git working tree is clean (aborts if uncommitted changes exist).
|
||||
2. Runs `git pull --ff-only` to fast-forward the current branch.
|
||||
3. Runs `docker compose pull` to fetch updated container images.
|
||||
4. Runs `docker compose up -d --remove-orphans` to recreate containers.
|
||||
2. Runs `git pull --ff-only [origin <expected_branch>]` to fast-forward the current branch.
|
||||
3. Re-validates `app.yaml`, expected branch declaration, and Compose security rules against the newly pulled working tree.
|
||||
4. Executes declared actions in `app.yaml` (`actions: [git_pull, compose_pull, compose_build, compose_up, compose_restart]`):
|
||||
* `compose_pull`: Runs `docker compose pull` to fetch updated container images.
|
||||
* `compose_build`: Runs `docker compose build --pull` (and `--no-cache` if requested).
|
||||
* `compose_up`: Runs `docker compose up -d --remove-orphans` to recreate containers.
|
||||
* When `--build` is passed via CLI, `compose_build` is automatically executed prior to `compose_up`, even if omitted from manifest actions.
|
||||
* When `--no-cache` is passed, build is implied and executes with `--no-cache`.
|
||||
5. Runs `appctl sync` to update the Homepage dashboard.
|
||||
|
||||
> [!NOTE]
|
||||
> **Source-Built Workload Policy**: For workloads built directly from local source Dockerfiles rather than pre-built registry images, declare `compose_build` in `app.yaml` `deployment.actions` (`actions: [git_pull, compose_build, compose_up]`). Both manual `appctl update` and automated GitOps dispatcher runs will execute `docker compose build --pull` before recreating containers, ensuring reproducible builds with current upstream base layers.
|
||||
|
||||
> [!NOTE]
|
||||
> Core platform updates are managed via version-controlled NixOS generations (`git pull` followed by `nixos-rebuild switch`), not through `appctl update core` (as Core is mounted read-only for `homelab-appctl.service`).
|
||||
|
||||
#### `appctl pull <service|core>`
|
||||
Pulls latest container images and recreates the target service.
|
||||
|
||||
#### `appctl logs <service|core>`
|
||||
Streams container logs (`docker compose logs -f`). Supports passing specific container names (`appctl logs core traefik` or `appctl logs stalwart`).
|
||||
#### `appctl logs <service|core> [--tail N]`
|
||||
Fetches a bounded snapshot of container logs (default: `--tail 100`). Supports passing a workload or targeted Core service container (e.g., `appctl logs traefik`).
|
||||
*(Note: As an HTTP/1.1 request-response API, log streaming `-f` is replaced by bounded snapshots).*
|
||||
|
||||
#### `appctl config <service|core>`
|
||||
Validates the manifest and renders the resolved Docker Compose configuration with all injected variables. Fails closed if `app.yaml` is missing or invalid.
|
||||
@@ -197,21 +304,21 @@ homepage:
|
||||
|
||||
## 4. Environment Injection & Resolution Precedence
|
||||
|
||||
When `appctl` executes commands against a workload, environment variables are resolved in this sequence:
|
||||
When `OperationalRouter` (`scripts/appctl_router.py`) executes commands against a workload or Core stack, the 6-layer execution environment is assembled in memory using a pure-Python inert `KEY=VALUE` parser (`parse_dotenv`) with zero shell `source` or variable expansion:
|
||||
|
||||
1. **Global Secrets & Templates**: Sourced from `/run/secrets/rendered/homeserver.env` and `/run/secrets/rendered/traefik-deployments.env` (with `/run/secrets/*` fallbacks).
|
||||
2. **Canonical Root Domain Lock**: `HOMELAB_DOMAIN` is locked at startup using precedence `HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN` so per-workload `DOMAIN` exports cannot corrupt the platform apex domain.
|
||||
3. **Infrastructure Defaults**:
|
||||
1. **Base System Path & Docker Config**: `PATH` and `DOCKER_CONFIG`.
|
||||
2. **Global Secrets & Templates**: Parsed inertly from `/run/secrets/rendered/homeserver.env` and `/run/secrets/rendered/traefik-deployments.env` (with `/run/secrets/*` fallbacks).
|
||||
3. **Canonical Root Domain Lock**: `HOMELAB_DOMAIN` is locked using precedence `HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN` (failing closed if unset).
|
||||
4. **Infrastructure Defaults & Application Identity**:
|
||||
- `PROXY_NETWORK` (defaults to `proxy-net`)
|
||||
- `CERT_RESOLVER` (defaults to `myresolver`)
|
||||
- `DOMAIN_SUFFIX` (defaults to `$HOMELAB_DOMAIN`)
|
||||
4. **Application Identity**:
|
||||
- `DOMAIN_SUFFIX` (`$HOMELAB_DOMAIN`)
|
||||
- `SERVICE_NAME` = `<canonical-name>`
|
||||
- `CONTAINER_NAME` = `<canonical-name>`
|
||||
- `SERVICE_DOMAIN` = `<resolved-domain>`
|
||||
- `DOMAIN` = `<resolved-domain>`
|
||||
5. **Manifest Variables**: Validated key-value pairs from the `env:` block in `app.yaml` (emitted via null-delimited stream without shell `eval`).
|
||||
6. **Local Repository Files**: Sourced from `$APP_DIR/.env` and `$APP_DIR/app.env` if present.
|
||||
- `SERVICE_DOMAIN` = `<canonical-name>.<HOMELAB_DOMAIN>`
|
||||
- `DOMAIN` = `<HOMELAB_DOMAIN>`
|
||||
5. **Manifest Variables**: Validated key-value pairs from the `env:` block in `app.yaml`.
|
||||
6. **Local Repository Files**: Parsed inertly from `$APP_DIR/.env` and `$APP_DIR/app.env` if present, rejecting any key violating `ENV_KEY_RE` or matching `RESERVED_ENV_KEYS`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+18
-16
@@ -3,8 +3,8 @@
|
||||
This document details the architectural structure, component roles, networking models, and security controls of the **Homelab Core** platform.
|
||||
|
||||
> [!NOTE]
|
||||
> **Implementation Scope**: This document details the **current runtime architecture (Milestone P3)**, edge routing, container topologies, and network isolation models of Homelab Core.
|
||||
> For the planned Milestone P4 control-plane daemon transition and phased engineering milestones, see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md).
|
||||
> **Implementation Scope**: This document details the **current runtime architecture (Milestone P4)**, operational control plane daemon (`homelab-appctl.service`), edge routing, container topologies, and network isolation models of Homelab Core.
|
||||
> For phased engineering milestones (P5–P7), see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md).
|
||||
|
||||
---
|
||||
|
||||
@@ -14,7 +14,7 @@ To understand how the system is organized, three architectural dimensions are di
|
||||
|
||||
### A. Ownership Boundary
|
||||
* **Core (`~/Core`) owns**: NixOS host configuration, shared platform services, edge ingress, identity boundaries, secrets distribution, and deployment orchestration mechanics.
|
||||
* **Workload Plane (`~/Sites`) owns**: Independent application deployments, workload-specific Docker Compose files, declarative `app.yaml` manifests, and workload-scoped runtime state (`~/var/lib/homelab/<app>/`).
|
||||
* **Workload Plane (`~/Workloads`) owns**: Independent application deployments, workload-specific Docker Compose files, declarative `app.yaml` manifests, `~/Workloads/deployments.yaml`, and workload-scoped runtime state (`~/var/lib/homelab/<app>/`).
|
||||
|
||||
### B. Four Runtime Layers
|
||||
The runtime environment consists of four functional layers:
|
||||
@@ -35,23 +35,24 @@ The runtime environment consists of four functional layers:
|
||||
│
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ 3. WORKLOAD PLANE (~/Sites) │
|
||||
│ 3. WORKLOAD PLANE (~/Workloads) │
|
||||
│ Autonomous Workload Repositories (SnappyMail, Docs, Gitea, etc.) │
|
||||
│ Declarative app.yaml Manifests & Compose Stacks │
|
||||
└───────────────────────────────────┬────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ 4. HOST FOUNDATION │
|
||||
│ 4. HOST FOUNDATION & CONTROL PLANE DAEMONS │
|
||||
│ NixOS Linux · sops-nix Secrets · Docker Engine · Systemd Units │
|
||||
│ homelab-appctl.service (Control Plane Daemon) · homelab-gitops │
|
||||
│ Smart Dynu DDNS Monitor · Host Firewall · /run Secret Projections │
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### C. Cross-Cutting Orchestration
|
||||
Orchestration coordinates operations across the runtime layers:
|
||||
* **`appctl` CLI, Provenance Engine & Schema Parser (`scripts/appctl`, `scripts/appctl_engine.py`, `scripts/core_manifest.py`)**: Current CLI implementation coordinating workload discovery, fail-closed Pydantic v2 `app.yaml` validation, two-axis provenance inspection, and Homepage compilation across workloads and Core. Under Milestone P4, this transitions into the centralized operational control plane daemon (`homelab-appctl.service`).
|
||||
* **GitOps Webhook Dispatcher (`scripts/gitops_dispatcher.py`)**: Governed by the `homelab-gitops.service` systemd unit, it receives webhooks on port 9000, verifies HMAC-SHA256 signatures, enforces the `config/deployments.yaml` allowlist and Compose AST security checks, and dispatches serialized deployment actions for `~/Sites` workloads.
|
||||
* **`appctl` Operational Control Plane Daemon (`homelab-appctl.service`, `scripts/appctl_daemon.py`, `scripts/appctl_router.py`)**: Centralized control plane running under isolated service identity `homelab-appctl:homelab-operators`. Exposes `POST /v1/operations` and `GET /v1/health` over `/run/homelab/appctl.sock` (mode `0660`) and `127.0.0.1:9001`, enforcing SHA-256 Bearer token authentication, 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`), per-target `flock` serialization, fail-closed append-only audit logging (`/var/log/homelab/appctl/audit.jsonl`), Pydantic v2 `app.yaml` validation, Compose AST security checks (enforcing host-granted `homelab.workloadGrants` from `/etc/homelab/grants.json` via `scripts/workload_grants.py`), and pure-Python `.env` assembly.
|
||||
* **GitOps Webhook Dispatcher (`scripts/gitops_dispatcher.py`)**: Governed by the `homelab-gitops.service` systemd unit, it receives webhooks on port 9000, verifies HMAC-SHA256 signatures, enforces the `~/Workloads/deployments.yaml` allowlist (configured via `HOMELAB_DEPLOYMENTS_FILE`, with `config/deployments.yaml` as the example template), and delegates serialized `workload.update` execution to `homelab-appctl.service` over `/run/homelab/appctl.sock` using its `homelab-operator` Bearer token.
|
||||
|
||||
---
|
||||
|
||||
@@ -69,7 +70,7 @@ Orchestration coordinates operations across the runtime layers:
|
||||
- Mounted read-only: `/var/run/docker.sock:/var/run/docker.sock:ro`.
|
||||
- State-modifying and execution endpoints disabled: `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`, `COMMIT=0`, `CONFIGS=0`, `DISTRIBUTION=0`, `NODES=0`, `PLUGINS=0`, `SECRETS=0`, `SWARM=0`, `SYSTEM=0`.
|
||||
- Read-only inspection endpoints enabled: `CONTAINERS=1`, `NETWORKS=1`, `SERVICES=1`, `TASKS=1`, `IMAGES=1`, `VOLUMES=1`, `INFO=1`, `EVENTS=1`, `PING=1`, `VERSION=1`.
|
||||
* **Network**: Attached exclusively to `socket-net`. Application containers in `~/Sites` are never attached to `socket-net`.
|
||||
* **Network**: Attached exclusively to `socket-net`. Application containers in `~/Workloads` are never attached to `socket-net`.
|
||||
|
||||
### C. Identity & Directory Services (`lldap` & `authelia`)
|
||||
* **`lldap`**: Lightweight LDAP directory service storing user accounts, password hashes, and groups. Web UI exposed at `users.${HOMELAB_DOMAIN}` (protected by Authelia). SQLite database stored in `config/lldap/data/users.db`.
|
||||
@@ -83,15 +84,16 @@ Orchestration coordinates operations across the runtime layers:
|
||||
- WebAdmin & JMAP endpoint accessible at `smtp.${HOMELAB_DOMAIN}` via Traefik.
|
||||
- Authenticates users against the LLDAP directory.
|
||||
- Outbound mail relay configured to route through an external smart host (Brevo SMTP relay via SOPS secrets).
|
||||
- *(Note: User-facing webmail, such as SnappyMail, runs as an independent Class B workload in `~/Sites/snappymail` with isolated state under `~/var/lib/homelab/snappymail/`.)*
|
||||
- *(Note: User-facing webmail, such as SnappyMail, runs as an independent Class B workload in `~/Workloads/snappymail` with isolated state under `~/var/lib/homelab/snappymail/`.)*
|
||||
|
||||
### E. Portal & Observability (`homepage`, `dozzle`)
|
||||
* **`homepage`**: Service dashboard at `dashboard.${HOMELAB_DOMAIN}`. Synchronized from `app.yaml` manifests in `~/Sites` by `appctl sync`.
|
||||
* **`homepage`**: Service dashboard at `dashboard.${HOMELAB_DOMAIN}`. Synchronized from `app.yaml` manifests in `~/Workloads` by `appctl sync`.
|
||||
* **`dozzle`**: Real-time container log viewer at `logs.${HOMELAB_DOMAIN}`, connecting read-only through `socket-proxy`.
|
||||
|
||||
### F. Host Foundation & Daemons
|
||||
* **`homeserver-core.service`**: Systemd unit managing the Core Docker Compose stack (`~/Core/docker-compose.yml`) using secrets projected to `/run/secrets/homeserver.env`.
|
||||
* **`homelab-gitops.service`**: Systemd unit listening on port 9000 executing `scripts/gitops_dispatcher.py` under strict systemd sandboxing (`ProtectSystem=strict`, `ProtectHome=read-only`).
|
||||
* **`homelab-appctl.service`**: Operational control plane daemon running as dedicated user `homelab-appctl:homelab-operators` with dual listeners (`/run/homelab/appctl.sock` and `127.0.0.1:9001`), fail-closed audit logging (`/var/log/homelab/appctl/audit.jsonl`), and strict systemd sandboxing (`ProtectSystem=strict`, `ProtectHome=read-only`).
|
||||
* **`homelab-gitops.service`**: Systemd unit listening on port 9000 executing `scripts/gitops_dispatcher.py` under strict systemd sandboxing (`ProtectSystem=strict`, `ProtectHome=read-only`), delegating worker deployments to `homelab-appctl.service`.
|
||||
* **`dynu-monitor.service` & `dynu-monitor.timer`**: IP change monitor executing `nixos/scripts/monitor.py` every 30 minutes to detect WAN IP changes and update DNS via `ddclient`.
|
||||
|
||||
---
|
||||
@@ -111,7 +113,7 @@ Homelab Core configures two isolated Docker bridge networks:
|
||||
│ │ • traefik (router) • authelia (sso) │ │
|
||||
│ │ • lldap (directory) • stalwart (mail) │ │
|
||||
│ │ • homepage (dashboard) • dozzle (logs) │ │
|
||||
│ │ • All User Workloads (~/Sites/*) │ │
|
||||
│ │ • All User Workloads (~/Workloads/*) │ │
|
||||
│ └──────────────────────────────┬───────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌──────────────────────────────┴───────────────────────────────┐ │
|
||||
@@ -127,7 +129,7 @@ Homelab Core configures two isolated Docker bridge networks:
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
1. **`proxy-net`**: Ingress routing network. Traefik directs traffic to backend service containers on this network. Workload containers in `~/Sites` join `proxy-net`.
|
||||
1. **`proxy-net`**: Ingress routing network. Traefik directs traffic to backend service containers on this network. Workload containers in `~/Workloads` join `proxy-net`.
|
||||
2. **`socket-net`**: Isolated Docker socket proxy network. Only Core infrastructure components needing read-only container metadata join this network.
|
||||
|
||||
---
|
||||
@@ -149,13 +151,13 @@ The host firewall is configured in `nixos/modules/homeserver.nix`:
|
||||
| **993** | TCP | Stalwart | IMAPS (Secure IMAP) | Public |
|
||||
| **4190** | TCP | Stalwart | ManageSieve (Mail Filters) | Public |
|
||||
|
||||
Application containers in `~/Sites` do not bind host ports directly; they receive traffic routed by Traefik over `proxy-net`.
|
||||
Application containers in `~/Workloads` do not bind host ports directly; they receive traffic routed by Traefik over `proxy-net`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Workload Integration Model
|
||||
|
||||
Workloads in `~/Sites/<app>` integrate with Core through three mechanisms:
|
||||
Workloads in `~/Workloads/<app>` integrate with Core through three mechanisms:
|
||||
|
||||
1. **Manifest Metadata (`app.yaml`)**: Validated by `scripts/core_manifest.py` (Schema v1.0). Declares canonical identity, routed domain, upstream source provenance (`source.url`, `source.ref`), environment defaults, Homepage card layout, and allowlisted GitOps deployment policy.
|
||||
2. **Compose Configuration (`docker-compose.yml`)**:
|
||||
@@ -175,4 +177,4 @@ Workloads in `~/Sites/<app>` integrate with Core through three mechanisms:
|
||||
# If auth is required:
|
||||
- "traefik.http.routers.${CONTAINER_NAME}.middlewares=authelia-auth@docker"
|
||||
```
|
||||
3. **Execution & State Isolation**: `appctl` and `gitops_dispatcher.py` validate the manifest and Compose AST (blocking privilege escalation and out-of-bounds mounts) before supplying runtime environment variables (`SERVICE_DOMAIN`, `CONTAINER_NAME`, and projected secrets). Persistent mutable workload data resides strictly under `~/var/lib/homelab/<app>/`.
|
||||
3. **Execution & State Isolation**: `appctl` and `gitops_dispatcher.py` validate the manifest and Compose AST (blocking privilege escalation and out-of-bounds mounts unless explicitly authorized per workload in `homelab.workloadGrants`, projected to `/etc/homelab/grants.json` and read via `HOMELAB_GRANTS_FILE` per ADR-0005) before supplying runtime environment variables (`SERVICE_DOMAIN`, `CONTAINER_NAME`, and projected secrets). Persistent mutable workload data resides strictly under `~/var/lib/homelab/<app>/`.
|
||||
@@ -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,139 @@
|
||||
---
|
||||
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, Model Context Protocol (MCP) Gateway & AI Boundary (P5–P7 Trajectory)
|
||||
* **Git is Authoritative**: Approved deployment definitions are versioned in Git; `appctl` reconciles desired Git state into running containers.
|
||||
* **Architecture Amendment (2026-10-23 — MCP Tool Gateway Supersedes On-Server Authoring)**:
|
||||
The 5-stage on-server AI deployment authoring compiler (`ApplicationProfile` $\to$ `DeploymentProposal` $\to$ `DeploymentModel`) originally planned for Milestone P6 is **deprecated and superseded by a decoupled Model Context Protocol (MCP) Tool Gateway**. Rather than building bespoke AI authoring engines or autonomous agents into the appliance host, platform management operations (`appctl_status`, `appctl_deploy`, `appctl_logs`, `appctl_audit`) will be exposed via standardized JSON-RPC MCP tools consumed by external developer clients (Antigravity, Claude Code, Cursor) with native human-in-the-loop confirmation. The deterministic boundary of `appctl` is preserved, with zero autonomous AI agent code executing inside the appliance host.
|
||||
* **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)
|
||||
@@ -0,0 +1,91 @@
|
||||
---
|
||||
type: decision
|
||||
status: accepted
|
||||
project: homelab-core
|
||||
date: 2026-11-16
|
||||
tags: [architecture, workloads, monorepo, gitops, state, nixos]
|
||||
amends: 0001-3tier-architecture-and-provenance.md
|
||||
---
|
||||
|
||||
# ADR 0004: Unified ~/Workloads Monorepo & State Isolation
|
||||
|
||||
## Context and Problem Statement
|
||||
|
||||
Under [ADR-0001](0001-3tier-architecture-and-provenance.md), Tier 2 deployment descriptors (`app.yaml` and `docker-compose.yml`) were hosted in `~/Sites/<app>` as one standalone Git repository per application. In practice, operating a fleet of 9+ Tier 2 workloads (including both Class A source-backed services and Class B off-the-shelf image-only tools) revealed structural friction:
|
||||
|
||||
1. **Per-App Repository Sprawl**: Every third-party tool (`jellyfin`, `snappymail`, `excalidraw`, `mermaid`) required its own Gitea repository, webhook configuration, and clone lifecycle just to version 2–3 declarative files.
|
||||
2. **Naming Coupling (`~/Sites`)**: The directory name `~/Sites` implied web-only sites rather than general self-hosted workloads (mail, media, diagrams, internal tools).
|
||||
3. **Cross-Workload Drift & Webhook Overhead**: Coordinating shared network, label, or manifest conventions across N separate deployment repositories required N separate commits and N separate Gitea webhook registrations.
|
||||
4. **State Co-location Risk**: Moving to a unified monorepo increases the blast radius if any workload stores mutable runtime state inside its deployment directory instead of the isolated host state root (`~/var/lib/homelab/<app>/`).
|
||||
|
||||
The central architectural question is: **How should Canopy NixOS Core organize Tier 2 deployment descriptors to eliminate per-app repository sprawl while preserving independent per-workload deployment, backward-compatible migration, and strict runtime state isolation?**
|
||||
|
||||
## Decision Drivers
|
||||
|
||||
* **Eliminate Tier 2 Repository Sprawl**: Consolidate Tier 2 deployment descriptors (`<app>/app.yaml`, `<app>/docker-compose.yml`) into a single unified `canopy-workloads` monorepo at `~/Workloads`.
|
||||
* **Preserve Per-Workload Independence**: Pushing to `canopy-workloads` must selectively deploy only the workload subdirectories modified in that push, without restarting unaffected services.
|
||||
* **Zero-Downtime Migration Compatibility**: Support `WORKLOADS_DIR` as the canonical configuration variable with a clean `SITES_DIR` fallback, and support hybrid per-app `.git` checkouts alongside monorepo subdirectories during transition.
|
||||
* **Strict State Isolation**: Enforce `~/var/lib/homelab/<app>/` as the sole persistent runtime state root so the `~/Workloads` Git working tree remains 100% declarative and clean.
|
||||
* **Preserve 3-Tier & Security Boundaries**: Keep Tier 1 application source repositories independent, keep Core platform services in `~/Core`, and maintain `deployments.yaml` allowlisting and Compose AST security validation.
|
||||
|
||||
## Considered Options
|
||||
|
||||
* **Option 1: Keep Per-App Tier 2 Repositories in `~/Sites/<app>` (Status Quo)**: Maintain one Git repository per workload under `~/Sites`.
|
||||
* **Option 2: Merge Tier 2 Workloads into `~/Core`**: Place all workload `app.yaml` and `docker-compose.yml` files directly inside `canopy-homelab/nixos-core`.
|
||||
* **Option 3: Unified `~/Workloads` Monorepo (`canopy-workloads`) with Isolated Host State (Adopted)**: Amend ADR-0001 to rename Tier 2 from `~/Sites` to `~/Workloads`, consolidate Tier 2 manifests into `canopy-workloads`, and enforce `~/var/lib/homelab/<app>/` state isolation.
|
||||
|
||||
## Decision Outcome
|
||||
|
||||
Chosen option: **Option 3: Unified `~/Workloads` Monorepo (`canopy-workloads`) with Isolated Host State**, because it eliminates Tier 2 repository and webhook sprawl while preserving the 3-tier boundary between Tier 1 application source, Tier 2 deployment intent, and Tier 3 NixOS Core platform infrastructure.
|
||||
|
||||
### Summary of Architectural Commitments
|
||||
|
||||
This ADR formally amends [ADR-0001](0001-3tier-architecture-and-provenance.md) with the following commitments:
|
||||
|
||||
1. **Tier 2 Rename (`~/Sites` $\rightarrow$ `~/Workloads`)**:
|
||||
* The canonical Tier 2 deployment root is `~/Workloads` (configured via `homelab.workloadsDir` / `homelab.sitesDir` in NixOS and `WORKLOADS_DIR` in Core services).
|
||||
* Core Python modules (`appctl_engine.py`, `appctl_daemon.py`, `appctl_router.py`, `gitops_dispatcher.py`) default to `~/Workloads`, honoring `WORKLOADS_DIR` first and falling back to `SITES_DIR` for backward compatibility.
|
||||
2. **Unified `canopy-workloads` Monorepo**:
|
||||
* Tier 2 workloads reside as subdirectories `~/Workloads/<app>/` inside the `canopy-workloads` monorepo, each owning its own `app.yaml` and `docker-compose.yml`.
|
||||
* During migration, `~/Workloads/<app>` may operate either as a monorepo subdirectory (sharing `~/Workloads/.git`) or as a standalone checkout (`~/Workloads/<app>/.git`).
|
||||
3. **Mandatory State Isolation (`~/var/lib/homelab/<app>/`)**:
|
||||
* All mutable application data (databases, caches, uploads, dynamic configs) must reside under `~/var/lib/homelab/<app>/` (or named Docker volumes) and never inside `~/Workloads/<app>/`.
|
||||
* NixOS `systemd.tmpfiles.rules` provisions `~/Workloads` and `~/var/lib/homelab` with recursive `A+` POSIX ACLs for `homelab-appctl`.
|
||||
4. **Core Registry & Safe Directory Containment**:
|
||||
* `config/deployments.yaml` maps admitted workload identities to canonical `~/Workloads/<app>` paths, enforced by strict containment inside `WORKLOADS_DIR`.
|
||||
* Host Git `safe.directory` configuration includes `~/Workloads` and `~/Workloads/*` (alongside `~/Core`).
|
||||
|
||||
## Pros and Cons of the Options
|
||||
|
||||
### Option 1: Keep Per-App Tier 2 Repositories in `~/Sites/<app>`
|
||||
* Good, because each workload has an isolated Git history and independent webhook.
|
||||
* Bad, because adding or updating a simple third-party service requires creating and maintaining a full Git repository.
|
||||
* Bad, because fleet-wide manifest or Compose conventions require N separate PRs and commits.
|
||||
|
||||
### Option 2: Merge Tier 2 Workloads into `~/Core`
|
||||
* Good, because only one repository exists for Core and Workloads.
|
||||
* Bad, because it violates the 3-tier boundary (ADR-0001), mixing NixOS host/platform configuration with application deployment topologies.
|
||||
* Bad, because `~/Core` changes would trigger NixOS evaluation/rebuild concerns alongside routine app updates.
|
||||
|
||||
### Option 3: Unified `~/Workloads` Monorepo (`canopy-workloads`) with Isolated Host State (Adopted)
|
||||
* Good, because Tier 2 deployment descriptors are managed in one repository with atomic cross-workload changes and a single GitOps webhook.
|
||||
* Good, because Tier 1 software repositories and Tier 3 NixOS Core remain strictly decoupled.
|
||||
* Good, because `WORKLOADS_DIR` $\rightarrow$ `SITES_DIR` fallback allows incremental host cutover without breaking existing environments.
|
||||
* Bad, because GitOps webhook dispatch and provenance inspection must distinguish monorepo-root `.git` from per-app `.git` checkouts (addressed in follow-up slices).
|
||||
* Bad, because monorepo commits touching multiple subdirectories require changed-path filtering to avoid redeploying unaffected workloads.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Consequences
|
||||
* **Single Tier 2 Control Surface**: One `canopy-workloads` repository versions all workload manifests and Compose topologies.
|
||||
* **Clean Git Working Tree**: Enforcing `~/var/lib/homelab/<app>/` ensures runtime state never dirties the monorepo checkout.
|
||||
* **Smooth Cutover**: Dual `WORKLOADS_DIR` / `SITES_DIR` environment support and `homelab.sitesDir` NixOS option compatibility prevent abrupt breakage.
|
||||
|
||||
### Negative Consequences & Accepted Trade-offs
|
||||
* **Hybrid Provenance & Subpath Dispatch Complexity**: Core tooling (`provenance.py`, `gitops_dispatcher.py`) must handle both monorepo-level `.git` and legacy per-app `.git` directories, as well as selective changed-directory deployment on monorepo pushes.
|
||||
|
||||
## More Information
|
||||
|
||||
* **Amended Decision**: [`0001-3tier-architecture-and-provenance.md`](0001-3tier-architecture-and-provenance.md)
|
||||
* **Architecture Specification**: [`docs/architecture.md`](../architecture.md)
|
||||
* **Secrets & State Contract**: [`docs/secrets-and-state.md`](../secrets-and-state.md)
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
type: decision
|
||||
status: accepted
|
||||
project: homelab-core
|
||||
date: 2026-11-20
|
||||
tags: [architecture, security, nixos, workloads, appctl, gitops]
|
||||
amends: 0002-appctl-control-plane-architecture.md
|
||||
---
|
||||
|
||||
# ADR 0005: Host-Granted Workload Capabilities ("Compose Requests, Nix Grants")
|
||||
|
||||
## Context and Problem Statement
|
||||
|
||||
Under [ADR-0001](0001-3tier-architecture-and-provenance.md), [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`), and [ADR-0004](0004-unified-workloads-monorepo.md), `validate_compose_security()` (shared pre-flight validator invoked authoritatively by `homelab-appctl.service` in `scripts/appctl_router.py` across CLI and GitOps paths) enforces a uniform deny-all policy on Tier 2 workload `docker-compose.yml` files:
|
||||
|
||||
* `devices:` mounts are blocked.
|
||||
* Host bind mounts outside `~/Workloads/<app>` and `~/var/lib/homelab/<app>` are blocked.
|
||||
* Host namespace sharing (`network_mode: host`, etc.) is blocked.
|
||||
|
||||
While this prevents a Tier 2 `git push` from escalating privileges on the host, it blocks required single-operator capability classes:
|
||||
|
||||
1. **Hardware-Accelerated & External-Storage Workloads**: Media transcoding or compute workloads requiring an integrated GPU (`/dev/dri/renderD128`) must mount host device nodes, pass a supplementary device group (such as `render` / GID `303`), and read an external read-only storage partition (`/media:ro`). Currently, `devices:` and external bind mounts are blocked, while `group_add:` and `user:` primary GIDs are unconstrained (risking arbitrary host GID elevation to groups such as `docker` or `wheel` unless constrained).
|
||||
2. **LAN Broadcast / Peer-Discovery Services (Out of Scope for Host Networking)**: Workloads that send Wake-on-LAN magic packets or discover LAN peers cannot traverse Docker bridge L2 isolation, prompting requests for `network_mode: host`. Because blanket host networking collapses network namespace isolation—exposing loopback control services such as `homelab-appctl.service` on `127.0.0.1:9001`—host networking remains out of scope for workload grants and must be handled via isolated L2 Docker networks (`macvlan`/`ipvlan`) or host-side intermediaries.
|
||||
3. **Host-Agnostic Core Boundary**: Hardcoding `/dev/dri`, `/media`, or specific workload names inside `nixos-core` violates platform portability and couples Core to one machine's hardware and app catalog.
|
||||
|
||||
The central architectural question is: **How should Canopy NixOS Core permit hardware devices, supplementary/primary GIDs, and external read-only storage paths for specific workloads without hardcoding personal infrastructure into `nixos-core` or weakening the Tier 2 -> Tier 3 trust boundary?**
|
||||
|
||||
## Decision Drivers
|
||||
|
||||
* **Preserve the Trust Split**: A push to Tier 2 (`canopy-workloads`) must never grant itself root-equivalent host access; capability grants must originate from root-level Tier 3 NixOS host configuration (`nixos-rebuild switch`).
|
||||
* **Keep `nixos-core` Generic**: Core defines the capability schema and enforcement logic only, with zero hardcoded personal app names, device nodes, or media paths.
|
||||
* **Keep `app.yaml` Free of Host Paths**: Workload manifests remain declarative routing/provenance metadata; `docker-compose.yml` already declares requested `devices`, `volumes`, `group_add`, and `user`.
|
||||
* **Documented Instance Schema**: Provide a tracked `nixos/instance.example.nix` template so new hosts can configure `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants` in `/etc/nixos/homelab-instance.nix` (or gitignored `nixos/instance.nix`).
|
||||
* **Fail-Closed Validation**: An absent grants file defaults to zero grants (current baseline); a present but unreadable, tampered, or malformed grants file fails closed across all workloads. `privileged: true`, `/var/run/docker.sock`, `cap_add`, `device_cgroup_rules:`, and host/container namespace sharing remain permanently prohibited.
|
||||
|
||||
## Considered Options
|
||||
|
||||
* **Option 1: Relax `validate_compose_security()` Globally**: Allow `/dev/dri` and arbitrary `:ro` paths for all workloads.
|
||||
* **Option 2: Store Grants in `~/Workloads/grants.yaml`**: Allow `canopy-workloads` to declare its own exceptions alongside `deployments.yaml`.
|
||||
* **Option 3: "Compose Requests, Nix Grants" via `homelab.workloadGrants` (Adopted)**: Define a typed `homelab.workloadGrants` option in `nixos-core` rendered to root-owned `/etc/homelab/grants.json`, validated with Pydantic v2 (`extra="forbid"`), and enforced by `validate_compose_security()`.
|
||||
|
||||
## Decision Outcome
|
||||
|
||||
Chosen option: **Option 3: "Compose Requests, Nix Grants" via `homelab.workloadGrants`**, because it keeps `nixos-core` hardware- and workload-agnostic while preserving the security boundary between Tier 2 Git pushes and Tier 3 `sudo nixos-rebuild switch`.
|
||||
|
||||
### Summary of Architectural Commitments
|
||||
|
||||
This ADR formally amends [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`) with the following commitments:
|
||||
|
||||
1. **Typed Host Grant Schema (`homelab.workloadGrants`)**:
|
||||
* `nixos/modules/homeserver.nix` defines `homelab.workloadGrants` as an attribute set keyed by workload name, supporting three explicit grant fields:
|
||||
* `devices` (list of exact device paths; prefer specific nodes such as `"/dev/dri/renderD128"` over whole directories unless display control is required).
|
||||
* `groups` (list of supplementary/primary group names or GIDs permitted in `group_add` and `user:`, such as `"render"` or `"303"`; privileged host groups `0`/`root`, `wheel`, and `docker` are permanently rejected).
|
||||
* `readOnlyPaths` (list of host directories permitted for read-only bind mounts only).
|
||||
* `privileged: true`, `/var/run/docker.sock`, `cap_add`, `device_cgroup_rules:`, and namespace sharing (`network_mode: host`, `network_mode: container:*`, `network_mode: service:*`, `pid`, `ipc`, `uts`, `userns_mode: host`) remain permanently prohibited and are not grantable.
|
||||
|
||||
2. **Immutable Host Projection (`/etc/homelab/grants.json`)**:
|
||||
* NixOS generates `/etc/homelab/grants.json` (`root`-owned, group-owned by `homelab-operators` with mode `0640`, granting read access to both `homelab-appctl` and `operator` without POSIX ACLs; overridable via `HOMELAB_GRANTS_FILE`, which is reserved in `RESERVED_ENV_KEYS` so workload `.env` / `app.yaml` cannot override it).
|
||||
* In production, the loader verifies regular-file (non-symlink), root-owned, non-world/group-writable permissions before parsing.
|
||||
* If `/etc/homelab/grants.json` is **absent**, `validate_compose_security()` defaults to zero grants. If it is **present** but unreadable, fails permission checks, or fails Pydantic v2 (`extra="forbid"`) validation, pre-flight fails closed for all workloads.
|
||||
|
||||
3. **Exact-Match Pre-Flight Enforcement**:
|
||||
* `validate_compose_security()` evaluates resolved values (post-6-layer env assembly, or rejects uninterpolated `${...}` in `devices`, `volumes`, `group_add`, and `user`). When `app_name` is `None` or unknown, zero grants apply.
|
||||
* Every capability requested in `<app>/docker-compose.yml` must match an explicit grant for `<app>`:
|
||||
* `devices` entries support `host:container[:perms]`, forbid `m` (`mknod`) in permissions, and require the host path to exist and resolve canonically within the granted device node or directory, disallowing `..` traversal or symlink escapes.
|
||||
* `group_add` transitions from unconstrained to **default-deny** when no `groups` grant exists; `groups` entries canonicalize bidirectionally between group names and integer GIDs via the host group database. `user:` primary GIDs must either fall within granted `groups` or be unprivileged numeric IDs that do not map to privileged or host-sensitive groups.
|
||||
* `readOnlyPaths` validates both short (`host:container:ro[,opts]`) and long (`type: bind`, `read_only: true`) volume syntax, rejects unsafe bind propagation, and requires the host path to exist and resolve canonically within the granted directory.
|
||||
|
||||
4. **Tracked Instance Template (`nixos/instance.example.nix`)**:
|
||||
* `nixos-core` tracks `nixos/instance.example.nix` documenting `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants`.
|
||||
* Live hosts keep concrete values in `/etc/nixos/homelab-instance.nix` (loaded via `--impure` flake evaluation, taking precedence over gitignored `nixos/instance.nix` if both exist). Both paths remain optional so pure `nix flake check` CI passes with defaults.
|
||||
|
||||
## Pros and Cons of the Options
|
||||
|
||||
### Option 1: Relax `validate_compose_security()` Globally
|
||||
* Good, because it requires minimal code.
|
||||
* Bad, because it hardcodes host hardware assumptions into `nixos-core` and weakens tenant isolation for all workloads.
|
||||
|
||||
### Option 2: Store Grants in `~/Workloads/grants.yaml`
|
||||
* Good, because grants live next to `deployments.yaml`.
|
||||
* Bad, because Tier 2 would self-authorize Tier 3 host privileges on a single `git push`.
|
||||
|
||||
### Option 3: "Compose Requests, Nix Grants" via `homelab.workloadGrants` (Adopted)
|
||||
* Good, because `nixos-core` stays generic, `canopy-workloads` remains free of host-privilege grants, and privilege elevation requires explicit host-level `nixos-rebuild switch`.
|
||||
* Bad, because adding a new privileged capability requires editing `/etc/nixos/homelab-instance.nix` and rebuilding NixOS before `appctl up`.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Consequences
|
||||
* **Hardware & Media Operability**: Workloads can use GPU acceleration and external `:ro` storage cleanly via standard `docker-compose.yml` syntax once authorized by the host.
|
||||
* **Closed GID & Namespace Loopholes**: Transitions `group_add:`, `user:` primary GIDs, `device_cgroup_rules:`, and `network_mode: container:*` to fail-closed enforcement.
|
||||
* **CI Compatibility**: Pure `nix flake check` evaluates cleanly with empty default grants.
|
||||
|
||||
### Negative Consequences & Accepted Trade-offs
|
||||
* **Tier 2 / Tier 3 Deployment Ordering**: Pushing a Compose file requesting a new capability before running `nixos-rebuild switch` fails closed at pre-flight (surfaced clearly via a distinct capability-denial error/audit signal such as `ERR_CAPABILITY_NOT_GRANTED`).
|
||||
* **Host Path Coupling**: Workload Compose files declare physical host paths matching host grants; logical capability aliasing via environment-variable injection remains an optional future refinement.
|
||||
|
||||
## More Information
|
||||
|
||||
* Amends [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`).
|
||||
* Related specifications: [docs/architecture.md](../architecture.md), [docs/appctl.md](../appctl.md), [docs/secrets-and-state.md](../secrets-and-state.md).
|
||||
+42
-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`).
|
||||
|
||||
---
|
||||
|
||||
@@ -10,16 +10,35 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
|
||||
|
||||
| Decision Record | Status | Date | Scope & One-Line Purpose |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| [**ADR-0005: Host-Granted Workload Capabilities**](0005-workload-capability-grants.md) | `accepted` | 2026-11-20 | Amends ADR-0002 to introduce `homelab.workloadGrants` (`/etc/homelab/grants.json`) and `nixos/instance.example.nix` so NixOS hosts explicitly authorize `devices`, `groups`, and `readOnlyPaths` per workload while keeping host/container networking prohibited. |
|
||||
| [**ADR-0004: Unified ~/Workloads Monorepo & State Isolation**](0004-unified-workloads-monorepo.md) | `accepted` | 2026-11-16 | Amends ADR-0001 to adopt the unified `~/Workloads` Tier 2 monorepo (`canopy-workloads`), rename `~/Sites` to `~/Workloads` with `WORKLOADS_DIR` fallback, and enforce `~/var/lib/homelab/<app>/` state isolation. |
|
||||
| [**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 deterministic Git-backed declarative deployment state. |
|
||||
| [**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-0005: Host-Granted Workload Capabilities ("Compose Requests, Nix Grants")](0005-workload-capability-grants.md)
|
||||
* **Canonical Document**: [`0005-workload-capability-grants.md`](0005-workload-capability-grants.md)
|
||||
* **Status**: `accepted` (Active — Amends ADR-0002)
|
||||
* **Core Commitments**:
|
||||
1. **Typed Host Grant Schema (`homelab.workloadGrants`)**: NixOS exposes per-workload `devices`, `groups`, and `readOnlyPaths` grants while keeping `privileged: true`, `docker.sock`, `cap_add`, `device_cgroup_rules`, and host/container namespace sharing permanently forbidden.
|
||||
2. **Immutable Host Projection (`/etc/homelab/grants.json`)**: Projected root-owned at rebuild time; absent file defaults to zero grants, malformed file fails closed.
|
||||
3. **Exact-Match Pre-Flight Enforcement**: `validate_compose_security()` allows requested capabilities only when canonically matched against the workload's Nix grant (and `:ro` for `readOnlyPaths`).
|
||||
4. **Tracked Instance Template (`nixos/instance.example.nix`)**: Documents `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants` for `/etc/nixos/homelab-instance.nix`.
|
||||
|
||||
### [ADR-0004: Unified ~/Workloads Monorepo & State Isolation](0004-unified-workloads-monorepo.md)
|
||||
* **Canonical Document**: [`0004-unified-workloads-monorepo.md`](0004-unified-workloads-monorepo.md)
|
||||
* **Status**: `accepted` (Active — Amends ADR-0001)
|
||||
* **Core Commitments**:
|
||||
1. **Tier 2 Rename (`~/Sites` -> `~/Workloads`)**: Canonical Tier 2 deployment root is `~/Workloads`, with `WORKLOADS_DIR` -> `SITES_DIR` environment fallback.
|
||||
2. **Unified `canopy-workloads` Monorepo**: Tier 2 workload manifests (`app.yaml`, `docker-compose.yml`) consolidate under `~/Workloads/<app>/`, supporting hybrid per-app `.git` checkouts during migration.
|
||||
3. **Mandatory State Isolation**: All mutable application data resides strictly under `~/var/lib/homelab/<app>/` (or named Docker volumes), never inside `~/Workloads`.
|
||||
4. **Workloads Registry & Safe Directory Containment**: `~/Workloads/deployments.yaml` (templated by `config/deployments.yaml`) resolves admitted workloads within `WORKLOADS_DIR`; NixOS `safe.directory` includes `~/Workloads` and `~/Workloads/*`.
|
||||
|
||||
### [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 +49,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, Model Context Protocol (MCP) Gateway & AI Boundary (P5–P7)**: Git remains authoritative deployment state; on-server AI proposal compilers deprecated in favor of a decoupled Model Context Protocol (MCP) tool gateway with human confirmation gating; 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 +80,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.
|
||||
+5
-5
@@ -27,7 +27,7 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 3. Authoritative Registry Resolution │
|
||||
│ Maps names via Core/config/deployments.yaml│
|
||||
│ Maps names via ~/Workloads/deployments.yaml│
|
||||
│ Fails closed; zero dynamic discovery on host│
|
||||
└───────────────────────┬───────────────────────┘
|
||||
│
|
||||
@@ -74,7 +74,7 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
|
||||
|
||||
### C. Authoritative Repository Registry (`deployments.yaml`)
|
||||
* Webhook payloads identify targets strictly by logical name (e.g. `docs`, `homelab-docs`), never by raw filesystem path.
|
||||
* `Core/config/deployments.yaml` is the **sole admission authority** for GitOps workloads.
|
||||
* `~/Workloads/deployments.yaml` (configured via `HOMELAB_DEPLOYMENTS_FILE`, with `Core/config/deployments.yaml` serving as the example template) is the **sole admission authority** for GitOps workloads.
|
||||
* **No Dynamic Discovery**: Scanning `~/Sites` dynamically is strictly prohibited. An unapproved directory created on disk cannot receive webhook deployment rights merely by providing an `app.yaml`.
|
||||
* **Fail-Closed Guarantee**: If `deployments.yaml` is missing, unreadable, or malformed, the dispatcher fails closed and admits zero repositories.
|
||||
* **Input Validation**: Names must match `^[a-zA-Z0-9][a-zA-Z0-9._-]*$`. Slashes, backslashes, and path traversal sequences (`..`) are rejected.
|
||||
@@ -106,7 +106,7 @@ Before executing `docker compose up -d`, `validate_compose_security()` parses th
|
||||
To avoid blocking HTTP connections and handle overlapping pushes:
|
||||
|
||||
1. **Immediate HTTP 200 Return**: Upon passing admission, the dispatcher writes a pending file (`~/.local/state/homelab/gitops/<target>.pending.json`), spawns a detached worker (`--worker <target>`), and returns HTTP 200.
|
||||
2. **Per-Target `flock` Serialization**: The worker acquires an exclusive non-blocking `fcntl.flock` on `~/.local/state/homelab/gitops/<target>.lock`. If a worker is already running for this target, the second worker exits safely while the running worker continues to drain the pending file.
|
||||
2. **Per-Target `flock` Serialization & Daemon Delegation**: The worker acquires an exclusive non-blocking `fcntl.flock` on `~/.local/state/homelab/gitops/<target>.lock`. When `/run/homelab/appctl.sock` is available, the worker delegates `workload.update` to `homelab-appctl.service` over UDS authenticating with `/run/secrets/gitops/appctl_token` (`homelab-operator` role), which executes `git pull --ff-only`, re-validates `app.yaml` and Compose security, runs the declared actions, logs to `/var/log/homelab/appctl/audit.jsonl`, and syncs Homepage.
|
||||
3. **Commit Superseding**:
|
||||
- Commit A begins deploying.
|
||||
- Commit B arrives and is written to the pending file.
|
||||
@@ -175,11 +175,11 @@ The continuous deployment engine operates strictly **downstream** of CI verifica
|
||||
|
||||
```
|
||||
[Developer / PR] ──► [Gitea Actions CI] ──► [Merge to main] ──► [Gitea Webhook] ──► [homelab-gitops] ──► [Deploy]
|
||||
(Ephemeral Container) (Host Daemon)
|
||||
(:host act_runner) (Host Daemon)
|
||||
```
|
||||
|
||||
1. **Pre-Merge CI Invariant (`.gitea/workflows/ci.yaml`)**:
|
||||
- Executes inside containerized `act_runner` environments using **pre-baked toolchain images** (`container: nixery.dev/shell/coreutils/git/nix/nodejs:latest`).
|
||||
- Executes directly on `:host` `act_runner` instances (`ubuntu-latest:host` / `nix:host`) with a **pre-baked host toolchain** (`nix`, `node`, `git`, `coreutils`), without spawning nested `container:` jobs.
|
||||
- Runs hermetic validation (`nix flake check`, `pytest`, `ruff`) with Git safe directory enforcement.
|
||||
- Prevents broken code, misconfigured flakes, or regression bugs from entering `main`.
|
||||
2. **Post-Merge CD Execution (`homelab-gitops.service`)**:
|
||||
|
||||
+360
-4
@@ -16,9 +16,15 @@ After modifying any file in `nixos/` (including `configuration.nix`, `hardware-c
|
||||
nix-switch
|
||||
|
||||
# Or using the explicit command:
|
||||
sudo nixos-rebuild switch --flake ~/Core#server
|
||||
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> **Flake Fetcher Scheme for Untracked Files**:
|
||||
> When importing the gitignored `nixos/instance.nix`, Nix's default Git fetcher filters it out unless the `path:` scheme is used (`path:/home/operator/Core#server` or `path:~/Core#server`). The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index.
|
||||
> If using `/etc/nixos/homelab-instance.nix`, a standard `--flake ~/Core#server --impure` works directly since `/etc/nixos` is outside the repository.
|
||||
|
||||
|
||||
### Dry Build Validation & Rollback
|
||||
```bash
|
||||
# Validate build without activating (catches evaluation and syntax errors)
|
||||
@@ -103,7 +109,7 @@ tail -n 20 /var/lib/dynu/ip_history.jsonl
|
||||
|
||||
## 3. Workload Lifecycle Operations (`appctl`)
|
||||
|
||||
Applications in `~/Sites` are managed with the `appctl` CLI.
|
||||
Applications in `~/Workloads` are managed with the `appctl` CLI.
|
||||
|
||||
### Inspection & Status
|
||||
```bash
|
||||
@@ -139,9 +145,8 @@ appctl restart docs
|
||||
appctl restart traefik
|
||||
appctl restart authelia
|
||||
|
||||
# Sequential stack update (clean working tree check -> git pull -> compose pull -> up -> sync)
|
||||
# Sequential stack update for independent Workloads (clean tree check -> git pull -> compose pull -> up -> sync)
|
||||
appctl update docs
|
||||
appctl update core
|
||||
|
||||
# Stream live container logs
|
||||
appctl logs docs
|
||||
@@ -151,6 +156,37 @@ appctl logs -f stalwart
|
||||
appctl config docs
|
||||
```
|
||||
|
||||
### Workload vs. Core Update Policy
|
||||
|
||||
Homelab enforces a strict architectural boundary between independent application workloads (`~/Workloads/<app>`) and Homelab Core (`~/Core`):
|
||||
|
||||
#### 1. Independent Workloads (`~/Workloads/<app>`)
|
||||
- **Automated Lifecycle**: Workloads declare their lifecycle via `app.yaml` manifests and Compose definitions.
|
||||
- **Update Command**: `appctl update <workload>` performs pre-flight verification, branch matching, `git pull --ff-only`, container image pull, stack reload, and dashboard synchronization.
|
||||
- **GitOps Webhook Dispatch**: Workloads registered in `~/Workloads/deployments.yaml` (with `config/deployments.yaml` as the example template) can be triggered automatically via authenticated GitOps webhooks on Gitea push events.
|
||||
- **Daemon Permissions**: `homelab-appctl.service` holds read-write permissions over `~/Workloads` to manage files, compose configurations, and workload state.
|
||||
|
||||
#### 2. Homelab Core Platform Stack (`~/Core`)
|
||||
- **Host Foundation & Invariant Boundary**: Core defines NixOS host definitions, platform secrets, edge ingress, and security sandboxes.
|
||||
- **No Untrusted Webhooks**: Core does **not** register for webhook dispatch in `~/Workloads/deployments.yaml`. External push events can never trigger an automated deployment or rebuild of Core.
|
||||
- **Read-Only Sandbox**: Under NixOS systemd sandboxing (`ProtectHome = "read-only"`), `homelab-appctl.service` has strictly read-only access to `/home/operator/Core`. The daemon cannot mutate the Core Git repository or run `git pull` on Core.
|
||||
- **Operator-Driven Update Workflow**: Core updates must be executed explicitly by the operator:
|
||||
1. Review and pull repository changes:
|
||||
```bash
|
||||
cd ~/Core && git pull --ff-only
|
||||
```
|
||||
2. If NixOS modules or secrets changed, evaluate and activate the new system generation:
|
||||
```bash
|
||||
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
|
||||
```
|
||||
3. If Compose definitions changed, restart the platform stack:
|
||||
```bash
|
||||
docker compose up -d --remove-orphans
|
||||
# or via systemd:
|
||||
sudo systemctl restart homeserver-core
|
||||
```
|
||||
4. Individual platform services can be restarted via appctl using an authenticated admin token (`appctl restart traefik`, `appctl restart authelia`).
|
||||
|
||||
---
|
||||
|
||||
## 4. User Identity & Access Management (LLDAP & Authelia)
|
||||
@@ -279,3 +315,323 @@ To bring up a replacement host from version control:
|
||||
```bash
|
||||
sudo systemctl start homeserver-core
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Operator Account Migration Runbook (Decision D2: Staged Coexistence Cutover)
|
||||
|
||||
> [!CAUTION]
|
||||
> **MAINTENANCE WINDOW REQUIRED — EXECUTION ON LIVE HOST CURRENTLY BLOCKED**
|
||||
> Live execution of this runbook against production hosts is strictly blocked until an authorized platform maintenance window is scheduled. This runbook is codified for procedural readiness and dry-run verification only.
|
||||
|
||||
This runbook defines the 4-stage staged coexistence cutover procedure to migrate host operation from a legacy personal operator account (`<legacy-operator>`) to the platform standard `operator` user (`uid = 1000`, `extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]`), fulfilling Decision D2 and eliminating personal identity coupling.
|
||||
|
||||
### Stage 1: Pre-Flight Checks & Session Preservation
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Maintain Active Legacy Shell Session**:
|
||||
> Do not terminate your active SSH or terminal session as `<legacy-operator>`. Keep at least one authenticated shell open throughout the entire cutover process to prevent lockout in case of SSH key, user profile, or PAM misconfiguration.
|
||||
|
||||
1. **Verify or provision `operator` account**:
|
||||
Check if the `operator` user exists in the running environment:
|
||||
```bash
|
||||
id operator
|
||||
```
|
||||
If `operator` does not exist yet (as `homelab.operatorUser` has not been switched in the active NixOS generation), provision the initial coexistence user before proceeding:
|
||||
```bash
|
||||
sudo useradd -m -s /run/current-system/sw/bin/bash -G wheel,docker,homelab-operators operator
|
||||
```
|
||||
|
||||
2. **Verify SSH key provisioning & permissions**:
|
||||
Ensure the operator's authorized keys are installed with strict permissions (copying from `<legacy-operator>` if needed):
|
||||
```bash
|
||||
sudo mkdir -p /home/operator/.ssh
|
||||
if [ ! -f /home/operator/.ssh/authorized_keys ] && [ -f /home/<legacy-operator>/.ssh/authorized_keys ]; then
|
||||
sudo cp /home/<legacy-operator>/.ssh/authorized_keys /home/operator/.ssh/authorized_keys
|
||||
fi
|
||||
sudo chmod 700 /home/operator/.ssh
|
||||
sudo chmod 600 /home/operator/.ssh/authorized_keys
|
||||
sudo chown -R operator:users /home/operator/.ssh
|
||||
```
|
||||
|
||||
3. **Verify administrative (`sudo`) access**:
|
||||
Test that `operator` can authenticate and execute privileged commands without failure:
|
||||
```bash
|
||||
sudo -u operator sudo -n true || echo "Passwordless or password sudo required for operator"
|
||||
```
|
||||
|
||||
4. **Prepare persistent directories**:
|
||||
Ensure `/home/operator/Sites`, `/home/operator/Core`, `/home/operator/var/lib/homelab`, and state parent paths are ready:
|
||||
```bash
|
||||
sudo mkdir -p /home/operator/{Core,Sites,.config/homelab,var/lib/homelab,.local/state/homelab}
|
||||
sudo chown -R operator:homelab-operators /home/operator/{Core,Sites,.config,var,.local}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Stage 2: State and Repository Synchronization
|
||||
Synchronize repository checkouts, workload persistent data, and runtime state from the legacy user account to `/home/operator/` using non-destructive archive flags (`-aHAX` preserves hard links, attributes, and extended ACLs):
|
||||
|
||||
1. **Initial background synchronization**:
|
||||
Seed the file trees for Core, Sites, workload databases, and configurations while services continue running:
|
||||
```bash
|
||||
sudo rsync -aHAX --info=progress2 \
|
||||
--exclude=".venv" \
|
||||
--exclude=".pytest_cache" \
|
||||
/home/<legacy-operator>/Core/ /home/operator/Core/
|
||||
|
||||
sudo rsync -aHAX --info=progress2 \
|
||||
/home/<legacy-operator>/Sites/ /home/operator/Sites/
|
||||
|
||||
if [ -d "/home/<legacy-operator>/var/lib/homelab" ]; then
|
||||
sudo rsync -aHAX --info=progress2 \
|
||||
/home/<legacy-operator>/var/lib/homelab/ /home/operator/var/lib/homelab/
|
||||
fi
|
||||
|
||||
if [ -d "/home/<legacy-operator>/.local/state/homelab" ]; then
|
||||
sudo rsync -aHAX --info=progress2 \
|
||||
/home/<legacy-operator>/.local/state/homelab/ /home/operator/.local/state/homelab/
|
||||
fi
|
||||
|
||||
if [ -d "/home/<legacy-operator>/.config/homelab" ]; then
|
||||
sudo rsync -aHAX --info=progress2 \
|
||||
/home/<legacy-operator>/.config/homelab/ /home/operator/.config/homelab/
|
||||
fi
|
||||
```
|
||||
|
||||
2. **Quiesce active database writers**:
|
||||
Stop running workload containers and the Core platform stack to guarantee point-in-time consistency across SQLite databases (e.g. LLDAP `users.db`, Authelia `db.sqlite3`, Stalwart storage, and workload app volumes in `~/var/lib/homelab/`) before the final sync:
|
||||
```bash
|
||||
# Stop running workload containers
|
||||
appctl down --all 2>/dev/null || docker stop $(docker ps -q) 2>/dev/null || true
|
||||
|
||||
# Stop platform core services
|
||||
sudo systemctl stop homeserver-core
|
||||
sudo systemctl stop homelab-appctl
|
||||
sudo systemctl stop homelab-gitops
|
||||
```
|
||||
|
||||
3. **Final delta synchronization (`--delete`)**:
|
||||
Perform a rapid final delta synchronization with `--delete` to capture the quiesced database state and prune removed files:
|
||||
```bash
|
||||
sudo rsync -aHAX --delete --info=progress2 \
|
||||
--exclude=".venv" \
|
||||
--exclude=".pytest_cache" \
|
||||
/home/<legacy-operator>/Core/ /home/operator/Core/
|
||||
|
||||
sudo rsync -aHAX --delete --info=progress2 \
|
||||
/home/<legacy-operator>/Sites/ /home/operator/Sites/
|
||||
|
||||
if [ -d "/home/<legacy-operator>/var/lib/homelab" ]; then
|
||||
sudo rsync -aHAX --delete --info=progress2 \
|
||||
/home/<legacy-operator>/var/lib/homelab/ /home/operator/var/lib/homelab/
|
||||
fi
|
||||
|
||||
if [ -d "/home/<legacy-operator>/.local/state/homelab" ]; then
|
||||
sudo rsync -aHAX --delete --info=progress2 \
|
||||
/home/<legacy-operator>/.local/state/homelab/ /home/operator/.local/state/homelab/
|
||||
fi
|
||||
```
|
||||
|
||||
4. **Fix ownership and permissions**:
|
||||
Set primary ownership to `operator` and group to `homelab-operators` across all migrated trees:
|
||||
```bash
|
||||
sudo chown -R operator:homelab-operators \
|
||||
/home/operator/Core \
|
||||
/home/operator/Sites \
|
||||
/home/operator/.config \
|
||||
/home/operator/.local \
|
||||
/home/operator/var
|
||||
sudo chmod -R u+rwX,g+rX /home/operator/Core /home/operator/Sites /home/operator/var
|
||||
|
||||
# ACME certificate security invariant: Traefik strictly requires 0600 on acme.json;
|
||||
# recursive group read permissions will cause Traefik to refuse to start.
|
||||
if [ -f /home/operator/Core/config/letsencrypt/acme.json ]; then
|
||||
sudo chmod 600 /home/operator/Core/config/letsencrypt/acme.json
|
||||
fi
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Stage 3: Service Rebuild & Environment Cutover
|
||||
Activate the declarative configuration under the `operator` profile:
|
||||
|
||||
1. **Configure instance domain injection (Decision D1)**:
|
||||
Ensure `nixos/instance.nix` (or `/etc/nixos/homelab-instance.nix`) is in place with the host's production domain:
|
||||
```bash
|
||||
cat << 'EOF' | sudo -u operator tee /home/operator/Core/nixos/instance.nix > /dev/null
|
||||
{
|
||||
homelab.domain = "example.com";
|
||||
}
|
||||
EOF
|
||||
chmod 600 /home/operator/Core/nixos/instance.nix
|
||||
```
|
||||
|
||||
2. **Bootstrap appctl control plane tokens (CR-SO-08)**:
|
||||
The `homelab-appctl.service` control plane daemon enforces 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`) authenticated via SHA-256 Bearer tokens stored in `/run/secrets/appctl/tokens.json`.
|
||||
|
||||
Generate the operator administrator token and local CLI credentials:
|
||||
```bash
|
||||
sudo -u operator python3 /home/operator/Core/scripts/bootstrap_token.py
|
||||
```
|
||||
This command:
|
||||
- Creates `~/.config/homelab/token` (mode `0600`) owned by `operator:homelab-operators` containing the raw Bearer token used automatically by the `appctl` CLI.
|
||||
- Outputs the JSON token descriptor containing the SHA-256 digest:
|
||||
```json
|
||||
{
|
||||
"token_id": "operator-admin",
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"sha256": "<64-character-sha256-digest>"
|
||||
}
|
||||
```
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Unprovisioned Token Behavior & RBAC Fallback**:
|
||||
> If tokens are not provisioned in `/run/secrets/appctl/tokens.json`, local UDS connections (`/run/homelab/appctl.sock`) fall back to Linux `SO_PEERCRED` socket credentials, granting callers in `homelab-operators` the read-only `homelab-viewer` role.
|
||||
> Under `homelab-viewer`, safe queries succeed (`appctl list`, `appctl status`, `appctl health`).
|
||||
> However, **all mutating and privileged operations** (`appctl up`, `appctl down`, `appctl restart`, `appctl update`, `appctl deploy`, `appctl config`, `appctl info`) **strictly require** a valid Bearer token with `homelab-operator` or `homelab-admin` role. If tokens are not enrolled in SOPS, attempting mutating actions fails with HTTP 403 `ERR_PERMISSION_DENIED`.
|
||||
|
||||
Enroll the token descriptor into SOPS secrets:
|
||||
```bash
|
||||
sops /home/operator/Core/nixos/secrets.yaml
|
||||
```
|
||||
Under `appctl.tokens_json`, insert the descriptor into the JSON array:
|
||||
```yaml
|
||||
appctl:
|
||||
tokens_json: |
|
||||
[
|
||||
{
|
||||
"token_id": "operator-admin",
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"sha256": "<paste-sha256-digest-here>"
|
||||
}
|
||||
]
|
||||
```
|
||||
*(Optional: If GitOps webhook dispatch is enabled, generate and enroll a `gitops-webhook` token with `homelab-operator` role using `python3 scripts/bootstrap_token.py --identity gitops --role homelab-operator --token-id gitops-webhook --print-json`).*
|
||||
|
||||
3. **Rebuild NixOS host configuration**:
|
||||
Execute the rebuild from the new canonical Core path using `--impure` and the `path:` scheme to import the untracked instance profile:
|
||||
```bash
|
||||
cd /home/operator/Core
|
||||
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index, ensuring untracked/gitignored `nixos/instance.nix` is evaluated. (If using `/etc/nixos/homelab-instance.nix`, bare `--flake .#server --impure` works directly). Rebuilding also decrypts and projects `/run/secrets/appctl/tokens.json` via `sops-nix`.
|
||||
|
||||
4. **Restart platform services**:
|
||||
Restart the Core Compose stack and control plane services to consume updated paths and secrets:
|
||||
```bash
|
||||
sudo systemctl restart homeserver-core
|
||||
sudo systemctl restart homelab-appctl
|
||||
sudo systemctl restart homelab-gitops
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Stage 4: Post-Flight Verification
|
||||
Validate system health and operational readiness under the `operator` identity:
|
||||
|
||||
1. **Verify Git safe directory**:
|
||||
Ensure Git does not complain about dubious ownership when invoked by `operator` or `homelab-appctl`:
|
||||
```bash
|
||||
sudo -u operator git -C /home/operator/Core status
|
||||
sudo -u operator git -C /home/operator/Sites/<any-workload> status
|
||||
```
|
||||
|
||||
2. **Verify SOPS secrets and tokens projection**:
|
||||
Ensure `/run/secrets/appctl/tokens.json` is readable by `homelab-appctl` (mode `0400`, owned by `homelab-appctl:homelab-operators`) and contains valid descriptors:
|
||||
```bash
|
||||
sudo ls -l /run/secrets/appctl/tokens.json
|
||||
```
|
||||
|
||||
3. **Verify appctl control plane status & RBAC authentication**:
|
||||
Execute CLI inspection using both UDS peercred authentication (read-only viewer fallback) and authenticated admin token operations:
|
||||
```bash
|
||||
# 1. Peercred UDS inspection (demonstrates viewer fallback for read-only actions)
|
||||
sudo -u operator appctl list --core
|
||||
sudo -u operator appctl status
|
||||
sudo -u operator appctl health
|
||||
|
||||
# 2. Authenticated operator admin verification (requires homelab-admin Bearer token)
|
||||
sudo -u operator appctl info docs
|
||||
sudo -u operator appctl config docs
|
||||
```
|
||||
Confirm that `info` and `config` return resolved configuration without `ERR_PERMISSION_DENIED`, verifying that `~/.config/homelab/token` matches the provisioned SHA-256 digest in `/run/secrets/appctl/tokens.json`.
|
||||
|
||||
4. **Verify container reachability & proxy routing**:
|
||||
Check that external endpoints and internal reverse proxies resolve:
|
||||
```bash
|
||||
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
|
||||
curl -s -k https://127.0.0.1 -H "Host: dashboard.example.com" | head -n 5
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Rollback Procedure
|
||||
If unexpected service degradation occurs during the cutover:
|
||||
|
||||
1. **Revert NixOS system generation**:
|
||||
```bash
|
||||
sudo nixos-rebuild switch --rollback
|
||||
```
|
||||
|
||||
2. **Restart legacy Core services**:
|
||||
```bash
|
||||
sudo systemctl restart homeserver-core
|
||||
sudo systemctl restart homelab-appctl
|
||||
sudo systemctl restart homelab-gitops
|
||||
```
|
||||
|
||||
3. **Log rollback reason**:
|
||||
Record the diagnostic failure logs in `journalctl -xe` and investigate before attempting another cutover window.
|
||||
|
||||
---
|
||||
|
||||
## 8. Read-Only Agent Inspection (`agents` SSH Identity)
|
||||
|
||||
For automated troubleshooting and agentic workflows, use the dedicated `agents` SSH user instead of the `operator` account.
|
||||
|
||||
### Workstation Setup
|
||||
1. Generate a dedicated Ed25519 keypair on the workstation (if not already provisioned during setup):
|
||||
```bash
|
||||
ssh-keygen -t ed25519 -f ~/.ssh/canopy_agents -C "canopy-agents"
|
||||
```
|
||||
2. Register the `.pub` key in `users.users.agents.openssh.authorizedKeys.keys` (`nixos/configuration.nix`) and rebuild NixOS.
|
||||
3. Add a host entry to `~/.ssh/config` (using your server hostname or `server.example.test`):
|
||||
```sshconfig
|
||||
Host server-agents
|
||||
HostName <server-host>
|
||||
User agents
|
||||
IdentityFile ~/.ssh/canopy_agents
|
||||
IdentitiesOnly yes
|
||||
```
|
||||
|
||||
### Safe Read-Only Usage Examples
|
||||
Commands are passed non-interactively over SSH and validated by the `ForceCommand` wrapper:
|
||||
```bash
|
||||
# Container status and logs (via read-only socket-proxy)
|
||||
ssh server-agents "docker ps"
|
||||
ssh server-agents "docker logs --tail 50 <container>"
|
||||
ssh server-agents "docker inspect <container>"
|
||||
|
||||
# Platform & workload status
|
||||
ssh server-agents "appctl list --core"
|
||||
ssh server-agents "appctl status"
|
||||
ssh server-agents "appctl info <app>"
|
||||
|
||||
# Systemd service logs
|
||||
ssh server-agents "journalctl -u homelab-appctl -n 5"
|
||||
```
|
||||
|
||||
### Security Boundaries & Allowlist
|
||||
The `agents` account is constrained at both the OS and OpenSSH layers (`nixos/configuration.nix` and `nixos/scripts/agents-force-command.sh`):
|
||||
- **Allowlisted commands only (`Match User agents` `ForceCommand`)**:
|
||||
- `docker`: `ps`, `logs`, `inspect` only (routed to `DOCKER_HOST=tcp://127.0.0.1:2375`; `-H`, `--host`, `--context`, `-c`, and `--config` overrides are rejected).
|
||||
- `appctl`: `list`, `status`, `info`, `logs`, `ssl`, `health`, `resolve` only.
|
||||
- `journalctl`: read-only queries only (mutating flags such as `--flush`, `--rotate`, `--vacuum-*`, `--relinquish-var`, `--sync`, `--setup-keys`, and `--update-catalog` are rejected).
|
||||
- Empty commands, control characters, and shell metacharacters (`;`, `&`, `|`, `` ` ``, `$`, `(`, `)`, `<`, `>`, `\`, `'`, `"`) are rejected.
|
||||
- **No privilege escalation or interactive shell**: `agents` is not in `wheel` or `docker`, has no `sudo` access, and OpenSSH enforces `PermitTTY no`, `PasswordAuthentication no`, `AllowTcpForwarding no`, `X11Forwarding no`, and `AllowAgentForwarding no`.
|
||||
- **No host state write access**: `agents` has no write permissions to `~/Core`, `~/Workloads`, or `~/var/lib/homelab/*`.
|
||||
@@ -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.
|
||||
@@ -391,4 +391,4 @@ Before marking Milestone P4 complete, the following automated regression suite m
|
||||
| **Truthful Error Reporting** | `test_execution_failure_audit`: Failing or timing-out Docker/Git subprocess returns `500 ERR_EXECUTION_FAILED` and records `phase: FAILED` in `audit.jsonl`. | Reject PR |
|
||||
| **Audit Persistence Gate** | `test_audit_failure_blocks_mutation`: Unwritable `audit.jsonl` aborts mutating command with `500 ERR_EXECUTION_FAILED` and zero Docker/Git invocations. | Block Release |
|
||||
| **Daemon Crash Recovery** | `test_daemon_restart_preserves_state`: Clean stop and restart of daemon unlinks/rebinds socket cleanly and leaves running workloads and Git state undisturbed. | Reject PR |
|
||||
| **Existing Invariant Regression** | Run `./scripts/test`: All 124 existing unit, security, structural, Ruff, Pyright, and Nix flake sandbox checks pass with 0 regressions. | Block Merge |
|
||||
| **Existing Invariant Regression** | Run `./scripts/run-tests`: All 124 existing unit, security, structural, Ruff, Pyright, and Nix flake sandbox checks pass with 0 regressions. | Block Merge |
|
||||
@@ -0,0 +1,106 @@
|
||||
# 📋 Implementation Plan: Control Plane Hardening, Instance Decoupling & MCP Alignment
|
||||
|
||||
**Document Version**: 1.0
|
||||
**Status**: 🚀 Approved for Implementation
|
||||
**Date**: 2026-10-23
|
||||
**Target Milestone**: P4 Hardening & P6 Deprecation
|
||||
**Branch**: `refactor/appctl-rework`
|
||||
|
||||
---
|
||||
|
||||
## 1. Executive Summary & Context
|
||||
|
||||
During the pre-merge readiness investigation of the `refactor/appctl-rework` branch, four deployment blockers and several architectural divergences were identified:
|
||||
1. **Unconfigured Root Domain**: `options.homelab.domain` defaulted to `"example.test"`, which would overwrite live routing templates (`homeserver.env`, `traefik-deployments.env`) upon `nixos-rebuild switch`.
|
||||
2. **Authelia/LLDAP Base DN Desynchronization**: Compose defaulted `LLDAP_LDAP_BASE_DN` to `dc=example,dc=test`, conflicting with the existing on-host LLDAP database (`dc=<domain-prefix>,dc=<tld>`).
|
||||
3. **Operator Identity Coupling**: Core configurations referenced legacy operator username literals rather than a generic system operator (`operator`).
|
||||
4. **POSIX ACL & Git Dubious Ownership**: `tmpfiles.rules` used lowercase `a+` (non-recursive), leaving existing checkouts in `~/Sites` unwriteable to `homelab-appctl`. Furthermore, Git 2.35.2+ lacked `safe.directory` declarations for `homelab-appctl`.
|
||||
5. **AI Authoring Boundary Evolution**: Earlier architectural planning explored an on-server 5-stage deployment authoring pipeline (`ApplicationProfile` $\to$ `DeploymentProposal` $\to$ `DeploymentModel` compiler). This requirement is formally deprecated in favor of a decoupled Model Context Protocol (MCP) tool gateway.
|
||||
|
||||
This plan establishes the concrete implementation work packages to resolve these findings and ensure 100% deployment safety.
|
||||
|
||||
---
|
||||
|
||||
## 2. Architectural Decisions & Scope
|
||||
|
||||
### A. Operator Identity Decoupling (Legacy Operator $\to$ `operator`)
|
||||
- Standardize the primary platform operator as `operator` with home directory `/home/operator`.
|
||||
- `config.homelab.operatorUser` defaults to `"operator"`.
|
||||
- NixOS declares user `operator` (`uid = 1000` or standard user, `extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]`).
|
||||
- Eliminates hardcoded personal usernames from the Core platform foundation.
|
||||
|
||||
### B. Platform Genericism & Instance Profile (Decision D1)
|
||||
- Core modules in `nixos/modules/` remain strictly generic, defaulting to RFC 2606 placeholders (`example.test` and `operator`).
|
||||
- **Decision D1: Dual-Path Instance Domain Injection**: Rather than committing host-specific production domains to tracked Git files, `nixos/configuration.nix` implements an optional dual-path import mechanism:
|
||||
```nix
|
||||
imports = [
|
||||
./hardware-configuration.nix
|
||||
./modules/homeserver.nix
|
||||
./modules/traefik-deployments.nix
|
||||
./modules/dynu.nix
|
||||
./modules/shell.nix
|
||||
] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix
|
||||
++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix;
|
||||
```
|
||||
- `nixos/instance.nix` is git-ignored, allowing host-specific overrides (like `homelab.domain = "example.com";`) without dirtying version control. Alternatively, `/etc/nixos/homelab-instance.nix` provides a persistent host-level configuration path outside the repository checkout.
|
||||
- `LLDAP_LDAP_BASE_DN` is computed dynamically in Nix from `config.homelab.domain` (`domain: example.test` $\implies$ `dc=example,dc=test`), eliminating hardcoded domain strings across templates and Compose files.
|
||||
|
||||
### C. Control Plane Security & POSIX Permissions
|
||||
- **Recursive ACLs**: Change `a+` to uppercase `A+` for `${config.homelab.sitesDir}` and `${config.homelab.coreDir}/config/homepage` in `systemd.tmpfiles.rules`.
|
||||
- **Git Safe Directory**: Configure `programs.git.config.safe.directory = [ "/home/operator/Sites/*" ]` for the host.
|
||||
- **Fail-Closed CLI**: If `/run/homelab/appctl.sock` is unavailable, `scripts/appctl` fails closed with an informative error rather than silently falling back to unauthenticated Bash execution.
|
||||
- **CLI Status Restoration**: Restore live container inspection (`get_docker_status()`) in `workload.list` and format the `STATUS` column in `scripts/appctl_cli.py`.
|
||||
|
||||
### D. Deprecation of On-Server AI Authoring Pipeline (MCP Gateway Adoption)
|
||||
- As documented in `~/Brain/02-discussions/homelab/mcp-gateway-and-platform-evolution.md`, on-server AI deployment agents (`DeploymentProposal` compilers) are deprecated.
|
||||
- Milestone P6 is redefined as the **Homelab MCP Gateway**:
|
||||
- Exposes deterministic `appctl` operations over JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`, `appctl_audit`).
|
||||
- Gated by native client-side human confirmation (Antigravity, Claude Code, Cursor).
|
||||
- Keeps Core 100% deterministic with zero autonomous agent loops executing on the appliance host.
|
||||
|
||||
---
|
||||
|
||||
## 3. Work Breakdown Structure (WBS)
|
||||
|
||||
### Phase 1: Host Configuration & Identity Migration
|
||||
- [x] **Task 1.1**: Update `nixos/configuration.nix` to declare user `operator` and configure `homelab.operatorUser = "operator"` and `homelab.domain` with the configured production domain.
|
||||
- [x] **Task 1.2**: Declare `programs.git.config.safe.directory = [ "/home/operator/Sites/*" ]` in `nixos/configuration.nix`.
|
||||
- [x] **Task 1.3**: Derive `LLDAP_LDAP_BASE_DN` dynamically from `config.homelab.domain` in `nixos/modules/homeserver.nix` and pass it to `sops.templates."homeserver.env"`.
|
||||
- [x] **Task 1.4**: Update `docker-compose.yml` to consume `LLDAP_LDAP_BASE_DN` from `homeserver.env`.
|
||||
- [x] **Task 1.5**: Update `systemd.tmpfiles.rules` in `nixos/modules/homeserver.nix` from `a+` to recursive `A+` on `sitesDir`.
|
||||
|
||||
### Phase 2: CLI Hardening & Status Parity
|
||||
- [x] **Task 2.1**: Update `scripts/appctl` to fail closed when `[ ! -S "$SOCKET_PATH" ]`, removing the silent fallback to legacy Bash.
|
||||
- [x] **Task 2.2**: Update `_op_workload_list` in `scripts/appctl_router.py` to query live container health (`get_docker_status()`).
|
||||
- [x] **Task 2.3**: Update `_format_workload_table` in `scripts/appctl_cli.py` to render the `STATUS` column (`🟢 Running (1)` / `🔴 Stopped`).
|
||||
- [x] **Task 2.4**: Bootstrap operator admin token documentation and setup instructions in `docs/appctl.md` and `docs/secrets-and-state.md`.
|
||||
- [x] **Task 2.5**: Wire `--build` and `--no-cache` in `scripts/appctl_cli.py`, pass `--pull` during `compose_build` in `scripts/appctl_router.py`, and document source-built action policy in `docs/appctl.md`.
|
||||
|
||||
### Phase 3: Architectural Records & Roadmap Synchronization
|
||||
- [x] **Task 3.1**: Update `ROADMAP.md` (P6 redefined as Homelab MCP Gateway; on-server AI compiler deprecated).
|
||||
- [x] **Task 3.2**: Add architectural amendment note to `docs/decisions/0002-appctl-control-plane-architecture.md`.
|
||||
- [x] **Task 3.3**: Update `docs/decisions/README.md`.
|
||||
- [x] **Task 3.4**: Update `docs/appctl.md` (clarifying bounded log snapshots and Core update workflow).
|
||||
- [x] **Task 3.5**: Synchronize `todo.txt` with active implementation tasks.
|
||||
|
||||
### Phase 4: Work Package 6 (WP6: Instance Decoupling & Operator Cutover Runbook)
|
||||
- [x] **Task 4.1**: Update `nixos/configuration.nix` with optional dual-path imports for `./instance.nix` and `/etc/nixos/homelab-instance.nix` (Decision D1).
|
||||
- [x] **Task 4.2**: Add `nixos/instance.nix` to `.gitignore` to preserve 100% repository genericism.
|
||||
- [x] **Task 4.3**: Implement automated invariant tests in `tests/security/test_security_invariants.py` (default domain evaluation, dynamic LDAP base DN, instance override, platform genericism).
|
||||
- [x] **Task 4.4**: Document instance domain injection procedure in `docs/setup_guide.md`.
|
||||
- [x] **Task 4.5**: Codify the 4-stage Staged Coexistence Cutover Runbook (Decision D2) in `docs/operations.md` with explicit notice blocking live host execution pending maintenance window.
|
||||
|
||||
---
|
||||
|
||||
## 4. Verification & Quality Gates
|
||||
|
||||
The implementation must pass:
|
||||
1. **Static Analysis & Linting**: `ruff check .` and `pyright` (0 errors, 0 warnings).
|
||||
2. **Full Regression Suite**: All 283 existing unit, security, and invariant tests passing.
|
||||
3. **New Test Coverage**:
|
||||
- Assert dynamic LDAP base DN computation from domain.
|
||||
- Assert `scripts/appctl` fails closed when socket is absent.
|
||||
- Assert `appctl list` output formatting includes container status.
|
||||
- Assert platform genericism invariants across updated Nix modules.
|
||||
4. **Hermetic Flake Check**: `nix flake check` builds cleanly.
|
||||
5. **NixOS Evaluation**: `nix eval .#nixosConfigurations.server.config.system.build.toplevel.drvPath` evaluates without warnings.
|
||||
@@ -29,17 +29,23 @@ This document explains the secrets distribution architecture, runtime projection
|
||||
│ 3. /run/secrets/gitops/webhook_secret │
|
||||
│ -> Consumed by homelab-gitops.service for HMAC verification │
|
||||
│ │
|
||||
│ 4. /run/credentials/ddclient.service/ddclient.conf │
|
||||
│ 4. /run/secrets/appctl/tokens.json (mode 0400, homelab-appctl) │
|
||||
│ -> Consumed by homelab-appctl.service for SHA-256 Bearer auth │
|
||||
│ │
|
||||
│ 5. /run/secrets/gitops/appctl_token (mode 0400, operatorUser) │
|
||||
│ -> Consumed by homelab-gitops.service worker for UDS daemon auth │
|
||||
│ │
|
||||
│ 6. /run/credentials/ddclient.service/ddclient.conf │
|
||||
│ -> Consumed by systemd ddclient service │
|
||||
│ │
|
||||
│ 5. /run/secrets/pdf_decrypt_password │
|
||||
│ 7. /run/secrets/pdf_decrypt_password │
|
||||
│ -> Consumed by shell pdf_dc utility │
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Projected Secret Templates
|
||||
## 3. Projected Secret Templates & Token Store
|
||||
|
||||
### A. Core Platform Environment (`/run/secrets/homeserver.env`)
|
||||
Generated by `nixos/modules/homeserver.nix`. Supplies credentials to the Core Compose stack:
|
||||
@@ -54,7 +60,13 @@ Generated by `nixos/modules/homeserver.nix`. Supplies credentials to the Core Co
|
||||
* `SMTP_SERVER`, `SMTP_PORT`, `SMTP_LOGIN`, `SMTP_KEY`: Outbound relay credentials (Brevo) for Stalwart mail transport.
|
||||
|
||||
### B. Workload Deployments Environment (`/run/secrets/traefik-deployments.env`)
|
||||
Generated by `nixos/modules/traefik-deployments.nix`. Projects shared infrastructure secrets and workload credentials that `appctl` sources when orchestrating stacks in `~/Sites` (such as database passwords, API keys, and runner tokens).
|
||||
Generated by `nixos/modules/traefik-deployments.nix`. Projects shared infrastructure secrets and workload credentials that `appctl` parses inertly in pure Python when orchestrating stacks in `~/Sites` (such as database passwords, API keys, and runner tokens).
|
||||
|
||||
### C. Control Plane Token Store (`/run/secrets/appctl/tokens.json` & `/run/secrets/gitops/appctl_token`)
|
||||
Provisioned from `nixos/secrets.yaml` (`appctl/tokens_json` and `gitops/appctl_token`):
|
||||
* `/run/secrets/appctl/tokens.json`: Owned by `homelab-appctl:homelab-operators` with strict mode `0400` (enforced fail-closed by `TokenStore._verify_permissions()`, rejecting any write bit or group/world readability). Stores a JSON array of SHA-256 token descriptors (`token_id`, `identity`, `role`, and 64-hex `sha256`) defined under `appctl/tokens_json` in `nixos/secrets.yaml`.
|
||||
* `/run/secrets/gitops/appctl_token`: Owned by `config.homelab.operatorUser` (mode `0400`). Supplies the `homelab-operator` Bearer secret to `homelab-gitops.service` when delegating `workload.update` to `homelab-appctl.service`.
|
||||
* `~/.config/homelab/token`: Local operator Bearer token written with strict mode `0600` (in a mode `0700` directory) by `scripts/bootstrap_token.py`. Automatically discovered and resolved by `appctl_cli.py` for authenticated operator interactions without needing `--token` flags or environment variables.
|
||||
|
||||
---
|
||||
|
||||
@@ -80,6 +92,9 @@ lldap:
|
||||
admin_password: "..."
|
||||
gitops:
|
||||
webhook_secret: "..."
|
||||
appctl_token: "..."
|
||||
appctl:
|
||||
tokens_json: "[...]"
|
||||
brevo:
|
||||
smtp_login: "..."
|
||||
smtp_key: "..."
|
||||
@@ -88,7 +103,7 @@ brevo:
|
||||
### 3. Save and Apply Changes
|
||||
Saving the file in your editor automatically re-encrypts it with Age. Apply the updated templates to running services:
|
||||
```bash
|
||||
sudo nixos-rebuild switch --flake ~/Core#server
|
||||
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
|
||||
```
|
||||
|
||||
---
|
||||
@@ -97,7 +112,7 @@ sudo nixos-rebuild switch --flake ~/Core#server
|
||||
|
||||
Homelab Core separates **user identity** from **static platform secrets**:
|
||||
|
||||
* **Static Secrets**: Stored in `nixos/secrets.yaml` (system API keys, JWT secrets, database passwords).
|
||||
* **Static Secrets**: Stored in `nixos/secrets.yaml` (system API keys, JWT secrets, database passwords, control-plane token hashes).
|
||||
* **Dynamic User Directory**: User accounts, credentials, and group memberships are managed live in **LLDAP** (`https://users.${HOMELAB_DOMAIN}`). User account updates do not require editing `secrets.yaml` or rebuilding NixOS.
|
||||
* **Authelia Integration**: Authelia queries LLDAP over LDAP (`ldap://lldap:3890`) at runtime using credentials projected from `/run/secrets/homeserver.env`.
|
||||
|
||||
@@ -109,7 +124,9 @@ Homelab Core separates **user identity** from **static platform secrets**:
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Declarative Config** | `~/Core/nixos/*.nix`, `docker-compose.yml` | ✅ Yes | System and container definitions |
|
||||
| **Encrypted Secrets** | `~/Core/nixos/secrets.yaml` | ✅ Yes (Encrypted) | SOPS Age-encrypted secret source |
|
||||
| **Runtime Secrets** | `/run/secrets/*` | ❌ No (RAM tmpfs) | Ephemeral decrypted environment files |
|
||||
| **Runtime Secrets** | `/run/secrets/*` | ❌ No (RAM tmpfs) | Ephemeral decrypted environment & token files |
|
||||
| **Control Plane Audit** | `/var/log/homelab/appctl/audit.jsonl` | ❌ No | Append-only JSONL security & mutation log (`0600`) |
|
||||
| **Control Plane Locks** | `/var/lib/homelab/appctl/locks/` | ❌ No | Per-target `flock` files & `_homepage_sync.lock` |
|
||||
| **SSL Certificates** | `~/Core/config/letsencrypt/acme.json` | ❌ No | Active Let's Encrypt certificates (mode 0600) |
|
||||
| **User Directory** | `~/Core/config/lldap/data/` | ❌ No | LLDAP SQLite database (`users.db`) |
|
||||
| **Auth Database** | `~/Core/config/authelia/db.sqlite3` | ❌ No | Authelia session database |
|
||||
|
||||
+76
-8
@@ -32,24 +32,64 @@ sudo ls -l /etc/ssh/ssh_host_ed25519_key
|
||||
sudo chmod 600 /etc/ssh/ssh_host_ed25519_key
|
||||
```
|
||||
|
||||
### Step 2: Apply Declarative NixOS Configuration
|
||||
### Step 2: Configure Appliance Instance Domain (Decision D1)
|
||||
To preserve strict platform genericism, the repository files tracked in Git never contain production domains or personal operator identities, defaulting to RFC 2606 placeholders (`example.test` and `operator`).
|
||||
|
||||
An appliance host supplies its production domain and local configuration overrides via one of two untracked dual-path files:
|
||||
1. **Repository-local instance profile (`nixos/instance.nix`)**:
|
||||
Create an untracked, git-ignored file in `nixos/instance.nix`:
|
||||
```nix
|
||||
{
|
||||
homelab.domain = "example.com";
|
||||
}
|
||||
```
|
||||
When rebuilding via `sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure` (or `path:~/Core#server --impure`), Nix automatically imports `nixos/instance.nix` if present.
|
||||
|
||||
> [!NOTE]
|
||||
> **Flake Fetcher Scheme for Untracked Files**:
|
||||
> Because `nixos/instance.nix` is gitignored, Nix's default Git fetcher filters it out when evaluating standard Git flake references (e.g. `--flake ~/Core#server`). Prefixing the path with the `path:` scheme (e.g. `path:/home/operator/Core#server` or `path:~/Core#server`) instructs Nix to evaluate directly from the filesystem without filtering by the Git index.
|
||||
> If using the host-level `/etc/nixos/homelab-instance.nix` instead, a bare `--flake .#server --impure` works directly because `/etc/nixos` resides outside the Git repository tree.
|
||||
|
||||
2. **Host-level instance profile (`/etc/nixos/homelab-instance.nix`)**:
|
||||
Alternatively, create a host-level file outside the Git checkout:
|
||||
```nix
|
||||
{
|
||||
homelab.domain = "example.com";
|
||||
}
|
||||
```
|
||||
This persists configuration across fresh repository clones or ephemeral branches.
|
||||
|
||||
Both paths are declared optionally in `nixos/configuration.nix`:
|
||||
```nix
|
||||
imports = [
|
||||
./hardware-configuration.nix
|
||||
./modules/homeserver.nix
|
||||
./modules/traefik-deployments.nix
|
||||
./modules/dynu.nix
|
||||
./modules/shell.nix
|
||||
] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix
|
||||
++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix;
|
||||
```
|
||||
When present, `homelab.domain` overrides the default (`example.test`), and all generated templates (`homeserver.env`, Traefik routing rules, and the dynamic `LLDAP_LDAP_BASE_DN`) automatically reflect the production domain without altering any tracked Git files.
|
||||
|
||||
### Step 3: Apply Declarative NixOS Configuration
|
||||
```bash
|
||||
cd ~/Core
|
||||
sudo nixos-rebuild switch --flake ~/Core#server
|
||||
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
|
||||
```
|
||||
This configures:
|
||||
* Docker daemon, host firewall rules, and system packages.
|
||||
* Decrypted secret files in `/run/secrets/homeserver.env` and `/run/secrets/traefik-deployments.env`.
|
||||
* Systemd service units (`homeserver-core`, `homelab-gitops`, `dynu-monitor`).
|
||||
* Systemd service units (`homeserver-core`, `homelab-appctl`, `homelab-gitops`, `dynu-monitor`).
|
||||
|
||||
### Step 3: Create External Docker Networks
|
||||
### Step 4: Create External Docker Networks
|
||||
The Core Compose stack and workloads require the `proxy-net` and `socket-net` bridge networks:
|
||||
```bash
|
||||
docker network create proxy-net 2>/dev/null || true
|
||||
docker network create socket-net 2>/dev/null || true
|
||||
```
|
||||
|
||||
### Step 4: Start Platform Services
|
||||
### Step 5: Start Platform Services
|
||||
```bash
|
||||
sudo systemctl start homeserver-core
|
||||
```
|
||||
@@ -58,7 +98,7 @@ Check running containers:
|
||||
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
|
||||
```
|
||||
|
||||
### Step 5: Verify DNS & Certificates
|
||||
### Step 6: Verify DNS & Certificates
|
||||
1. Trigger an immediate DDNS update:
|
||||
```bash
|
||||
sudo systemctl start dynu-monitor
|
||||
@@ -68,11 +108,39 @@ docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
|
||||
appctl ssl traefik
|
||||
```
|
||||
|
||||
### Step 6: Initialize LLDAP Directory
|
||||
### Step 7: Initialize LLDAP Directory
|
||||
1. Navigate to `https://users.${HOMELAB_DOMAIN}` (e.g., `https://users.example.com`).
|
||||
2. Authenticate using `admin` and the password configured in `nixos/secrets.yaml` (`lldap/admin_password`).
|
||||
3. Create standard user accounts and assign them to required groups.
|
||||
|
||||
### Step 8: Provision Read-Only Agent SSH Access (`agents`)
|
||||
The `agents` user provides a restricted, read-only SSH identity for automated or agentic diagnostics without granting `sudo`, `docker` group membership, or write access to host state.
|
||||
|
||||
1. **Generate a dedicated Ed25519 SSH keypair** on your workstation:
|
||||
```bash
|
||||
ssh-keygen -t ed25519 -f ~/.ssh/canopy_agents -C "canopy-agents"
|
||||
```
|
||||
2. **Wire the public key into NixOS**:
|
||||
Add the contents of `~/.ssh/canopy_agents.pub` to `users.users.agents.openssh.authorizedKeys.keys` in `nixos/configuration.nix` and apply the configuration on the server:
|
||||
```bash
|
||||
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
|
||||
```
|
||||
`nixos/configuration.nix` assigns `agents` only to `homelab-operators` (for read-only `appctl` socket queries) and `systemd-journal` (for `journalctl`), and enforces `Match User agents` with `ForceCommand` (`nixos/scripts/agents-force-command.sh`), `PermitTTY no`, `PasswordAuthentication no`, and forwarding disabled.
|
||||
3. **Configure workstation `~/.ssh/config`** (replace `<server-host>` with your host or `server.example.test`):
|
||||
```sshconfig
|
||||
Host server-agents
|
||||
HostName <server-host>
|
||||
User agents
|
||||
IdentityFile ~/.ssh/canopy_agents
|
||||
IdentitiesOnly yes
|
||||
```
|
||||
4. **Verify read-only inspection** from the workstation:
|
||||
```bash
|
||||
ssh server-agents "docker ps"
|
||||
ssh server-agents "appctl list --core"
|
||||
ssh server-agents "journalctl -u homelab-appctl -n 5"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Onboarding a New Application Workload
|
||||
@@ -167,7 +235,7 @@ Before committing changes to Homelab Core, run the repository test runner:
|
||||
|
||||
```bash
|
||||
cd ~/Core
|
||||
./scripts/test
|
||||
./scripts/run-tests
|
||||
```
|
||||
This runs:
|
||||
* Code formatting and lint checks (`ruff`).
|
||||
|
||||
Generated
+7
-7
@@ -2,11 +2,11 @@
|
||||
"nodes": {
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1792773339,
|
||||
"narHash": "sha256-17eNBI5Khe4JZaRkL5hRGPWf8MZ6qv+bWAr4V8YeKBw=",
|
||||
"rev": "3ec636362e1816bc2f0888fa0fa2c69f1bc9e504",
|
||||
"lastModified": 1795234589,
|
||||
"narHash": "sha256-pAEASBc6wof0S58XcSEdZoQ2iFQDkCnZwH+wFLrkd1Q=",
|
||||
"rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f",
|
||||
"type": "tarball",
|
||||
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1100280.3ec636362e18/nixexprs.tar.zst"
|
||||
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1125864.2786a2a72088/nixexprs.tar.zst"
|
||||
},
|
||||
"original": {
|
||||
"type": "tarball",
|
||||
@@ -26,11 +26,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1792056300,
|
||||
"narHash": "sha256-YU1LjDe1o2Ymg5zEiCHbmMXLkDCtxHQRiVqZ3nC5GGk=",
|
||||
"lastModified": 1794866654,
|
||||
"narHash": "sha256-Y28AMB8lyKjASdJ0BVsR2AqR1cUsVuo8RVVpzHoECho=",
|
||||
"owner": "Mic92",
|
||||
"repo": "sops-nix",
|
||||
"rev": "44931708c62937c2b1bf7953902989fa5bb9ee1b",
|
||||
"rev": "7c637afdccdf9bcf35c4a2d67b58a77c1fd843a4",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
@@ -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/
|
||||
'';
|
||||
};
|
||||
|
||||
+49
-5
@@ -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`
|
||||
|
||||
@@ -10,9 +10,23 @@
|
||||
./hardware-configuration.nix # Server-specific disk and CPU configuration
|
||||
./modules/homeserver.nix # Core services: systemd units, Authelia, SOPS secrets
|
||||
./modules/traefik-deployments.nix # Traefik deployment secrets and env templates
|
||||
./modules/dynu.nix # Dynu DDNS smart IP monitor service
|
||||
./modules/shell.nix # Declarative bash environment for the server
|
||||
] ++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix
|
||||
++ lib.optional (!(builtins.pathExists /etc/nixos/homelab-instance.nix) && builtins.pathExists ./instance.nix) ./instance.nix;
|
||||
|
||||
# ── Homelab platform settings ────────────────────────────────────────────────
|
||||
homelab.operatorUser = "operator";
|
||||
|
||||
# ── Host Git Safe Directory ──────────────────────────────────────────────────
|
||||
programs.git = {
|
||||
enable = true;
|
||||
config.safe.directory = [
|
||||
"/home/${config.homelab.operatorUser}/Core"
|
||||
"/home/${config.homelab.operatorUser}/Workloads"
|
||||
"/home/${config.homelab.operatorUser}/Workloads/*"
|
||||
"/home/${config.homelab.operatorUser}/Sites/*"
|
||||
];
|
||||
};
|
||||
|
||||
# ── SOPS secrets configuration ──────────────────────────────────────────────
|
||||
# Set once here to avoid duplicate-option conflicts across submodules
|
||||
@@ -53,24 +67,54 @@
|
||||
networking.hostName = "server";
|
||||
networking.networkmanager.enable = true;
|
||||
|
||||
# ── User account ─────────────────────────────────────────────────────────────
|
||||
users.users.kiskaadee = {
|
||||
# ── User accounts ────────────────────────────────────────────────────────────
|
||||
users.users.${config.homelab.operatorUser} = {
|
||||
isNormalUser = true;
|
||||
description = "Primary server administrator";
|
||||
openssh.authorizedKeys.keys = [
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICAVPPMk+WApUd/fo78+lsRGnLKSlY4GDZiNGKwBAifD"
|
||||
];
|
||||
extraGroups = [
|
||||
"wheel" # sudo access
|
||||
"docker" # run docker without sudo
|
||||
"homelab-operators" # access /run/homelab/appctl.sock
|
||||
"networkmanager" # modify network settings
|
||||
];
|
||||
};
|
||||
|
||||
users.users.agents = {
|
||||
isNormalUser = true;
|
||||
description = "Read-only agent inspection user";
|
||||
openssh.authorizedKeys.keys = [
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIE1pxTdygG5696q0jT7clfJZWtx48ugfUjpzvkHzovVd canopy-agents"
|
||||
];
|
||||
extraGroups = [
|
||||
"homelab-operators" # read-only access via /run/homelab/appctl.sock
|
||||
"systemd-journal" # read-only access to journalctl
|
||||
];
|
||||
};
|
||||
|
||||
# ── SSH ──────────────────────────────────────────────────────────────────────
|
||||
services.openssh = {
|
||||
services.openssh = let
|
||||
agentsForceCommand = pkgs.writeShellScriptBin "agents-force-command" ''
|
||||
export CORE_DIR="''${CORE_DIR:-/home/${config.homelab.operatorUser}/Core}"
|
||||
export WORKLOADS_DIR="''${WORKLOADS_DIR:-/home/${config.homelab.operatorUser}/Workloads}"
|
||||
export DOCKER_HOST="''${DOCKER_HOST:-tcp://127.0.0.1:2375}"
|
||||
exec ${pkgs.bash}/bin/bash ${./scripts/agents-force-command.sh} "$@"
|
||||
'';
|
||||
in {
|
||||
enable = true;
|
||||
ports = [ 22 ];
|
||||
settings.PermitRootLogin = "no";
|
||||
extraConfig = ''
|
||||
Match User agents
|
||||
ForceCommand ${agentsForceCommand}/bin/agents-force-command
|
||||
AllowTcpForwarding no
|
||||
X11Forwarding no
|
||||
AllowAgentForwarding no
|
||||
PermitTTY no
|
||||
PasswordAuthentication no
|
||||
'';
|
||||
};
|
||||
|
||||
# ── Virtualisation ───────────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# Example host-local instance configuration for Canopy NixOS Core.
|
||||
# Copy to /etc/nixos/homelab-instance.nix (recommended, loaded with --impure)
|
||||
# or gitignored nixos/instance.nix, and customize for your host.
|
||||
{ ... }:
|
||||
|
||||
{
|
||||
homelab.domain = "example.com";
|
||||
homelab.operatorUser = "operator";
|
||||
|
||||
# Host-granted workload capabilities ("Compose Requests, Nix Grants" — ADR-0005).
|
||||
# Keyed by workload name matching ~/Workloads/<app>.
|
||||
homelab.workloadGrants = {
|
||||
# Example hardware-accelerated media workload:
|
||||
# media-server = {
|
||||
# devices = [ "/dev/dri/renderD128" ];
|
||||
# groups = [ "render" ];
|
||||
# readOnlyPaths = [ "/mnt/media" ];
|
||||
# };
|
||||
};
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
# 🌐 Dynu DDNS IP Monitor & Updater Service
|
||||
# This NixOS module configures a smart, local-first IP change detector.
|
||||
# It queries public IP providers, maintains a history log of WAN IP rotations,
|
||||
# and triggers ddclient only when an actual change is detected to prevent API rate limits.
|
||||
|
||||
{ config, lib, pkgs, ... }:
|
||||
|
||||
let
|
||||
# Declaratively read the external Python script into the Nix store at evaluation time
|
||||
ipMonitorScript = pkgs.writers.writePython3Bin "dynu-ip-monitor" { } (builtins.readFile ../scripts/monitor.py);
|
||||
in
|
||||
{
|
||||
# Define the keys to decrypt
|
||||
sops.secrets."dynu/user" = { };
|
||||
sops.secrets."dynu/domain" = { };
|
||||
sops.secrets."dynu/password" = { };
|
||||
sops.secrets."system/pdf_decrypt_password" = {
|
||||
owner = "kiskaadee";
|
||||
};
|
||||
|
||||
# Assemble the ddclient config file securely at boot time in /run/secrets/
|
||||
# Defaults to owner root:root (which avoids dynamic user evaluation issues)
|
||||
sops.templates."ddclient.conf" = {
|
||||
content = builtins.replaceStrings
|
||||
[ "@dynu_user@" "@dynu_password@" "@dynu_domain@" ]
|
||||
[
|
||||
config.sops.placeholder."dynu/user"
|
||||
config.sops.placeholder."dynu/password"
|
||||
config.sops.placeholder."dynu/domain"
|
||||
]
|
||||
(builtins.readFile ../scripts/ddclient.conf);
|
||||
};
|
||||
|
||||
# Enable ddclient and feed it the decrypted configuration template via systemd credentials
|
||||
services.ddclient = {
|
||||
enable = true;
|
||||
configFile = "/run/credentials/ddclient.service/ddclient.conf";
|
||||
};
|
||||
|
||||
systemd.services.ddclient = {
|
||||
serviceConfig = {
|
||||
# Securely load the root-owned secret file into the dynamic ddclient service
|
||||
LoadCredential = [ "ddclient.conf:${config.sops.templates."ddclient.conf".path}" ];
|
||||
};
|
||||
};
|
||||
|
||||
# Disable ddclient's automatic timer.
|
||||
# This stops ddclient from polling every 10 minutes on its own.
|
||||
systemd.timers.ddclient.enable = false;
|
||||
|
||||
# Define the smart IP change detector service
|
||||
systemd.services.dynu-monitor = {
|
||||
description = "Dynu DDNS Smart IP Change Monitor";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
path = with pkgs; [
|
||||
systemd # Required for systemctl
|
||||
];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
User = "root";
|
||||
Group = "root";
|
||||
StateDirectory = "dynu";
|
||||
Environment = "HISTORY_FILE=/var/lib/dynu/ip_history.jsonl";
|
||||
ExecStart = "${ipMonitorScript}/bin/dynu-ip-monitor";
|
||||
TimeoutSec = 30;
|
||||
|
||||
# Hardening
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
ReadWritePaths = "/var/lib/dynu";
|
||||
};
|
||||
};
|
||||
|
||||
# Run the smart IP change monitor periodically (every 30 minutes)
|
||||
systemd.timers.dynu-monitor = {
|
||||
description = "Run Dynu IP monitor periodically";
|
||||
timerConfig = {
|
||||
OnBootSec = "5min";
|
||||
OnUnitActiveSec = "30min";
|
||||
AccuracySec = "1min";
|
||||
Persistent = true;
|
||||
};
|
||||
wantedBy = [ "timers.target" ];
|
||||
};
|
||||
}
|
||||
+249
-33
@@ -4,9 +4,113 @@
|
||||
{ config, lib, pkgs, ... }:
|
||||
|
||||
{
|
||||
# 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}/Workloads";
|
||||
description = "Path to Workloads directory (legacy option name: sitesDir)";
|
||||
};
|
||||
workloadGrants = lib.mkOption {
|
||||
type = lib.types.attrsOf (lib.types.submodule {
|
||||
options = {
|
||||
devices = lib.mkOption {
|
||||
type = lib.types.listOf lib.types.str;
|
||||
default = [];
|
||||
description = "Host device paths permitted for this workload (prefer specific nodes such as /dev/dri/renderD128).";
|
||||
};
|
||||
groups = lib.mkOption {
|
||||
type = lib.types.listOf lib.types.str;
|
||||
default = [];
|
||||
description = "Host group names or numeric GIDs permitted in group_add and user: primary GID.";
|
||||
};
|
||||
readOnlyPaths = lib.mkOption {
|
||||
type = lib.types.listOf lib.types.str;
|
||||
default = [];
|
||||
description = "Host directories permitted for read-only (:ro) bind mounts.";
|
||||
};
|
||||
};
|
||||
});
|
||||
default = {};
|
||||
description = "Host-granted hardware devices, groups, and read-only storage paths keyed by workload name.";
|
||||
};
|
||||
};
|
||||
|
||||
config = let
|
||||
domainParts = lib.splitString "." config.homelab.domain;
|
||||
ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts);
|
||||
in {
|
||||
# ── Workload Capability Grant Invariants (ADR-0005) ─────────────────────────
|
||||
assertions = let
|
||||
grantsList = lib.mapAttrsToList (app: grant: { inherit app grant; }) config.homelab.workloadGrants;
|
||||
privilegedGroups = [ "0" "root" "wheel" "docker" ];
|
||||
hasInvalidPath = p:
|
||||
!(lib.hasPrefix "/" p)
|
||||
|| (lib.hasInfix "/../" p)
|
||||
|| (lib.hasSuffix "/.." p)
|
||||
|| (p == "..");
|
||||
in
|
||||
(map ({ app, grant }: {
|
||||
assertion = lib.all (g: !(lib.elem (lib.toLower (lib.strings.trim g)) privilegedGroups)) grant.groups;
|
||||
message = "homelab.workloadGrants.${app}.groups must not contain privileged groups (0, root, wheel, docker).";
|
||||
}) grantsList)
|
||||
++ (map ({ app, grant }: {
|
||||
assertion = lib.all (p: !(hasInvalidPath p)) grant.devices;
|
||||
message = "homelab.workloadGrants.${app}.devices must contain absolute paths without '..' traversal.";
|
||||
}) grantsList)
|
||||
++ (map ({ app, grant }: {
|
||||
assertion = lib.all (p: !(hasInvalidPath p)) grant.readOnlyPaths;
|
||||
message = "homelab.workloadGrants.${app}.readOnlyPaths must contain absolute paths without '..' traversal.";
|
||||
}) grantsList);
|
||||
|
||||
# ── Host Capability Grants Projection (/etc/homelab/grants.json) ─────────────
|
||||
environment.etc."homelab/grants.json" = {
|
||||
user = "root";
|
||||
group = "homelab-operators";
|
||||
mode = "0640";
|
||||
text = builtins.toJSON {
|
||||
schemaVersion = "1.0";
|
||||
workloads = config.homelab.workloadGrants;
|
||||
};
|
||||
};
|
||||
|
||||
# ── Host Activation Guard ────────────────────────────────────────────────────
|
||||
# Prevents activating on a live host if homelab.domain defaulted to example.test (e.g. forgot --impure)
|
||||
system.activationScripts.checkHomelabDomain = {
|
||||
text = ''
|
||||
if [ "${config.homelab.domain}" = "example.test" ]; then
|
||||
echo "❌ [homelab] FATAL: homelab.domain is defaulting to 'example.test'!" >&2
|
||||
echo "❌ [homelab] Did you run 'nixos-rebuild switch' without the '--impure' flag?" >&2
|
||||
echo "❌ [homelab] To activate properly: sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure" >&2
|
||||
exit 1
|
||||
fi
|
||||
'';
|
||||
};
|
||||
|
||||
# Re-apply home-dir traverse ACL after `users` activation (chmod 0700 resets POSIX ACL mask::---)
|
||||
system.activationScripts.homelabHomeAcl = lib.stringAfter [ "users" ] ''
|
||||
if [ -d "/home/${config.homelab.operatorUser}" ]; then
|
||||
${pkgs.acl}/bin/setfacl -m u:homelab-appctl:x,g:homelab-operators:x,m::rx "/home/${config.homelab.operatorUser}"
|
||||
fi
|
||||
'';
|
||||
# Define the keys to decrypt from secrets.yaml
|
||||
sops.secrets = lib.genAttrs [
|
||||
"dynu/api_key"
|
||||
sops.secrets = (lib.genAttrs [
|
||||
"cloudflare/dns_api_token"
|
||||
"traefik/acme_email"
|
||||
"authelia/session_secret"
|
||||
"authelia/storage_encryption_key"
|
||||
@@ -18,15 +122,30 @@
|
||||
"brevo/smtp_login"
|
||||
"brevo/smtp_key"
|
||||
"diun/smtp_password"
|
||||
] (name: { owner = "kiskaadee"; });
|
||||
] (name: { owner = config.homelab.operatorUser; })) // {
|
||||
"appctl/tokens_json" = {
|
||||
owner = "homelab-appctl";
|
||||
group = "homelab-operators";
|
||||
mode = "0400";
|
||||
path = "/run/secrets/appctl/tokens.json";
|
||||
};
|
||||
"gitops/appctl_token" = {
|
||||
owner = config.homelab.operatorUser;
|
||||
group = "homelab-operators";
|
||||
mode = "0400";
|
||||
};
|
||||
};
|
||||
|
||||
# Generate the unified environment file at runtime in /run/secrets/homeserver.env
|
||||
sops.templates."homeserver.env" = {
|
||||
owner = "kiskaadee";
|
||||
owner = config.homelab.operatorUser;
|
||||
group = "homelab-operators";
|
||||
mode = "0440";
|
||||
content = lib.generators.toKeyValue {} {
|
||||
DOMAIN = "roadtotech.me";
|
||||
DOMAIN = config.homelab.domain;
|
||||
LLDAP_LDAP_BASE_DN = ldapBaseDn;
|
||||
DOCKER_API_VERSION = "1.40";
|
||||
DYNU_API_KEY = config.sops.placeholder."dynu/api_key";
|
||||
CF_DNS_API_TOKEN = config.sops.placeholder."cloudflare/dns_api_token";
|
||||
ACME_EMAIL = config.sops.placeholder."traefik/acme_email";
|
||||
AUTHELIA_SESSION_SECRET = config.sops.placeholder."authelia/session_secret";
|
||||
AUTHELIA_STORAGE_ENCRYPTION_KEY = config.sops.placeholder."authelia/storage_encryption_key";
|
||||
@@ -53,7 +172,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";
|
||||
};
|
||||
@@ -62,6 +181,79 @@
|
||||
# Declarative Dynamic GitOps Webhook Service (Internal Port 9000)
|
||||
systemd.services.homelab-gitops = {
|
||||
description = "Dynamic Homelab GitOps Webhook Dispatcher";
|
||||
after = [ "network-online.target" "docker.service" "homelab-appctl.service" ];
|
||||
wants = [ "network-online.target" "homelab-appctl.service" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
|
||||
path = with pkgs; [
|
||||
git
|
||||
docker
|
||||
docker-compose
|
||||
(python3.withPackages (ps: with ps; [ pyyaml pydantic ]))
|
||||
coreutils
|
||||
bash
|
||||
openssh
|
||||
];
|
||||
|
||||
environment = {
|
||||
GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path;
|
||||
GITOPS_APPCTL_TOKEN_FILE = config.sops.secrets."gitops/appctl_token".path;
|
||||
DOCKER_CONFIG = "/home/${config.homelab.operatorUser}/.local/state/homelab/docker";
|
||||
HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab";
|
||||
WORKLOADS_DIR = config.homelab.sitesDir;
|
||||
SITES_DIR = config.homelab.sitesDir;
|
||||
HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.sitesDir}/deployments.yaml";
|
||||
HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";
|
||||
};
|
||||
|
||||
serviceConfig = {
|
||||
Type = "simple";
|
||||
User = config.homelab.operatorUser;
|
||||
SupplementaryGroups = [ "docker" "homelab-operators" ];
|
||||
WorkingDirectory = config.homelab.coreDir;
|
||||
ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [
|
||||
{
|
||||
id = "deploy";
|
||||
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 = config.homelab.coreDir;
|
||||
response-message = "Deployment payload dispatched successfully.";
|
||||
}
|
||||
])} -port 9000 -verbose";
|
||||
Restart = "on-failure";
|
||||
RestartSec = "5s";
|
||||
|
||||
# Privilege separation & Systemd sandboxing
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = "read-only";
|
||||
ProtectKernelTunables = true;
|
||||
ProtectControlGroups = true;
|
||||
ReadWritePaths = [
|
||||
config.homelab.sitesDir
|
||||
"/home/${config.homelab.operatorUser}/.local/state/homelab"
|
||||
"-/run/homelab"
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
# Declarative Users and Groups for Control Plane Service Identity
|
||||
users.groups.homelab-operators.members = [ config.homelab.operatorUser ];
|
||||
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" ];
|
||||
@@ -77,32 +269,41 @@
|
||||
];
|
||||
|
||||
environment = {
|
||||
GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path;
|
||||
DOCKER_CONFIG = "/home/kiskaadee/.local/state/homelab/docker";
|
||||
HOME = "/var/lib/homelab/appctl";
|
||||
DOCKER_CONFIG = "/var/lib/homelab/appctl/.docker";
|
||||
HOMELAB_DOMAIN = config.homelab.domain;
|
||||
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 = config.sops.secrets."appctl/tokens_json".path;
|
||||
WORKLOADS_DIR = config.homelab.sitesDir;
|
||||
SITES_DIR = config.homelab.sitesDir;
|
||||
CORE_DIR = config.homelab.coreDir;
|
||||
HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab";
|
||||
HOMELAB_CONFIG_DIR = "/home/${config.homelab.operatorUser}/.config/homelab";
|
||||
HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.sitesDir}/deployments.yaml";
|
||||
HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";
|
||||
};
|
||||
|
||||
serviceConfig = {
|
||||
Type = "simple";
|
||||
User = "kiskaadee";
|
||||
User = "homelab-appctl";
|
||||
Group = "homelab-operators";
|
||||
SupplementaryGroups = [ "docker" ];
|
||||
WorkingDirectory = "/home/kiskaadee/Core";
|
||||
ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [
|
||||
{
|
||||
id = "deploy";
|
||||
execute-command = "/home/kiskaadee/Core/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";
|
||||
response-message = "Deployment payload dispatched successfully.";
|
||||
}
|
||||
])} -port 9000 -verbose";
|
||||
Restart = "on-failure";
|
||||
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";
|
||||
|
||||
# Privilege separation & Systemd sandboxing
|
||||
RuntimeDirectory = "homelab";
|
||||
RuntimeDirectoryMode = "0750";
|
||||
StateDirectory = "homelab/appctl";
|
||||
StateDirectoryMode = "0700";
|
||||
LogsDirectory = "homelab/appctl";
|
||||
LogsDirectoryMode = "0700";
|
||||
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectSystem = "strict";
|
||||
@@ -110,21 +311,36 @@
|
||||
ProtectKernelTunables = true;
|
||||
ProtectControlGroups = true;
|
||||
ReadWritePaths = [
|
||||
"/home/kiskaadee/Sites"
|
||||
"/home/kiskaadee/.local/state/homelab"
|
||||
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 -"
|
||||
"a+ ${config.homelab.coreDir}/config/authelia - - - - d:u:1000:rwX,u:1000:rwx,m::rwx"
|
||||
"a+ ${config.homelab.coreDir}/config/authelia/db.sqlite3 - - - - u:1000:rw,m::rw"
|
||||
"a+ ${config.homelab.coreDir}/config/authelia/emails.txt - - - - u:1000:rw,m::rw"
|
||||
"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 -"
|
||||
"d /home/${config.homelab.operatorUser}/var/lib/homelab 0755 ${config.homelab.operatorUser} users -"
|
||||
# POSIX ACLs granting homelab-appctl and homelab-operators traverse & access (explicit mask m:: required on 0700 home dirs)
|
||||
"a+ /home/${config.homelab.operatorUser} - - - - u:homelab-appctl:x,g:homelab-operators:x,m::rx"
|
||||
"a+ ${config.homelab.coreDir} - - - - u:homelab-appctl:x,g:homelab-operators:x,m::rx"
|
||||
"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 ];
|
||||
};
|
||||
}
|
||||
@@ -3,9 +3,12 @@
|
||||
# This replaces the laptop-inherited ~/.bashrc with a clean, server-appropriate profile.
|
||||
# Delivered via /etc/bashrc — no Home Manager required.
|
||||
|
||||
{ pkgs, ... }:
|
||||
{ config, pkgs, ... }:
|
||||
|
||||
{
|
||||
sops.secrets."system/pdf_decrypt_password" = {
|
||||
owner = config.homelab.operatorUser;
|
||||
};
|
||||
# ── Shell-integrated programs ─────────────────────────────────────────────────
|
||||
# These handle both installation and bash hook injection automatically
|
||||
programs.zoxide.enable = true; # smart cd with bash init wired into /etc/bashrc
|
||||
@@ -62,8 +65,8 @@
|
||||
reload = "exec bash";
|
||||
pgoog = "ping google.com -c 3";
|
||||
wifi = "nmtui";
|
||||
# NixOS rebuild targeting this flake
|
||||
nix-switch = "sudo nixos-rebuild switch --flake ~/Core#server";
|
||||
# NixOS rebuild targeting this flake (path scheme + impure required for instance.nix)
|
||||
nix-switch = "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure";
|
||||
};
|
||||
|
||||
interactiveShellInit = ''
|
||||
|
||||
@@ -15,31 +15,33 @@
|
||||
"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;
|
||||
group = "homelab-operators";
|
||||
mode = "0440";
|
||||
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 +50,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 +62,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 +70,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";
|
||||
|
||||
Executable
+92
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env bash
|
||||
# Read-only ForceCommand allowlist wrapper for the `agents` SSH user.
|
||||
set -euo pipefail
|
||||
|
||||
export CORE_DIR="${CORE_DIR:-/home/operator/Core}"
|
||||
export WORKLOADS_DIR="${WORKLOADS_DIR:-/home/operator/Workloads}"
|
||||
export DOCKER_HOST="${DOCKER_HOST:-tcp://127.0.0.1:2375}"
|
||||
|
||||
raw_cmd="${SSH_ORIGINAL_COMMAND:-}"
|
||||
|
||||
if [[ -z "${raw_cmd// }" ]]; then
|
||||
echo "Error: empty SSH_ORIGINAL_COMMAND is not permitted" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "$raw_cmd" == *$'\n'* || "$raw_cmd" == *$'\r'* ]]; then
|
||||
echo "Error: control characters are not permitted" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "$raw_cmd" == *[';&|`$()<>\\'\''"']* ]]; then
|
||||
echo "Error: shell metacharacters are not permitted" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Word-split without globbing or shell evaluation
|
||||
set -f
|
||||
read -r -a args <<< "$raw_cmd"
|
||||
set +f
|
||||
|
||||
if [[ ${#args[@]} -eq 0 ]]; then
|
||||
echo "Error: empty SSH_ORIGINAL_COMMAND is not permitted" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cmd="${args[0]}"
|
||||
|
||||
case "$cmd" in
|
||||
docker)
|
||||
if [[ ${#args[@]} -lt 2 ]]; then
|
||||
echo "Error: docker subcommand is required" >&2
|
||||
exit 1
|
||||
fi
|
||||
subcmd="${args[1]}"
|
||||
case "$subcmd" in
|
||||
ps|logs|inspect) ;;
|
||||
*)
|
||||
echo "Error: docker subcommand '$subcmd' is not permitted" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
for arg in "${args[@]:2}"; do
|
||||
case "$arg" in
|
||||
-H|-H=*|--host|--host=*|--context|--context=*|-c|-c=*|--config|--config=*)
|
||||
echo "Error: docker connection override flag '$arg' is not permitted" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
exec docker "${args[@]:1}"
|
||||
;;
|
||||
journalctl)
|
||||
for arg in "${args[@]:1}"; do
|
||||
case "$arg" in
|
||||
--flush|--rotate|--vacuum-*|--relinquish-var|--sync|--setup-keys|--update-catalog)
|
||||
echo "Error: mutating journalctl flag '$arg' is not permitted" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
exec journalctl "${args[@]:1}"
|
||||
;;
|
||||
appctl)
|
||||
if [[ ${#args[@]} -lt 2 ]]; then
|
||||
echo "Error: appctl subcommand is required" >&2
|
||||
exit 1
|
||||
fi
|
||||
subcmd="${args[1]}"
|
||||
case "$subcmd" in
|
||||
list|status|info|logs|ssl|health|resolve) ;;
|
||||
*)
|
||||
echo "Error: appctl subcommand '$subcmd' is not permitted" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
exec appctl "${args[@]:1}"
|
||||
;;
|
||||
*)
|
||||
echo "Error: command '$cmd' is not permitted" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -1,12 +0,0 @@
|
||||
# General configuration
|
||||
syslog=no
|
||||
pid=/run/ddclient/ddclient.pid
|
||||
cache=/var/lib/ddclient/ddclient.cache
|
||||
usev4=webv4
|
||||
|
||||
# Provider definition using credentials decrypted at runtime
|
||||
protocol=dyndns2
|
||||
server=api.dynu.com
|
||||
login=@dynu_user@
|
||||
password=@dynu_password@
|
||||
@dynu_domain@
|
||||
@@ -1,204 +0,0 @@
|
||||
"""
|
||||
Dynu DDNS Smart IP Change Monitor and Updater.
|
||||
|
||||
This script determines the current public IPv4 address by querying multiple
|
||||
external resolvers sequentially. It compares the discovered IP against the last
|
||||
recorded successful IP in a local history log. If a change is detected, it
|
||||
triggers the `ddclient.service` on-demand to perform the DNS record update.
|
||||
|
||||
This local-first state verification prevents making redundant API requests to
|
||||
the DNS provider, avoiding rate-limiting, IP bans, or API abuse flags.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import UTC, datetime
|
||||
|
||||
# History file location storing the transition log of public IP states.
|
||||
# Defaults to a state directory managed securely by the systemd service unit.
|
||||
HISTORY_FILE = os.environ.get("HISTORY_FILE", "/var/lib/dynu/ip_history.jsonl")
|
||||
|
||||
# Fallback sequence of external services to discover the public WAN IP.
|
||||
PROVIDERS = [
|
||||
"https://api.ipify.org",
|
||||
"https://ifconfig.me/ip",
|
||||
"https://icanhazip.com",
|
||||
"https://wtfismyip.com/text"
|
||||
]
|
||||
|
||||
|
||||
def is_valid_public_ipv4(ip):
|
||||
"""
|
||||
Validates that a string is a properly formatted public IPv4 address.
|
||||
|
||||
This function excludes standard private, loopback, link-local, and CGNAT
|
||||
blocks to avoid recording temporary, local, or invalid network states.
|
||||
"""
|
||||
match = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
|
||||
if not match:
|
||||
return False
|
||||
octets = [int(x) for x in match.groups()]
|
||||
if any(x > 255 for x in octets):
|
||||
return False
|
||||
a, b, _c, _d = octets
|
||||
|
||||
# RFC 1918 Private ranges: 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12
|
||||
if a == 10:
|
||||
return False
|
||||
if a == 192 and b == 168:
|
||||
return False
|
||||
if a == 172 and 16 <= b <= 31:
|
||||
return False
|
||||
|
||||
# Carrier-Grade NAT (CGNAT) RFC 6598: 100.64.0.0/10
|
||||
if a == 100 and 64 <= b <= 127:
|
||||
return False
|
||||
|
||||
# Loopback address range: 127.0.0.0/8
|
||||
if a == 127:
|
||||
return False
|
||||
|
||||
# Link-local addresses: 169.254.0.0/16
|
||||
return not (a == 169 and b == 254)
|
||||
|
||||
|
||||
def get_public_ip():
|
||||
"""
|
||||
Queries public IP providers until a valid public IPv4 is returned.
|
||||
|
||||
Returns:
|
||||
str: The validated public IP string, or None if all providers fail.
|
||||
"""
|
||||
errors = []
|
||||
for provider in PROVIDERS:
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
provider,
|
||||
headers={
|
||||
'User-Agent': 'Mozilla/5.0 (NixOS WAN Monitor)'
|
||||
}
|
||||
)
|
||||
# Fetch with 5s timeout to avoid hanging the systemd service
|
||||
with urllib.request.urlopen(req, timeout=5) as response:
|
||||
ip = response.read().decode('utf-8').strip()
|
||||
if is_valid_public_ipv4(ip):
|
||||
return ip
|
||||
else:
|
||||
errors.append(f"{provider}: invalid public IPv4 '{ip}'")
|
||||
except (urllib.error.URLError, OSError, ValueError) as e:
|
||||
errors.append(f"{provider}: {e!s}")
|
||||
|
||||
print(
|
||||
f"Error: All IP discovery providers failed. Details: {errors}",
|
||||
file=sys.stderr
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def get_last_recorded_ip():
|
||||
"""
|
||||
Reads the history log to locate the last successful IP address.
|
||||
|
||||
Returns:
|
||||
str: The last successfully updated IP, or None if no log exists yet.
|
||||
"""
|
||||
if not os.path.exists(HISTORY_FILE):
|
||||
return None
|
||||
try:
|
||||
with open(HISTORY_FILE, "r") as f:
|
||||
lines = f.readlines()
|
||||
if not lines:
|
||||
return None
|
||||
# Search backwards to find the most recent successful transition
|
||||
for line in reversed(lines):
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
if entry.get("status") == "success":
|
||||
return entry.get("ip")
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
except OSError as e:
|
||||
print(f"Warning: Failed to read history file: {e}", file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def record_ip(ip, status, details=None):
|
||||
"""
|
||||
Appends a new event entry into the JSONLines history registry.
|
||||
"""
|
||||
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
|
||||
entry = {
|
||||
"timestamp": datetime.now(tz=UTC).isoformat(),
|
||||
"ip": ip,
|
||||
"status": status
|
||||
}
|
||||
if details:
|
||||
entry["details"] = details
|
||||
try:
|
||||
with open(HISTORY_FILE, "a") as f:
|
||||
f.write(json.dumps(entry) + "\n")
|
||||
except OSError as e:
|
||||
print(f"Error: Failed to write to history file: {e}", file=sys.stderr)
|
||||
|
||||
|
||||
def trigger_ddclient():
|
||||
"""
|
||||
Invokes the systemd service unit for `ddclient` on-demand.
|
||||
|
||||
Returns:
|
||||
tuple: (bool, str) representing (success_boolean, error_details_string)
|
||||
"""
|
||||
try:
|
||||
# Run ddclient as a one-shot activation via systemd to perform API call
|
||||
res = subprocess.run(
|
||||
["systemctl", "start", "ddclient.service"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if res.returncode == 0:
|
||||
return True, None
|
||||
else:
|
||||
err_msg = (
|
||||
f"systemctl exited with {res.returncode}: "
|
||||
f"{res.stderr.strip()}"
|
||||
)
|
||||
return False, err_msg
|
||||
except (OSError, subprocess.SubprocessError) as e:
|
||||
return False, str(e)
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
Orchestrator logic for DDNS state management.
|
||||
"""
|
||||
current_ip = get_public_ip()
|
||||
if not current_ip:
|
||||
sys.exit(1)
|
||||
|
||||
last_ip = get_last_recorded_ip()
|
||||
if current_ip == last_ip:
|
||||
# IP matches last recorded working IP; do nothing to conserve quota
|
||||
sys.exit(0)
|
||||
|
||||
print(f"IP rotation detected! Old: {last_ip}, New: {current_ip}")
|
||||
|
||||
# Trigger ddclient to perform the DNS record update
|
||||
success, error_msg = trigger_ddclient()
|
||||
if success:
|
||||
print("Dynu DDNS update via ddclient triggered successfully.")
|
||||
record_ip(current_ip, "success")
|
||||
else:
|
||||
err_msg = f"Error: Failed to trigger ddclient update: {error_msg}"
|
||||
print(err_msg, file=sys.stderr)
|
||||
record_ip(current_ip, "failed_update", details=error_msg)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+10
-2
@@ -30,6 +30,7 @@ system:
|
||||
pdf_decrypt_password: ENC[AES256_GCM,data:n3XTANd+PbejUw==,iv:y2VIabyv/DfTgztbjS6M/xIfRNKOL+U+r3eXsal32OQ=,tag:oFpXg2E9dDM5dwkjSZkLgw==,type:str]
|
||||
gitops:
|
||||
webhook_secret: ENC[AES256_GCM,data:Kj3d0Repa3OOvjCkW6+kakQEfsCdpdVJQd71Am6zQHBt7QkLtxlnovUmmS+zJ+jChQBbCc9/7LunFvFT2pL36w==,iv:qh1pEIVtvB/fxbMv+a9pworhbXsIpfF5gKWS22Zn0GU=,tag:D4RNXkWhg9l3BJFp7MMloA==,type:str]
|
||||
appctl_token: ENC[AES256_GCM,data:+2BK6LejtvIj68+88zrjzgod8tXXVSRH+WpmIIHCbGU7aKbdTK20JlIIKb2u+2w/fHVrTwxUkX+dp5/AHsU+ZvVWh7tUsEo=,iv:tX5+bTfFFil46o7ZXa3dLIQH5+ET2e+75qRvjSJrhwU=,tag:mVGkDADx8RqaSi3AnDyPEw==,type:str]
|
||||
lldap:
|
||||
jwt_secret: ENC[AES256_GCM,data:RHtVgZJzNK7PFFvYO4jSsv+3928PYG2RdajG3ETEfN5eh0FwAmqcC98X2scT8H2JAeDV+bRI6QMZ3FoNRNcOHw==,iv:YGYImZJQzf1ONkc9lq2bEV/eWKIPfTyH+2hKzObaY08=,tag:jcUYKHrYSPYvHjQ86hLl0g==,type:str]
|
||||
key_seed: ENC[AES256_GCM,data:8Jf/xyMMXQFYxSO9RezTQRcS+Amm9hYOf97K03H/8cI=,iv:D5BJ4I12cMp2HAdCJC8MD/LnrBskbX7X/a6TnyisuMk=,tag:fhxge0iBSPllyrGQfCkw7w==,type:str]
|
||||
@@ -37,6 +38,13 @@ lldap:
|
||||
brevo:
|
||||
smtp_login: ENC[AES256_GCM,data:zfqKsAtoAOWCrSqx38sknwcJZT2m8W2J,iv:tMwTNDf+2CE3/8rKqWTWLl5Zp4LUVNSFV90QN94VXxo=,tag:XYXz9w3oIa0qkcfjCcgcYg==,type:str]
|
||||
smtp_key: ENC[AES256_GCM,data:YulXyaVF/sLWE9x12yxdBAj9KMbfP/CK/7FS3XkYO8sCj3GWgPbNoSaUT/9quLWHPtCsBxxdLeLoDNa1jE2WRyHP1W+Ioyyx5sAzdzevzHIBmfP+fdw0rKhe,iv:QT0HfzNPsTqXlN3IC/+bBzJfUzN9YkXYiv/3uqkXHBw=,tag:vBetkZPDYoh0Yy3BpMT9BQ==,type:str]
|
||||
cloudflare:
|
||||
account_name: ENC[AES256_GCM,data:fIuzvJbLoz/w,iv:tT3rCldA9hqHzKjJa4gENTk/XprzS5X6Wm/rqkb6jow=,tag:p0aEezfUFlJn25PdW/DAOA==,type:str]
|
||||
global_api_key: ENC[AES256_GCM,data:IDFHetxM2LE1/cytHo2Jn16piLeIvM27ui3Qld4Z5hwWauDRaY05nZH6+V6ic9dYFfagvA==,iv:9q3cosnJ+eC1BLmQ1Hx1y3Dksyc5k4UMQPZ6Or9vWFE=,tag:k/RilX02EJzMWZcfzBtu4A==,type:str]
|
||||
account_id: ENC[AES256_GCM,data:/IyUXySFGQSGs16Kv6yZajMiGTxwOuxILvcFZ/6YROo=,iv:TdMwtzs/LMnbhpsEbqunj4n+P+JxcscYGKaM42fYQ20=,tag:HHmIq03Jc4g8fBvuaWevAA==,type:str]
|
||||
dns_api_token: ENC[AES256_GCM,data:lTByYg0BM+mloaHDb2WkN7LY9twnVzKn6NO8W1rTH5FXyWaNlEovLxCPT2sG+JuRfqGJ52w=,iv:nBX3rUSdf1wFSTz0sY/ApNKVaYkCPJAJPhmMu+abzhE=,tag:LK8qyYap/T1HZb+jWnHyuA==,type:str]
|
||||
appctl:
|
||||
tokens_json: ENC[AES256_GCM,data:O2vsiMMcZjsduFSRen1MnnckdRYK45aPH40EhX42h1WUwf62Nm58PV5BQJOgJ97AH3hOH97mzg1tjL0C1oV/epXMaypRWY9AGLS00CfzD2sgdM5Wx7VKbfGggFnGqgd7veaCA+pxUC0uTk/Dq2Cz/uhXhLX1wVjafX0OAqS6fxO+L9Oza3+RBtKgx2xX0AKW+KSZQUM1nvNW8R/Eyvnqvw2OSb2FdKN1CKhlVWhCZiaxTe8617BqGhJDL9pu4lfn0m+tdIwvluI3h8cmKuT6dzd01Jxr0EHBY/+mZZ/WQoNhIy4QulFpKiMudiT+WGzUm+UT4mYBoGwzQCVV8MD7W1r84mkbCkLc/HpWG08TqK4tpAdtLgYK3Zslr1+lmboWyJ6WcinmxkhUexhj+gTyfXYmVSB3fF8PIeyQINGB3rLvmpZ7DDMzYa1ICgFbJ6zmYa54TXRDLGzLD09koeDp9FhXNKPvuwz2x4uwWDDUfU8wwTkGbw==,iv:FJpB+WZiE4PKUhIuwBWIB/TLtifwCzGRMtbMx7x6ly8=,tag:NZQXYFnVBqbOONl+Yh3tuA==,type:str]
|
||||
sops:
|
||||
age:
|
||||
- enc: |
|
||||
@@ -57,7 +65,7 @@ sops:
|
||||
yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A==
|
||||
-----END AGE ENCRYPTED FILE-----
|
||||
recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg
|
||||
lastmodified: "2026-09-25T00:49:38Z"
|
||||
mac: ENC[AES256_GCM,data:EyJ9V0aYo7isyqnW6HWBz4hD2X6xa+VRNg3TaK88gkX6YCG/H0htBfMf/VYl/hOA/eEZW+uMVys8Ocula9zpY1Pd1gUbWt5FrXQvooYNhtCFCFUAJdsrmif8Ru7AXazFbyhhaeBSBjSQURM0qi69XqllVvfmiSz32WlX/QIOZ/c=,iv:znmm8JuFKSFl2IGGhRG77SE9kqy3uFWUK8VjocJ18n4=,tag:tG000kt5a6W1fa0IEfvLLQ==,type:str]
|
||||
lastmodified: "2026-11-23T20:45:18Z"
|
||||
mac: ENC[AES256_GCM,data:3Rm8olJtCErH+KGisvQENqwFhMF3Y9acXjrBHC7ot3ThRzT8Yo3X1RyxKXzyYzB6Yy2G3ua9yUtgQjydXgjQR1b6KY6ERmyu6H2S1IF/Ps4grYVZ6xEhJMDtjNKDvhtjhRM61eFByeYzJeHWD6K8dsxDcWUI2GKRRH7U8iG95Fo=,iv:/IY6iKamEEoi5vVLRGOmmPpyJte3amLfjVhYIDbMdBE=,tag:gT3RSrnwl0TH14LJvbiPlg==,type:str]
|
||||
unencrypted_suffix: _unencrypted
|
||||
version: 3.13.3
|
||||
@@ -14,3 +14,11 @@ extraPaths = ["scripts"]
|
||||
venvPath = "."
|
||||
venv = ".venv"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
# Automatically adds app modules and script hooks to the sys.venvPath
|
||||
pythonpath = [
|
||||
".",
|
||||
"scripts"
|
||||
]
|
||||
|
||||
|
||||
+35
-290
@@ -1,174 +1,26 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# appctl - Unified, Manifest-Driven Container Orchestrator
|
||||
# Discovers individual application repositories located in ~/Sites/*/
|
||||
# Injects global homelab secrets, per-app metadata from app.yaml, and monitors Git sync
|
||||
# Thin CLI wrapper delegating operational commands to homelab-appctl.service over UDS
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ENGINE="$SCRIPT_DIR/appctl_engine.py"
|
||||
PYTHON_BIN="${PYTHON_BIN:-python3}"
|
||||
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"
|
||||
if [ -z "$PYTHON_BIN" ]; then
|
||||
if [ -x "$SCRIPT_DIR/../.venv/bin/python3" ]; then
|
||||
PYTHON_BIN="$SCRIPT_DIR/../.venv/bin/python3"
|
||||
else
|
||||
PYTHON_BIN="python3"
|
||||
fi
|
||||
export SITES_DIR="${SITES_DIR:-$HOME/Sites}"
|
||||
export CORE_DIR="${CORE_DIR:-$HOME/Core}"
|
||||
export ENV_FILE
|
||||
|
||||
# Source global secrets/environment if available
|
||||
HOMESERVER_ENV="/run/secrets/rendered/homeserver.env"
|
||||
if [ ! -f "$HOMESERVER_ENV" ] && [ -f "/run/secrets/homeserver.env" ]; then
|
||||
HOMESERVER_ENV="/run/secrets/homeserver.env"
|
||||
fi
|
||||
if [ -f "$HOMESERVER_ENV" ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1090
|
||||
source "$HOMESERVER_ENV"
|
||||
set +a
|
||||
fi
|
||||
SOCKET_PATH="${APPCTL_SOCKET_PATH:-/run/homelab/appctl.sock}"
|
||||
CLI_CLIENT="$SCRIPT_DIR/appctl_cli.py"
|
||||
|
||||
if [ -f "$ENV_FILE" ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1090
|
||||
source "$ENV_FILE"
|
||||
set +a
|
||||
fi
|
||||
|
||||
# Lock the homelab root domain before setup_app_env can mutate $DOMAIN
|
||||
# Canonical precedence: HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN
|
||||
export HOMELAB_DOMAIN="${HOMELAB_DOMAIN:-${DOMAIN_SUFFIX:-${DOMAIN:-}}}"
|
||||
|
||||
# Show help usage
|
||||
show_help() {
|
||||
echo "🚀 appctl - Homelab Container Orchestrator"
|
||||
echo ""
|
||||
echo "Usage: appctl <command> [service] [options...]"
|
||||
echo ""
|
||||
echo "Commands:"
|
||||
echo " list, status [--fetch] [--core] [--ssl] List all applications with Git sync & container status"
|
||||
echo " ssl [service] Inspect SSL/TLS certificates across homelab domains"
|
||||
echo " info <service> [--ssl] Display comprehensive application & Git diagnostics"
|
||||
echo " up <service|core> Start/build a service stack or Core component"
|
||||
echo " down <service|core> Stop and remove a service stack or Core component"
|
||||
echo " restart <service|core> Restart a service stack, Core component, or entire Core"
|
||||
echo " update <service> Full stack update (git pull -> compose pull -> recreate)"
|
||||
echo " pull <service|core> Pull latest images and recreate service or Core component"
|
||||
echo " logs <service|core> Stream service or Core component logs"
|
||||
echo " config <service|core> Validate and view resolved compose configuration"
|
||||
echo " sync Synchronize Homepage dashboard services.yaml from app.yaml"
|
||||
echo " completion [bash] Output shell autocompletion script"
|
||||
}
|
||||
|
||||
# Setup application environment based on resolved metadata
|
||||
setup_app_env() {
|
||||
local query="$1"
|
||||
local resolved_json
|
||||
resolved_json=$("$PYTHON_BIN" "$ENGINE" resolve "$query" || true)
|
||||
|
||||
if [ -z "$resolved_json" ]; then
|
||||
echo "❌ Error: Service '$query' not found under $SITES_DIR or Core"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Extract fields via python json
|
||||
TARGET_TYPE=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('type', 'app'))" "$resolved_json")
|
||||
APP_DIR=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['dir_path'])" "$resolved_json")
|
||||
CANONICAL_NAME=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['name'])" "$resolved_json")
|
||||
TARGET_CONTAINER=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('container', ''))" "$resolved_json")
|
||||
|
||||
if [ "$TARGET_TYPE" = "core" ] || [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
if [ ! -d "$CORE_DIR" ]; then
|
||||
echo "❌ Error: Core directory not found at $CORE_DIR"
|
||||
exit 1
|
||||
fi
|
||||
CORE_ENV_FILE="/run/secrets/rendered/homeserver.env"
|
||||
if [ ! -f "$CORE_ENV_FILE" ] && [ -f "/run/secrets/homeserver.env" ]; then
|
||||
CORE_ENV_FILE="/run/secrets/homeserver.env"
|
||||
fi
|
||||
COMPOSE_ENV_ARG=()
|
||||
if [ -f "$CORE_ENV_FILE" ]; then
|
||||
COMPOSE_ENV_ARG=(--env-file "$CORE_ENV_FILE")
|
||||
fi
|
||||
return
|
||||
fi
|
||||
|
||||
RESOLVED_DOMAIN=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['domain'])" "$resolved_json")
|
||||
|
||||
# 1. Base infrastructure defaults
|
||||
export PROXY_NETWORK="${PROXY_NETWORK:-proxy-net}"
|
||||
export NETWORK_NAME="${NETWORK_NAME:-$PROXY_NETWORK}"
|
||||
export CERT_RESOLVER="${CERT_RESOLVER:-myresolver}"
|
||||
export DOMAIN_SUFFIX="${DOMAIN_SUFFIX:-$HOMELAB_DOMAIN}"
|
||||
|
||||
# 2. Canonical application identity
|
||||
export SERVICE_NAME="$CANONICAL_NAME"
|
||||
export CONTAINER_NAME="$CANONICAL_NAME"
|
||||
export SERVICE_DOMAIN="$RESOLVED_DOMAIN"
|
||||
export DOMAIN="$RESOLVED_DOMAIN"
|
||||
|
||||
# 3. Dynamic environment variables from app.yaml (e.g. PROJECT_PATH, MEDIA_PATH, etc.)
|
||||
while IFS= read -r -d '' k && IFS= read -r -d '' v; do
|
||||
export "$k=$v"
|
||||
done < <("$PYTHON_BIN" -c "
|
||||
import json, re, sys
|
||||
RESERVED = {'PATH', 'LD_PRELOAD', 'IFS', 'SHELL', 'USER', 'CORE_DIR', 'SITES_DIR', 'ENV_FILE', 'HOMESERVER_ENV'}
|
||||
d = json.loads(sys.argv[1])
|
||||
env_dict = d.get('env', {})
|
||||
if isinstance(env_dict, dict):
|
||||
for k, v in env_dict.items():
|
||||
k_str = str(k).strip()
|
||||
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', k_str) or k_str in RESERVED:
|
||||
continue
|
||||
if v is not None and v != '':
|
||||
sys.stdout.buffer.write(k_str.encode('utf-8') + b'\0' + str(v).encode('utf-8') + b'\0')
|
||||
" "$resolved_json")
|
||||
|
||||
# 4. Source local .env if present
|
||||
if [ -f "$APP_DIR/.env" ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1090
|
||||
source "$APP_DIR/.env"
|
||||
set +a
|
||||
fi
|
||||
|
||||
# 5. Source local app.env if present
|
||||
if [ -f "$APP_DIR/app.env" ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1090
|
||||
source "$APP_DIR/app.env"
|
||||
set +a
|
||||
fi
|
||||
}
|
||||
|
||||
if [ $# -lt 1 ]; then
|
||||
show_help
|
||||
exit 1
|
||||
fi
|
||||
|
||||
COMMAND=$1
|
||||
APP=$2
|
||||
|
||||
case "$COMMAND" in
|
||||
list|status)
|
||||
"$PYTHON_BIN" "$ENGINE" list "${@:2}"
|
||||
;;
|
||||
ssl)
|
||||
"$PYTHON_BIN" "$ENGINE" ssl "${@:2}"
|
||||
;;
|
||||
info)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
"$PYTHON_BIN" "$ENGINE" info "${@:2}"
|
||||
;;
|
||||
sync)
|
||||
"$PYTHON_BIN" "$ENGINE" sync "${@:2}"
|
||||
;;
|
||||
# Fast-path local shell completion helpers
|
||||
case "${1:-}" in
|
||||
complete)
|
||||
"$PYTHON_BIN" "$ENGINE" complete "${@:2}"
|
||||
;;
|
||||
resolve)
|
||||
"$PYTHON_BIN" "$ENGINE" resolve "${@:2}"
|
||||
exec "$PYTHON_BIN" "$ENGINE" complete "${@:2}"
|
||||
;;
|
||||
completion)
|
||||
cat <<'EOF'
|
||||
@@ -184,7 +36,7 @@ _appctl_completions() {
|
||||
cword=$COMP_CWORD
|
||||
fi
|
||||
|
||||
local commands="list status ssl info up down restart update pull logs config sync completion"
|
||||
local commands="list status ssl info up down restart update pull logs config sync health resolve completion"
|
||||
|
||||
if [ "$cword" -eq 1 ]; then
|
||||
COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
|
||||
@@ -218,7 +70,25 @@ _appctl_completions() {
|
||||
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
|
||||
fi
|
||||
;;
|
||||
up|down|restart|update|pull|logs|config)
|
||||
up|deploy)
|
||||
if [[ "$cur" == -* ]]; then
|
||||
COMPREPLY=( $(compgen -W "--build --no-cache" -- "$cur") )
|
||||
else
|
||||
local services
|
||||
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
|
||||
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
|
||||
fi
|
||||
;;
|
||||
update)
|
||||
if [[ "$cur" == -* ]]; then
|
||||
COMPREPLY=( $(compgen -W "--branch --build --no-cache" -- "$cur") )
|
||||
else
|
||||
local services
|
||||
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
|
||||
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
|
||||
fi
|
||||
;;
|
||||
down|restart|pull|logs|config)
|
||||
local services
|
||||
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
|
||||
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
|
||||
@@ -230,138 +100,13 @@ _appctl_completions() {
|
||||
}
|
||||
complete -F _appctl_completions appctl
|
||||
EOF
|
||||
;;
|
||||
up)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ]; then
|
||||
echo "🚀 Starting Core stack ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "${@:3}"
|
||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
echo "🚀 Starting Core service: $TARGET_CONTAINER ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "$TARGET_CONTAINER" "${@:3}"
|
||||
else
|
||||
echo "🚀 Starting $CANONICAL_NAME ($APP_DIR)..."
|
||||
cd "$APP_DIR" && docker compose up -d --remove-orphans "${@:3}"
|
||||
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
|
||||
fi
|
||||
;;
|
||||
down)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ]; then
|
||||
echo "🛑 Stopping Core stack ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" down "${@:3}"
|
||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
echo "🛑 Stopping Core service: $TARGET_CONTAINER ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" stop "$TARGET_CONTAINER" "${@:3}"
|
||||
else
|
||||
echo "🛑 Stopping $CANONICAL_NAME ($APP_DIR)..."
|
||||
cd "$APP_DIR" && docker compose down "${@:3}"
|
||||
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
|
||||
fi
|
||||
;;
|
||||
restart)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ]; then
|
||||
if [ -n "$3" ] && [[ "$3" != -* ]]; then
|
||||
echo "🔄 Restarting Core service: $3 ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "$3" "${@:4}"
|
||||
else
|
||||
echo "🔄 Restarting Core stack ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "${@:3}"
|
||||
fi
|
||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
echo "🔄 Restarting Core service: $TARGET_CONTAINER ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "$TARGET_CONTAINER" "${@:3}"
|
||||
else
|
||||
echo "🔄 Restarting $CANONICAL_NAME ($APP_DIR)..."
|
||||
cd "$APP_DIR" && docker compose down && docker compose up -d "${@:3}"
|
||||
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
|
||||
fi
|
||||
;;
|
||||
update)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ]; then
|
||||
echo "🔄 Updating Core stack ($CORE_DIR)..."
|
||||
if [ -d "$CORE_DIR/.git" ]; then
|
||||
if [ -n "$(git -C "$CORE_DIR" status --porcelain)" ]; then
|
||||
echo "❌ Error: Cannot update. Working tree in $CORE_DIR has uncommitted changes."
|
||||
exit 1
|
||||
fi
|
||||
echo "📥 Pulling latest git changes for Core..."
|
||||
git -C "$CORE_DIR" pull --ff-only
|
||||
fi
|
||||
echo "🐳 Pulling latest Core container images..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull
|
||||
echo "🚀 Recreating Core container stack..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "${@:3}"
|
||||
echo "✨ Core successfully updated!"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "🔄 Updating $CANONICAL_NAME ($APP_DIR)..."
|
||||
if [ -d "$APP_DIR/.git" ]; then
|
||||
if [ -n "$(git -C "$APP_DIR" status --porcelain)" ]; then
|
||||
echo "❌ Error: Cannot update. Working tree in $APP_DIR has uncommitted changes."
|
||||
echo "Commit or stash your changes before updating."
|
||||
exit 1
|
||||
fi
|
||||
echo "📥 Pulling latest git changes..."
|
||||
git -C "$APP_DIR" pull --ff-only
|
||||
fi
|
||||
|
||||
echo "🐳 Pulling latest container images..."
|
||||
cd "$APP_DIR" && docker compose pull
|
||||
|
||||
echo "🚀 Recreating container stack..."
|
||||
cd "$APP_DIR" && docker compose up -d --remove-orphans "${@:3}"
|
||||
|
||||
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
|
||||
echo "✨ $CANONICAL_NAME successfully updated!"
|
||||
;;
|
||||
pull)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ]; then
|
||||
echo "📥 Pulling latest images for Core stack..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull "${@:3}"
|
||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
echo "📥 Pulling latest image for Core service: $TARGET_CONTAINER..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull "$TARGET_CONTAINER" "${@:3}"
|
||||
else
|
||||
echo "📥 Pulling latest images for $CANONICAL_NAME..."
|
||||
cd "$APP_DIR" && docker compose pull && docker compose up -d --remove-orphans "${@:3}"
|
||||
fi
|
||||
;;
|
||||
logs)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ]; then
|
||||
if [ -n "$3" ] && [[ "$3" != -* ]]; then
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "$3" "${@:4}"
|
||||
else
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "${@:3}"
|
||||
fi
|
||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "$TARGET_CONTAINER" "${@:3}"
|
||||
else
|
||||
cd "$APP_DIR" && docker compose logs -f "${@:3}"
|
||||
fi
|
||||
;;
|
||||
config)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ] || [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" config "${@:3}"
|
||||
else
|
||||
cd "$APP_DIR" && docker compose config "${@:3}"
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
show_help
|
||||
if [ ! -S "$SOCKET_PATH" ]; then
|
||||
echo "❌ Error: appctl daemon socket not found at $SOCKET_PATH. Ensure homelab-appctl.service is running." >&2
|
||||
exit 1
|
||||
fi
|
||||
exec "$PYTHON_BIN" "$CLI_CLIENT" "$@"
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,406 @@
|
||||
"""
|
||||
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,398 @@
|
||||
"""
|
||||
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 ~/Workloads/deployments.yaml (or HOMELAB_DEPLOYMENTS_FILE / WORKLOADS_DIR override) 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(
|
||||
os.environ.get("WORKLOADS_DIR")
|
||||
or os.environ.get("SITES_DIR")
|
||||
or os.path.expanduser("~/Workloads")
|
||||
)
|
||||
/ "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.lower()):
|
||||
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 ~/Workloads/deployments.yaml
|
||||
(or HOMELAB_DEPLOYMENTS_FILE / WORKLOADS_DIR override).
|
||||
Fails closed (empty set) if registry is missing or malformed.
|
||||
"""
|
||||
if deployments_path is not None:
|
||||
reg_file = Path(deployments_path)
|
||||
elif env_deploy := os.environ.get("HOMELAB_DEPLOYMENTS_FILE"):
|
||||
reg_file = Path(env_deploy)
|
||||
elif env_workloads := (
|
||||
os.environ.get("WORKLOADS_DIR") or os.environ.get("SITES_DIR")
|
||||
):
|
||||
reg_file = Path(env_workloads) / "deployments.yaml"
|
||||
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.strip().lower() in CORE_TARGETS:
|
||||
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
+412
@@ -0,0 +1,412 @@
|
||||
#!/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_workload_table(workloads: list[dict[str, Any]]) -> str:
|
||||
"""Format a list of workload dictionaries into a human-readable tabular display."""
|
||||
if not workloads:
|
||||
return "ℹ️ No workloads found."
|
||||
|
||||
has_ssl = any("ssl" in w and isinstance(w["ssl"], dict) for w in workloads)
|
||||
lines: list[str] = []
|
||||
|
||||
if has_ssl:
|
||||
lines.append(
|
||||
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
|
||||
)
|
||||
lines.append(
|
||||
f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
|
||||
)
|
||||
else:
|
||||
lines.append(
|
||||
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN'}"
|
||||
)
|
||||
lines.append(
|
||||
f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------'}"
|
||||
)
|
||||
|
||||
for w in workloads:
|
||||
name = str(w.get("name") or "-")
|
||||
domain = str(w.get("domain") or "-")
|
||||
status = str(w.get("status") or "-")
|
||||
|
||||
if w.get("manifest_error"):
|
||||
dep = "⚠️ Manifest Error"
|
||||
prov = "⚠️ Invalid Manifest"
|
||||
elif "deployment_status" in w:
|
||||
dep = str(w["deployment_status"])
|
||||
prov = str(w.get("provenance_status") or "-")
|
||||
else:
|
||||
dep = "-"
|
||||
prov = str(w.get("provenance_status") or "-")
|
||||
|
||||
if has_ssl:
|
||||
ssl_info = w.get("ssl")
|
||||
cert_status = (
|
||||
str(ssl_info.get("status", "-"))
|
||||
if isinstance(ssl_info, dict)
|
||||
else "-"
|
||||
)
|
||||
lines.append(
|
||||
f"{name:<16} {dep:<22} {prov:<22} {status:<15} {domain:<28} {cert_status}"
|
||||
)
|
||||
else:
|
||||
lines.append(
|
||||
f"{name:<16} {dep:<22} {prov:<24} {status:<15} {domain}"
|
||||
)
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _format_workload_info(workload: dict[str, Any]) -> str:
|
||||
"""Format a single workload metadata dictionary for `appctl info`."""
|
||||
name = workload.get("name", "unknown")
|
||||
w_type = workload.get("type", workload.get("app_type", "app"))
|
||||
header = (
|
||||
f"ℹ️ Core Infrastructure Service: {name}"
|
||||
if w_type in ("core", "core_service")
|
||||
else f"ℹ️ Workload Overview: {name}"
|
||||
)
|
||||
lines = [
|
||||
header,
|
||||
"-" * 50,
|
||||
f"Directory: {workload.get('dir_path', '-')}",
|
||||
f"Domain: {workload.get('domain', '-')}",
|
||||
f"Type: {w_type}",
|
||||
f"Description: {workload.get('description', '-')}",
|
||||
]
|
||||
if workload.get("container"):
|
||||
lines.append(f"Container: {workload['container']}")
|
||||
aliases = workload.get("aliases")
|
||||
if isinstance(aliases, list) and aliases:
|
||||
lines.append(f"Aliases: {', '.join(str(a) for a in aliases)}")
|
||||
networks = workload.get("networks")
|
||||
if isinstance(networks, list) and networks:
|
||||
lines.append(f"Networks: {', '.join(str(n) for n in networks)}")
|
||||
if "auth" in workload:
|
||||
lines.append(f"Auth Protected: {workload['auth']}")
|
||||
if "visible" in workload:
|
||||
lines.append(f"Dashboard: {'Visible' if workload['visible'] else 'Hidden'}")
|
||||
source = workload.get("source")
|
||||
if isinstance(source, dict):
|
||||
lines.append(f"Source URL: {source.get('url', '-')}")
|
||||
lines.append(f"Target Ref: {source.get('ref', '-')}")
|
||||
if workload.get("manifest_error"):
|
||||
lines.append(f"\n⚠️ Manifest Validation Error:\n {workload['manifest_error']}")
|
||||
ssl_info = workload.get("ssl")
|
||||
if isinstance(ssl_info, dict):
|
||||
lines.append("\n🔒 SSL/TLS Certificate:")
|
||||
lines.append(f" Status: {ssl_info.get('status', '-')}")
|
||||
lines.append(f" Issuer: {ssl_info.get('issuer', '-')}")
|
||||
lines.append(f" Expiration: {ssl_info.get('formatted_expiry', '-')}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _format_ssl_info(ssl_info: dict[str, Any]) -> str:
|
||||
"""Format SSL certificate details for `appctl ssl`."""
|
||||
domain = ssl_info.get("domain", "-")
|
||||
lines = [
|
||||
f"🔒 SSL/TLS Certificate: {domain}",
|
||||
"-" * 50,
|
||||
f"Domain: {domain}",
|
||||
f"Status: {ssl_info.get('status', '-')}",
|
||||
f"Issuer: {ssl_info.get('issuer', '-')}",
|
||||
f"Subject: {ssl_info.get('subject', '-')}",
|
||||
f"Expiration: {ssl_info.get('not_after', '-')}",
|
||||
]
|
||||
if ssl_info.get("days_remaining") is not None:
|
||||
lines.append(
|
||||
f"Days Remaining: {ssl_info['days_remaining']} days ({ssl_info.get('formatted_expiry', '-')})"
|
||||
)
|
||||
if ssl_info.get("error"):
|
||||
lines.append(f"Details/Error: {ssl_info['error']}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
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 "workloads" in resp.result and isinstance(resp.result["workloads"], list):
|
||||
return _format_workload_table(resp.result["workloads"])
|
||||
if resp.operation == OperationType.WORKLOAD_RESOLVE and "workload" in resp.result:
|
||||
return json.dumps(resp.result["workload"])
|
||||
if "workload" in resp.result and isinstance(resp.result["workload"], dict):
|
||||
return _format_workload_info(resp.result["workload"])
|
||||
if "ssl" in resp.result and isinstance(resp.result["ssl"], dict):
|
||||
return _format_ssl_info(resp.result["ssl"])
|
||||
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", "-c", "--all", "-a", action="store_true", dest="core", help="Include core platform services")
|
||||
list_p.add_argument("--fetch", "-f", action="store_true", help="Fetch remote git revisions")
|
||||
list_p.add_argument("--ssl", "-s", 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", "-s", action="store_true", help="Check SSL certificate status")
|
||||
|
||||
# resolve
|
||||
resolve_p = subparsers.add_parser("resolve", parents=[common_parser], help="Resolve target metadata")
|
||||
resolve_p.add_argument("target", help="Workload or core target")
|
||||
|
||||
# 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")
|
||||
up_p.add_argument("--no-cache", action="store_true", help="Rebuild container images without cache")
|
||||
|
||||
# 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")
|
||||
update_p.add_argument("--build", action="store_true", help="Rebuild container images")
|
||||
update_p.add_argument("--no-cache", action="store_true", help="Rebuild container images without cache")
|
||||
|
||||
# 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 == "resolve":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_RESOLVE,
|
||||
target=parsed.target,
|
||||
)
|
||||
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"):
|
||||
build_flag = getattr(parsed, "build", False)
|
||||
no_cache_flag = getattr(parsed, "no_cache", False)
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_DEPLOY,
|
||||
target=parsed.target,
|
||||
parameters={
|
||||
"build": build_flag or no_cache_flag,
|
||||
"no_cache": no_cache_flag,
|
||||
},
|
||||
)
|
||||
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
|
||||
build_flag = getattr(parsed, "build", False)
|
||||
no_cache_flag = getattr(parsed, "no_cache", False)
|
||||
if build_flag or no_cache_flag:
|
||||
params["build"] = True
|
||||
if no_cache_flag:
|
||||
params["no_cache"] = True
|
||||
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,352 @@
|
||||
"""
|
||||
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, ignored_types=(dict,))
|
||||
|
||||
|
||||
|
||||
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 7-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_CAPABILITY_NOT_GRANTED = "ERR_CAPABILITY_NOT_GRANTED"
|
||||
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_CAPABILITY_NOT_GRANTED: 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
|
||||
no_cache: StrictBool = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def imply_build_from_no_cache(self) -> DeployParams:
|
||||
if self.no_cache:
|
||||
self.build = True
|
||||
return self
|
||||
|
||||
|
||||
class UpdateParams(StrictModel):
|
||||
"""Parameters for workload.update."""
|
||||
|
||||
expected_branch: Annotated[StrictStr, Field(min_length=1)] | None = None
|
||||
build: StrictBool = False
|
||||
no_cache: StrictBool = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def imply_build_from_no_cache(self) -> UpdateParams:
|
||||
if self.no_cache:
|
||||
self.build = True
|
||||
return self
|
||||
|
||||
|
||||
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,
|
||||
ignored_types=(dict,),
|
||||
)
|
||||
|
||||
|
||||
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[self.operation]
|
||||
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[self.operation]
|
||||
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
+604
@@ -0,0 +1,604 @@
|
||||
#!/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))
|
||||
WORKLOADS_DIR = Path(
|
||||
os.environ.get("WORKLOADS_DIR")
|
||||
or os.environ.get("SITES_DIR")
|
||||
or os.path.expanduser("~/Workloads")
|
||||
)
|
||||
SITES_DIR = WORKLOADS_DIR
|
||||
DEPLOYMENTS_FILE = Path(
|
||||
os.environ.get("HOMELAB_DEPLOYMENTS_FILE") or (WORKLOADS_DIR / "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
|
||||
try:
|
||||
resp = self.appctl_server.router.dispatch(
|
||||
request=req,
|
||||
principal=principal,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client_header,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Top-level unhandled exception during operation dispatch")
|
||||
self._send_operation_error(
|
||||
status_code=500,
|
||||
error=OperationError(
|
||||
code=ErrorCode.ERR_EXECUTION_FAILED,
|
||||
message=f"Internal daemon execution error: {exc}",
|
||||
),
|
||||
operation=req.operation,
|
||||
target=req.target,
|
||||
op_id=generate_operation_id(),
|
||||
)
|
||||
return
|
||||
|
||||
status_code = resp.error.code.http_status if (not resp.success and resp.error) else 200
|
||||
self._send_operation_response(status_code, resp)
|
||||
|
||||
|
||||
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: %s", 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()
|
||||
+186
-67
@@ -33,15 +33,23 @@ from provenance import (
|
||||
|
||||
# Dynamic Environment Paths
|
||||
CORE_DIR = os.environ.get(
|
||||
"CORE_DIR", os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
||||
"CORE_DIR",
|
||||
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
||||
)
|
||||
|
||||
SITES_DIR = os.environ.get(
|
||||
"SITES_DIR",
|
||||
os.path.join(os.path.dirname(CORE_DIR), "Sites")
|
||||
if os.path.isdir(os.path.join(os.path.dirname(CORE_DIR), "Sites"))
|
||||
else os.path.expanduser("~/Sites"),
|
||||
)
|
||||
def _resolve_default_workloads_dir() -> str:
|
||||
"""Resolve workloads root honoring WORKLOADS_DIR, SITES_DIR, sibling Workloads, or ~/Workloads."""
|
||||
env_dir = os.environ.get("WORKLOADS_DIR") or os.environ.get("SITES_DIR")
|
||||
if env_dir:
|
||||
return env_dir
|
||||
sibling_workloads = os.path.join(os.path.dirname(CORE_DIR), "Workloads")
|
||||
if os.path.isdir(sibling_workloads):
|
||||
return sibling_workloads
|
||||
return os.path.expanduser("~/Workloads")
|
||||
|
||||
|
||||
WORKLOADS_DIR = _resolve_default_workloads_dir()
|
||||
SITES_DIR = WORKLOADS_DIR
|
||||
|
||||
HOMELAB_DOMAIN = (
|
||||
os.environ.get("HOMELAB_DOMAIN")
|
||||
@@ -78,12 +86,19 @@ class App:
|
||||
name: str # Canonical identifier (e.g., "traefik", "jellyfin")
|
||||
description: str = "" # Human-readable summary for dashboards and CLI info
|
||||
domain: str = "" # Routing FQDN (e.g., "auth.example.com") or "internal".
|
||||
dir_path: str = "" # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
|
||||
dir_path: str = (
|
||||
"" # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
|
||||
)
|
||||
|
||||
@property
|
||||
def is_internal(self) -> bool:
|
||||
"""Returns True if the service does not expose a public TLS endpoint."""
|
||||
return not self.domain or self.domain == "internal" or self.domain.endswith(".local") or ":" in self.domain
|
||||
return (
|
||||
not self.domain
|
||||
or self.domain == "internal"
|
||||
or self.domain.endswith(".local")
|
||||
or ":" in self.domain
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Serialize for JSON consumption by scripts/appctl"""
|
||||
@@ -100,16 +115,24 @@ class CoreService(App):
|
||||
app_type: str = "core_service"
|
||||
dir_path: str = CORE_DIR
|
||||
|
||||
@property
|
||||
def container_name(self) -> str:
|
||||
return self.container
|
||||
|
||||
|
||||
@dataclass
|
||||
class SitesApp(App):
|
||||
dir_name: str = "" # directory name in ~/Sites (e.g., "homelab-vaultwarden")
|
||||
source: SourceConfig | None = None # Upstream source provenance (None = Class B Image-Only)
|
||||
source: SourceConfig | None = (
|
||||
None # Upstream source provenance (None = Class B Image-Only)
|
||||
)
|
||||
aliases: list[str] = field(default_factory=list) # CLI resolution aliases
|
||||
visible: bool = True # Defines whether the icon is visible in Homepage
|
||||
auth: bool = True # Authelia protection guard indicator
|
||||
has_compose: bool = False # Whether a docker-compose.yml exists
|
||||
networks: list[str] = field(default_factory=lambda: ["proxy-net"]) # Docker network attachments
|
||||
networks: list[str] = field(
|
||||
default_factory=lambda: ["proxy-net"]
|
||||
) # Docker network attachments
|
||||
env: dict[str, Any] = field(default_factory=dict) # Environment variable overrides
|
||||
homepage: HomepageConfig | None = None # Dashboard Card Configuration
|
||||
manifest_error: str | None = None # Captured syntax/loading errors
|
||||
@@ -121,15 +144,21 @@ class SitesApp(App):
|
||||
data = asdict(self)
|
||||
data.pop("manifest_obj", None)
|
||||
if self.source is not None:
|
||||
data["source"] = self.source.to_dict() if hasattr(self.source, "to_dict") else self.source.model_dump()
|
||||
data["source"] = (
|
||||
self.source.to_dict()
|
||||
if hasattr(self.source, "to_dict")
|
||||
else self.source.model_dump()
|
||||
)
|
||||
if self.homepage is not None:
|
||||
data["homepage"] = self.homepage.to_dict() if hasattr(self.homepage, "to_dict") else self.homepage.model_dump()
|
||||
data["homepage"] = (
|
||||
self.homepage.to_dict()
|
||||
if hasattr(self.homepage, "to_dict")
|
||||
else self.homepage.model_dump()
|
||||
)
|
||||
data["type"] = getattr(self, "app_type", "app")
|
||||
return data
|
||||
|
||||
|
||||
|
||||
|
||||
def sites_app_from_manifest(
|
||||
app_dir: str,
|
||||
manifest: Manifest | dict[str, Any] | None = None,
|
||||
@@ -139,10 +168,9 @@ def sites_app_from_manifest(
|
||||
raw_dir_name = os.path.basename(app_dir)
|
||||
|
||||
if isinstance(manifest, Manifest):
|
||||
has_compose = (
|
||||
os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or
|
||||
os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
|
||||
)
|
||||
has_compose = os.path.isfile(
|
||||
os.path.join(app_dir, "docker-compose.yaml")
|
||||
) or os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
|
||||
canonical_name = manifest.name
|
||||
domain = manifest.domain or f"{canonical_name}.{HOMELAB_DOMAIN}"
|
||||
return SitesApp(
|
||||
@@ -169,7 +197,9 @@ def sites_app_from_manifest(
|
||||
return sites_app_from_manifest(app_dir, parsed, manifest_error)
|
||||
except ManifestValidationError as err:
|
||||
manifest_error = f"{manifest_error}; {err}" if manifest_error else str(err)
|
||||
canonical_name = str(manifest.get("name") or raw_dir_name.replace("homelab-", ""))
|
||||
canonical_name = str(
|
||||
manifest.get("name") or raw_dir_name.replace("homelab-", "")
|
||||
)
|
||||
return SitesApp(
|
||||
name=canonical_name,
|
||||
dir_name=raw_dir_name,
|
||||
@@ -217,13 +247,18 @@ def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]:
|
||||
try:
|
||||
manifest_obj = parse_manifest(manifest_file)
|
||||
apps.append(sites_app_from_manifest(app_dir=app_dir, manifest=manifest_obj))
|
||||
except (ManifestValidationError, yaml.YAMLError, OSError, ValueError, KeyError) as err:
|
||||
except (
|
||||
ManifestValidationError,
|
||||
yaml.YAMLError,
|
||||
OSError,
|
||||
ValueError,
|
||||
KeyError,
|
||||
) as err:
|
||||
raw_data = None
|
||||
with (
|
||||
contextlib.suppress(Exception),
|
||||
open(manifest_path, "r", encoding="utf-8") as f,
|
||||
):
|
||||
with contextlib.suppress(Exception), open(manifest_path, "r", encoding="utf-8") as f:
|
||||
raw_data = yaml.safe_load(f)
|
||||
|
||||
|
||||
app_dict = raw_data if isinstance(raw_data, dict) else {}
|
||||
apps.append(
|
||||
sites_app_from_manifest(
|
||||
@@ -322,14 +357,18 @@ def resolve_app(
|
||||
query: str,
|
||||
apps: list[SitesApp] | None = None,
|
||||
sites_dir: str | None = None,
|
||||
core_dir: str | None = None,
|
||||
) -> App | None:
|
||||
"""
|
||||
Resolve a query string to a SitesApp or CoreService.
|
||||
Priority: Canonical Name > Alias > Dir Name > Stripped 'homelab-' Prefix > Core Services.
|
||||
"""
|
||||
if apps is None:
|
||||
apps = get_sites_apps(sites_dir=sites_dir if sites_dir is not None else SITES_DIR)
|
||||
apps = get_sites_apps(
|
||||
sites_dir=sites_dir if sites_dir is not None else SITES_DIR
|
||||
)
|
||||
|
||||
c_dir = core_dir if core_dir is not None else CORE_DIR
|
||||
query_clean = query.strip().lower()
|
||||
|
||||
# 1. Exact match on canonical name
|
||||
@@ -353,7 +392,7 @@ def resolve_app(
|
||||
return app
|
||||
|
||||
# 5. Match Core services
|
||||
for svc in get_core_services():
|
||||
for svc in get_core_services(core_dir=c_dir):
|
||||
if svc.name.lower() == query_clean:
|
||||
return svc
|
||||
|
||||
@@ -363,7 +402,7 @@ def resolve_app(
|
||||
domain=HOMELAB_DOMAIN,
|
||||
container="",
|
||||
description="Homelab Core Platform Stack",
|
||||
dir_path=CORE_DIR,
|
||||
dir_path=c_dir,
|
||||
app_type="core",
|
||||
)
|
||||
|
||||
@@ -383,13 +422,22 @@ def get_docker_status(
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if inspect_res.returncode != 0:
|
||||
err = (inspect_res.stderr or "").lower()
|
||||
if "no such object" in err or "no such container" in err:
|
||||
return "🔴 Stopped"
|
||||
return "❓ Unknown"
|
||||
state = inspect_res.stdout.strip()
|
||||
if state.lower() == "true":
|
||||
return "🟢 Running (1)"
|
||||
return "🔴 Stopped"
|
||||
|
||||
path = Path(dir_path)
|
||||
if path.exists() and not (path / "docker-compose.yml").is_file() and not (path / "docker-compose.yaml").is_file():
|
||||
if (
|
||||
path.exists()
|
||||
and not (path / "docker-compose.yml").is_file()
|
||||
and not (path / "docker-compose.yaml").is_file()
|
||||
):
|
||||
return "⚪ Not Stack"
|
||||
|
||||
res = subprocess.run(
|
||||
@@ -399,6 +447,9 @@ def get_docker_status(
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if res.returncode != 0:
|
||||
return "❓ Unknown"
|
||||
|
||||
container_ids = [c for c in res.stdout.strip().splitlines() if c]
|
||||
if not container_ids:
|
||||
return "🔴 Stopped"
|
||||
@@ -409,6 +460,9 @@ def get_docker_status(
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if inspect_res.returncode != 0:
|
||||
return "❓ Unknown"
|
||||
|
||||
running_states = inspect_res.stdout.strip().splitlines()
|
||||
running_count = sum(1 for s in running_states if s.lower() == "true")
|
||||
total_count = len(container_ids)
|
||||
@@ -465,7 +519,9 @@ def get_docker_image_revision(
|
||||
return None
|
||||
|
||||
|
||||
def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[str, Any]:
|
||||
def check_ssl_cert(
|
||||
domain: str, port: int = 443, timeout: float = 3.0
|
||||
) -> dict[str, Any]:
|
||||
"""Inspect SSL/TLS certificate for a domain using standard library ssl and socket."""
|
||||
if not domain or domain == "internal" or domain.endswith(".local") or ":" in domain:
|
||||
return {
|
||||
@@ -481,10 +537,8 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
||||
|
||||
try:
|
||||
ctx = ssl.create_default_context()
|
||||
with (
|
||||
socket.create_connection((domain, port), timeout=timeout) as sock,
|
||||
ctx.wrap_socket(sock, server_hostname=domain) as ssock,
|
||||
):
|
||||
with socket.create_connection((domain, port), timeout=timeout) as sock: # noqa: SIM117
|
||||
with ctx.wrap_socket(sock, server_hostname=domain) as ssock:
|
||||
raw_cert = ssock.getpeercert()
|
||||
cert = raw_cert if isinstance(raw_cert, dict) else {}
|
||||
|
||||
@@ -492,9 +546,9 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
||||
days_remaining = None
|
||||
formatted_expiry = "-"
|
||||
if not_after_str:
|
||||
expiry_dt = datetime.datetime.strptime(not_after_str, "%b %d %H:%M:%S %Y %Z").replace(
|
||||
tzinfo=datetime.UTC
|
||||
)
|
||||
expiry_dt = datetime.datetime.strptime(
|
||||
not_after_str, "%b %d %H:%M:%S %Y %Z"
|
||||
).replace(tzinfo=datetime.UTC)
|
||||
now_dt = datetime.datetime.now(datetime.UTC)
|
||||
days_remaining = (expiry_dt - now_dt).days
|
||||
formatted_expiry = expiry_dt.strftime("%Y-%m-%d")
|
||||
@@ -507,7 +561,11 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
||||
entry = rdn[0]
|
||||
if isinstance(entry, (list, tuple)) and len(entry) >= 2:
|
||||
issuer_dict[str(entry[0])] = str(entry[1])
|
||||
issuer = str(issuer_dict.get("organizationName") or issuer_dict.get("commonName") or "Unknown")
|
||||
issuer = str(
|
||||
issuer_dict.get("organizationName")
|
||||
or issuer_dict.get("commonName")
|
||||
or "Unknown"
|
||||
)
|
||||
|
||||
subject_dict: dict[str, str] = {}
|
||||
subject_raw = cert.get("subject")
|
||||
@@ -519,7 +577,6 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
||||
subject_dict[str(entry[0])] = str(entry[1])
|
||||
subject = str(subject_dict.get("commonName") or domain)
|
||||
|
||||
|
||||
if days_remaining is not None:
|
||||
if days_remaining < 0:
|
||||
status = f"🔴 Expired ({abs(days_remaining)}d ago)"
|
||||
@@ -540,7 +597,14 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
||||
"formatted_expiry": formatted_expiry,
|
||||
"error": None,
|
||||
}
|
||||
except (ssl.SSLError, socket.gaierror, TimeoutError, ConnectionRefusedError, OSError, ValueError) as e:
|
||||
except (
|
||||
ssl.SSLError,
|
||||
socket.gaierror,
|
||||
TimeoutError,
|
||||
ConnectionRefusedError,
|
||||
OSError,
|
||||
ValueError,
|
||||
) as e:
|
||||
return {
|
||||
"domain": domain,
|
||||
"status": "🔴 Failed",
|
||||
@@ -555,13 +619,19 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
||||
|
||||
def check_all_ssl_certs(domains: list[str]) -> dict[str, dict[str, Any]]:
|
||||
"""Check multiple domains concurrently with ThreadPoolExecutor."""
|
||||
valid_domains = [d for d in set(domains) if d and d != "internal" and not d.endswith(".local") and ":" not in d]
|
||||
valid_domains = [
|
||||
d
|
||||
for d in set(domains)
|
||||
if d and d != "internal" and not d.endswith(".local") and ":" not in d
|
||||
]
|
||||
results: dict[str, dict[str, Any]] = {}
|
||||
if not valid_domains:
|
||||
return results
|
||||
|
||||
with ThreadPoolExecutor(max_workers=min(len(valid_domains), 8)) as executor:
|
||||
future_to_domain = {executor.submit(check_ssl_cert, d): d for d in valid_domains}
|
||||
future_to_domain = {
|
||||
executor.submit(check_ssl_cert, d): d for d in valid_domains
|
||||
}
|
||||
for future, d in future_to_domain.items():
|
||||
with contextlib.suppress(subprocess.SubprocessError, OSError):
|
||||
results[d] = future.result()
|
||||
@@ -591,7 +661,8 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
||||
groups[core_group] = []
|
||||
for svc in core_services:
|
||||
if not svc.is_internal:
|
||||
groups[core_group].append({
|
||||
groups[core_group].append(
|
||||
{
|
||||
"title": svc.name.title(),
|
||||
"icon": getattr(svc, "icon", "default.png"),
|
||||
"href": f"https://{svc.domain}",
|
||||
@@ -599,7 +670,8 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
||||
"server": "my-docker",
|
||||
"container": getattr(svc, "container", svc.name),
|
||||
"weight": getattr(svc, "weight", 50),
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
# 2. Add Sites applications
|
||||
icons_dir = os.path.join(hp_dir, "icons")
|
||||
@@ -633,7 +705,8 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
||||
if matched_icon:
|
||||
icon = f"/icons/{matched_icon}"
|
||||
|
||||
groups[group_name].append({
|
||||
groups[group_name].append(
|
||||
{
|
||||
"title": card_title,
|
||||
"icon": icon,
|
||||
"href": f"https://{app.domain}",
|
||||
@@ -641,7 +714,8 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
||||
"server": "my-docker",
|
||||
"container": container,
|
||||
"weight": weight,
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
# Preferred group order
|
||||
preferred_order = [
|
||||
@@ -675,10 +749,16 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
||||
lines.append("")
|
||||
|
||||
content = "\n".join(lines).strip() + "\n"
|
||||
with open(services_yaml_path, "w", encoding="utf-8") as f:
|
||||
tmp_services_path = services_yaml_path + ".tmp"
|
||||
with open(tmp_services_path, "w", encoding="utf-8") as f:
|
||||
f.write(content)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp_services_path, services_yaml_path)
|
||||
|
||||
print(f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)")
|
||||
print(
|
||||
f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)"
|
||||
)
|
||||
print(f"📄 Generated {services_yaml_path}")
|
||||
|
||||
|
||||
@@ -699,11 +779,19 @@ def cmd_list(args: list[str]) -> None:
|
||||
ssl_data = check_all_ssl_certs(domains_to_check)
|
||||
|
||||
if show_ssl:
|
||||
print(f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}")
|
||||
print(f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}")
|
||||
print(
|
||||
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
|
||||
)
|
||||
print(
|
||||
f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
|
||||
)
|
||||
else:
|
||||
print(f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}")
|
||||
print(f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}")
|
||||
print(
|
||||
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}"
|
||||
)
|
||||
print(
|
||||
f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}"
|
||||
)
|
||||
|
||||
for app in apps:
|
||||
app_path = Path(app.dir_path)
|
||||
@@ -713,7 +801,9 @@ def cmd_list(args: list[str]) -> None:
|
||||
dep_str = "⚠️ Manifest Error"
|
||||
prov_str = "⚠️ Invalid Manifest"
|
||||
else:
|
||||
manifest_obj = app.manifest_obj or Manifest(name=app.name, domain=app.domain)
|
||||
manifest_obj = app.manifest_obj or Manifest(
|
||||
name=app.name, domain=app.domain
|
||||
)
|
||||
two_axis = inspect_workload_two_axis(
|
||||
app_dir=app_path,
|
||||
manifest=manifest_obj,
|
||||
@@ -726,9 +816,13 @@ def cmd_list(args: list[str]) -> None:
|
||||
if show_ssl:
|
||||
cert_info = ssl_data.get(app.domain, check_ssl_cert(app.domain))
|
||||
cert_badge = cert_info.get("status", "-")
|
||||
print(f"{app.name:<16} {dep_str:<22} {prov_str:<22} {docker_status:<15} {app.domain:<28} {cert_badge}")
|
||||
print(
|
||||
f"{app.name:<16} {dep_str:<22} {prov_str:<22} {docker_status:<15} {app.domain:<28} {cert_badge}"
|
||||
)
|
||||
else:
|
||||
print(f"{app.name:<16} {dep_str:<22} {prov_str:<24} {docker_status:<15} {app.domain:<28}")
|
||||
print(
|
||||
f"{app.name:<16} {dep_str:<22} {prov_str:<24} {docker_status:<15} {app.domain:<28}"
|
||||
)
|
||||
|
||||
if show_core:
|
||||
core_path = Path(CORE_DIR)
|
||||
@@ -736,11 +830,19 @@ def cmd_list(args: list[str]) -> None:
|
||||
core_dep_str = core_checkout.status_label
|
||||
print()
|
||||
if show_ssl:
|
||||
print(f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}")
|
||||
print(f"{'------------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}")
|
||||
print(
|
||||
f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
|
||||
)
|
||||
print(
|
||||
f"{'------------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
|
||||
)
|
||||
else:
|
||||
print(f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}")
|
||||
print(f"{'------------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}")
|
||||
print(
|
||||
f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}"
|
||||
)
|
||||
print(
|
||||
f"{'------------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}"
|
||||
)
|
||||
|
||||
core_services = get_core_services()
|
||||
for i, svc in enumerate(core_services):
|
||||
@@ -749,9 +851,13 @@ def cmd_list(args: list[str]) -> None:
|
||||
if show_ssl:
|
||||
cert_info = ssl_data.get(svc.domain, check_ssl_cert(svc.domain))
|
||||
cert_badge = cert_info.get("status", "-")
|
||||
print(f"{svc.name:<16} {row_dep:<22} {'— Core Platform':<22} {svc_docker:<15} {svc.domain:<28} {cert_badge}")
|
||||
print(
|
||||
f"{svc.name:<16} {row_dep:<22} {'— Core Platform':<22} {svc_docker:<15} {svc.domain:<28} {cert_badge}"
|
||||
)
|
||||
else:
|
||||
print(f"{svc.name:<16} {row_dep:<22} {'— Core Platform':<24} {svc_docker:<15} {svc.domain:<28}")
|
||||
print(
|
||||
f"{svc.name:<16} {row_dep:<22} {'— Core Platform':<24} {svc_docker:<15} {svc.domain:<28}"
|
||||
)
|
||||
|
||||
|
||||
def cmd_info(args: list[str]) -> None:
|
||||
@@ -775,7 +881,9 @@ def cmd_info(args: list[str]) -> None:
|
||||
print(f"Directory: {app.dir_path}")
|
||||
print(f"Domain: {app.domain}")
|
||||
print(f"Container: {app.container}")
|
||||
print(f"Status: {get_docker_status(Path(app.dir_path), app.container)}")
|
||||
print(
|
||||
f"Status: {get_docker_status(Path(app.dir_path), app.container)}"
|
||||
)
|
||||
print(f"Description: {app.description}")
|
||||
return
|
||||
|
||||
@@ -791,7 +899,9 @@ def cmd_info(args: list[str]) -> None:
|
||||
print(f"Description: {app.description}")
|
||||
if app.aliases:
|
||||
print(f"Aliases: {', '.join(app.aliases)}")
|
||||
print(f"Class: {'Class A (Source-Backed)' if app.source else 'Class B (Image-Only)'}")
|
||||
print(
|
||||
f"Class: {'Class A (Source-Backed)' if app.source else 'Class B (Image-Only)'}"
|
||||
)
|
||||
print(f"Networks: {', '.join(app.networks)}")
|
||||
print(f"Auth Protected: {app.auth}")
|
||||
print(f"Dashboard: {'Visible' if app.visible else 'Hidden'}")
|
||||
@@ -816,7 +926,9 @@ def cmd_info(args: list[str]) -> None:
|
||||
if two_axis.checkout.is_git:
|
||||
print(f" Branch: {two_axis.checkout.branch}")
|
||||
print(f" Commit SHA: {two_axis.checkout.commit_sha}")
|
||||
print(f" Checkout: {'* Dirty (Uncommitted changes)' if two_axis.checkout.is_dirty else '✓ Clean'}")
|
||||
print(
|
||||
f" Checkout: {'* Dirty (Uncommitted changes)' if two_axis.checkout.is_dirty else '✓ Clean'}"
|
||||
)
|
||||
print(f" Docker Status: {two_axis.docker_status}")
|
||||
if two_axis.image_revision:
|
||||
print(f" Image Revision:{two_axis.image_revision}")
|
||||
@@ -847,7 +959,10 @@ def cmd_resolve(args: list[str]) -> None:
|
||||
if not app:
|
||||
sys.exit(1)
|
||||
if isinstance(app, SitesApp) and app.manifest_error:
|
||||
print(f"❌ Error: Workload '{app.name}' has invalid manifest: {app.manifest_error}", file=sys.stderr)
|
||||
print(
|
||||
f"❌ Error: Workload '{app.name}' has invalid manifest: {app.manifest_error}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
print(json.dumps(app.to_dict()))
|
||||
|
||||
@@ -874,7 +989,9 @@ def cmd_ssl(args: list[str]) -> None:
|
||||
print(f"Subject: {cert_info['subject']}")
|
||||
print(f"Expiration: {cert_info['not_after']}")
|
||||
if cert_info["days_remaining"] is not None:
|
||||
print(f"Days Remaining: {cert_info['days_remaining']} days ({cert_info['formatted_expiry']})")
|
||||
print(
|
||||
f"Days Remaining: {cert_info['days_remaining']} days ({cert_info['formatted_expiry']})"
|
||||
)
|
||||
if cert_info["error"]:
|
||||
print(f"Details/Error: {cert_info['error']}")
|
||||
print()
|
||||
@@ -896,7 +1013,9 @@ def cmd_ssl(args: list[str]) -> None:
|
||||
|
||||
for name, domain in services_to_check:
|
||||
info = ssl_results.get(domain, check_ssl_cert(domain))
|
||||
print(f"{name:<20} {domain:<30} {info['status']:<24} {info['issuer']:<20} {info['formatted_expiry']}")
|
||||
print(
|
||||
f"{name:<20} {domain:<30} {info['status']:<24} {info['issuer']:<20} {info['formatted_expiry']}"
|
||||
)
|
||||
|
||||
|
||||
def cmd_complete(args: list[str]) -> None:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Executable
+173
@@ -0,0 +1,173 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
bootstrap_token.py — Operator Admin Token Bootstrap & Rotation Helper (WP4)
|
||||
|
||||
Generates a 256-bit cryptographically secure Bearer token, saves it locally
|
||||
with strict mode 0600 permissions (~/.config/homelab/token), and prints the
|
||||
corresponding JSON descriptor for insertion into the SOPS tokens store
|
||||
(nixos/secrets.yaml -> appctl/tokens_json).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import stat
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
# Ensure scripts directory is in sys.path when executed directly
|
||||
_scripts_dir = Path(__file__).resolve().parent
|
||||
if str(_scripts_dir) not in sys.path:
|
||||
sys.path.insert(0, str(_scripts_dir))
|
||||
|
||||
from appctl_auth import Role, TokenDescriptor
|
||||
|
||||
DEFAULT_TOKEN_PATH = Path.home() / ".config/homelab/token"
|
||||
DEFAULT_TOKEN_ID = "operator-admin"
|
||||
DEFAULT_IDENTITY = "operator"
|
||||
DEFAULT_ROLE = Role.ADMIN.value
|
||||
|
||||
|
||||
def generate_token() -> tuple[str, str]:
|
||||
"""Generate a 256-bit cryptographically secure Bearer token and its SHA-256 digest."""
|
||||
raw_token = secrets.token_hex(32)
|
||||
digest = hashlib.sha256(raw_token.encode()).hexdigest()
|
||||
return raw_token, digest
|
||||
|
||||
|
||||
def write_token_file(path: Path, raw_token: str, force: bool = False) -> None:
|
||||
"""
|
||||
Write raw Bearer token to path with mode 0600.
|
||||
Ensures parent directory exists with mode 0700.
|
||||
Fails closed if the destination exists and force is False.
|
||||
"""
|
||||
path = path.expanduser().resolve()
|
||||
if path.exists() and not force:
|
||||
raise FileExistsError(
|
||||
f"Token file '{path}' already exists. Use --force / -f to overwrite."
|
||||
)
|
||||
|
||||
parent = path.parent
|
||||
if not parent.exists():
|
||||
parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
try:
|
||||
parent.chmod(0o700)
|
||||
except OSError:
|
||||
pass
|
||||
elif stat.S_IMODE(parent.stat().st_mode) != 0o700:
|
||||
try:
|
||||
parent.chmod(0o700)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
fd = os.open(str(path), os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o600)
|
||||
try:
|
||||
content = f"{raw_token}\n".encode()
|
||||
os.write(fd, content)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
path.chmod(0o600)
|
||||
|
||||
|
||||
def bootstrap_token(
|
||||
output_path: Path | str = DEFAULT_TOKEN_PATH,
|
||||
token_id: str = DEFAULT_TOKEN_ID,
|
||||
identity: str = DEFAULT_IDENTITY,
|
||||
role: str = DEFAULT_ROLE,
|
||||
force: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Generate Bearer token, persist to file with strict permissions,
|
||||
and return the validated TokenDescriptor dictionary.
|
||||
"""
|
||||
path = Path(output_path).expanduser().resolve()
|
||||
raw_token, digest = generate_token()
|
||||
|
||||
write_token_file(path, raw_token, force=force)
|
||||
|
||||
# Validate against TokenDescriptor model
|
||||
validated = TokenDescriptor(
|
||||
token_id=token_id,
|
||||
identity=identity,
|
||||
role=Role(role),
|
||||
sha256=digest,
|
||||
)
|
||||
return validated.model_dump(mode="json")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Bootstrap or rotate an operator Bearer token for appctl."
|
||||
)
|
||||
parser.add_argument(
|
||||
"-o",
|
||||
"--output",
|
||||
default=str(DEFAULT_TOKEN_PATH),
|
||||
help=f"Destination token file path (default: {DEFAULT_TOKEN_PATH})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--token-id",
|
||||
default=DEFAULT_TOKEN_ID,
|
||||
help=f"Token descriptor ID (default: {DEFAULT_TOKEN_ID})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--identity",
|
||||
default=DEFAULT_IDENTITY,
|
||||
help=f"Caller identity (default: {DEFAULT_IDENTITY})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--role",
|
||||
default=DEFAULT_ROLE,
|
||||
choices=[r.value for r in Role],
|
||||
help=f"Role assignment (default: {DEFAULT_ROLE})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-f",
|
||||
"--force",
|
||||
action="store_true",
|
||||
help="Overwrite existing token file if present",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--print-json",
|
||||
action="store_true",
|
||||
help="Output only the JSON descriptor snippet for piping/automation",
|
||||
)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
descriptor = bootstrap_token(
|
||||
output_path=args.output,
|
||||
token_id=args.token_id,
|
||||
identity=args.identity,
|
||||
role=args.role,
|
||||
force=args.force,
|
||||
)
|
||||
except FileExistsError as err:
|
||||
sys.stderr.write(f"Error: {err}\n")
|
||||
return 1
|
||||
|
||||
json_snippet = json.dumps(descriptor, indent=2)
|
||||
|
||||
if args.print_json:
|
||||
sys.stdout.write(f"{json_snippet}\n")
|
||||
else:
|
||||
sys.stdout.write(
|
||||
f"Generated Bearer token and saved to {args.output} (mode 0600).\n\n"
|
||||
f"Add the following descriptor to your SOPS tokens store (nixos/secrets.yaml -> appctl/tokens_json):\n\n"
|
||||
f"{json_snippet}\n\n"
|
||||
f"After updating nixos/secrets.yaml with `sops nixos/secrets.yaml`, apply changes with:\n"
|
||||
f" sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure\n"
|
||||
)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+104
-36
@@ -36,9 +36,9 @@ class ManifestValidationError(Exception):
|
||||
"""Raised when an application manifest violates schema or security constraints."""
|
||||
|
||||
|
||||
|
||||
class RefType(str, Enum):
|
||||
"""Semantic classification of an upstream git reference."""
|
||||
|
||||
BRANCH = "branch" # Moving branch (e.g. main, master, develop, release/v1)
|
||||
TAG = "tag" # Pinned release tag (e.g. v1.0.0, 2.3.1)
|
||||
COMMIT = "commit" # Immutable commit SHA (40-character hex)
|
||||
@@ -47,6 +47,7 @@ class RefType(str, Enum):
|
||||
|
||||
class TransportScheme(str, Enum):
|
||||
"""Supported secure git network transports."""
|
||||
|
||||
HTTPS = "https"
|
||||
SSH = "ssh"
|
||||
GIT_SCP = "git_scp"
|
||||
@@ -57,15 +58,40 @@ NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]*$")
|
||||
COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$")
|
||||
SHORT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,12}$")
|
||||
SEMVER_TAG_RE = re.compile(r"^v?[0-9]+(\.[0-9]+)+([a-zA-Z0-9._-]*)$")
|
||||
SCP_URL_RE = re.compile(r"^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:([0-9]+/)?([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+(\.git)?$")
|
||||
SCP_URL_RE = re.compile(
|
||||
r"^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:([0-9]+/)?([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+(\.git)?$"
|
||||
)
|
||||
ENV_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
|
||||
RESERVED_ENV_KEYS = {
|
||||
"PATH", "LD_PRELOAD", "IFS", "SHELL", "USER",
|
||||
"CORE_DIR", "SITES_DIR", "ENV_FILE", "HOMESERVER_ENV"
|
||||
"PATH",
|
||||
"LD_PRELOAD",
|
||||
"IFS",
|
||||
"SHELL",
|
||||
"USER",
|
||||
"CORE_DIR",
|
||||
"SITES_DIR",
|
||||
"ENV_FILE",
|
||||
"HOMESERVER_ENV",
|
||||
"HOMELAB_DOMAIN",
|
||||
"DOMAIN_SUFFIX",
|
||||
"DOMAIN",
|
||||
"PROXY_NETWORK",
|
||||
"CERT_RESOLVER",
|
||||
"DOCKER_CONFIG",
|
||||
"SERVICE_NAME",
|
||||
"CONTAINER_NAME",
|
||||
"SERVICE_DOMAIN",
|
||||
"HOMELAB_GRANTS_FILE",
|
||||
}
|
||||
|
||||
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]:
|
||||
@@ -80,35 +106,49 @@ def validate_transport(url: str) -> tuple[TransportScheme, str]:
|
||||
|
||||
# Reject path traversal / directory escapes
|
||||
if ".." in clean_url or "\\" in clean_url or clean_url.startswith(("/", "~")):
|
||||
raise ManifestValidationError(f"Prohibited filesystem path or traversal in source URL: '{clean_url}'")
|
||||
raise ManifestValidationError(
|
||||
f"Prohibited filesystem path or traversal in source URL: '{clean_url}'"
|
||||
)
|
||||
|
||||
# 1. HTTPS transport
|
||||
if clean_url.startswith("https://"):
|
||||
parsed = urlparse(clean_url)
|
||||
if not parsed.netloc:
|
||||
raise ManifestValidationError(f"Malformed HTTPS source URL (missing host): '{clean_url}'")
|
||||
raise ManifestValidationError(
|
||||
f"Malformed HTTPS source URL (missing host): '{clean_url}'"
|
||||
)
|
||||
if not parsed.path or parsed.path == "/":
|
||||
raise ManifestValidationError(f"Malformed HTTPS source URL (missing repository path): '{clean_url}'")
|
||||
raise ManifestValidationError(
|
||||
f"Malformed HTTPS source URL (missing repository path): '{clean_url}'"
|
||||
)
|
||||
return TransportScheme.HTTPS, clean_url
|
||||
|
||||
# 2. Standard SSH transport (ssh://[user@]host[:port]/path)
|
||||
if clean_url.startswith("ssh://"):
|
||||
parsed = urlparse(clean_url)
|
||||
if not parsed.netloc:
|
||||
raise ManifestValidationError(f"Malformed SSH source URL (missing host): '{clean_url}'")
|
||||
raise ManifestValidationError(
|
||||
f"Malformed SSH source URL (missing host): '{clean_url}'"
|
||||
)
|
||||
if not parsed.path or parsed.path == "/":
|
||||
raise ManifestValidationError(f"Malformed SSH source URL (missing repository path): '{clean_url}'")
|
||||
raise ManifestValidationError(
|
||||
f"Malformed SSH source URL (missing repository path): '{clean_url}'"
|
||||
)
|
||||
return TransportScheme.SSH, clean_url
|
||||
|
||||
# 3. SCP-style SSH transport (git@host:owner/repo.git)
|
||||
if clean_url.startswith("git@") or ("@" in clean_url and ":" in clean_url and not clean_url.startswith("http")):
|
||||
if clean_url.startswith("git@") or (
|
||||
"@" in clean_url and ":" in clean_url and not clean_url.startswith("http")
|
||||
):
|
||||
if SCP_URL_RE.match(clean_url):
|
||||
return TransportScheme.GIT_SCP, clean_url
|
||||
raise ManifestValidationError(f"Malformed SCP-style source URL: '{clean_url}'")
|
||||
|
||||
# Reject plaintext HTTP or unsupported schemes
|
||||
if clean_url.startswith("http://"):
|
||||
raise ManifestValidationError(f"Insecure HTTP source URL rejected (HTTPS or SSH required): '{clean_url}'")
|
||||
raise ManifestValidationError(
|
||||
f"Insecure HTTP source URL rejected (HTTPS or SSH required): '{clean_url}'"
|
||||
)
|
||||
|
||||
raise ManifestValidationError(
|
||||
f"Invalid source.url scheme: '{clean_url}'. "
|
||||
@@ -140,20 +180,14 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]:
|
||||
if SEMVER_TAG_RE.match(ref):
|
||||
return RefType.TAG, ref
|
||||
|
||||
# Standard branch naming patterns
|
||||
if ref in {"main", "master", "develop", "dev", "trunk", "staging", "prod", "production"}:
|
||||
return RefType.BRANCH, ref
|
||||
|
||||
if ref.startswith(("feat/", "fix/", "release/", "chore/", "refactor/")):
|
||||
return RefType.BRANCH, ref
|
||||
|
||||
# Fallback default: non-versioned arbitrary string treated as branch
|
||||
# Non-versioned arbitrary string treated as branch
|
||||
return RefType.BRANCH, ref
|
||||
|
||||
|
||||
class SourceConfig(BaseModel):
|
||||
"""Upstream source provenance descriptor."""
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||
|
||||
url: str
|
||||
ref: str = "main"
|
||||
@@ -167,7 +201,9 @@ class SourceConfig(BaseModel):
|
||||
if isinstance(data, dict):
|
||||
src_type = str(data.get("type", "git")).strip().lower()
|
||||
if src_type != "git":
|
||||
raise ManifestValidationError(f"Unsupported source type '{src_type}'. Only 'git' is supported.")
|
||||
raise ManifestValidationError(
|
||||
f"Unsupported source type '{src_type}'. Only 'git' is supported."
|
||||
)
|
||||
data["type"] = src_type
|
||||
|
||||
raw_url = data.get("url")
|
||||
@@ -198,7 +234,8 @@ class SourceConfig(BaseModel):
|
||||
|
||||
class DeploymentConfig(BaseModel):
|
||||
"""Continuous deployment strategy and action policy."""
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||
|
||||
strategy: str = "compose"
|
||||
branch: str = "main"
|
||||
@@ -223,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:
|
||||
@@ -237,7 +274,8 @@ class DeploymentConfig(BaseModel):
|
||||
|
||||
class HomepageConfig(BaseModel):
|
||||
"""Dashboard card metadata for Homepage."""
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||
|
||||
title: str
|
||||
group: str = "Applications"
|
||||
@@ -262,7 +300,12 @@ class Manifest(BaseModel):
|
||||
Authoritative Workload Manifest Model (Schema v1.0).
|
||||
Represents the full contract declared in a workload's app.yaml.
|
||||
"""
|
||||
model_config = ConfigDict(extra="forbid", populate_by_name=True)
|
||||
|
||||
model_config = ConfigDict(
|
||||
extra="forbid",
|
||||
populate_by_name=True,
|
||||
ignored_types=(dict,),
|
||||
)
|
||||
|
||||
name: str
|
||||
schema_version: str = Field(default="1.0", alias="schemaVersion")
|
||||
@@ -282,8 +325,14 @@ class Manifest(BaseModel):
|
||||
def prepare_manifest(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict):
|
||||
raw_name = data.get("name")
|
||||
if raw_name is None or not isinstance(raw_name, str) or not raw_name.strip():
|
||||
raise ManifestValidationError("Manifest is missing mandatory string field 'name'.")
|
||||
if (
|
||||
raw_name is None
|
||||
or not isinstance(raw_name, str)
|
||||
or not raw_name.strip()
|
||||
):
|
||||
raise ManifestValidationError(
|
||||
"Manifest is missing mandatory string field 'name'."
|
||||
)
|
||||
clean_name = raw_name.strip()
|
||||
if not NAME_RE.match(clean_name):
|
||||
raise ManifestValidationError(
|
||||
@@ -359,7 +408,12 @@ class Manifest(BaseModel):
|
||||
@property
|
||||
def is_internal(self) -> bool:
|
||||
"""True if the workload does not expose a public TLS endpoint."""
|
||||
return not self.domain or self.domain == "internal" or self.domain.endswith(".local") or ":" in self.domain
|
||||
return (
|
||||
not self.domain
|
||||
or self.domain == "internal"
|
||||
or self.domain.endswith(".local")
|
||||
or ":" in self.domain
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
data: dict[str, Any] = {
|
||||
@@ -401,23 +455,35 @@ def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest:
|
||||
try:
|
||||
content = raw_input.read_text(encoding="utf-8")
|
||||
except OSError as e:
|
||||
raise ManifestValidationError(f"Failed to read manifest {raw_input}: {e}") from e
|
||||
raise ManifestValidationError(
|
||||
f"Failed to read manifest {raw_input}: {e}"
|
||||
) from e
|
||||
try:
|
||||
data = (yaml.safe_load(content) if yaml else _parse_yaml_basic(content)) or {}
|
||||
data = (
|
||||
yaml.safe_load(content) if yaml else _parse_yaml_basic(content)
|
||||
) or {}
|
||||
except Exception as e:
|
||||
raise ManifestValidationError(f"YAML parsing error in {raw_input}: {e}") from e
|
||||
raise ManifestValidationError(
|
||||
f"YAML parsing error in {raw_input}: {e}"
|
||||
) from e
|
||||
elif isinstance(raw_input, str):
|
||||
try:
|
||||
data = (yaml.safe_load(raw_input) if yaml else _parse_yaml_basic(raw_input)) or {}
|
||||
data = (
|
||||
yaml.safe_load(raw_input) if yaml else _parse_yaml_basic(raw_input)
|
||||
) or {}
|
||||
except Exception as e:
|
||||
raise ManifestValidationError(f"YAML parsing error: {e}") from e
|
||||
elif isinstance(raw_input, dict):
|
||||
data = raw_input
|
||||
else:
|
||||
raise ManifestValidationError(f"Invalid input type for manifest parsing: {type(raw_input)}")
|
||||
raise ManifestValidationError(
|
||||
f"Invalid input type for manifest parsing: {type(raw_input)}"
|
||||
)
|
||||
|
||||
if not isinstance(data, dict):
|
||||
raise ManifestValidationError("Manifest root must be a YAML dictionary mapping.")
|
||||
raise ManifestValidationError(
|
||||
"Manifest root must be a YAML dictionary mapping."
|
||||
)
|
||||
|
||||
try:
|
||||
return Manifest.model_validate(data)
|
||||
@@ -433,7 +499,9 @@ def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest:
|
||||
msg = msg.removeprefix("Value error, ")
|
||||
loc = ".".join(str(p) for p in first_error.get("loc", []))
|
||||
if loc and first_error.get("type") == "extra_forbidden":
|
||||
raise ManifestValidationError(f"Manifest contains unrecognized or forbidden field '{loc}'.") from e
|
||||
raise ManifestValidationError(
|
||||
f"Manifest contains unrecognized or forbidden field '{loc}'."
|
||||
) from e
|
||||
raise ManifestValidationError(msg) from e
|
||||
|
||||
|
||||
|
||||
+1220
-186
File diff suppressed because it is too large.
Load diff
+41
-17
@@ -19,6 +19,7 @@ from core_manifest import Manifest, RefType, SourceConfig
|
||||
|
||||
class ProvenanceStatus(str, Enum):
|
||||
"""Evaluation result of local state vs. upstream software provenance."""
|
||||
|
||||
SYNCED = "✓ Synced"
|
||||
UPDATE_AVAILABLE = "↓ Update Available"
|
||||
IMAGE_ONLY = "— Image-Only (Class B)"
|
||||
@@ -32,6 +33,7 @@ class ProvenanceStatus(str, Enum):
|
||||
@dataclass
|
||||
class CheckoutStatus:
|
||||
"""Axis 1: Local deployment checkout state."""
|
||||
|
||||
is_git: bool
|
||||
is_dirty: bool
|
||||
branch: str
|
||||
@@ -51,6 +53,7 @@ class CheckoutStatus:
|
||||
@dataclass
|
||||
class UpstreamProvenance:
|
||||
"""Axis 2: Upstream software provenance state."""
|
||||
|
||||
status: ProvenanceStatus
|
||||
remote_sha: str = ""
|
||||
target_ref: str = ""
|
||||
@@ -68,6 +71,7 @@ class UpstreamProvenance:
|
||||
@dataclass
|
||||
class TwoAxisStatus:
|
||||
"""Unified inspection combining local deployment and upstream provenance."""
|
||||
|
||||
app_name: str
|
||||
checkout: CheckoutStatus
|
||||
provenance: UpstreamProvenance
|
||||
@@ -88,10 +92,17 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
|
||||
"""
|
||||
Inspect local git repository checkout state.
|
||||
Reports clean/dirty status, active branch/ref, and current commit SHA.
|
||||
Supports standalone <dir_path>/.git checkouts (checked first) and
|
||||
unified monorepo checkouts where <dir_path>.parent/.git exists.
|
||||
"""
|
||||
path = Path(dir_path)
|
||||
git_dir = path / ".git"
|
||||
if not git_dir.exists():
|
||||
subpath: str | None = None
|
||||
if (path / ".git").exists():
|
||||
git_root = path
|
||||
elif (path.parent / ".git").exists():
|
||||
git_root = path.parent
|
||||
subpath = f"{path.name}/"
|
||||
else:
|
||||
return CheckoutStatus(
|
||||
is_git=False,
|
||||
is_dirty=False,
|
||||
@@ -103,27 +114,35 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
|
||||
# Clean git environment so calls are not polluted by outer hooks
|
||||
git_env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
||||
|
||||
# 1. Check cleanliness
|
||||
# 1. Check cleanliness (scoped to workload subpath in monorepo mode)
|
||||
is_dirty = False
|
||||
git_error: str | None = None
|
||||
status_cmd = ["git", "-C", str(git_root), "status", "--porcelain"]
|
||||
if subpath is not None:
|
||||
status_cmd.extend(["--", subpath])
|
||||
try:
|
||||
status_res = subprocess.run(
|
||||
["git", "-C", str(path), "status", "--porcelain"],
|
||||
status_cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=5.0,
|
||||
env=git_env,
|
||||
)
|
||||
if status_res.returncode == 0 and status_res.stdout.strip():
|
||||
if status_res.returncode == 0:
|
||||
if status_res.stdout.strip():
|
||||
is_dirty = True
|
||||
except (subprocess.SubprocessError, OSError):
|
||||
else:
|
||||
git_error = f"⚠️ Git Error (exit {status_res.returncode})"
|
||||
except (subprocess.SubprocessError, OSError) as exc:
|
||||
is_dirty = False
|
||||
git_error = f"⚠️ Git Error ({exc.__class__.__name__})"
|
||||
|
||||
# 2. Get active branch
|
||||
branch = ""
|
||||
try:
|
||||
branch_res = subprocess.run(
|
||||
["git", "-C", str(path), "rev-parse", "--abbrev-ref", "HEAD"],
|
||||
["git", "-C", str(git_root), "rev-parse", "--abbrev-ref", "HEAD"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
@@ -135,7 +154,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
|
||||
if branch == "HEAD":
|
||||
# Detached HEAD, check describe
|
||||
desc_res = subprocess.run(
|
||||
["git", "-C", str(path), "describe", "--tags", "--exact-match"],
|
||||
["git", "-C", str(git_root), "describe", "--tags", "--exact-match"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
@@ -151,7 +170,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
|
||||
commit_sha = ""
|
||||
try:
|
||||
sha_res = subprocess.run(
|
||||
["git", "-C", str(path), "rev-parse", "--short", "HEAD"],
|
||||
["git", "-C", str(git_root), "rev-parse", "--short", "HEAD"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
@@ -164,6 +183,9 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
|
||||
commit_sha = ""
|
||||
|
||||
# 4. Format status label
|
||||
if git_error:
|
||||
status_label = git_error
|
||||
else:
|
||||
state_symbol = "* Dirty" if is_dirty else "✓ Clean"
|
||||
ref_desc = f"{branch}@{commit_sha}" if commit_sha else branch
|
||||
status_label = f"{state_symbol} ({ref_desc})" if ref_desc else state_symbol
|
||||
@@ -198,12 +220,12 @@ def resolve_upstream_provenance(
|
||||
|
||||
# Commits pinned directly in manifest cannot be checked via ls-remote ref matching
|
||||
if source.ref_type == RefType.COMMIT:
|
||||
is_match = (
|
||||
local_commit and (
|
||||
is_match = local_commit and (
|
||||
source.ref.startswith(local_commit) or local_commit.startswith(source.ref)
|
||||
)
|
||||
status = (
|
||||
ProvenanceStatus.SYNCED if is_match else ProvenanceStatus.UPDATE_AVAILABLE
|
||||
)
|
||||
status = ProvenanceStatus.SYNCED if is_match else ProvenanceStatus.UPDATE_AVAILABLE
|
||||
return UpstreamProvenance(
|
||||
status=status,
|
||||
remote_sha=source.ref,
|
||||
@@ -248,10 +270,10 @@ def resolve_upstream_provenance(
|
||||
for line in proc.stdout.splitlines():
|
||||
parts = line.strip().split()
|
||||
if len(parts) >= 2 and (
|
||||
parts[1] == target_ref or
|
||||
parts[1] == f"refs/heads/{target_ref}" or
|
||||
parts[1] == f"refs/tags/{target_ref}" or
|
||||
parts[1] == f"refs/tags/{target_ref}^{{}}"
|
||||
parts[1] == target_ref
|
||||
or parts[1] == f"refs/heads/{target_ref}"
|
||||
or parts[1] == f"refs/tags/{target_ref}"
|
||||
or parts[1] == f"refs/tags/{target_ref}^{{}}"
|
||||
):
|
||||
remote_sha = parts[0]
|
||||
# Peaked tags (^{}) take precedence over lightweight tag refs
|
||||
@@ -271,7 +293,9 @@ def resolve_upstream_provenance(
|
||||
|
||||
# Compare local commit with remote SHA
|
||||
is_synced = False
|
||||
if local_commit and (remote_sha.startswith(local_commit) or local_commit.startswith(remote_sha[:7])):
|
||||
if local_commit and (
|
||||
remote_sha.startswith(local_commit) or local_commit.startswith(remote_sha[:7])
|
||||
):
|
||||
is_synced = True
|
||||
|
||||
status = ProvenanceStatus.SYNCED if is_synced else ProvenanceStatus.UPDATE_AVAILABLE
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# scripts/test - Automated test & invariant verification runner for Homelab Core
|
||||
# scripts/run-tests - Automated test & invariant verification runner for Homelab Core
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
workload_grants.py — Host-Granted Workload Capability Loader & Schema (ADR-0005)
|
||||
|
||||
Loads and validates /etc/homelab/grants.json (or HOMELAB_GRANTS_FILE) using strict
|
||||
Pydantic v2 models (ConfigDict(extra="forbid")).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
|
||||
|
||||
DEFAULT_GRANTS_FILE = Path("/etc/homelab/grants.json")
|
||||
PRIVILEGED_GROUPS: frozenset[str] = frozenset({"0", "root", "wheel", "docker"})
|
||||
|
||||
|
||||
class WorkloadGrantsError(Exception):
|
||||
"""Raised when the host capability grants file fails integrity or schema checks."""
|
||||
|
||||
|
||||
class WorkloadGrant(BaseModel):
|
||||
"""Explicit host-granted capabilities for a single workload."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
devices: list[str] = Field(default_factory=list)
|
||||
groups: list[str] = Field(default_factory=list)
|
||||
readOnlyPaths: list[str] = Field(default_factory=list)
|
||||
|
||||
@field_validator("groups")
|
||||
@classmethod
|
||||
def _validate_groups(cls, values: list[str]) -> list[str]:
|
||||
cleaned: list[str] = []
|
||||
for raw in values:
|
||||
group = raw.strip()
|
||||
if not group:
|
||||
raise ValueError("Granted group entry cannot be empty.")
|
||||
if group.lower() in PRIVILEGED_GROUPS:
|
||||
raise ValueError(
|
||||
f"Privileged group '{group}' cannot be granted to workloads."
|
||||
)
|
||||
cleaned.append(group)
|
||||
return cleaned
|
||||
|
||||
@field_validator("devices", "readOnlyPaths")
|
||||
@classmethod
|
||||
def _validate_absolute_paths(cls, values: list[str]) -> list[str]:
|
||||
cleaned: list[str] = []
|
||||
for raw in values:
|
||||
path_str = raw.strip()
|
||||
if not path_str:
|
||||
raise ValueError("Granted path entry cannot be empty.")
|
||||
posix = PurePosixPath(path_str)
|
||||
if not posix.is_absolute():
|
||||
raise ValueError(
|
||||
f"Granted path '{path_str}' must be an absolute path."
|
||||
)
|
||||
if ".." in posix.parts:
|
||||
raise ValueError(
|
||||
f"Granted path '{path_str}' must not contain '..' traversal."
|
||||
)
|
||||
cleaned.append(path_str)
|
||||
return cleaned
|
||||
|
||||
|
||||
class GrantsRegistry(BaseModel):
|
||||
"""Root schema for /etc/homelab/grants.json."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
schemaVersion: Literal["1.0"] = "1.0"
|
||||
workloads: dict[str, WorkloadGrant] = Field(default_factory=dict)
|
||||
|
||||
|
||||
def load_workload_grants(
|
||||
grants_file: Path | None = None,
|
||||
*,
|
||||
verify_permissions: bool | None = None,
|
||||
) -> dict[str, WorkloadGrant]:
|
||||
"""
|
||||
Load host-granted workload capabilities from grants_file or HOMELAB_GRANTS_FILE.
|
||||
|
||||
- If the target file does not exist (and is not a symlink), returns {} (zero grants).
|
||||
- If the file is present (or is a symlink) and fails permission/integrity checks,
|
||||
is unreadable, or fails JSON/Pydantic validation, raises WorkloadGrantsError.
|
||||
"""
|
||||
if grants_file is None:
|
||||
env_path = os.environ.get("HOMELAB_GRANTS_FILE", "").strip()
|
||||
target_path = Path(env_path) if env_path else DEFAULT_GRANTS_FILE
|
||||
else:
|
||||
target_path = grants_file
|
||||
|
||||
should_verify = (
|
||||
(target_path == DEFAULT_GRANTS_FILE)
|
||||
if verify_permissions is None
|
||||
else verify_permissions
|
||||
)
|
||||
|
||||
if not target_path.exists() and not target_path.is_symlink():
|
||||
return {}
|
||||
|
||||
if should_verify:
|
||||
try:
|
||||
st = os.lstat(target_path)
|
||||
except OSError as exc:
|
||||
raise WorkloadGrantsError(
|
||||
f"Failed to stat grants file '{target_path}': {exc}"
|
||||
) from exc
|
||||
|
||||
if stat.S_ISLNK(st.st_mode) or not stat.S_ISREG(st.st_mode):
|
||||
raise WorkloadGrantsError(
|
||||
f"Grants file '{target_path}' must be a regular non-symlink file."
|
||||
)
|
||||
if st.st_uid != 0:
|
||||
raise WorkloadGrantsError(
|
||||
f"Grants file '{target_path}' must be owned by root (uid 0)."
|
||||
)
|
||||
if (st.st_mode & 0o022) != 0:
|
||||
raise WorkloadGrantsError(
|
||||
f"Grants file '{target_path}' must not be group- or world-writable."
|
||||
)
|
||||
|
||||
try:
|
||||
raw_text = target_path.read_text(encoding="utf-8")
|
||||
except OSError as exc:
|
||||
raise WorkloadGrantsError(
|
||||
f"Failed to read grants file '{target_path}': {exc}"
|
||||
) from exc
|
||||
|
||||
try:
|
||||
payload = json.loads(raw_text)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise WorkloadGrantsError(
|
||||
f"Malformed JSON in grants file '{target_path}': {exc}"
|
||||
) from exc
|
||||
|
||||
try:
|
||||
registry = GrantsRegistry.model_validate(payload)
|
||||
except ValidationError as exc:
|
||||
raise WorkloadGrantsError(
|
||||
f"Invalid schema in grants file '{target_path}': {exc}"
|
||||
) from exc
|
||||
|
||||
return registry.workloads
|
||||
@@ -0,0 +1,6 @@
|
||||
[mutmut]
|
||||
also_copy=
|
||||
pyproject.toml
|
||||
docker-compose.yml
|
||||
config
|
||||
scripts
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Shared pytest fixtures for Canopy NixOS Core test suites."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
import pytest
|
||||
|
||||
_STRIPPED_WORKLOAD_ENV_VARS = frozenset(
|
||||
{"HOMELAB_DEPLOYMENTS_FILE", "WORKLOADS_DIR", "SITES_DIR"}
|
||||
)
|
||||
_SCRIPTS_DIR = Path(__file__).resolve().parent.parent / "scripts"
|
||||
|
||||
|
||||
class IsolatedScriptRunner(Protocol):
|
||||
"""Callable protocol for executing a Python expression in an isolated env."""
|
||||
|
||||
def __call__(
|
||||
self, expr: str, extra_env: dict[str, str] | None = None
|
||||
) -> str: ...
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def run_isolated_script_expr(tmp_path: Path) -> IsolatedScriptRunner:
|
||||
"""
|
||||
Execute a Python expression in a clean subprocess with workload env vars stripped.
|
||||
|
||||
Strips ``HOMELAB_DEPLOYMENTS_FILE``, ``WORKLOADS_DIR``, and ``SITES_DIR``,
|
||||
sets ``HOME`` to ``tmp_path`` and ``PYTHONPATH`` to ``scripts/``, and
|
||||
merges any optional ``extra_env`` overrides.
|
||||
"""
|
||||
|
||||
def _run(expr: str, extra_env: dict[str, str] | None = None) -> str:
|
||||
env = {
|
||||
k: v
|
||||
for k, v in os.environ.items()
|
||||
if k not in _STRIPPED_WORKLOAD_ENV_VARS
|
||||
}
|
||||
env["HOME"] = str(tmp_path)
|
||||
env["PYTHONPATH"] = str(_SCRIPTS_DIR)
|
||||
if extra_env:
|
||||
env.update(extra_env)
|
||||
return subprocess.check_output(
|
||||
[sys.executable, "-c", expr],
|
||||
env=env,
|
||||
text=True,
|
||||
).strip()
|
||||
|
||||
return _run
|
||||
@@ -0,0 +1,338 @@
|
||||
"""
|
||||
Security and structural tests for the read-only `agents` SSH user,
|
||||
`ForceCommand` allowlist wrapper, and loopback-only `socket-proxy` binding.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
NIXOS_CONFIG = CORE_ROOT / "nixos" / "configuration.nix"
|
||||
COMPOSE_FILE = CORE_ROOT / "docker-compose.yml"
|
||||
FORCE_COMMAND_SCRIPT = CORE_ROOT / "nixos" / "scripts" / "agents-force-command.sh"
|
||||
|
||||
EXPECTED_AGENT_PUBKEY = (
|
||||
"ssh-ed25519 "
|
||||
"AAAAC3NzaC1lZDI1NTE5AAAAIE1pxTdygG5696q0jT7clfJZWtx48ugfUjpzvkHzovVd "
|
||||
"canopy-agents"
|
||||
)
|
||||
|
||||
|
||||
def _extract_nix_block(content: str, header_pattern: str) -> str:
|
||||
"""Extract a brace-delimited Nix attribute block starting at header_pattern."""
|
||||
match = re.search(header_pattern, content)
|
||||
assert match is not None, f"Missing Nix block matching: {header_pattern}"
|
||||
pos = match.end()
|
||||
# Skip `let ... in` bindings if present before the attribute set `{ ... }`
|
||||
tail = content[pos:]
|
||||
if re.match(r"\s*let\b", tail):
|
||||
in_match = re.search(r"\bin\s*\{", tail)
|
||||
assert in_match is not None, f"Missing 'in {{' for let-block: {header_pattern}"
|
||||
start = pos + in_match.end() - 1
|
||||
else:
|
||||
start = content.find("{", pos)
|
||||
assert start != -1, f"Opening brace not found for: {header_pattern}"
|
||||
depth = 0
|
||||
for idx in range(start, len(content)):
|
||||
ch = content[idx]
|
||||
if ch == "{":
|
||||
depth += 1
|
||||
elif ch == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return content[start : idx + 1]
|
||||
raise AssertionError(f"Unclosed Nix block for: {header_pattern}")
|
||||
|
||||
|
||||
def _setup_mock_bin(tmp_path: Path) -> tuple[Path, Path]:
|
||||
"""Create mock docker, journalctl, and appctl binaries that log invocations."""
|
||||
mock_bin = tmp_path / "mock_bin"
|
||||
mock_bin.mkdir()
|
||||
invocations_log = tmp_path / "invocations.log"
|
||||
bash_bin = shutil.which("bash") or "/bin/bash"
|
||||
|
||||
for cmd in ("docker", "journalctl", "appctl"):
|
||||
stub = mock_bin / cmd
|
||||
stub.write_text(
|
||||
f"#!{bash_bin}\n"
|
||||
f'printf "%s|%s|%s|%s|%s\\n" '
|
||||
f'"{cmd}" "$*" "${{CORE_DIR:-}}" "${{WORKLOADS_DIR:-}}" "${{DOCKER_HOST:-}}" '
|
||||
f'>> "{invocations_log}"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
stub.chmod(0o755)
|
||||
|
||||
return mock_bin, invocations_log
|
||||
|
||||
|
||||
def _run_force_command(
|
||||
ssh_original_command: str | None,
|
||||
tmp_path: Path,
|
||||
) -> tuple[subprocess.CompletedProcess[str], Path]:
|
||||
"""Execute agents-force-command.sh with isolated mock PATH and SSH_ORIGINAL_COMMAND."""
|
||||
assert FORCE_COMMAND_SCRIPT.exists(), (
|
||||
f"ForceCommand script not found at {FORCE_COMMAND_SCRIPT}"
|
||||
)
|
||||
mock_bin, invocations_log = _setup_mock_bin(tmp_path)
|
||||
env = {
|
||||
"PATH": f"{mock_bin}:{os.environ.get('PATH', '/usr/bin:/bin')}",
|
||||
"HOME": str(tmp_path),
|
||||
}
|
||||
if ssh_original_command is not None:
|
||||
env["SSH_ORIGINAL_COMMAND"] = ssh_original_command
|
||||
|
||||
bash_bin = shutil.which("bash") or "/bin/bash"
|
||||
proc = subprocess.run(
|
||||
[bash_bin, str(FORCE_COMMAND_SCRIPT)],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
return proc, invocations_log
|
||||
|
||||
|
||||
def test_socket_proxy_binds_loopback_only():
|
||||
"""Ensure socket-proxy publishes port 2375 strictly on 127.0.0.1."""
|
||||
compose = yaml.safe_load(COMPOSE_FILE.read_text(encoding="utf-8"))
|
||||
services = compose.get("services", {})
|
||||
assert "socket-proxy" in services, "socket-proxy service must exist"
|
||||
|
||||
ports = services["socket-proxy"].get("ports", [])
|
||||
assert isinstance(ports, list) and len(ports) > 0, (
|
||||
"socket-proxy must declare non-empty ports list"
|
||||
)
|
||||
assert all(isinstance(p, str) and p.startswith("127.0.0.1:") for p in ports), (
|
||||
f"Every socket-proxy port must bind strictly to 127.0.0.1, got: {ports!r}"
|
||||
)
|
||||
assert "127.0.0.1:2375:2375" in ports, (
|
||||
"socket-proxy must bind 127.0.0.1:2375:2375"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_agents_user_least_privilege():
|
||||
"""Verify users.users.agents has read-only groups and excludes wheel/docker."""
|
||||
content = NIXOS_CONFIG.read_text(encoding="utf-8")
|
||||
agents_block = _extract_nix_block(content, r"users\.users\.agents\s*=")
|
||||
|
||||
assert re.search(r"isNormalUser\s*=\s*true\s*;", agents_block), (
|
||||
"users.users.agents must set isNormalUser = true"
|
||||
)
|
||||
assert EXPECTED_AGENT_PUBKEY in agents_block, (
|
||||
"users.users.agents must configure the canopy-agents SSH public key"
|
||||
)
|
||||
|
||||
groups_match = re.search(r"extraGroups\s*=\s*\[(.*?)\]\s*;", agents_block, re.DOTALL)
|
||||
assert groups_match is not None, "users.users.agents must declare extraGroups"
|
||||
groups_text = groups_match.group(1)
|
||||
|
||||
actual_groups = set(re.findall(r'"([^"]+)"', groups_text))
|
||||
assert actual_groups == {"homelab-operators", "systemd-journal"}, (
|
||||
f"agents extraGroups must be strictly {{'homelab-operators', 'systemd-journal'}}, got: {actual_groups!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_openssh_match_user_agents_hardening():
|
||||
"""Verify services.openssh configures Match User agents with ForceCommand and hardening."""
|
||||
content = NIXOS_CONFIG.read_text(encoding="utf-8")
|
||||
ssh_block = _extract_nix_block(content, r"services\.openssh\s*=")
|
||||
|
||||
assert "Match User agents" in ssh_block, (
|
||||
"services.openssh must configure Match User agents"
|
||||
)
|
||||
match_section = ssh_block[ssh_block.index("Match User agents") :]
|
||||
|
||||
required_directives = [
|
||||
r"ForceCommand\s+\S*agents-force-command\b",
|
||||
r"AllowTcpForwarding\s+no",
|
||||
r"X11Forwarding\s+no",
|
||||
r"AllowAgentForwarding\s+no",
|
||||
r"PermitTTY\s+no",
|
||||
r"PasswordAuthentication\s+no",
|
||||
]
|
||||
for pattern in required_directives:
|
||||
assert re.search(pattern, match_section), (
|
||||
f"Match User agents must include directive matching: {pattern}"
|
||||
)
|
||||
|
||||
|
||||
def test_force_command_script_has_no_eval_or_sh_c():
|
||||
"""Ensure agents-force-command.sh never uses eval or subshell invocation."""
|
||||
assert FORCE_COMMAND_SCRIPT.exists(), (
|
||||
f"ForceCommand script not found at {FORCE_COMMAND_SCRIPT}"
|
||||
)
|
||||
content = FORCE_COMMAND_SCRIPT.read_text(encoding="utf-8")
|
||||
assert "eval " not in content, "Dangerous 'eval' detected in ForceCommand script"
|
||||
assert "sh -c" not in content, "Dangerous 'sh -c' detected in ForceCommand script"
|
||||
assert "bash -c" not in content, "Dangerous 'bash -c' detected in ForceCommand script"
|
||||
|
||||
|
||||
def test_force_command_exports_expected_environment(tmp_path: Path):
|
||||
"""Verify ForceCommand exports CORE_DIR, WORKLOADS_DIR, and loopback DOCKER_HOST."""
|
||||
proc, invocations_log = _run_force_command("docker ps", tmp_path)
|
||||
assert proc.returncode == 0, f"Unexpected failure: {proc.stderr}"
|
||||
lines = invocations_log.read_text(encoding="utf-8").strip().splitlines()
|
||||
assert len(lines) == 1
|
||||
cmd, args, core_dir, workloads_dir, docker_host = lines[0].split("|")
|
||||
assert cmd == "docker"
|
||||
assert args == "ps"
|
||||
assert core_dir == "/home/operator/Core"
|
||||
assert workloads_dir == "/home/operator/Workloads"
|
||||
assert docker_host == "tcp://127.0.0.1:2375"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("command", "expected_bin", "expected_args"),
|
||||
[
|
||||
("docker ps", "docker", "ps"),
|
||||
("docker ps -a --format {{.Names}}", "docker", "ps -a --format {{.Names}}"),
|
||||
("docker logs --tail 50 traefik", "docker", "logs --tail 50 traefik"),
|
||||
("docker inspect traefik", "docker", "inspect traefik"),
|
||||
(
|
||||
"journalctl -u homelab-appctl -n 50 --no-pager",
|
||||
"journalctl",
|
||||
"-u homelab-appctl -n 50 --no-pager",
|
||||
),
|
||||
("appctl list --core", "appctl", "list --core"),
|
||||
("appctl status", "appctl", "status"),
|
||||
("appctl info traefik", "appctl", "info traefik"),
|
||||
("appctl logs traefik", "appctl", "logs traefik"),
|
||||
("appctl ssl --all", "appctl", "ssl --all"),
|
||||
("appctl health", "appctl", "health"),
|
||||
("appctl resolve traefik", "appctl", "resolve traefik"),
|
||||
],
|
||||
)
|
||||
def test_force_command_allows_read_only_commands(
|
||||
tmp_path: Path, command: str, expected_bin: str, expected_args: str
|
||||
):
|
||||
"""Verify allowlisted read-only commands execute cleanly with exact arguments."""
|
||||
proc, invocations_log = _run_force_command(command, tmp_path)
|
||||
assert proc.returncode == 0, f"Allowed command '{command}' failed: {proc.stderr}"
|
||||
lines = invocations_log.read_text(encoding="utf-8").strip().splitlines()
|
||||
assert len(lines) == 1
|
||||
cmd, args, *_ = lines[0].split("|")
|
||||
assert cmd == expected_bin
|
||||
assert args == expected_args
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad_command",
|
||||
[
|
||||
None,
|
||||
"",
|
||||
" ",
|
||||
"docker ps; id",
|
||||
"docker ps && id",
|
||||
"docker ps || id",
|
||||
"docker ps | cat",
|
||||
"docker ps `id`",
|
||||
"docker ps $(id)",
|
||||
"docker ps > /tmp/pwn",
|
||||
"docker ps < /etc/passwd",
|
||||
"docker ps\nid",
|
||||
"docker ps\rid",
|
||||
"docker ps 'traefik'",
|
||||
'docker ps "traefik"',
|
||||
"docker ps \\ id",
|
||||
],
|
||||
)
|
||||
def test_force_command_rejects_empty_and_metacharacters(
|
||||
tmp_path: Path, bad_command: str | None
|
||||
):
|
||||
"""Verify empty commands and shell metacharacters are rejected without execution."""
|
||||
proc, invocations_log = _run_force_command(bad_command, tmp_path)
|
||||
assert proc.returncode != 0, f"Dangerous input was unexpectedly allowed: {bad_command!r}"
|
||||
assert not invocations_log.exists(), (
|
||||
f"Command stub should not have been executed for: {bad_command!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"disallowed_command",
|
||||
[
|
||||
"sudo id",
|
||||
"su root",
|
||||
"sh",
|
||||
"bash",
|
||||
"cat /etc/shadow",
|
||||
"rm -rf /tmp/foo",
|
||||
"systemctl restart docker",
|
||||
"docker",
|
||||
"docker run alpine",
|
||||
"docker exec -it traefik sh",
|
||||
"docker rm traefik",
|
||||
"docker build .",
|
||||
"docker stop traefik",
|
||||
"docker start traefik",
|
||||
"docker restart traefik",
|
||||
"docker kill traefik",
|
||||
"docker compose up -d",
|
||||
"docker -H unix:///var/run/docker.sock ps",
|
||||
"journalctl --flush",
|
||||
"journalctl --rotate",
|
||||
"journalctl --vacuum-size=1M",
|
||||
"journalctl --vacuum-time=1d",
|
||||
"journalctl --vacuum-files=1",
|
||||
"journalctl --relinquish-var",
|
||||
"journalctl --sync",
|
||||
"journalctl --setup-keys",
|
||||
"journalctl --update-catalog",
|
||||
"appctl",
|
||||
"appctl up traefik",
|
||||
"appctl down traefik",
|
||||
"appctl restart traefik",
|
||||
"appctl update traefik",
|
||||
"appctl pull traefik",
|
||||
"appctl sync",
|
||||
"appctl config",
|
||||
"appctl deploy traefik",
|
||||
"appctl complete services",
|
||||
],
|
||||
)
|
||||
def test_force_command_rejects_disallowed_commands_and_subcommands(
|
||||
tmp_path: Path, disallowed_command: str
|
||||
):
|
||||
"""Verify disallowed binaries, mutating subcommands, and mutating flags are rejected."""
|
||||
proc, invocations_log = _run_force_command(disallowed_command, tmp_path)
|
||||
assert proc.returncode != 0, (
|
||||
f"Disallowed command was unexpectedly allowed: {disallowed_command!r}"
|
||||
)
|
||||
assert not invocations_log.exists(), (
|
||||
f"Command stub should not have been executed for: {disallowed_command!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("subcmd", ["ps", "logs", "inspect"])
|
||||
@pytest.mark.parametrize(
|
||||
"override_flag",
|
||||
[
|
||||
"-H unix:///var/run/docker.sock",
|
||||
"-H=unix:///var/run/docker.sock",
|
||||
"--host unix:///var/run/docker.sock",
|
||||
"--host=unix:///var/run/docker.sock",
|
||||
"--context default",
|
||||
"--context=default",
|
||||
"-c default",
|
||||
"-c=default",
|
||||
"--config /tmp",
|
||||
"--config=/tmp",
|
||||
],
|
||||
)
|
||||
def test_force_command_rejects_post_subcommand_docker_override_flags(
|
||||
tmp_path: Path, subcmd: str, override_flag: str
|
||||
):
|
||||
"""Verify Docker connection/context/config override flags are rejected after valid subcommands."""
|
||||
command = f"docker {subcmd} {override_flag}"
|
||||
proc, invocations_log = _run_force_command(command, tmp_path)
|
||||
assert proc.returncode != 0, (
|
||||
f"Docker override flag was unexpectedly allowed: {command!r}"
|
||||
)
|
||||
assert not invocations_log.exists(), (
|
||||
f"Command stub should not have been executed for: {command!r}"
|
||||
)
|
||||
+1038
-160
File diff suppressed because it is too large.
Load diff
@@ -2,19 +2,24 @@
|
||||
Security invariant tests for Docker Compose and container isolation.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
from appctl_audit import AuditLogger, TargetLockManager
|
||||
from appctl_auth import Principal, Role
|
||||
from appctl_contracts import OperationRequest
|
||||
from appctl_router import OperationalRouter, assemble_workload_env
|
||||
from core_manifest import parse_manifest
|
||||
|
||||
# Comment-out reason: testing pyproject-level pythonpath definition
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
|
||||
|
||||
def test_socket_proxy_is_strictly_read_only():
|
||||
|
||||
"""Ensure socket-proxy container blocks state-modifying requests (POST=0, DELETE=0)."""
|
||||
compose_path = CORE_ROOT / "docker-compose.yml"
|
||||
with open(compose_path, encoding="utf-8") as f:
|
||||
@@ -47,8 +52,12 @@ def test_no_direct_docker_sock_mounts_except_socket_proxy():
|
||||
volumes = svc.get("volumes", [])
|
||||
for vol in volumes:
|
||||
if isinstance(vol, str) and "/var/run/docker.sock" in vol:
|
||||
assert name == "socket-proxy", f"Service '{name}' directly mounts docker.sock!"
|
||||
assert vol.endswith(":ro"), "socket-proxy docker.sock mount must be read-only (:ro)"
|
||||
assert name == "socket-proxy", (
|
||||
f"Service '{name}' directly mounts docker.sock!"
|
||||
)
|
||||
assert vol.endswith(":ro"), (
|
||||
"socket-proxy docker.sock mount must be read-only (:ro)"
|
||||
)
|
||||
|
||||
|
||||
def test_no_privileged_containers():
|
||||
@@ -60,7 +69,9 @@ def test_no_privileged_containers():
|
||||
services = compose.get("services", {})
|
||||
for name, svc in services.items():
|
||||
privileged = svc.get("privileged", False)
|
||||
assert privileged is not True, f"Service '{name}' is configured as privileged: true!"
|
||||
assert privileged is not True, (
|
||||
f"Service '{name}' is configured as privileged: true!"
|
||||
)
|
||||
|
||||
|
||||
def test_no_shell_true_in_core_scripts():
|
||||
@@ -78,10 +89,14 @@ def test_portainer_is_deprecated_and_absent():
|
||||
compose = yaml.safe_load(f)
|
||||
|
||||
services = compose.get("services", {})
|
||||
assert "portainer" not in services, "Deprecated service 'portainer' must not exist in docker-compose.yml"
|
||||
assert "portainer" not in services, (
|
||||
"Deprecated service 'portainer' must not exist in docker-compose.yml"
|
||||
)
|
||||
|
||||
volumes = compose.get("volumes", {}) or {}
|
||||
assert "portainer_data" not in volumes, "Deprecated volume 'portainer_data' must not exist in docker-compose.yml"
|
||||
assert "portainer_data" not in volumes, (
|
||||
"Deprecated volume 'portainer_data' must not exist in docker-compose.yml"
|
||||
)
|
||||
|
||||
|
||||
def test_no_eval_in_appctl_script():
|
||||
@@ -91,10 +106,9 @@ def test_no_eval_in_appctl_script():
|
||||
assert "eval " not in content, "Dangerous 'eval' detected in scripts/appctl!"
|
||||
|
||||
|
||||
def test_appctl_env_injection_resilience(tmp_path: Path):
|
||||
def test_appctl_env_injection_resilience(tmp_path: Path, monkeypatch):
|
||||
"""Ensure environment values from app.yaml cannot execute shell commands via command substitution
|
||||
|
||||
in scripts/appctl during environment setup. Executes scripts/appctl directly with a mock docker binary.
|
||||
during P4 production environment assembly and router dispatch. Executes OperationalRouter with a mock docker binary.
|
||||
"""
|
||||
canary = tmp_path / "pwned.txt"
|
||||
payload = f"$(touch {canary})"
|
||||
@@ -113,16 +127,26 @@ env:
|
||||
"""
|
||||
|
||||
(app_dir / "app.yaml").write_text(app_yaml.strip(), encoding="utf-8")
|
||||
(app_dir / "docker-compose.yml").write_text("services:\n web:\n image: nginx\n", encoding="utf-8")
|
||||
(app_dir / "docker-compose.yml").write_text(
|
||||
"services:\n web:\n image: nginx\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
# 2. Setup mock docker binary to capture environment without requiring a running Docker daemon
|
||||
# 2. Verify unit-level pure Python environment assembly
|
||||
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
|
||||
manifest = parse_manifest(app_dir / "app.yaml")
|
||||
assembled_env = assemble_workload_env(app_dir, manifest, "vuln-app")
|
||||
assert not canary.exists(), "Command substitution executed during assemble_workload_env!"
|
||||
assert assembled_env["INJECTION_TEST"] == payload
|
||||
assert assembled_env["NORMAL_VAR"] == "safe_value"
|
||||
|
||||
# 3. Setup mock docker binary to capture environment without requiring a running Docker daemon
|
||||
mock_bin = tmp_path / "bin"
|
||||
mock_bin.mkdir()
|
||||
mock_docker = mock_bin / "docker"
|
||||
bash_bin = shutil.which("bash") or "bash"
|
||||
|
||||
mock_docker_script = f"""#!{bash_bin}
|
||||
if [ "$1" = "compose" ] && [ "$2" = "config" ]; then
|
||||
if [ "$1" = "compose" ] && [ "$4" = "config" ]; then
|
||||
echo "MOCK_DOCKER_COMPOSE_CONFIG"
|
||||
echo "CAPTURED_INJECTION=$INJECTION_TEST"
|
||||
echo "CAPTURED_NORMAL=$NORMAL_VAR"
|
||||
@@ -133,45 +157,60 @@ exit 0
|
||||
mock_docker.write_text(mock_docker_script, encoding="utf-8")
|
||||
mock_docker.chmod(0o755)
|
||||
|
||||
# 3. Execute scripts/appctl config vuln-app directly
|
||||
appctl_path = CORE_ROOT / "scripts" / "appctl"
|
||||
env = os.environ.copy()
|
||||
if "NIX_PYTHONPATH" in env and "PYTHONPATH" not in env:
|
||||
env["PYTHONPATH"] = env["NIX_PYTHONPATH"]
|
||||
env["PATH"] = f"{mock_bin}:{Path(sys.executable).parent}:{env['PATH']}"
|
||||
env["PYTHON_BIN"] = sys.executable
|
||||
env["SITES_DIR"] = str(sites_dir)
|
||||
env["HOMELAB_DOMAIN"] = "example.test"
|
||||
env["CORE_DIR"] = str(CORE_ROOT)
|
||||
|
||||
res = subprocess.run(
|
||||
[bash_bin, str(appctl_path), "config", "vuln-app"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
# 4. Dispatch workload.config through OperationalRouter
|
||||
monkeypatch.setenv("PATH", f"{mock_bin}:{os.environ.get('PATH', '')}")
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=sites_dir,
|
||||
core_dir=CORE_ROOT,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "workload.config",
|
||||
"target": "vuln-app",
|
||||
})
|
||||
admin_principal = Principal(
|
||||
identity="operator",
|
||||
role=Role.ADMIN,
|
||||
token_id="tok_admin",
|
||||
auth_method="bearer_token",
|
||||
)
|
||||
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
|
||||
# 4. Assertions: command substitution was not executed, script ran, and mock docker received literal value
|
||||
assert not canary.exists(), "Command substitution was executed on the host during environment setup!"
|
||||
assert res.returncode == 0, f"appctl config failed: {res.stderr}\nStdout: {res.stdout}"
|
||||
assert "MOCK_DOCKER_COMPOSE_CONFIG" in res.stdout
|
||||
assert f"CAPTURED_INJECTION={payload}" in res.stdout
|
||||
assert "CAPTURED_NORMAL=safe_value" in res.stdout
|
||||
assert "/dangerous/override" not in res.stdout
|
||||
# 5. Assertions: command substitution was not executed, router succeeded, mock docker received literal value
|
||||
assert not canary.exists(), (
|
||||
"Command substitution was executed on the host during environment setup!"
|
||||
)
|
||||
assert resp.success is True, (
|
||||
f"OperationalRouter dispatch failed: {resp.error}"
|
||||
)
|
||||
assert resp.result is not None
|
||||
output = resp.result.get("output", "")
|
||||
assert "MOCK_DOCKER_COMPOSE_CONFIG" in output
|
||||
assert f"CAPTURED_INJECTION={payload}" in output
|
||||
assert "CAPTURED_NORMAL=safe_value" in output
|
||||
|
||||
|
||||
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",
|
||||
CORE_ROOT / "nixos" / "configuration.nix",
|
||||
CORE_ROOT / "nixos" / "instance.example.nix",
|
||||
]
|
||||
violations = []
|
||||
|
||||
@@ -182,15 +221,352 @@ def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests(
|
||||
for file_path in candidate_files:
|
||||
if (
|
||||
file_path.is_file()
|
||||
and file_path.suffix in (".py", ".sh", ".bash", ".yml", ".yaml", ".md", ".nix", "")
|
||||
and file_path.suffix
|
||||
in (".py", ".sh", ".bash", ".yml", ".yaml", ".md", ".nix", "")
|
||||
and file_path.name != "test_security_invariants.py"
|
||||
):
|
||||
content = file_path.read_text(encoding="utf-8", errors="ignore")
|
||||
for term in forbidden:
|
||||
if term in content:
|
||||
violations.append(f"{file_path.relative_to(CORE_ROOT)}: contains prohibited literal '{term}'")
|
||||
violations.append(
|
||||
f"{file_path.relative_to(CORE_ROOT)}: contains prohibited literal '{term}'"
|
||||
)
|
||||
|
||||
assert not violations, "Platform genericism violations detected:\n" + "\n".join(violations)
|
||||
assert not violations, "Platform genericism violations detected:\n" + "\n".join(
|
||||
violations
|
||||
)
|
||||
|
||||
|
||||
def test_docker_compose_authelia_and_lldap_base_dn():
|
||||
"""Ensure both lldap and authelia services receive LLDAP_LDAP_BASE_DN in docker-compose.yml."""
|
||||
compose_path = CORE_ROOT / "docker-compose.yml"
|
||||
with open(compose_path, encoding="utf-8") as f:
|
||||
compose = yaml.safe_load(f)
|
||||
|
||||
services = compose.get("services", {})
|
||||
assert "lldap" in services, "lldap service must exist in docker-compose.yml"
|
||||
assert "authelia" in services, "authelia service must exist in docker-compose.yml"
|
||||
|
||||
def get_env_map(svc_def: dict) -> dict[str, str]:
|
||||
env_items = svc_def.get("environment", [])
|
||||
res = {}
|
||||
for item in env_items:
|
||||
if isinstance(item, str) and "=" in item:
|
||||
k, v = item.split("=", 1)
|
||||
res[k.strip()] = v.strip()
|
||||
return res
|
||||
|
||||
lldap_env = get_env_map(services["lldap"])
|
||||
authelia_env = get_env_map(services["authelia"])
|
||||
|
||||
assert "LLDAP_LDAP_BASE_DN" in lldap_env, (
|
||||
"LLDAP_LDAP_BASE_DN must be declared in lldap environment"
|
||||
)
|
||||
assert "LLDAP_LDAP_BASE_DN" in authelia_env, (
|
||||
"LLDAP_LDAP_BASE_DN must be passed to authelia environment for LDAP template expansion"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_homeserver_env_template_defines_dynamic_base_dn():
|
||||
"""Ensure homeserver.nix derives LLDAP_LDAP_BASE_DN dynamically from homelab.domain."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert "LLDAP_LDAP_BASE_DN" in content, (
|
||||
"homeserver.nix must define LLDAP_LDAP_BASE_DN in homeserver.env template"
|
||||
)
|
||||
assert 'lib.splitString "."' in content or "splitString" in content, (
|
||||
"homeserver.nix must compute LDAP base DN dynamically from domain components"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_tmpfiles_rules_use_recursive_acls():
|
||||
"""Ensure tmpfiles.rules uses uppercase A+ for recursive ACL inheritance on sites and homepage."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert '"A+ ${config.homelab.sitesDir}' in content, (
|
||||
"tmpfiles.rules must use uppercase 'A+' for recursive ACL inheritance on sitesDir"
|
||||
)
|
||||
assert '"A+ ${config.homelab.coreDir}/config/homepage' in content, (
|
||||
"tmpfiles.rules must use uppercase 'A+' for recursive ACL inheritance on homepage config"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_tmpfiles_rules_creates_operator_var_lib_homelab():
|
||||
"""Ensure tmpfiles.rules creates operator var/lib/homelab state dir before ACL assignment (#22)."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
expected_create = '"d /home/${config.homelab.operatorUser}/var/lib/homelab 0755 ${config.homelab.operatorUser} users -"'
|
||||
expected_acl = '"A+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"'
|
||||
|
||||
assert expected_create in content, (
|
||||
"tmpfiles.rules must declare creation of operator var/lib/homelab directory"
|
||||
)
|
||||
assert expected_acl in content, (
|
||||
"tmpfiles.rules must declare ACLs for operator var/lib/homelab directory"
|
||||
)
|
||||
assert content.index(expected_create) < content.index(expected_acl), (
|
||||
"operator var/lib/homelab directory creation must precede its ACL rule"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_appctl_readwritepaths_optional_prefixes():
|
||||
"""Ensure appctl service ReadWritePaths uses '-' prefix for optional runtime paths (#22)."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert '"-/home/${config.homelab.operatorUser}/var/lib/homelab"' in content
|
||||
assert '"-${config.homelab.coreDir}/config/homepage"' in content
|
||||
assert '"-/var/lib/homelab/appctl"' in content
|
||||
assert '"-/run/homelab"' in content
|
||||
|
||||
|
||||
def test_nixos_gitops_orders_after_appctl():
|
||||
"""Ensure homelab-gitops service declares after and wants dependency on homelab-appctl.service (#22)."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert '"homelab-appctl.service"' in content
|
||||
|
||||
nix_bin = shutil.which("nix")
|
||||
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
|
||||
for attr in ["after", "wants"]:
|
||||
cmd = [
|
||||
nix_bin,
|
||||
"eval",
|
||||
f".#nixosConfigurations.server.config.systemd.services.homelab-gitops.{attr}",
|
||||
"--json",
|
||||
]
|
||||
res = subprocess.run(
|
||||
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
|
||||
)
|
||||
data = json.loads(res.stdout)
|
||||
assert "homelab-appctl.service" in data, (
|
||||
f"homelab-gitops {attr} must include homelab-appctl.service"
|
||||
)
|
||||
|
||||
|
||||
def test_default_homelab_domain_evaluates_to_example_test():
|
||||
"""Assert default homelab.domain in NixOS config evaluates to 'example.test'."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
assert 'default = "example.test";' in content, (
|
||||
"homeserver.nix must set default homelab.domain to 'example.test'"
|
||||
)
|
||||
|
||||
nix_bin = shutil.which("nix")
|
||||
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
|
||||
cmd = [
|
||||
nix_bin,
|
||||
"eval",
|
||||
".#nixosConfigurations.server.config.homelab.domain",
|
||||
"--raw",
|
||||
]
|
||||
res = subprocess.run(
|
||||
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
|
||||
)
|
||||
assert res.stdout.strip() == "example.test", (
|
||||
f"Default homelab.domain must be 'example.test', got '{res.stdout.strip()}'"
|
||||
)
|
||||
|
||||
|
||||
def test_dynamic_lldap_base_dn_splits_domain_components():
|
||||
"""Assert dynamic LLDAP_LDAP_BASE_DN splits domain into dc=... components for any domain."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
assert "LLDAP_LDAP_BASE_DN = ldapBaseDn;" in content, (
|
||||
"homeserver.nix must bind LLDAP_LDAP_BASE_DN to ldapBaseDn in homeserver.env template"
|
||||
)
|
||||
assert 'domainParts = lib.splitString "." config.homelab.domain;' in content, (
|
||||
"homeserver.nix must split homelab.domain by '.'"
|
||||
)
|
||||
assert 'ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts);' in content, (
|
||||
"homeserver.nix must map domain components into dc=${part}"
|
||||
)
|
||||
|
||||
nix_bin = shutil.which("nix")
|
||||
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
|
||||
cases = [
|
||||
("example.test", "dc=example,dc=test"),
|
||||
("my.homelab.internal", "dc=my,dc=homelab,dc=internal"),
|
||||
("local", "dc=local"),
|
||||
]
|
||||
for domain, expected_dn in cases:
|
||||
expr = (
|
||||
f'let flake = builtins.getFlake (toString ./.); lib = flake.inputs.nixpkgs.lib; '
|
||||
f'domainParts = lib.splitString "." "{domain}"; '
|
||||
f'in lib.concatStringsSep "," (map (part: "dc=${{part}}") domainParts)'
|
||||
)
|
||||
cmd = [
|
||||
nix_bin,
|
||||
"eval",
|
||||
"--impure",
|
||||
"--expr",
|
||||
expr,
|
||||
"--raw",
|
||||
]
|
||||
res = subprocess.run(
|
||||
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
|
||||
)
|
||||
assert res.stdout.strip() == expected_dn, (
|
||||
f"Expected {expected_dn} for domain {domain}, got {res.stdout.strip()}"
|
||||
)
|
||||
|
||||
# Also assert rendered sops template in default configuration contains correct LLDAP_LDAP_BASE_DN
|
||||
cmd_tpl = [
|
||||
nix_bin,
|
||||
"eval",
|
||||
'.#nixosConfigurations.server.config.sops.templates."homeserver.env".content',
|
||||
"--raw",
|
||||
]
|
||||
res_tpl = subprocess.run(
|
||||
cmd_tpl, cwd=CORE_ROOT, capture_output=True, text=True, check=True
|
||||
)
|
||||
assert "LLDAP_LDAP_BASE_DN=dc=example,dc=test" in res_tpl.stdout
|
||||
|
||||
|
||||
def test_dual_path_import_overrides_homelab_domain():
|
||||
"""Assert dual-path import overrides homelab.domain when ./nixos/instance.nix is present."""
|
||||
nix_bin = shutil.which("nix")
|
||||
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
|
||||
instance_nix = CORE_ROOT / "nixos" / "instance.nix"
|
||||
try:
|
||||
instance_nix.write_text(
|
||||
'{ homelab.domain = "custom.internal"; }\n', encoding="utf-8"
|
||||
)
|
||||
cmd = [
|
||||
nix_bin,
|
||||
"eval",
|
||||
"--impure",
|
||||
"path:.#nixosConfigurations.server.config.homelab.domain",
|
||||
"--raw",
|
||||
]
|
||||
res = subprocess.run(
|
||||
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
|
||||
)
|
||||
assert res.stdout.strip() == "custom.internal", (
|
||||
f"Expected homelab.domain to be overridden to 'custom.internal', got '{res.stdout.strip()}'"
|
||||
)
|
||||
finally:
|
||||
if instance_nix.exists():
|
||||
instance_nix.unlink()
|
||||
|
||||
|
||||
def test_nixos_configuration_declares_dual_path_instance_imports():
|
||||
"""Ensure nixos/configuration.nix includes optional dual-path instance imports."""
|
||||
config_nix = CORE_ROOT / "nixos" / "configuration.nix"
|
||||
content = config_nix.read_text(encoding="utf-8")
|
||||
assert "builtins.pathExists ./instance.nix" in content, (
|
||||
"nixos/configuration.nix must check for ./instance.nix via builtins.pathExists"
|
||||
)
|
||||
assert "builtins.pathExists /etc/nixos/homelab-instance.nix" in content, (
|
||||
"nixos/configuration.nix must check for /etc/nixos/homelab-instance.nix via builtins.pathExists"
|
||||
)
|
||||
|
||||
|
||||
def test_gitignore_includes_instance_nix():
|
||||
"""Ensure nixos/instance.nix is ignored in .gitignore to preserve platform genericism."""
|
||||
gitignore = CORE_ROOT / ".gitignore"
|
||||
content = gitignore.read_text(encoding="utf-8")
|
||||
lines = [line.strip() for line in content.splitlines()]
|
||||
assert "nixos/instance.nix" in lines, (
|
||||
"nixos/instance.nix must be explicitly ignored in .gitignore"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_switch_alias_uses_path_and_impure():
|
||||
"""Ensure nix-switch alias in nixos/modules/shell.nix uses path: and --impure to prevent silent fail-open."""
|
||||
shell_nix = CORE_ROOT / "nixos" / "modules" / "shell.nix"
|
||||
content = shell_nix.read_text(encoding="utf-8")
|
||||
assert 'nix-switch = "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure";' in content, (
|
||||
"nixos/modules/shell.nix must configure nix-switch alias with path:$HOME/Core#server --impure"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_safe_directory_includes_core_and_sites():
|
||||
"""Ensure programs.git.config.safe.directory includes Core, Workloads, and Sites to prevent dubious ownership errors."""
|
||||
config_nix = CORE_ROOT / "nixos" / "configuration.nix"
|
||||
content = config_nix.read_text(encoding="utf-8")
|
||||
assert '"/home/${config.homelab.operatorUser}/Core"' in content, (
|
||||
"nixos/configuration.nix must include Core in git safe.directory"
|
||||
)
|
||||
assert '"/home/${config.homelab.operatorUser}/Workloads"' in content, (
|
||||
"nixos/configuration.nix must include Workloads in git safe.directory"
|
||||
)
|
||||
assert '"/home/${config.homelab.operatorUser}/Workloads/*"' in content, (
|
||||
"nixos/configuration.nix must include Workloads/* in git safe.directory"
|
||||
)
|
||||
assert '"/home/${config.homelab.operatorUser}/Sites/*"' in content, (
|
||||
"nixos/configuration.nix must include Sites/* in git safe.directory"
|
||||
)
|
||||
|
||||
nix_bin = shutil.which("nix")
|
||||
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
|
||||
cmd = [
|
||||
nix_bin,
|
||||
"eval",
|
||||
".#nixosConfigurations.server.config.programs.git.config",
|
||||
"--json",
|
||||
]
|
||||
res = subprocess.run(
|
||||
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
|
||||
)
|
||||
import json
|
||||
|
||||
configs = json.loads(res.stdout)
|
||||
safe_dirs = []
|
||||
for cfg in configs:
|
||||
if isinstance(cfg, dict) and "safe" in cfg and "directory" in cfg["safe"]:
|
||||
dirs = cfg["safe"]["directory"]
|
||||
if isinstance(dirs, list):
|
||||
safe_dirs.extend(dirs)
|
||||
else:
|
||||
safe_dirs.append(dirs)
|
||||
|
||||
assert "/home/operator/Core" in safe_dirs, (
|
||||
f"Expected '/home/operator/Core' in git safe.directory, got {safe_dirs}"
|
||||
)
|
||||
assert "/home/operator/Workloads" in safe_dirs, (
|
||||
f"Expected '/home/operator/Workloads' in git safe.directory, got {safe_dirs}"
|
||||
)
|
||||
assert "/home/operator/Workloads/*" in safe_dirs, (
|
||||
f"Expected '/home/operator/Workloads/*' in git safe.directory, got {safe_dirs}"
|
||||
)
|
||||
assert "/home/operator/Sites/*" in safe_dirs, (
|
||||
f"Expected '/home/operator/Sites/*' in git safe.directory, got {safe_dirs}"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_homeserver_defaults_to_workloads_dir():
|
||||
"""Ensure homeserver.nix defaults sitesDir to ~/Workloads and exports WORKLOADS_DIR + SITES_DIR (#33)."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert 'default = "/home/${config.homelab.operatorUser}/Workloads";' in content, (
|
||||
"homelab.sitesDir must default to /home/${config.homelab.operatorUser}/Workloads"
|
||||
)
|
||||
assert "WORKLOADS_DIR = config.homelab.sitesDir;" in content, (
|
||||
"homeserver.nix must export WORKLOADS_DIR"
|
||||
)
|
||||
assert "SITES_DIR = config.homelab.sitesDir;" in content, (
|
||||
"homeserver.nix must export SITES_DIR for backward compatibility"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_workload_grants_option_and_projection():
|
||||
"""Ensure homeserver.nix defines homelab.workloadGrants, /etc/homelab/grants.json, and HOMELAB_GRANTS_FILE."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert "workloadGrants = lib.mkOption" in content
|
||||
assert 'environment.etc."homelab/grants.json"' in content
|
||||
assert 'user = "root";' in content
|
||||
assert 'group = "homelab-operators";' in content
|
||||
assert 'mode = "0640";' in content
|
||||
assert content.count('HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";') >= 2
|
||||
assert "PrivateUsers" not in content
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ def test_required_architectural_paths_exist():
|
||||
"SECURITY.md",
|
||||
"nixos",
|
||||
"nixos/configuration.nix",
|
||||
"nixos/instance.example.nix",
|
||||
"nixos/modules/homeserver.nix",
|
||||
"nixos/secrets.yaml",
|
||||
"scripts/gitops_dispatcher.py",
|
||||
@@ -36,7 +37,9 @@ def test_required_architectural_paths_exist():
|
||||
|
||||
pre_commit = CORE_ROOT / ".githooks" / "pre-commit"
|
||||
assert pre_commit.is_file(), ".githooks/pre-commit must be a regular file"
|
||||
assert os.access(pre_commit, os.X_OK), ".githooks/pre-commit must be marked executable"
|
||||
assert os.access(pre_commit, os.X_OK), (
|
||||
".githooks/pre-commit must be marked executable"
|
||||
)
|
||||
|
||||
|
||||
def test_deprecated_legacy_structures_are_absent():
|
||||
@@ -61,4 +64,7 @@ def test_unlicense_preserved():
|
||||
unlicense = CORE_ROOT / "UNLICENSE"
|
||||
assert unlicense.is_file(), "UNLICENSE file must be present"
|
||||
content = unlicense.read_text(encoding="utf-8")
|
||||
assert "This is free and unencumbered software released into the public domain." in content
|
||||
assert (
|
||||
"This is free and unencumbered software released into the public domain."
|
||||
in content
|
||||
)
|
||||
@@ -0,0 +1,373 @@
|
||||
"""
|
||||
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 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.target == "jellyfin"
|
||||
assert evt_comp.parameters == {"expected_branch": "main", "build": False}
|
||||
assert evt_comp.result is not None
|
||||
assert evt_comp.result.status == "SUCCESS"
|
||||
assert evt_comp.result.exit_code == 0
|
||||
assert evt_comp.result.duration_ms == 1450
|
||||
assert evt_comp.result.message == "Workload updated and reconciled successfully"
|
||||
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.target == "jellyfin"
|
||||
assert event.parameters == {"recreate": True}
|
||||
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"
|
||||
assert event.result.duration_ms == 320
|
||||
assert event.result.message == "Docker compose failed with exit code 1"
|
||||
|
||||
|
||||
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_redact_sensitive_data_masks_bare_keys():
|
||||
"""Ensure bare keys (token, secret, password, key, pass, hash) without underscores are redacted (CR-DI-04)."""
|
||||
raw_params = {
|
||||
"token": "tok_12345",
|
||||
"secret": "shh_secret",
|
||||
"password": "mypassword",
|
||||
"key": "encryption_key",
|
||||
"pass": "quick_pass",
|
||||
"hash": "$2b$12$hashval",
|
||||
"TOKEN": "uppercase_tok",
|
||||
"SECRET": "uppercase_sec",
|
||||
"normal_field": "keep_this",
|
||||
}
|
||||
redacted = redact_sensitive_data(raw_params)
|
||||
assert redacted["token"] == "[REDACTED]"
|
||||
assert redacted["secret"] == "[REDACTED]"
|
||||
assert redacted["password"] == "[REDACTED]"
|
||||
assert redacted["key"] == "[REDACTED]"
|
||||
assert redacted["pass"] == "[REDACTED]"
|
||||
assert redacted["hash"] == "[REDACTED]"
|
||||
assert redacted["TOKEN"] == "[REDACTED]"
|
||||
assert redacted["SECRET"] == "[REDACTED]"
|
||||
assert redacted["normal_field"] == "keep_this"
|
||||
|
||||
|
||||
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
|
||||
):
|
||||
# Using a directory as the audit path causes os.open with O_WRONLY to fail with
|
||||
# EISDIR / OSError across all platforms and environments (including root containers).
|
||||
unwritable_target = tmp_path / "unwritable_audit_dir"
|
||||
unwritable_target.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
logger = AuditLogger(unwritable_target)
|
||||
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)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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"
|
||||
|
||||
|
||||
def test_target_lock_manager_sanitizes_special_characters_and_supports_env(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
custom_lock_dir = tmp_path / "custom_locks"
|
||||
monkeypatch.setenv("APPCTL_LOCK_DIR", str(custom_lock_dir))
|
||||
manager = TargetLockManager()
|
||||
assert manager.lock_dir == custom_lock_dir
|
||||
|
||||
with manager.lock_target("special/tenant:workload@v1!#$") as lock:
|
||||
assert lock.lock_path.name == "special_tenant_workload_v1___.lock"
|
||||
assert lock.lock_path.exists()
|
||||
@@ -0,0 +1,536 @@
|
||||
"""
|
||||
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_authenticates_uppercase_hex_descriptor(tmp_path: Path):
|
||||
"""Ensure tokens with uppercase hex characters in tokens.json authenticate cleanly (CR-DI-10)."""
|
||||
raw_secret = "my_custom_secret_token"
|
||||
raw_hash_upper = hashlib.sha256(raw_secret.encode("utf-8")).hexdigest().upper()
|
||||
tokens_file = tmp_path / "upper_tokens.json"
|
||||
tokens_file.write_text(
|
||||
json.dumps(
|
||||
[
|
||||
{
|
||||
"token_id": "tok_upper_01",
|
||||
"identity": "upper-user",
|
||||
"role": "homelab-operator",
|
||||
"sha256": raw_hash_upper,
|
||||
}
|
||||
]
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
os.chmod(tokens_file, 0o400)
|
||||
store = TokenStore(tokens_file)
|
||||
principal = store.authenticate_bearer(raw_secret)
|
||||
assert principal.identity == "upper-user"
|
||||
assert principal.role == Role.OPERATOR
|
||||
|
||||
|
||||
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_handles_aliases_edge_cases_and_json(tmp_path: Path):
|
||||
deploy_file = tmp_path / "deployments.json"
|
||||
deploy_file.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"repositories": {
|
||||
"app1": {
|
||||
"path": "/home/operator/Sites/app1",
|
||||
"aliases": [123, None, " ", "valid_alias"],
|
||||
}
|
||||
}
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
admitted = load_admitted_workloads(deploy_file)
|
||||
assert "app1" in admitted
|
||||
assert "valid_alias" in admitted
|
||||
assert 123 not in admitted
|
||||
assert None not in admitted
|
||||
assert "" not in admitted
|
||||
|
||||
|
||||
def test_load_admitted_workloads_fails_closed_on_missing_file(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
admitted = load_admitted_workloads(tmp_path / "missing.yaml")
|
||||
assert admitted == set()
|
||||
|
||||
# Test HOMELAB_DEPLOYMENTS_FILE fallback
|
||||
deploy_file = tmp_path / "env_deploy.yaml"
|
||||
deploy_file.write_text(
|
||||
"repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8"
|
||||
)
|
||||
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deploy_file))
|
||||
admitted_env = load_admitted_workloads(None)
|
||||
assert "env_app" in admitted_env
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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
|
||||
)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_operator_denied_on_case_variant_core_targets(admitted_workloads: set[str]):
|
||||
"""Ensure case variants ('Core', 'TRAEFIK', 'Authelia') are rejected for operator role (CR-DI-06)."""
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
for variant in ["Core", "CORE", "Traefik", "TRAEFIK", "Authelia"]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, variant, admitted_workloads)
|
||||
assert "not permitted to target core service" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
|
||||
def test_rbac_operator_denied_without_target_on_mutating_or_sensitive_ops(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(
|
||||
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
|
||||
)
|
||||
|
||||
for op in [
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_CONFIG,
|
||||
OperationType.WORKLOAD_LOGS,
|
||||
]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, op, None, admitted_workloads)
|
||||
assert f"Operation '{op.value}' requires an explicit workload target" in str(
|
||||
exc_info.value
|
||||
)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, op, "", admitted_workloads)
|
||||
assert f"Operation '{op.value}' requires an explicit workload target" in str(
|
||||
exc_info.value
|
||||
)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_operator_with_default_admitted_workloads(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
):
|
||||
deployments_file = tmp_path / "deployments.yaml"
|
||||
deployments_file.write_text(
|
||||
"repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8"
|
||||
)
|
||||
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file))
|
||||
|
||||
operator = Principal(
|
||||
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
|
||||
)
|
||||
enforce_rbac(
|
||||
operator, OperationType.WORKLOAD_DEPLOY, "customapp", admitted_workloads=None
|
||||
)
|
||||
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(
|
||||
operator,
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
"unknownapp",
|
||||
admitted_workloads=None,
|
||||
)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_default_deployments_file_resolves_to_workloads_dir(
|
||||
tmp_path: Path, run_isolated_script_expr
|
||||
):
|
||||
"""DEFAULT_DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml."""
|
||||
resolved = run_isolated_script_expr(
|
||||
"import appctl_auth; print(appctl_auth.DEFAULT_DEPLOYMENTS_FILE)"
|
||||
)
|
||||
assert Path(resolved) == tmp_path / "Workloads" / "deployments.yaml"
|
||||
|
||||
|
||||
def test_load_admitted_workloads_fails_closed_when_absent(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
"""Absent ~/Workloads/deployments.yaml fails closed (empty set, no CORE_DIR fallback)."""
|
||||
import appctl_auth
|
||||
|
||||
monkeypatch.delenv("HOMELAB_DEPLOYMENTS_FILE", raising=False)
|
||||
monkeypatch.delenv("WORKLOADS_DIR", raising=False)
|
||||
monkeypatch.delenv("SITES_DIR", raising=False)
|
||||
monkeypatch.setattr(
|
||||
appctl_auth, "DEFAULT_DEPLOYMENTS_FILE", tmp_path / "Workloads" / "deployments.yaml"
|
||||
)
|
||||
assert appctl_auth.load_admitted_workloads() == set()
|
||||
|
||||
|
||||
def test_load_admitted_workloads_honors_workloads_dir_override(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
"""WORKLOADS_DIR takes precedence when HOMELAB_DEPLOYMENTS_FILE is unset."""
|
||||
import appctl_auth
|
||||
|
||||
custom_workloads = tmp_path / "CustomWorkloads"
|
||||
custom_workloads.mkdir()
|
||||
(custom_workloads / "deployments.yaml").write_text(
|
||||
"repositories:\n custom_app:\n path: ~/Workloads/custom_app\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.delenv("HOMELAB_DEPLOYMENTS_FILE", raising=False)
|
||||
monkeypatch.setenv("WORKLOADS_DIR", str(custom_workloads))
|
||||
assert appctl_auth.load_admitted_workloads() == {"custom_app"}
|
||||
@@ -0,0 +1,596 @@
|
||||
"""
|
||||
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_up_and_deploy_build_and_no_cache_flags():
|
||||
"""Ensure appctl up/deploy with --build and --no-cache flags dispatches correct parameters."""
|
||||
mock_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_build_01",
|
||||
operation=OperationType.WORKLOAD_DEPLOY,
|
||||
target="jellyfin",
|
||||
result={"action": "deployed", "message": "Workload deployed"},
|
||||
)
|
||||
|
||||
# 1. up with --build
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["up", "jellyfin", "--build", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req: OperationRequest = mock_send.call_args[1]["operation_request"]
|
||||
assert req.operation == OperationType.WORKLOAD_DEPLOY
|
||||
assert req.parameters.get("build") is True
|
||||
assert req.parameters.get("no_cache") is False
|
||||
|
||||
# 2. up with --no-cache implies build=True
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["up", "jellyfin", "--no-cache", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req = mock_send.call_args[1]["operation_request"]
|
||||
assert req.parameters.get("no_cache") is True
|
||||
assert req.parameters.get("build") is True
|
||||
|
||||
# 3. deploy alias with --no-cache
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["deploy", "jellyfin", "--no-cache", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req = mock_send.call_args[1]["operation_request"]
|
||||
assert req.parameters.get("no_cache") is True
|
||||
assert req.parameters.get("build") is True
|
||||
|
||||
|
||||
def test_cli_update_build_and_no_cache_flags():
|
||||
"""Ensure appctl update with --build and --no-cache flags dispatches correct parameters."""
|
||||
mock_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_upd_01",
|
||||
operation=OperationType.WORKLOAD_UPDATE,
|
||||
target="jellyfin",
|
||||
result={"action": "updated", "message": "Workload updated"},
|
||||
)
|
||||
|
||||
# 1. update with --build
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["update", "jellyfin", "--build", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req: OperationRequest = mock_send.call_args[1]["operation_request"]
|
||||
assert req.operation == OperationType.WORKLOAD_UPDATE
|
||||
assert req.parameters.get("build") is True
|
||||
assert req.parameters.get("no_cache", False) is False
|
||||
|
||||
# 2. update with --no-cache implies build=True
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["update", "jellyfin", "--no-cache", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req = mock_send.call_args[1]["operation_request"]
|
||||
assert req.parameters.get("no_cache") is True
|
||||
assert req.parameters.get("build") is True
|
||||
|
||||
# 3. update with --branch and --no-cache
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["update", "jellyfin", "--branch", "main", "--no-cache", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req = mock_send.call_args[1]["operation_request"]
|
||||
assert req.parameters.get("expected_branch") == "main"
|
||||
assert req.parameters.get("no_cache") is True
|
||||
assert req.parameters.get("build") is True
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_list_table():
|
||||
"""Ensure workload.list renders the canonical 5-column layout matching docs/appctl.md."""
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_list_01",
|
||||
operation=OperationType.WORKLOAD_LIST,
|
||||
result={
|
||||
"total": 2,
|
||||
"workloads": [
|
||||
{
|
||||
"name": "snappymail",
|
||||
"type": "app",
|
||||
"domain": "mail.example.test",
|
||||
"deployment_status": "✓ Synced (main)",
|
||||
"provenance_status": "✓ Synced",
|
||||
"status": "🟢 Running (1)",
|
||||
},
|
||||
{
|
||||
"name": "traefik",
|
||||
"type": "core_service",
|
||||
"domain": "traefik.example.test",
|
||||
"deployment_status": "",
|
||||
"provenance_status": "— Core Platform",
|
||||
"status": "🟢 Running (1)",
|
||||
},
|
||||
],
|
||||
"message": "Found 2 workloads",
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
lines = rendered.splitlines()
|
||||
assert len(lines) >= 4
|
||||
assert lines[0] == "SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN"
|
||||
assert lines[1] == "------- ---------- ---------- ------ ------"
|
||||
assert "snappymail" in lines[2]
|
||||
assert "✓ Synced (main)" in lines[2]
|
||||
assert "✓ Synced" in lines[2]
|
||||
assert "🟢 Running (1)" in lines[2]
|
||||
assert "mail.example.test" in lines[2]
|
||||
|
||||
assert "traefik" in lines[3]
|
||||
assert "— Core Platform" in lines[3]
|
||||
assert "🟢 Running (1)" in lines[3]
|
||||
assert "traefik.example.test" in lines[3]
|
||||
assert "✨ Found 2 workloads" not in rendered
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_list_table_with_ssl():
|
||||
"""Ensure workload.list with SSL renders the canonical 6-column layout with CERT."""
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_list_ssl_01",
|
||||
operation=OperationType.WORKLOAD_LIST,
|
||||
result={
|
||||
"total": 1,
|
||||
"workloads": [
|
||||
{
|
||||
"name": "snappymail",
|
||||
"type": "app",
|
||||
"domain": "mail.example.test",
|
||||
"deployment_status": "✓ Synced (main)",
|
||||
"provenance_status": "✓ Synced",
|
||||
"status": "🟢 Running (1)",
|
||||
"ssl": {"status": "🟢 80d remaining"},
|
||||
},
|
||||
],
|
||||
"message": "Found 1 workloads",
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
lines = rendered.splitlines()
|
||||
assert len(lines) >= 3
|
||||
assert lines[0] == "SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN CERT"
|
||||
assert lines[1] == "------- ---------- ---------- ------ ------ ----"
|
||||
assert "snappymail" in lines[2]
|
||||
assert "🟢 80d remaining" in lines[2]
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_list_table_with_manifest_error():
|
||||
"""Ensure workload.list renders ⚠️ Manifest Error and ⚠️ Invalid Manifest, and status=None renders as '-'."""
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_list_err",
|
||||
operation=OperationType.WORKLOAD_LIST,
|
||||
result={
|
||||
"total": 1,
|
||||
"workloads": [
|
||||
{
|
||||
"name": "broken-app",
|
||||
"type": "app",
|
||||
"domain": "broken.example.test",
|
||||
"manifest_error": "Syntax error in app.yaml",
|
||||
"status": None,
|
||||
},
|
||||
],
|
||||
"message": "Found 1 workloads",
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
lines = rendered.splitlines()
|
||||
assert len(lines) >= 3
|
||||
assert "broken-app" in lines[2]
|
||||
assert "⚠️ Manifest Error" in lines[2]
|
||||
assert "⚠️ Invalid Manifest" in lines[2]
|
||||
# Ensure status is '-' and NOT 'None'
|
||||
assert " None " not in lines[2]
|
||||
assert " - " in lines[2]
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_get_info():
|
||||
"""Ensure workload.get (appctl info) renders structured workload metadata."""
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_get_01",
|
||||
operation=OperationType.WORKLOAD_GET,
|
||||
target="snappymail",
|
||||
result={
|
||||
"workload": {
|
||||
"name": "snappymail",
|
||||
"type": "app",
|
||||
"dir_path": "/home/operator/Sites/snappymail",
|
||||
"domain": "mail.example.test",
|
||||
"description": "Lightweight Webmail",
|
||||
"aliases": ["webmail", "mail"],
|
||||
"networks": ["proxy-net"],
|
||||
"auth": True,
|
||||
"visible": True,
|
||||
},
|
||||
"message": "Retrieved metadata for snappymail",
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert "Workload Overview: snappymail" in rendered
|
||||
assert "/home/operator/Sites/snappymail" in rendered
|
||||
assert "mail.example.test" in rendered
|
||||
assert "webmail, mail" in rendered
|
||||
assert "✨ Retrieved metadata" not in rendered
|
||||
|
||||
|
||||
def test_cli_format_response_renders_empty_workload_list():
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_list_empty",
|
||||
operation=OperationType.WORKLOAD_LIST,
|
||||
result={"total": 0, "workloads": []},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert rendered == "ℹ️ No workloads found."
|
||||
|
||||
|
||||
def test_cli_format_response_renders_core_service_and_rich_metadata():
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_get_core",
|
||||
operation=OperationType.WORKLOAD_GET,
|
||||
target="traefik",
|
||||
result={
|
||||
"workload": {
|
||||
"name": "traefik",
|
||||
"type": "core_service",
|
||||
"dir_path": "/home/operator/Core",
|
||||
"domain": "traefik.example.test",
|
||||
"container": "traefik-proxy",
|
||||
"description": "Edge Ingress",
|
||||
"aliases": ["edge"],
|
||||
"networks": ["proxy-net", "internal"],
|
||||
"auth": False,
|
||||
"visible": False,
|
||||
"source": {
|
||||
"url": "https://git.example.com/repo.git",
|
||||
"ref": "main",
|
||||
},
|
||||
"manifest_error": "Syntax error in app.yaml",
|
||||
"ssl": {
|
||||
"status": "valid",
|
||||
"issuer": "Let's Encrypt",
|
||||
"formatted_expiry": "2027-01-01",
|
||||
},
|
||||
},
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert "ℹ️ Core Infrastructure Service: traefik" in rendered
|
||||
assert "Container: traefik-proxy" in rendered
|
||||
assert "Aliases: edge" in rendered
|
||||
assert "Networks: proxy-net, internal" in rendered
|
||||
assert "Auth Protected: False" in rendered
|
||||
assert "Dashboard: Hidden" in rendered
|
||||
assert "Source URL: https://git.example.com/repo.git" in rendered
|
||||
assert "Target Ref: main" in rendered
|
||||
assert "⚠️ Manifest Validation Error:" in rendered
|
||||
assert "Syntax error in app.yaml" in rendered
|
||||
assert "🔒 SSL/TLS Certificate:" in rendered
|
||||
assert "Status: valid" in rendered
|
||||
|
||||
|
||||
def test_cli_format_response_renders_ssl_info():
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_ssl_01",
|
||||
operation=OperationType.PLATFORM_SSL,
|
||||
result={
|
||||
"ssl": {
|
||||
"domain": "app.example.test",
|
||||
"status": "valid",
|
||||
"issuer": "Let's Encrypt Authority X3",
|
||||
"subject": "CN=app.example.test",
|
||||
"not_after": "2027-01-01 00:00:00 GMT",
|
||||
"days_remaining": 75,
|
||||
"formatted_expiry": "in 75 days",
|
||||
"error": "Near expiration warning",
|
||||
}
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert "🔒 SSL/TLS Certificate: app.example.test" in rendered
|
||||
assert "Domain: app.example.test" in rendered
|
||||
assert "Status: valid" in rendered
|
||||
assert "Issuer: Let's Encrypt Authority X3" in rendered
|
||||
assert "Subject: CN=app.example.test" in rendered
|
||||
assert "Expiration: 2027-01-01 00:00:00 GMT" in rendered
|
||||
assert "Days Remaining: 75 days (in 75 days)" in rendered
|
||||
assert "Details/Error: Near expiration warning" in rendered
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_resolve_json():
|
||||
import json
|
||||
workload_data = {"name": "app1", "dir": "/sites/app1"}
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_resolve_01",
|
||||
operation=OperationType.WORKLOAD_RESOLVE,
|
||||
result={"workload": workload_data},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert json.loads(rendered) == workload_data
|
||||
|
||||
|
||||
def test_cli_format_response_error_without_error_payload():
|
||||
from unittest.mock import MagicMock
|
||||
resp = MagicMock(spec=OperationResponse)
|
||||
resp.success = False
|
||||
resp.error = None
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert rendered == "❌ Error: Unknown error"
|
||||
|
||||
|
||||
|
||||
def test_cli_format_response_default_success_message():
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_succ",
|
||||
operation=OperationType.PLATFORM_HEALTH,
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert rendered == "✨ Operation 'platform.health' succeeded."
|
||||
|
||||
|
||||
|
||||
def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path, monkeypatch):
|
||||
"""Ensure scripts/appctl executes `complete` and `completion` via appctl_engine.py even when socket exists."""
|
||||
import os
|
||||
import shutil
|
||||
import socket as std_socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
bash_bin = shutil.which("bash") or "bash"
|
||||
sock_dir = tempfile.TemporaryDirectory(prefix="appctl_sock_", dir="/tmp")
|
||||
sock_path = Path(sock_dir.name) / "appctl.sock"
|
||||
srv = std_socket.socket(std_socket.AF_UNIX, std_socket.SOCK_STREAM)
|
||||
srv.bind(str(sock_path))
|
||||
try:
|
||||
appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl"
|
||||
env = {
|
||||
"PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"),
|
||||
"PYTHON_BIN": sys.executable,
|
||||
"HOMELAB_DOMAIN": "example.test",
|
||||
"APPCTL_SOCKET_PATH": str(sock_path),
|
||||
"SITES_DIR": str(tmp_path),
|
||||
}
|
||||
if "PYTHONPATH" in os.environ:
|
||||
env["PYTHONPATH"] = os.environ["PYTHONPATH"]
|
||||
|
||||
res_comp = subprocess.run(
|
||||
[bash_bin, str(appctl_script), "completion", "bash"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert res_comp.returncode == 0
|
||||
assert "_appctl_completions()" in res_comp.stdout
|
||||
|
||||
res_words = subprocess.run(
|
||||
[bash_bin, str(appctl_script), "complete", "services"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert res_words.returncode == 0
|
||||
assert "traefik" in res_words.stdout
|
||||
assert "core" in res_words.stdout
|
||||
finally:
|
||||
srv.close()
|
||||
sock_dir.cleanup()
|
||||
|
||||
|
||||
def test_appctl_wrapper_fails_closed_when_socket_is_missing(tmp_path: Path):
|
||||
"""Ensure scripts/appctl fails closed with exit code 1 and diagnostic stderr when socket is missing."""
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
bash_bin = shutil.which("bash") or "bash"
|
||||
non_existent_sock = tmp_path / "missing_appctl.sock"
|
||||
appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl"
|
||||
|
||||
env = {
|
||||
"PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"),
|
||||
"PYTHON_BIN": sys.executable,
|
||||
"HOMELAB_DOMAIN": "example.test",
|
||||
"APPCTL_SOCKET_PATH": str(non_existent_sock),
|
||||
"SITES_DIR": str(tmp_path),
|
||||
}
|
||||
if "PYTHONPATH" in os.environ:
|
||||
env["PYTHONPATH"] = os.environ["PYTHONPATH"]
|
||||
|
||||
res = subprocess.run(
|
||||
[bash_bin, str(appctl_script), "status"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert res.returncode == 1
|
||||
assert "daemon socket not found" in res.stderr
|
||||
|
||||
|
||||
def test_appctl_wrapper_fast_paths_completion_without_socket(tmp_path: Path):
|
||||
"""Ensure scripts/appctl completes offline via appctl_engine.py even when socket is missing."""
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
bash_bin = shutil.which("bash") or "bash"
|
||||
non_existent_sock = tmp_path / "missing_appctl.sock"
|
||||
appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl"
|
||||
|
||||
env = {
|
||||
"PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"),
|
||||
"PYTHON_BIN": sys.executable,
|
||||
"HOMELAB_DOMAIN": "example.test",
|
||||
"APPCTL_SOCKET_PATH": str(non_existent_sock),
|
||||
"SITES_DIR": str(tmp_path),
|
||||
}
|
||||
if "PYTHONPATH" in os.environ:
|
||||
env["PYTHONPATH"] = os.environ["PYTHONPATH"]
|
||||
|
||||
res_comp = subprocess.run(
|
||||
[bash_bin, str(appctl_script), "completion", "bash"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert res_comp.returncode == 0
|
||||
assert "_appctl_completions()" in res_comp.stdout
|
||||
assert "up|deploy)" in res_comp.stdout
|
||||
assert "--build --no-cache" in res_comp.stdout
|
||||
|
||||
res_words = subprocess.run(
|
||||
[bash_bin, str(appctl_script), "complete", "services"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert res_words.returncode == 0
|
||||
assert "traefik" in res_words.stdout
|
||||
assert "core" in res_words.stdout
|
||||
|
||||
|
||||
@@ -0,0 +1,695 @@
|
||||
"""
|
||||
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
|
||||
assert p_default.no_cache is False
|
||||
|
||||
# Explicit
|
||||
p_custom = DeployParams(recreate=False, remove_orphans=False, build=True, no_cache=False)
|
||||
assert p_custom.recreate is False
|
||||
assert p_custom.remove_orphans is False
|
||||
assert p_custom.build is True
|
||||
assert p_custom.no_cache is False
|
||||
|
||||
# no_cache implies build=True
|
||||
p_no_cache = DeployParams(no_cache=True)
|
||||
assert p_no_cache.no_cache is True
|
||||
assert p_no_cache.build is True
|
||||
|
||||
# no_cache overrides explicit build=False
|
||||
p_override = DeployParams(build=False, no_cache=True)
|
||||
assert p_override.no_cache is True
|
||||
assert p_override.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]
|
||||
with pytest.raises(ValidationError):
|
||||
DeployParams(no_cache=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
|
||||
assert p_default.no_cache is False
|
||||
|
||||
# Explicit
|
||||
p_custom = UpdateParams(expected_branch="main", build=True, no_cache=False)
|
||||
assert p_custom.expected_branch == "main"
|
||||
assert p_custom.build is True
|
||||
assert p_custom.no_cache is False
|
||||
|
||||
# no_cache implies build=True
|
||||
p_no_cache = UpdateParams(no_cache=True)
|
||||
assert p_no_cache.no_cache is True
|
||||
assert p_no_cache.build is True
|
||||
|
||||
# no_cache overrides explicit build=False
|
||||
p_override = UpdateParams(build=False, no_cache=True)
|
||||
assert p_override.no_cache is True
|
||||
assert p_override.build is True
|
||||
|
||||
|
||||
def test_update_params_rejects_empty_branch_and_non_strict_types():
|
||||
for bad_bool in ["true", "false", 1, 0, None, [True]]:
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(build=bad_bool) # type: ignore[arg-type]
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(no_cache=bad_bool) # type: ignore[arg-type]
|
||||
|
||||
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.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_7_canonical_codes():
|
||||
assert len(ErrorCode) == 7
|
||||
expected_codes = {
|
||||
"ERR_VALIDATION_FAILED",
|
||||
"ERR_AUTH_REQUIRED",
|
||||
"ERR_PERMISSION_DENIED",
|
||||
"ERR_CAPABILITY_NOT_GRANTED",
|
||||
"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_CAPABILITY_NOT_GRANTED.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) == 1
|
||||
detail = op_err.details[0]
|
||||
|
||||
# Ensure neither input nor url appears in any details dictionary
|
||||
assert "input" not in detail
|
||||
assert "url" not in detail
|
||||
assert "SUPER_SECRET_TOKEN_DO_NOT_LEAK" not in str(detail)
|
||||
assert detail["loc"] == ["tail"]
|
||||
assert detail["type"] == "int_type"
|
||||
assert "Input should be a valid integer" in detail["msg"]
|
||||
|
||||
# Verify defense-in-depth: exc.errors called with include_input=False and include_url=False
|
||||
from unittest.mock import MagicMock
|
||||
mock_exc = MagicMock(spec=ValidationError)
|
||||
mock_exc.errors.return_value = [{"loc": ("field",), "type": "value_error", "msg": "Invalid"}]
|
||||
sanitize_validation_error(mock_exc)
|
||||
mock_exc.errors.assert_called_once_with(include_input=False, include_url=False)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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,645 @@
|
||||
"""
|
||||
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 concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
import socket
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import gitops_dispatcher
|
||||
import pytest
|
||||
from appctl_audit import AuditLogger, AuditPersistenceError, 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")
|
||||
sock_dir = tempfile.TemporaryDirectory(prefix="appctl_sock_", dir="/tmp")
|
||||
socket_path = Path(sock_dir.name) / "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",
|
||||
)
|
||||
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file))
|
||||
|
||||
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()
|
||||
sock_dir.cleanup()
|
||||
|
||||
|
||||
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("appctl_router.run_bounded_subprocess") 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("appctl_router.run_bounded_subprocess") 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_daemon_multi_threaded_lock_contention_rejects_concurrent_mutation(daemon_env):
|
||||
"""
|
||||
Simultaneous mutating requests for the same target result in one 200 SUCCESS
|
||||
and one 409 ERR_CONCURRENT_MUTATION via multi-threaded lock contention.
|
||||
"""
|
||||
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
first_started = threading.Event()
|
||||
|
||||
def slow_subproc(cmd, *args, **kwargs):
|
||||
first_started.set()
|
||||
time.sleep(0.2)
|
||||
return (0, "Started", "")
|
||||
|
||||
def send_first():
|
||||
return send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
|
||||
def send_second():
|
||||
first_started.wait(timeout=2.0)
|
||||
return send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
|
||||
with (
|
||||
patch("appctl_router.run_bounded_subprocess", side_effect=slow_subproc),
|
||||
patch("appctl_router.OperationalRouter._trigger_homepage_sync"),
|
||||
concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor,
|
||||
):
|
||||
fut1 = executor.submit(send_first)
|
||||
fut2 = executor.submit(send_second)
|
||||
resp1 = fut1.result(timeout=5.0)
|
||||
resp2 = fut2.result(timeout=5.0)
|
||||
|
||||
responses = [resp1, resp2]
|
||||
successes = [r for r in responses if r.success]
|
||||
conflicts = [r for r in responses if not r.success and r.error and r.error.code == ErrorCode.ERR_CONCURRENT_MUTATION]
|
||||
|
||||
assert len(successes) == 1
|
||||
assert len(conflicts) == 1
|
||||
assert successes[0].result is not None
|
||||
assert successes[0].result["action"] == "deployed"
|
||||
assert conflicts[0].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.
|
||||
"""
|
||||
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
daemon_env.daemon.audit_logger,
|
||||
"emit_event",
|
||||
side_effect=AuditPersistenceError("Simulated disk full or permission error"),
|
||||
),
|
||||
patch("appctl_router.run_bounded_subprocess") 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
|
||||
|
||||
|
||||
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))
|
||||
|
||||
def mock_subproc(cmd, *args, **kwargs):
|
||||
if "status" in cmd:
|
||||
return (0, "", "")
|
||||
if "rev-parse" in cmd:
|
||||
return (0, "sha12345", "")
|
||||
return (0, "ok", "")
|
||||
|
||||
with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc) as mock_sub, patch(
|
||||
"appctl_router.OperationalRouter._trigger_homepage_sync"
|
||||
):
|
||||
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_sub.call_count >= 1
|
||||
|
||||
|
||||
def test_daemon_deployments_file_defaults_to_workloads(
|
||||
tmp_path: Path, run_isolated_script_expr
|
||||
):
|
||||
"""DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml."""
|
||||
resolved_default = run_isolated_script_expr(
|
||||
"import appctl_daemon; print(appctl_daemon.DEPLOYMENTS_FILE)"
|
||||
)
|
||||
assert Path(resolved_default) == tmp_path / "Workloads" / "deployments.yaml"
|
||||
|
||||
|
||||
def test_daemon_deployments_file_honors_workloads_dir_override(
|
||||
tmp_path: Path, run_isolated_script_expr
|
||||
):
|
||||
"""DEPLOYMENTS_FILE honors WORKLOADS_DIR override when HOMELAB_DEPLOYMENTS_FILE is unset."""
|
||||
custom_workloads = tmp_path / "CustomWorkloads"
|
||||
resolved_override = run_isolated_script_expr(
|
||||
"import appctl_daemon; print(appctl_daemon.DEPLOYMENTS_FILE)",
|
||||
extra_env={"WORKLOADS_DIR": str(custom_workloads)},
|
||||
)
|
||||
assert Path(resolved_override) == custom_workloads / "deployments.yaml"
|
||||
|
||||
|
||||
def test_daemon_operator_fails_closed_when_deployments_file_absent(
|
||||
daemon_env, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
"""homelab-operator fails closed (403 ERR_PERMISSION_DENIED) when ~/Workloads/deployments.yaml is absent."""
|
||||
import appctl_auth
|
||||
|
||||
# When HOMELAB_DEPLOYMENTS_FILE is unset and ~/Workloads/deployments.yaml is absent,
|
||||
# homelab-operator must be denied (403) without falling back to CORE_DIR/config/deployments.yaml.
|
||||
monkeypatch.delenv("HOMELAB_DEPLOYMENTS_FILE", raising=False)
|
||||
monkeypatch.delenv("WORKLOADS_DIR", raising=False)
|
||||
monkeypatch.delenv("SITES_DIR", raising=False)
|
||||
monkeypatch.setattr(
|
||||
appctl_auth,
|
||||
"DEFAULT_DEPLOYMENTS_FILE",
|
||||
tmp_path / "empty-home" / "Workloads" / "deployments.yaml",
|
||||
)
|
||||
deploy_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_DEPLOY, target="docs"
|
||||
)
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=OPERATOR_SECRET,
|
||||
)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
assert resp.error.code.http_status == 403
|
||||
@@ -1,20 +1,19 @@
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import appctl_engine as engine
|
||||
import pytest
|
||||
|
||||
# Import appctl engine
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
|
||||
import appctl_engine as engine
|
||||
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
|
||||
|
||||
@dataclass
|
||||
class AppFactory:
|
||||
"""Helper class to generate mock app directories and configurations"""
|
||||
|
||||
sites_dir: Path
|
||||
|
||||
def create(
|
||||
@@ -28,9 +27,12 @@ class AppFactory:
|
||||
if manifest_yaml:
|
||||
(app_dir / "app.yaml").write_text(manifest_yaml, encoding="utf-8")
|
||||
if has_compose:
|
||||
(app_dir / "docker-compose.yml").write_text("services: {}\n", encoding="utf-8")
|
||||
(app_dir / "docker-compose.yml").write_text(
|
||||
"services: {}\n", encoding="utf-8"
|
||||
)
|
||||
return app_dir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
"""Fixture that creates an isolated Sites directory and points engine.SITES_DIR to it"""
|
||||
@@ -39,23 +41,24 @@ def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "mydomain.test")
|
||||
return sites
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app_factory(mock_sites_dir: Path) -> AppFactory:
|
||||
"""Fixture that provides the AppFactory instance to test"""
|
||||
return AppFactory(mock_sites_dir)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_core_dir(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch
|
||||
) -> Path:
|
||||
def mock_core_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
"""Fixture that creates an isolated Core directory and points engine.CORE_DIR to it"""
|
||||
core = tmp_path / "CORE"
|
||||
core.mkdir(parents=True, exist_ok=True)
|
||||
return core
|
||||
|
||||
|
||||
## GREEN TEST: Existing implementation should not break
|
||||
|
||||
|
||||
def test_resolve_app_hierarchy(app_factory: AppFactory):
|
||||
"""Ensure resolution follows: Canonical Name > Alias > Dir Name > Prefix"""
|
||||
app_factory.create(
|
||||
@@ -73,28 +76,30 @@ def test_resolve_app_hierarchy(app_factory: AppFactory):
|
||||
assert engine.resolve_app("homelab-jellyfin", apps) is not None
|
||||
assert engine.resolve_app("unknown", apps) is None
|
||||
|
||||
|
||||
def test_manifest_data_overrides_default_values(app_factory: AppFactory):
|
||||
"""Ensure app.yaml values successfully override the system defaults"""
|
||||
app_factory.create(
|
||||
dir_name="homelab-custom",
|
||||
manifest_yaml="""
|
||||
name: custom-app
|
||||
domain: custom.roadtotech.local
|
||||
domain: custom.example.test
|
||||
auth: false
|
||||
visible: false
|
||||
networks:
|
||||
- custom-net
|
||||
"""
|
||||
""",
|
||||
)
|
||||
|
||||
apps = engine.get_sites_apps()
|
||||
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"]
|
||||
|
||||
|
||||
def test_sites_app_normalization(app_factory: AppFactory):
|
||||
"""Ensure missing or badly typed manifest fields are safely normalized"""
|
||||
app_factory.create(
|
||||
@@ -106,7 +111,7 @@ def test_sites_app_normalization(app_factory: AppFactory):
|
||||
auth: "False" # should evaluate based on boolean casting
|
||||
homepage:
|
||||
weight: "99" # this should be casted as an int
|
||||
"""
|
||||
""",
|
||||
)
|
||||
apps = engine.get_sites_apps()
|
||||
app = engine.resolve_app("testapp", apps)
|
||||
@@ -131,7 +136,7 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
||||
type: git
|
||||
url: https://git.example.com/operator/bitetrack.git
|
||||
ref: v1.2.0
|
||||
"""
|
||||
""",
|
||||
)
|
||||
# 2. Source-backed app with default ref (main)
|
||||
app_factory.create(
|
||||
@@ -140,14 +145,14 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
||||
name: doc2site
|
||||
source:
|
||||
url: https://git.example.com/operator/doc2site.git
|
||||
"""
|
||||
""",
|
||||
)
|
||||
# 3. Image-only app (no source block)
|
||||
app_factory.create(
|
||||
dir_name="homelab-jellyfin",
|
||||
manifest_yaml="""
|
||||
name: jellyfin
|
||||
"""
|
||||
""",
|
||||
)
|
||||
|
||||
apps = engine.get_sites_apps()
|
||||
@@ -177,7 +182,7 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
||||
name: malformed
|
||||
source:
|
||||
url: file:///etc/passwd
|
||||
"""
|
||||
""",
|
||||
)
|
||||
apps_updated = engine.get_sites_apps()
|
||||
malformed = engine.resolve_app("malformed", apps_updated)
|
||||
@@ -189,10 +194,13 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
||||
|
||||
## RED TESTS: TDD Goals for next implementation
|
||||
|
||||
|
||||
def test_docker_status_parser_running(monkeypatch):
|
||||
"""Ensure get_docker_status reports running compose stack when all containers are running."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
mock.returncode = 0
|
||||
if "ps" in args:
|
||||
mock.stdout = "container123\n"
|
||||
if "inspect" in args:
|
||||
@@ -207,8 +215,10 @@ def test_docker_status_parser_running(monkeypatch):
|
||||
|
||||
def test_docker_status_parser_stopped(monkeypatch):
|
||||
"""Ensure get_docker_status reports stopped when no containers exist."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
mock.returncode = 0
|
||||
if "ps" in args:
|
||||
mock.stdout = ""
|
||||
return mock
|
||||
@@ -221,8 +231,10 @@ def test_docker_status_parser_stopped(monkeypatch):
|
||||
|
||||
def test_docker_status_parser_degraded(monkeypatch):
|
||||
"""Ensure get_docker_status reports degraded when partial containers are running."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
mock.returncode = 0
|
||||
if "ps" in args:
|
||||
mock.stdout = "c1\nc2\n"
|
||||
if "inspect" in args:
|
||||
@@ -244,8 +256,10 @@ def test_docker_status_parser_not_stack(tmp_path: Path):
|
||||
|
||||
def test_docker_status_single_container(monkeypatch):
|
||||
"""Ensure get_docker_status inspects single Core container by name."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
mock.returncode = 0
|
||||
if "authelia" in args:
|
||||
mock.stdout = "true\n"
|
||||
else:
|
||||
@@ -258,8 +272,75 @@ def test_docker_status_single_container(monkeypatch):
|
||||
assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped"
|
||||
|
||||
|
||||
def test_docker_status_compose_ps_daemon_error(monkeypatch):
|
||||
"""Ensure get_docker_status returns '❓ Unknown' when docker compose ps fails (e.g. daemon unreachable)."""
|
||||
import subprocess
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
return subprocess.CompletedProcess(
|
||||
args=args,
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
|
||||
)
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_status("/fake/dir") == "❓ Unknown"
|
||||
|
||||
|
||||
def test_docker_status_compose_inspect_error(monkeypatch):
|
||||
"""Ensure get_docker_status returns '❓ Unknown' when docker inspect fails for compose containers."""
|
||||
import subprocess
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
if "ps" in args:
|
||||
return subprocess.CompletedProcess(args=args, returncode=0, stdout="c1\n", stderr="")
|
||||
return subprocess.CompletedProcess(
|
||||
args=args,
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
|
||||
)
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_status("/fake/dir") == "❓ Unknown"
|
||||
|
||||
|
||||
def test_docker_status_single_container_daemon_error(monkeypatch):
|
||||
"""Ensure get_docker_status returns '❓ Unknown' when inspecting single container fails due to daemon error."""
|
||||
import subprocess
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
return subprocess.CompletedProcess(
|
||||
args=args,
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
|
||||
)
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_status("", container_name="traefik") == "❓ Unknown"
|
||||
|
||||
|
||||
def test_docker_status_single_container_no_such_object(monkeypatch):
|
||||
"""Ensure get_docker_status returns '🔴 Stopped' when container does not exist."""
|
||||
import subprocess
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
return subprocess.CompletedProcess(
|
||||
args=args,
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="Error: No such object: traefik",
|
||||
)
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped"
|
||||
|
||||
|
||||
def test_docker_status_error_handling(monkeypatch):
|
||||
"""Ensure get_docker_status handles subprocess failures gracefully."""
|
||||
|
||||
def mock_err(*args, **kwargs):
|
||||
raise OSError("Docker socket unreachable")
|
||||
|
||||
@@ -269,6 +350,7 @@ def test_docker_status_error_handling(monkeypatch):
|
||||
|
||||
def test_docker_image_revision_extraction(monkeypatch):
|
||||
"""Ensure get_docker_image_revision extracts org.opencontainers.image.revision."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
if "ps" in args:
|
||||
@@ -278,7 +360,10 @@ def test_docker_image_revision_extraction(monkeypatch):
|
||||
return mock
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_image_revision("/fake/dir") == "9d82577f489f0d478e465a36077538d0ded16ba5"
|
||||
assert (
|
||||
engine.get_docker_image_revision("/fake/dir")
|
||||
== "9d82577f489f0d478e465a36077538d0ded16ba5"
|
||||
)
|
||||
|
||||
def mock_run_empty(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
@@ -293,9 +378,8 @@ def test_docker_image_revision_extraction(monkeypatch):
|
||||
|
||||
|
||||
def test_homepage_sync_groups_and_sorts_correctly(
|
||||
mock_core_dir: Path,
|
||||
app_factory: AppFactory,
|
||||
monkeypatch):
|
||||
mock_core_dir: Path, app_factory: AppFactory, monkeypatch
|
||||
):
|
||||
"""
|
||||
TDD Goal: Port `cmd_sync_homepage` to V2 using the new Dataclass structure.
|
||||
It must group by `homepage.group` and sort by `homepage.weight`.
|
||||
@@ -312,7 +396,7 @@ def test_homepage_sync_groups_and_sorts_correctly(
|
||||
title: App1
|
||||
group: Group B
|
||||
weight: 20
|
||||
"""
|
||||
""",
|
||||
)
|
||||
|
||||
app_factory.create(
|
||||
@@ -324,7 +408,7 @@ def test_homepage_sync_groups_and_sorts_correctly(
|
||||
title: App2
|
||||
group: Group A
|
||||
weight: 10
|
||||
"""
|
||||
""",
|
||||
)
|
||||
|
||||
monkeypatch.setattr(engine, "get_core_services", list)
|
||||
@@ -334,7 +418,9 @@ def test_homepage_sync_groups_and_sorts_correctly(
|
||||
assert output_file.exists(), "The services.yaml file must be generated"
|
||||
|
||||
content = output_file.read_text()
|
||||
assert content.find("- Group A") < content.find("- Group B") # Group A should appear before Group B
|
||||
assert content.find("- Group A") < content.find(
|
||||
"- Group B"
|
||||
) # Group A should appear before Group B
|
||||
assert "App2" in content # App 2 is in the file
|
||||
|
||||
|
||||
@@ -380,7 +466,9 @@ def test_resolve_core_stack_type():
|
||||
assert traefik.container == "traefik"
|
||||
|
||||
|
||||
def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(app_factory: AppFactory):
|
||||
def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(
|
||||
app_factory: AppFactory,
|
||||
):
|
||||
"""Ensure manifest parsing uses core_manifest and catches invalid env keys."""
|
||||
app_factory.create(
|
||||
dir_name="homelab-badenv",
|
||||
@@ -397,7 +485,9 @@ def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(app_facto
|
||||
assert "Invalid or reserved environment variable key" in app.manifest_error
|
||||
|
||||
|
||||
def test_cmd_resolve_fails_closed_on_manifest_error(app_factory: AppFactory, capsys: pytest.CaptureFixture):
|
||||
def test_cmd_resolve_fails_closed_on_manifest_error(
|
||||
app_factory: AppFactory, capsys: pytest.CaptureFixture
|
||||
):
|
||||
"""Ensure cmd_resolve exits with non-zero on workload with manifest errors."""
|
||||
app_factory.create(
|
||||
dir_name="homelab-corrupt",
|
||||
@@ -449,7 +539,9 @@ def test_unification_uses_core_manifest_dataclasses(app_factory: AppFactory):
|
||||
assert app.source.transport == core_manifest.TransportScheme.HTTPS
|
||||
|
||||
|
||||
def test_cmd_list_flags_manifest_error(app_factory: AppFactory, capsys: pytest.CaptureFixture):
|
||||
def test_cmd_list_flags_manifest_error(
|
||||
app_factory: AppFactory, capsys: pytest.CaptureFixture
|
||||
):
|
||||
"""Ensure cmd_list flags workloads with manifest errors instead of swallowing them."""
|
||||
app_factory.create(
|
||||
dir_name="homelab-broken",
|
||||
@@ -463,3 +555,55 @@ def test_cmd_list_flags_manifest_error(app_factory: AppFactory, capsys: pytest.C
|
||||
captured = capsys.readouterr()
|
||||
assert "Manifest Error" in captured.out
|
||||
|
||||
|
||||
def test_workloads_dir_env_precedence_and_fallback(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
"""Ensure WORKLOADS_DIR > SITES_DIR > ~/Workloads fallback across core modules (#33)."""
|
||||
import importlib
|
||||
|
||||
import appctl_daemon
|
||||
import gitops_dispatcher
|
||||
|
||||
workloads_override = tmp_path / "custom-workloads"
|
||||
sites_override = tmp_path / "legacy-sites"
|
||||
fake_home = tmp_path / "home"
|
||||
fake_core = tmp_path / "repo" / "core"
|
||||
fake_core.mkdir(parents=True)
|
||||
|
||||
try:
|
||||
# 1. WORKLOADS_DIR takes precedence over SITES_DIR
|
||||
monkeypatch.setenv("CORE_DIR", str(fake_core))
|
||||
monkeypatch.setenv("WORKLOADS_DIR", str(workloads_override))
|
||||
monkeypatch.setenv("SITES_DIR", str(sites_override))
|
||||
importlib.reload(engine)
|
||||
importlib.reload(appctl_daemon)
|
||||
importlib.reload(gitops_dispatcher)
|
||||
assert engine.SITES_DIR == str(workloads_override)
|
||||
assert appctl_daemon.SITES_DIR == workloads_override
|
||||
assert gitops_dispatcher.SITES_DIR == workloads_override
|
||||
|
||||
# 2. SITES_DIR acts as fallback when WORKLOADS_DIR is unset
|
||||
monkeypatch.delenv("WORKLOADS_DIR", raising=False)
|
||||
importlib.reload(engine)
|
||||
importlib.reload(appctl_daemon)
|
||||
importlib.reload(gitops_dispatcher)
|
||||
assert engine.SITES_DIR == str(sites_override)
|
||||
assert appctl_daemon.SITES_DIR == sites_override
|
||||
assert gitops_dispatcher.SITES_DIR == sites_override
|
||||
|
||||
# 3. Default resolves to ~/Workloads when neither env var is set
|
||||
monkeypatch.delenv("SITES_DIR", raising=False)
|
||||
monkeypatch.setenv("HOME", str(fake_home))
|
||||
importlib.reload(engine)
|
||||
importlib.reload(appctl_daemon)
|
||||
importlib.reload(gitops_dispatcher)
|
||||
expected_default = fake_home / "Workloads"
|
||||
assert engine.SITES_DIR == str(expected_default)
|
||||
assert appctl_daemon.SITES_DIR == expected_default
|
||||
assert gitops_dispatcher.SITES_DIR == expected_default
|
||||
finally:
|
||||
monkeypatch.undo()
|
||||
importlib.reload(engine)
|
||||
importlib.reload(appctl_daemon)
|
||||
importlib.reload(gitops_dispatcher)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,176 @@
|
||||
"""
|
||||
tests/unit/test_bootstrap_token.py — Unit Tests for Operator Admin Token Bootstrap Helper (WP4)
|
||||
|
||||
Verifies:
|
||||
- 256-bit secure token generation (64 hex characters) and matching SHA-256 digest
|
||||
- Strict 0600 file mode and 0700 parent directory creation
|
||||
- TokenDescriptor Pydantic validation (scripts/appctl_auth.py)
|
||||
- Refusal to overwrite existing token file without --force
|
||||
- Overwriting existing token file when --force is supplied
|
||||
- Secrets leakage prevention: raw Bearer token never appears in stdout/stderr
|
||||
- Machine-readable JSON output via --print-json
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import stat
|
||||
import string
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from appctl_auth import Role, TokenDescriptor
|
||||
from bootstrap_token import (
|
||||
bootstrap_token,
|
||||
generate_token,
|
||||
main,
|
||||
write_token_file,
|
||||
)
|
||||
|
||||
|
||||
def test_generate_token_produces_64_hex_token_and_valid_sha256() -> None:
|
||||
raw_token, digest = generate_token()
|
||||
assert len(raw_token) == 64
|
||||
assert all(c in string.hexdigits for c in raw_token)
|
||||
assert len(digest) == 64
|
||||
assert all(c in string.hexdigits for c in digest)
|
||||
expected_digest = hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
|
||||
assert digest == expected_digest
|
||||
|
||||
|
||||
def test_write_token_file_creates_file_and_enforces_0600(tmp_path: Path) -> None:
|
||||
token_file = tmp_path / "subdir" / "token"
|
||||
write_token_file(token_file, "secret-token-12345")
|
||||
assert token_file.is_file()
|
||||
assert stat.S_IMODE(token_file.stat().st_mode) == 0o600
|
||||
assert stat.S_IMODE(token_file.parent.stat().st_mode) == 0o700
|
||||
assert token_file.read_text(encoding="utf-8") == "secret-token-12345\n"
|
||||
|
||||
|
||||
def test_bootstrap_token_generates_file_with_strict_mode_0600(tmp_path: Path) -> None:
|
||||
nested_dir = tmp_path / "nested" / "homelab"
|
||||
token_file = nested_dir / "token"
|
||||
|
||||
descriptor = bootstrap_token(output_path=token_file)
|
||||
|
||||
assert token_file.is_file()
|
||||
# Check parent directory mode is 0700
|
||||
parent_mode = stat.S_IMODE(nested_dir.stat().st_mode)
|
||||
assert parent_mode == 0o700, f"Expected parent mode 0700, got {oct(parent_mode)}"
|
||||
|
||||
# Check token file mode is 0600
|
||||
file_mode = stat.S_IMODE(token_file.stat().st_mode)
|
||||
assert file_mode == 0o600, f"Expected file mode 0600, got {oct(file_mode)}"
|
||||
|
||||
raw_token = token_file.read_text(encoding="utf-8").strip()
|
||||
assert len(raw_token) == 64
|
||||
assert hashlib.sha256(raw_token.encode("utf-8")).hexdigest() == descriptor["sha256"]
|
||||
|
||||
|
||||
def test_bootstrap_token_descriptor_validates_against_token_descriptor(tmp_path: Path) -> None:
|
||||
token_file = tmp_path / "custom_token"
|
||||
descriptor = bootstrap_token(
|
||||
output_path=token_file,
|
||||
token_id="custom-admin",
|
||||
identity="operator",
|
||||
role="homelab-admin",
|
||||
)
|
||||
|
||||
validated = TokenDescriptor.model_validate(descriptor)
|
||||
assert validated.token_id == "custom-admin"
|
||||
assert validated.identity == "operator"
|
||||
assert validated.role == Role.ADMIN
|
||||
assert len(validated.sha256) == 64
|
||||
|
||||
|
||||
def test_bootstrap_token_refuses_overwrite_without_force(tmp_path: Path) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
bootstrap_token(output_path=token_file)
|
||||
original_token = token_file.read_text(encoding="utf-8")
|
||||
|
||||
with pytest.raises(FileExistsError, match="already exists"):
|
||||
bootstrap_token(output_path=token_file, force=False)
|
||||
|
||||
assert token_file.read_text(encoding="utf-8") == original_token
|
||||
|
||||
|
||||
def test_bootstrap_token_overwrites_with_force(tmp_path: Path) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
descriptor1 = bootstrap_token(output_path=token_file)
|
||||
first_token = token_file.read_text(encoding="utf-8").strip()
|
||||
|
||||
descriptor2 = bootstrap_token(output_path=token_file, force=True)
|
||||
second_token = token_file.read_text(encoding="utf-8").strip()
|
||||
|
||||
assert first_token != second_token
|
||||
assert descriptor1["sha256"] != descriptor2["sha256"]
|
||||
assert descriptor2["sha256"] == hashlib.sha256(second_token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def test_bootstrap_cli_never_prints_raw_secret_to_stdout_or_stderr(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
ret = main(["--output", str(token_file)])
|
||||
assert ret == 0
|
||||
|
||||
raw_token = token_file.read_text(encoding="utf-8").strip()
|
||||
captured = capsys.readouterr()
|
||||
|
||||
# RAW SECRET MUST NEVER APPEAR IN STDOUT OR STDERR
|
||||
assert raw_token not in captured.out, "Leak: raw token found in stdout!"
|
||||
assert raw_token not in captured.err, "Leak: raw token found in stderr!"
|
||||
|
||||
# Ensure stdout provides helpful human guidance
|
||||
assert "operator-admin" in captured.out
|
||||
assert "sops nixos/secrets.yaml" in captured.out
|
||||
assert "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure" in captured.out
|
||||
|
||||
|
||||
def test_bootstrap_cli_print_json_outputs_valid_json_descriptor(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
ret = main(["--output", str(token_file), "--print-json"])
|
||||
assert ret == 0
|
||||
|
||||
raw_token = token_file.read_text(encoding="utf-8").strip()
|
||||
captured = capsys.readouterr()
|
||||
|
||||
assert raw_token not in captured.out
|
||||
assert captured.err == ""
|
||||
|
||||
# Must be cleanly parseable as pure JSON
|
||||
data: dict[str, Any] = json.loads(captured.out.strip())
|
||||
validated = TokenDescriptor.model_validate(data)
|
||||
assert validated.token_id == "operator-admin"
|
||||
assert validated.identity == "operator"
|
||||
assert validated.role == Role.ADMIN
|
||||
assert validated.sha256 == hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def test_bootstrap_cli_refuses_overwrite_and_exits_nonzero(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
assert main(["--output", str(token_file)]) == 0
|
||||
|
||||
ret = main(["--output", str(token_file)])
|
||||
assert ret != 0
|
||||
captured = capsys.readouterr()
|
||||
assert "already exists" in captured.err
|
||||
|
||||
|
||||
def test_bootstrap_cli_force_overwrites(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
assert main(["--output", str(token_file)]) == 0
|
||||
tok1 = token_file.read_text(encoding="utf-8").strip()
|
||||
|
||||
assert main(["--output", str(token_file), "--force"]) == 0
|
||||
tok2 = token_file.read_text(encoding="utf-8").strip()
|
||||
|
||||
assert tok1 != tok2
|
||||
@@ -2,15 +2,13 @@
|
||||
Unit test suite for scripts/core_manifest.py (Schema v1.0 & Parser Library).
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
# Add scripts directory to path
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
|
||||
# # Add scripts directory to path
|
||||
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
from core_manifest import (
|
||||
Manifest,
|
||||
ManifestValidationError,
|
||||
@@ -24,13 +22,17 @@ from core_manifest import (
|
||||
|
||||
def test_validate_transport_https():
|
||||
|
||||
scheme, url = validate_transport("https://git.example.com/operator/homelab-snappymail.git")
|
||||
scheme, url = validate_transport(
|
||||
"https://git.example.com/operator/homelab-snappymail.git"
|
||||
)
|
||||
assert scheme == TransportScheme.HTTPS
|
||||
assert url == "https://git.example.com/operator/homelab-snappymail.git"
|
||||
|
||||
|
||||
def test_validate_transport_ssh():
|
||||
scheme, url = validate_transport("ssh://git@git.example.com:2223/operator/homelab-docs.git")
|
||||
scheme, url = validate_transport(
|
||||
"ssh://git@git.example.com:2223/operator/homelab-docs.git"
|
||||
)
|
||||
assert scheme == TransportScheme.SSH
|
||||
assert url == "ssh://git@git.example.com:2223/operator/homelab-docs.git"
|
||||
|
||||
@@ -41,31 +43,103 @@ def test_validate_transport_git_scp():
|
||||
assert url == "git@github.com:operator/custom-workload.git"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("insecure_url", [
|
||||
@pytest.mark.parametrize(
|
||||
"insecure_url",
|
||||
[
|
||||
"http://insecure.example.com/repo.git",
|
||||
"http://github.com/repo.git",
|
||||
])
|
||||
],
|
||||
)
|
||||
def test_validate_transport_rejects_http(insecure_url: str):
|
||||
with pytest.raises(ManifestValidationError, match="Insecure HTTP source URL rejected"):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="Insecure HTTP source URL rejected"
|
||||
):
|
||||
validate_transport(insecure_url)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("traversal_url", [
|
||||
@pytest.mark.parametrize(
|
||||
"empty_or_invalid_url",
|
||||
[
|
||||
"",
|
||||
" ",
|
||||
None,
|
||||
],
|
||||
)
|
||||
def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match=r"^Source URL cannot be empty\.$"
|
||||
):
|
||||
validate_transport(empty_or_invalid_url) # type: ignore[arg-type]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("root_path_url", "scheme"),
|
||||
[
|
||||
("https://git.example.com/", "HTTPS"),
|
||||
("ssh://git.example.com/", "SSH"),
|
||||
],
|
||||
)
|
||||
def test_validate_transport_rejects_root_repository_path(
|
||||
root_path_url: str, scheme: str
|
||||
):
|
||||
with pytest.raises(
|
||||
ManifestValidationError,
|
||||
match=rf"^Malformed {scheme} source URL \(missing repository path\)",
|
||||
):
|
||||
validate_transport(root_path_url)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"traversal_url",
|
||||
[
|
||||
"../../etc/shadow",
|
||||
"/home/operator/secret",
|
||||
"~/vault",
|
||||
"file:///etc/passwd",
|
||||
])
|
||||
r"repo\windows\payload",
|
||||
r"..\traversal",
|
||||
],
|
||||
)
|
||||
def test_validate_transport_rejects_paths_and_traversal(traversal_url: str):
|
||||
with pytest.raises(ManifestValidationError):
|
||||
with pytest.raises(
|
||||
ManifestValidationError,
|
||||
match="Prohibited filesystem path or traversal in source URL",
|
||||
):
|
||||
validate_transport(traversal_url)
|
||||
|
||||
|
||||
def test_validate_transport_rejects_file_scheme():
|
||||
with pytest.raises(
|
||||
ManifestValidationError,
|
||||
match="Invalid source.url scheme: 'file:///etc/passwd'",
|
||||
):
|
||||
validate_transport("file:///etc/passwd")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"empty_ref",
|
||||
[
|
||||
"",
|
||||
" ",
|
||||
None,
|
||||
12345,
|
||||
],
|
||||
)
|
||||
def test_classify_ref_empty_or_invalid_defaults_to_main(empty_ref):
|
||||
assert classify_ref(empty_ref) == (RefType.BRANCH, "main") # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_classify_ref_branches():
|
||||
assert classify_ref("main") == (RefType.BRANCH, "main")
|
||||
assert classify_ref("refs/heads/develop") == (RefType.BRANCH, "develop")
|
||||
assert classify_ref("feat/manifest-engine") == (RefType.BRANCH, "feat/manifest-engine")
|
||||
assert classify_ref("feat/manifest-engine") == (
|
||||
RefType.BRANCH,
|
||||
"feat/manifest-engine",
|
||||
)
|
||||
assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0")
|
||||
assert classify_ref("custom-adhoc-branch") == (
|
||||
RefType.BRANCH,
|
||||
"custom-adhoc-branch",
|
||||
)
|
||||
|
||||
|
||||
def test_classify_ref_tags():
|
||||
@@ -145,7 +219,9 @@ deployment:
|
||||
|
||||
|
||||
def test_parse_manifest_rejects_missing_name():
|
||||
with pytest.raises(ManifestValidationError, match="missing mandatory string field 'name'"):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="missing mandatory string field 'name'"
|
||||
):
|
||||
parse_manifest("domain: test.example.com\n")
|
||||
|
||||
|
||||
@@ -162,7 +238,9 @@ deployment:
|
||||
- compose_up
|
||||
- rm_rf_root
|
||||
"""
|
||||
with pytest.raises(ManifestValidationError, match="Prohibited deployment action 'rm_rf_root'"):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="Prohibited deployment action 'rm_rf_root'"
|
||||
):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
|
||||
@@ -172,7 +250,9 @@ name: "app"
|
||||
deployment:
|
||||
strategy: "swarm"
|
||||
"""
|
||||
with pytest.raises(ManifestValidationError, match="Unsupported deployment strategy 'swarm'"):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="Unsupported deployment strategy 'swarm'"
|
||||
):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
|
||||
@@ -185,7 +265,9 @@ def test_parse_manifest_from_path(tmp_path: Path):
|
||||
assert manifest.is_internal is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid_key", [
|
||||
@pytest.mark.parametrize(
|
||||
"invalid_key",
|
||||
[
|
||||
"123_BAD",
|
||||
"INVALID-KEY",
|
||||
"FOO;BAR",
|
||||
@@ -195,14 +277,26 @@ def test_parse_manifest_from_path(tmp_path: Path):
|
||||
"IFS",
|
||||
"CORE_DIR",
|
||||
"SITES_DIR",
|
||||
])
|
||||
"HOMELAB_DOMAIN",
|
||||
"DOMAIN_SUFFIX",
|
||||
"DOMAIN",
|
||||
"PROXY_NETWORK",
|
||||
"CERT_RESOLVER",
|
||||
"DOCKER_CONFIG",
|
||||
"SERVICE_NAME",
|
||||
"CONTAINER_NAME",
|
||||
"SERVICE_DOMAIN",
|
||||
],
|
||||
)
|
||||
def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str):
|
||||
raw_yaml = f"""
|
||||
name: "app"
|
||||
env:
|
||||
"{invalid_key}": "some_value"
|
||||
"""
|
||||
with pytest.raises(ManifestValidationError, match="Invalid or reserved environment variable key"):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="Invalid or reserved environment variable key"
|
||||
):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
|
||||
@@ -226,7 +320,9 @@ def test_parse_manifest_rejects_extra_fields():
|
||||
name: "app"
|
||||
unrecognized_field: "should_fail"
|
||||
"""
|
||||
with pytest.raises(ManifestValidationError, match="unrecognized or forbidden field"):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="unrecognized or forbidden field"
|
||||
):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
|
||||
@@ -261,3 +357,13 @@ description: "Pydantic serialization test"
|
||||
assert manifest.to_dict()["name"] == "serialized-app"
|
||||
|
||||
|
||||
def test_parse_manifest_rejects_homelab_grants_file_in_env():
|
||||
"""Ensure HOMELAB_GRANTS_FILE is in RESERVED_ENV_KEYS and cannot be overridden by app.yaml."""
|
||||
raw_yaml = """
|
||||
name: "grants-override-app"
|
||||
env:
|
||||
HOMELAB_GRANTS_FILE: "/tmp/evil-grants.json"
|
||||
"""
|
||||
with pytest.raises(ManifestValidationError):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
+186
-16
@@ -4,14 +4,12 @@ Unit test suite for scripts/provenance.py (Two-Axis Inspection & Provenance Reso
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
# Add scripts directory to path
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
|
||||
# # Add scripts directory to path
|
||||
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
from core_manifest import Manifest, RefType, SourceConfig, TransportScheme
|
||||
from provenance import (
|
||||
ProvenanceStatus,
|
||||
@@ -43,12 +41,28 @@ def test_get_local_checkout_status_clean_repo(tmp_path: Path):
|
||||
app_dir = tmp_path / "git_app"
|
||||
app_dir.mkdir()
|
||||
env = _clean_git_env()
|
||||
subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env)
|
||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env)
|
||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "init", "-b", "main"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "config", "user.email", "test@example.com"],
|
||||
check=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env
|
||||
)
|
||||
(app_dir / "file.txt").write_text("hello", encoding="utf-8")
|
||||
subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env)
|
||||
subprocess.run(["git", "-C", str(app_dir), "commit", "-m", "init"], check=True, capture_output=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "commit", "-m", "init"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
status = get_local_checkout_status(app_dir)
|
||||
assert status.is_git is True
|
||||
@@ -62,12 +76,28 @@ def test_get_local_checkout_status_dirty_repo(tmp_path: Path):
|
||||
app_dir = tmp_path / "git_dirty_app"
|
||||
app_dir.mkdir()
|
||||
env = _clean_git_env()
|
||||
subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env)
|
||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env)
|
||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "init", "-b", "main"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "config", "user.email", "test@example.com"],
|
||||
check=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env
|
||||
)
|
||||
(app_dir / "file.txt").write_text("hello", encoding="utf-8")
|
||||
subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env)
|
||||
subprocess.run(["git", "-C", str(app_dir), "commit", "-m", "init"], check=True, capture_output=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "commit", "-m", "init"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
# Modify file to create dirty state
|
||||
(app_dir / "file.txt").write_text("modified", encoding="utf-8")
|
||||
@@ -131,7 +161,10 @@ def test_resolve_upstream_provenance_timeout():
|
||||
transport=TransportScheme.HTTPS,
|
||||
)
|
||||
|
||||
with patch("subprocess.run", side_effect=subprocess.TimeoutExpired(cmd=["git"], timeout=10.0)):
|
||||
with patch(
|
||||
"subprocess.run",
|
||||
side_effect=subprocess.TimeoutExpired(cmd=["git"], timeout=10.0),
|
||||
):
|
||||
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
|
||||
|
||||
assert prov.status == ProvenanceStatus.TIMEOUT
|
||||
@@ -183,13 +216,150 @@ def test_inspect_workload_two_axis(tmp_path: Path):
|
||||
)
|
||||
|
||||
# Without fetch_upstream: Axis 2 returns UNKNOWN
|
||||
status_no_fetch = inspect_workload_two_axis(tmp_path, manifest, fetch_upstream=False)
|
||||
status_no_fetch = inspect_workload_two_axis(
|
||||
tmp_path, manifest, fetch_upstream=False
|
||||
)
|
||||
assert status_no_fetch.provenance.status == ProvenanceStatus.UNKNOWN
|
||||
assert "Pass --fetch" in status_no_fetch.provenance.message
|
||||
|
||||
# With fetch_upstream: Axis 2 queries remote
|
||||
with patch("provenance.resolve_upstream_provenance") as mock_resolve:
|
||||
mock_resolve.return_value = MagicMock(status=ProvenanceStatus.SYNCED)
|
||||
status_fetch = inspect_workload_two_axis(tmp_path, manifest, fetch_upstream=True)
|
||||
status_fetch = inspect_workload_two_axis(
|
||||
tmp_path, manifest, fetch_upstream=True
|
||||
)
|
||||
assert status_fetch.provenance.status == ProvenanceStatus.SYNCED
|
||||
mock_resolve.assert_called_once()
|
||||
|
||||
|
||||
def test_resolve_upstream_provenance_class_b_and_default_timeout():
|
||||
# 1. Class B workload (source is None)
|
||||
prov_class_b = resolve_upstream_provenance(None)
|
||||
assert prov_class_b.status == ProvenanceStatus.IMAGE_ONLY
|
||||
assert prov_class_b.message == "Class B workload deploys prebuilt container images directly"
|
||||
|
||||
# 2. Default timeout (10.0s) verification
|
||||
source = SourceConfig(
|
||||
url="https://git.example.com/operator/app.git",
|
||||
ref="main",
|
||||
ref_type=RefType.BRANCH,
|
||||
transport=TransportScheme.HTTPS,
|
||||
)
|
||||
with patch("subprocess.run") as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=0, stdout="abc1234567890abcdef1234567890abcdef12345\trefs/heads/main\n")
|
||||
prov = resolve_upstream_provenance(source, local_commit="abc1234")
|
||||
assert prov.status == ProvenanceStatus.SYNCED
|
||||
assert mock_run.call_args[1]["timeout"] == 10.0
|
||||
|
||||
|
||||
def test_get_local_checkout_status_git_error(tmp_path: Path):
|
||||
app_dir = tmp_path / "git_error_app"
|
||||
app_dir.mkdir()
|
||||
(app_dir / ".git").mkdir()
|
||||
|
||||
with patch("subprocess.run") as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
returncode=128, stdout="", stderr="fatal: dubious ownership"
|
||||
)
|
||||
status = get_local_checkout_status(app_dir)
|
||||
assert status.is_git is True
|
||||
assert status.is_dirty is False
|
||||
assert status.status_label == "⚠️ Git Error (exit 128)"
|
||||
|
||||
|
||||
def _init_git_repo(repo_dir: Path, branch: str = "main") -> None:
|
||||
env = _clean_git_env()
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_dir), "init", "-b", branch],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_dir), "config", "user.email", "test@example.com"],
|
||||
check=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_dir), "config", "user.name", "Test"],
|
||||
check=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
|
||||
def test_get_local_checkout_status_monorepo_subpath_isolation(tmp_path: Path):
|
||||
"""Ensure monorepo subpath inspection isolates dirty state per workload directory (#33)."""
|
||||
workloads_dir = tmp_path / "Workloads"
|
||||
app_a = workloads_dir / "app_a"
|
||||
app_b = workloads_dir / "app_b"
|
||||
app_a.mkdir(parents=True)
|
||||
app_b.mkdir(parents=True)
|
||||
_init_git_repo(workloads_dir, branch="main")
|
||||
|
||||
(app_a / "app.yaml").write_text("name: app_a\n", encoding="utf-8")
|
||||
(app_b / "app.yaml").write_text("name: app_b\n", encoding="utf-8")
|
||||
|
||||
env = _clean_git_env()
|
||||
subprocess.run(["git", "-C", str(workloads_dir), "add", "."], check=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(workloads_dir), "commit", "-m", "init monorepo"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
# Dirty only app_b
|
||||
(app_b / "app.yaml").write_text("name: app_b_dirty\n", encoding="utf-8")
|
||||
(app_b / "untracked.txt").write_text("dirty\n", encoding="utf-8")
|
||||
|
||||
status_a = get_local_checkout_status(app_a)
|
||||
assert status_a.is_git is True
|
||||
assert status_a.is_dirty is False
|
||||
assert status_a.branch == "main"
|
||||
assert status_a.commit_sha != ""
|
||||
assert "✓ Clean" in status_a.status_label
|
||||
|
||||
status_b = get_local_checkout_status(app_b)
|
||||
assert status_b.is_git is True
|
||||
assert status_b.is_dirty is True
|
||||
assert status_b.branch == "main"
|
||||
assert "* Dirty" in status_b.status_label
|
||||
|
||||
|
||||
def test_get_local_checkout_status_hybrid_precedence_standalone_over_monorepo(
|
||||
tmp_path: Path,
|
||||
):
|
||||
"""Ensure standalone <app>/.git takes precedence over parent monorepo .git (#33)."""
|
||||
workloads_dir = tmp_path / "Workloads"
|
||||
app_a = workloads_dir / "app_a"
|
||||
app_a.mkdir(parents=True)
|
||||
_init_git_repo(workloads_dir, branch="main")
|
||||
|
||||
env = _clean_git_env()
|
||||
(workloads_dir / "README.md").write_text("monorepo\n", encoding="utf-8")
|
||||
subprocess.run(
|
||||
["git", "-C", str(workloads_dir), "add", "README.md"], check=True, env=env
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(workloads_dir), "commit", "-m", "monorepo root"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
# Nested standalone .git inside app_a on a distinct branch
|
||||
_init_git_repo(app_a, branch="standalone-branch")
|
||||
(app_a / "app.yaml").write_text("name: app_a\n", encoding="utf-8")
|
||||
subprocess.run(["git", "-C", str(app_a), "add", "app.yaml"], check=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_a), "commit", "-m", "standalone commit"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
status_a = get_local_checkout_status(app_a)
|
||||
assert status_a.is_git is True
|
||||
assert status_a.is_dirty is False
|
||||
assert status_a.branch == "standalone-branch"
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Unit tests for Pydantic v2 workload capability grants loader (ADR-0005)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
from workload_grants import (
|
||||
GrantsRegistry,
|
||||
WorkloadGrant,
|
||||
WorkloadGrantsError,
|
||||
load_workload_grants,
|
||||
)
|
||||
|
||||
|
||||
def test_load_workload_grants_absent_file_returns_empty(tmp_path: Path) -> None:
|
||||
missing = tmp_path / "does-not-exist.json"
|
||||
assert load_workload_grants(missing) == {}
|
||||
|
||||
|
||||
def test_load_workload_grants_honors_env_var_when_none(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
grants_path = tmp_path / "grants.json"
|
||||
grants_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"schemaVersion": "1.0",
|
||||
"workloads": {
|
||||
"media": {
|
||||
"devices": ["/dev/dri/renderD128"],
|
||||
"groups": ["render", "303"],
|
||||
"readOnlyPaths": ["/mnt/media"],
|
||||
}
|
||||
},
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setenv("HOMELAB_GRANTS_FILE", str(grants_path))
|
||||
loaded = load_workload_grants(verify_permissions=False)
|
||||
assert "media" in loaded
|
||||
assert loaded["media"].devices == ["/dev/dri/renderD128"]
|
||||
assert loaded["media"].groups == ["render", "303"]
|
||||
assert loaded["media"].readOnlyPaths == ["/mnt/media"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad_group", ["0", "root", "wheel", "docker", "ROOT", " wheel "])
|
||||
def test_workload_grant_rejects_privileged_groups(bad_group: str) -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
WorkloadGrant(groups=[bad_group])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad_path",
|
||||
[
|
||||
"dev/dri/renderD128",
|
||||
"../etc/passwd",
|
||||
"/dev/../etc/shadow",
|
||||
"/mnt/media/..",
|
||||
"",
|
||||
],
|
||||
)
|
||||
def test_workload_grant_rejects_relative_and_traversal_paths(bad_path: str) -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
WorkloadGrant(devices=[bad_path])
|
||||
with pytest.raises(ValidationError):
|
||||
WorkloadGrant(readOnlyPaths=[bad_path])
|
||||
|
||||
|
||||
def test_grants_registry_rejects_extra_fields() -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
GrantsRegistry.model_validate(
|
||||
{
|
||||
"schemaVersion": "1.0",
|
||||
"workloads": {"app": {"devices": [], "extra_field": True}},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_grants_registry_rejects_bad_schema_version() -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
GrantsRegistry.model_validate({"schemaVersion": "2.0", "workloads": {}})
|
||||
|
||||
|
||||
def test_load_workload_grants_malformed_json_fails_closed(tmp_path: Path) -> None:
|
||||
grants_path = tmp_path / "grants.json"
|
||||
grants_path.write_text("{not valid json", encoding="utf-8")
|
||||
with pytest.raises(WorkloadGrantsError):
|
||||
load_workload_grants(grants_path)
|
||||
|
||||
|
||||
def test_load_workload_grants_unreadable_file_fails_closed(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
grants_path = tmp_path / "grants.json"
|
||||
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
|
||||
|
||||
def raise_perm_error(self: Path, *args: object, **kwargs: object) -> str:
|
||||
raise PermissionError("Permission denied")
|
||||
|
||||
monkeypatch.setattr(Path, "read_text", raise_perm_error)
|
||||
with pytest.raises(WorkloadGrantsError, match="read"):
|
||||
load_workload_grants(grants_path)
|
||||
|
||||
|
||||
def test_load_workload_grants_verify_permissions_rejects_symlink(tmp_path: Path) -> None:
|
||||
real_file = tmp_path / "real.json"
|
||||
real_file.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
|
||||
link_file = tmp_path / "grants.json"
|
||||
link_file.symlink_to(real_file)
|
||||
|
||||
with pytest.raises(WorkloadGrantsError, match="symlink"):
|
||||
load_workload_grants(link_file, verify_permissions=True)
|
||||
|
||||
|
||||
def test_load_workload_grants_verify_permissions_rejects_non_root_owner(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
grants_path = tmp_path / "grants.json"
|
||||
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(
|
||||
os,
|
||||
"lstat",
|
||||
lambda _p: SimpleNamespace(st_mode=0o100640, st_uid=1000),
|
||||
)
|
||||
with pytest.raises(WorkloadGrantsError, match="root"):
|
||||
load_workload_grants(grants_path, verify_permissions=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad_mode", [0o100664, 0o100660, 0o100642, 0o100646])
|
||||
def test_load_workload_grants_verify_permissions_rejects_writable_mode(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bad_mode: int
|
||||
) -> None:
|
||||
grants_path = tmp_path / "grants.json"
|
||||
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(
|
||||
os,
|
||||
"lstat",
|
||||
lambda _p: SimpleNamespace(st_mode=bad_mode, st_uid=0),
|
||||
)
|
||||
with pytest.raises(WorkloadGrantsError, match="writable"):
|
||||
load_workload_grants(grants_path, verify_permissions=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("good_mode", [0o100640, 0o100644])
|
||||
def test_load_workload_grants_verify_permissions_accepts_non_writable_mode(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, good_mode: int
|
||||
) -> None:
|
||||
grants_path = tmp_path / "grants.json"
|
||||
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(
|
||||
os,
|
||||
"lstat",
|
||||
lambda _p: SimpleNamespace(st_mode=good_mode, st_uid=0),
|
||||
)
|
||||
assert load_workload_grants(grants_path, verify_permissions=True) == {}
|
||||
@@ -22,11 +22,26 @@ 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
|
||||
x 2026-10-19 (A) Enable Core platform stack and core_service container-scoped dispatch in OperationalRouter in scripts/appctl_router.py +router @p4
|
||||
x 2026-10-19 (A) Restore human-readable tabular output, list filter parameters, and bash autocompletion fast-path in scripts/appctl_cli.py and scripts/appctl +cli @p4
|
||||
x 2026-10-19 (A) Add operatorUser to homelab-operators group and configure daemon systemd sandbox HOME and DOCKER_CONFIG in nixos/modules/homeserver.nix +nixos @p4
|
||||
x 2026-10-19 (A) Provision SOPS appctl/tokens_json and gitops/appctl_token secrets and wire GITOPS_APPCTL_TOKEN_FILE in nixos/secrets.yaml and nixos/modules/homeserver.nix +secrets @p4
|
||||
x 2026-10-19 (B) Reconcile operational documentation and ROADMAP.md with Milestone P4 control plane daemon architecture +docs @p4
|
||||
x 2026-10-23 (A) Migrate operator user from kiskaadee to operator in nixos/configuration.nix and homeserver.nix +nixos @core
|
||||
x 2026-10-23 (A) Derive LLDAP_LDAP_BASE_DN dynamically from homelab.domain in nixos/modules/homeserver.nix and docker-compose.yml +nixos @auth
|
||||
x 2026-10-23 (A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms
|
||||
x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git
|
||||
x 2026-10-30 (B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security
|
||||
x 2026-10-30 (B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux
|
||||
x 2026-10-30 (B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth
|
||||
x 2026-10-30 (B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4
|
||||
x 2026-10-30 (C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap
|
||||
x 2026-10-30 (A) Implement instance domain injection dual-path import and operator cutover runbook in nixos/configuration.nix and docs/ +generic @nixos
|
||||
Reference in new issue
Block a user