Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
+11
-1
@@ -21,7 +21,17 @@ else
|
|||||||
echo "⚠️ [pre-commit] Neither ruff nor nix found; skipping ruff"
|
echo "⚠️ [pre-commit] Neither ruff nor nix found; skipping ruff"
|
||||||
fi
|
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..."
|
echo " ↳ Running structural and security test suite with Pytest..."
|
||||||
if [ -x ".venv/bin/pytest" ]; then
|
if [ -x ".venv/bin/pytest" ]; then
|
||||||
.venv/bin/pytest tests/
|
.venv/bin/pytest tests/
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ backup.zip
|
|||||||
.envrc
|
.envrc
|
||||||
.direnv
|
.direnv
|
||||||
.venv
|
.venv
|
||||||
|
nixos/instance.nix
|
||||||
|
|
||||||
# SSL / ACME Certificates & Keys
|
# SSL / ACME Certificates & Keys
|
||||||
config/letsencrypt/*
|
config/letsencrypt/*
|
||||||
@@ -40,13 +41,20 @@ config/homepage/custom.js
|
|||||||
Thumbs.db
|
Thumbs.db
|
||||||
.vscode/
|
.vscode/
|
||||||
.idea/
|
.idea/
|
||||||
|
.worktrees/
|
||||||
|
|
||||||
# Python & Testing Caches
|
# Python & Testing Caches
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.ruff_cache/
|
.ruff_cache/
|
||||||
|
mutants/
|
||||||
|
.mutmut-cache/
|
||||||
|
|
||||||
# Local Bootstrap & Operational Scripts
|
# Local Bootstrap & Operational Scripts
|
||||||
scripts/bootstrap_lldap_users.py
|
scripts/bootstrap_lldap_users.py
|
||||||
scripts/bootstrap_*.py
|
scripts/bootstrap_*.py
|
||||||
|
!scripts/bootstrap_token.py
|
||||||
|
|
||||||
|
# Worktrees & Slices
|
||||||
|
.worktrees/
|
||||||
@@ -9,7 +9,7 @@ It is designed around a strict two-tier boundary:
|
|||||||
All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime.
|
All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime.
|
||||||
|
|
||||||
> [!NOTE]
|
> [!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:9876`). 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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -49,8 +49,10 @@ All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_
|
|||||||
▲
|
▲
|
||||||
│ (Host Orchestration & CD)
|
│ (Host Orchestration & CD)
|
||||||
┌───────────────┴───────────────┐
|
┌───────────────┴───────────────┐
|
||||||
│ Host Control Plane Baseline │
|
│ Host Control Plane (P4) │
|
||||||
│ • appctl CLI + Engine │
|
│ • thin appctl CLI │
|
||||||
|
│ • homelab-appctl.service │
|
||||||
|
│ (UDS / HTTP daemon) │
|
||||||
│ • homelab-gitops.service │
|
│ • homelab-gitops.service │
|
||||||
└───────────────────────────────┘
|
└───────────────────────────────┘
|
||||||
```
|
```
|
||||||
@@ -82,10 +84,17 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran
|
|||||||
├── nixos/ # Declarative NixOS modules, systemd units, and SOPS secret wiring
|
├── nixos/ # Declarative NixOS modules, systemd units, and SOPS secret wiring
|
||||||
├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml)
|
├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml)
|
||||||
├── scripts/
|
├── scripts/
|
||||||
│ ├── appctl # Operational CLI entrypoint and Compose environment orchestrator
|
│ ├── appctl # Thin operational CLI delegating to control plane daemon
|
||||||
│ ├── appctl_engine.py # Discovery, two-axis provenance, TLS inspection, and Homepage sync engine
|
│ ├── appctl_daemon.py # Async HTTP/UDS daemon server (homelab-appctl.service)
|
||||||
│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for workload app.yaml
|
│ ├── appctl_router.py # Operational router, locking, RBAC & dispatch
|
||||||
│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST security validation
|
│ ├── 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
|
||||||
│ └── test # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks)
|
│ └── test # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks)
|
||||||
├── tests/ # Unit, structural, and security invariant test suites
|
├── tests/ # Unit, structural, and security invariant test suites
|
||||||
└── docs/ # Architecture references, operational runbooks, and MADR decisions
|
└── docs/ # Architecture references, operational runbooks, and MADR decisions
|
||||||
@@ -93,7 +102,7 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Quickstart & Operations (Current CLI Baseline)
|
## Quickstart & Operations (Control Plane Daemon & CLI)
|
||||||
|
|
||||||
### Development & Verification
|
### Development & Verification
|
||||||
|
|
||||||
@@ -111,7 +120,12 @@ pyright
|
|||||||
|
|
||||||
### Workload Management (`appctl` CLI)
|
### 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
|
```bash
|
||||||
|
# Check daemon health status
|
||||||
|
appctl health
|
||||||
|
|
||||||
# List all workloads with container health and local Git checkout status
|
# List all workloads with container health and local Git checkout status
|
||||||
appctl list
|
appctl list
|
||||||
|
|
||||||
@@ -121,7 +135,7 @@ appctl list --fetch --ssl --core
|
|||||||
# Inspect detailed manifest, provenance, and container diagnostics for a workload
|
# Inspect detailed manifest, provenance, and container diagnostics for a workload
|
||||||
appctl info <service>
|
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 up <service|core>
|
||||||
appctl down <service|core>
|
appctl down <service|core>
|
||||||
appctl restart <service|core>
|
appctl restart <service|core>
|
||||||
@@ -136,11 +150,12 @@ appctl sync
|
|||||||
### Host System Management
|
### Host System Management
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Rebuild and activate the NixOS host configuration
|
# Rebuild and activate the NixOS host configuration (or use the 'nix-switch' alias)
|
||||||
sudo nixos-rebuild switch --flake .#server
|
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
|
||||||
|
|
||||||
# Inspect platform systemd units
|
# Inspect platform systemd units
|
||||||
systemctl status homeserver-core.service
|
systemctl status homeserver-core.service
|
||||||
|
systemctl status homelab-appctl.service
|
||||||
systemctl status homelab-gitops.service
|
systemctl status homelab-gitops.service
|
||||||
systemctl status dynu-monitor.service
|
systemctl status dynu-monitor.service
|
||||||
```
|
```
|
||||||
|
|||||||
+31
-29
@@ -1,36 +1,38 @@
|
|||||||
# 🗺️ Homelab Core & Appctl Engineering Roadmap
|
# 🗺️ Homelab Core & Appctl Engineering Roadmap
|
||||||
|
|
||||||
This document serves as the repository-facing projection of the authoritative **Homelab Architecture Consolidation & Control Plane Roadmap (v5)**.
|
This document serves as the repository-facing projection of the authoritative **Homelab Architecture Consolidation & Control Plane Roadmap (v6)** and the locked Milestone P4 boundary specification ([`docs/plans/p4-readiness-plan.md`](docs/plans/p4-readiness-plan.md)).
|
||||||
|
|
||||||
It describes the implementation trajectory and phased engineering milestones for transitioning Homelab Core into a unified platform driven by the `appctl` Operational Control Plane.
|
It describes the implementation trajectory and phased engineering milestones for transitioning Homelab Core into a unified platform driven by the `appctl` Operational Control Plane.
|
||||||
|
|
||||||
> **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index (Control Plane Architecture, 3-Tier Provenance Model, and Pydantic v2 Runtime Validation).
|
> **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index ([ADR-0001: 3-Tier Provenance Model](docs/decisions/0001-3tier-architecture-and-provenance.md), [ADR-0002: Operational Control Plane Architecture](docs/decisions/0002-appctl-control-plane-architecture.md), and [ADR-0003: Pydantic v2 Runtime Validation](docs/decisions/0003-pydantic-v2-runtime-validation.md)).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🎯 Architectural Invariants Governing Execution
|
## 🎯 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.
|
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.
|
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 Authority**: Entering via SSH does not bypass authentication. Every mutating operation requires an explicit, authenticated user-scoped token.
|
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. **Separation of Intent from Implementation**: `DeploymentModel` captures implementation-agnostic intent; concrete platform descriptors (`app.yaml` + Compose) are materialized and enforced by `appctl`.
|
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. **AI Authoring Boundary**: AI agents act strictly as proposal generators (`DeploymentProposal`). Humans approve the intent (`DeploymentModel`). The AI possesses zero execution authority.
|
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. **Secret Reference Invariant**: Deployment definitions store secret references (`secretKeyRef`), never plaintext material, resolved at runtime via `SecretProvider`.
|
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. **Clean State Root**: Mutable application runtime data resides strictly under `~/var/lib/homelab/<app>/`, isolated from Git repositories.
|
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
|
## 🔍 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. |
|
| **`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** | 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). |
|
| **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** | 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. |
|
| **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** | 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. |
|
| **Deployment Model** | Direct authoring of `app.yaml` and `docker-compose.yml` in `~/Sites/<app>/`. | Authoritative declarative Git state (`app.yaml` + Compose) managed via CLI, GitOps, or client-gated MCP tools (P6). |
|
||||||
| **GitOps Engine** | Webhook dispatcher (`scripts/gitops_dispatcher.py`) with HMAC-SHA256 auth, Compose AST security validator, and `flock` serialization. | Integrated into control-plane admission, invoking central reconciliation endpoints. |
|
| **GitOps Engine** | 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). |
|
| **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,9 @@ 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. |
|
| **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. |
|
| **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`. |
|
| **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. |
|
| **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. |
|
||||||
| **P5** | **Identity & Secrets** | Auth & Providers | ⏳ **Planned** | LLDAP RBAC group mapping, Authelia ForwardAuth header integration, user-scoped token lifecycle, `SecretProvider` reference resolution. |
|
| **P5** | **Identity & Secrets** | Auth & Providers | 🎯 **Current / Up Next** | 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. |
|
| **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. |
|
| **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -55,7 +57,7 @@ It describes the implementation trajectory and phased engineering milestones for
|
|||||||
**Status**: ✅ **Completed**
|
**Status**: ✅ **Completed**
|
||||||
* Merged `refactor/appctl-rework` and `main` into a unified architectural baseline (commit `2297cd5`).
|
* 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.
|
* 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.
|
* Verified test suite and NixOS flake sandbox evaluation.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -97,7 +99,7 @@ It describes the implementation trajectory and phased engineering milestones for
|
|||||||
---
|
---
|
||||||
|
|
||||||
### Milestone P4: Appctl Control Plane Daemon & Command-Oriented API
|
### 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.
|
* **Objective**: Evolve `appctl` from a collection of local shell scripts into the authoritative platform daemon while enforcing authorization gates from day one.
|
||||||
* **Key Deliverables**:
|
* **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`).
|
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 +122,15 @@ It describes the implementation trajectory and phased engineering milestones for
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Milestone P6: Homelab Deployment Model & AI Authoring Workflow
|
### Milestone P6: Homelab MCP Gateway (Protocol Tool Integration)
|
||||||
**Status**: ⏳ **Planned**
|
**Status**: ⏳ **Planned** *(Amended: Deprecated on-server `DeploymentProposal` compiler in favor of decoupled Model Context Protocol gateway)*
|
||||||
* **Objective**: Enable safe, human-reviewed workload authoring from upstream repositories.
|
* **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**:
|
* **Key Deliverables**:
|
||||||
1. *Platform Capability Catalog*: Machine-readable specification of Core capabilities and security invariants.
|
1. *Protocol Tool Gateway*: Standardized MCP server wrapping deterministic `appctl` operations (`appctl_status`, `appctl_logs`, `appctl_deploy`, `appctl_audit`) over JSON-RPC.
|
||||||
2. *DeploymentProposal Schema*: Candidate model format produced by AI discovery workflows.
|
2. *Client-Side Human-in-the-Loop Confirmation*: Native IDE/client confirmation gating for all mutating tools before execution.
|
||||||
3. *DeploymentModel Git Pipeline*: Operator approves proposal into a `DeploymentModel`; the model is committed to the version-controlled deployment repository (Git).
|
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. *Materialization & Reconciliation*: `appctl` validates the committed model, provisions state roots, compiles platform descriptors (`app.yaml` + Compose), and reconciles running containers.
|
4. *Schema & Tool Security Guards*: Strict Pydantic parameter validation on incoming MCP tool calls matching `appctl_contracts.py`.
|
||||||
* **Exit Criteria**: Human approval gate strictly enforced; AI possesses zero execution authority; generated workloads conform to all Core invariants.
|
* **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 +138,7 @@ It describes the implementation trajectory and phased engineering milestones for
|
|||||||
**Status**: ⏳ **Planned**
|
**Status**: ⏳ **Planned**
|
||||||
* **Objective**: Deliver a unified web-based management experience without coupling the control plane to specific frontend engines.
|
* **Objective**: Deliver a unified web-based management experience without coupling the control plane to specific frontend engines.
|
||||||
* **Key Deliverables**:
|
* **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.
|
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.
|
* **Exit Criteria**: End-to-end browser and CLI deployment verification; Homepage accurately reflecting live container health.
|
||||||
|
|
||||||
|
|||||||
+12
@@ -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`).
|
* 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.
|
* 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
|
## 2. Threat Model & Operational Considerations
|
||||||
@@ -57,3 +66,6 @@ This document outlines the security controls, container isolation rules, and ope
|
|||||||
- [x] Invariant test runner (`./scripts/test`) passing on changes.
|
- [x] Invariant test runner (`./scripts/test`) passing on changes.
|
||||||
- [x] `config/letsencrypt/acme.json` permissions set to `0600`.
|
- [x] `config/letsencrypt/acme.json` permissions set to `0600`.
|
||||||
- [x] Host firewall ports restricted to declared services in `nixos/modules/homeserver.nix`.
|
- [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'
|
address: 'ldap://lldap:3890'
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
start_tls: false
|
start_tls: false
|
||||||
base_dn: 'dc=roadtotech,dc=me'
|
base_dn: '{{ env "LLDAP_LDAP_BASE_DN" "dc=example,dc=test" }}'
|
||||||
additional_users_dn: 'ou=people'
|
additional_users_dn: 'ou=people'
|
||||||
users_filter: '(&({username_attribute}={input})(objectClass=person))'
|
users_filter: '(&({username_attribute}={input})(objectClass=person))'
|
||||||
additional_groups_dn: 'ou=groups'
|
additional_groups_dn: 'ou=groups'
|
||||||
@@ -24,7 +24,7 @@ authentication_backend:
|
|||||||
display_name: 'displayName'
|
display_name: 'displayName'
|
||||||
mail: 'mail'
|
mail: 'mail'
|
||||||
group_name: 'cn'
|
group_name: 'cn'
|
||||||
user: 'uid=admin,ou=people,dc=roadtotech,dc=me'
|
user: 'uid=admin,ou=people,{{ env "LLDAP_LDAP_BASE_DN" "dc=example,dc=test" }}'
|
||||||
|
|
||||||
access_control:
|
access_control:
|
||||||
default_policy: deny
|
default_policy: deny
|
||||||
|
|||||||
+10
-10
@@ -6,48 +6,48 @@
|
|||||||
schemaVersion: "1.0"
|
schemaVersion: "1.0"
|
||||||
repositories:
|
repositories:
|
||||||
snappymail:
|
snappymail:
|
||||||
path: "/home/kiskaadee/Sites/snappymail"
|
path: "~/Sites/snappymail"
|
||||||
aliases:
|
aliases:
|
||||||
- "homelab-snappymail"
|
- "homelab-snappymail"
|
||||||
- "mail"
|
- "mail"
|
||||||
- "webmail"
|
- "webmail"
|
||||||
gitea:
|
gitea:
|
||||||
path: "/home/kiskaadee/Sites/homelab-gitea"
|
path: "~/Sites/homelab-gitea"
|
||||||
aliases:
|
aliases:
|
||||||
- "homelab-gitea"
|
- "homelab-gitea"
|
||||||
- "git"
|
- "git"
|
||||||
jellyfin:
|
jellyfin:
|
||||||
path: "/home/kiskaadee/Sites/homelab-jellyfin"
|
path: "~/Sites/homelab-jellyfin"
|
||||||
aliases:
|
aliases:
|
||||||
- "homelab-jellyfin"
|
- "homelab-jellyfin"
|
||||||
- "media"
|
- "media"
|
||||||
docs:
|
docs:
|
||||||
path: "/home/kiskaadee/Sites/homelab-doc2site"
|
path: "~/Sites/homelab-doc2site"
|
||||||
aliases:
|
aliases:
|
||||||
- "doc2site"
|
- "doc2site"
|
||||||
- "homelab-doc2site"
|
- "homelab-doc2site"
|
||||||
courses:
|
courses:
|
||||||
path: "/home/kiskaadee/Sites/courses"
|
path: "~/Sites/courses"
|
||||||
aliases:
|
aliases:
|
||||||
- "homelab-courses"
|
- "homelab-courses"
|
||||||
bdinvite:
|
bdinvite:
|
||||||
path: "/home/kiskaadee/Sites/homelab-bdinvite"
|
path: "~/Sites/homelab-bdinvite"
|
||||||
aliases:
|
aliases:
|
||||||
- "homelab-bdinvite"
|
- "homelab-bdinvite"
|
||||||
- "birthday"
|
- "birthday"
|
||||||
landing:
|
landing:
|
||||||
path: "/home/kiskaadee/Sites/homelab-landing"
|
path: "~/Sites/homelab-landing"
|
||||||
aliases:
|
aliases:
|
||||||
- "homelab-landing"
|
- "homelab-landing"
|
||||||
mermaid:
|
mermaid:
|
||||||
path: "/home/kiskaadee/Sites/homelab-mermaid"
|
path: "~/Sites/homelab-mermaid"
|
||||||
aliases:
|
aliases:
|
||||||
- "homelab-mermaid"
|
- "homelab-mermaid"
|
||||||
excalidraw:
|
excalidraw:
|
||||||
path: "/home/kiskaadee/Sites/homelab-excalidraw"
|
path: "~/Sites/homelab-excalidraw"
|
||||||
aliases:
|
aliases:
|
||||||
- "homelab-excalidraw"
|
- "homelab-excalidraw"
|
||||||
houston:
|
houston:
|
||||||
path: "/home/kiskaadee/Sites/homelab-houston"
|
path: "~/Sites/homelab-houston"
|
||||||
aliases:
|
aliases:
|
||||||
- "homelab-houston"
|
- "homelab-houston"
|
||||||
@@ -5,7 +5,7 @@
|
|||||||
- My Projects:
|
- My Projects:
|
||||||
- Github:
|
- Github:
|
||||||
- abbr: GH
|
- abbr: GH
|
||||||
href: https://github.com/kiskaadee?tab=repositories
|
href: https://github.com
|
||||||
|
|
||||||
- Social Media:
|
- Social Media:
|
||||||
- Instagram:
|
- Instagram:
|
||||||
|
|||||||
@@ -4,13 +4,13 @@
|
|||||||
- Knowledge & Notes:
|
- Knowledge & Notes:
|
||||||
- Docs-Viewer:
|
- Docs-Viewer:
|
||||||
icon: files.png
|
icon: files.png
|
||||||
href: https://docs.roadtotech.me
|
href: https://docs.example.test
|
||||||
description: Reactive Obsidian & Markdown Documentation Viewer
|
description: Reactive Obsidian & Markdown Documentation Viewer
|
||||||
server: my-docker
|
server: my-docker
|
||||||
container: docs
|
container: docs
|
||||||
- Excalidraw:
|
- Excalidraw:
|
||||||
icon: excalidraw.png
|
icon: excalidraw.png
|
||||||
href: https://excalidraw.roadtotech.me
|
href: https://excalidraw.example.test
|
||||||
description: Collaborative Whiteboarding & Sketching Tool
|
description: Collaborative Whiteboarding & Sketching Tool
|
||||||
server: my-docker
|
server: my-docker
|
||||||
container: excalidraw
|
container: excalidraw
|
||||||
@@ -18,7 +18,7 @@
|
|||||||
- Media & Productivity:
|
- Media & Productivity:
|
||||||
- Jellyfin:
|
- Jellyfin:
|
||||||
icon: jellyfin.png
|
icon: jellyfin.png
|
||||||
href: https://jellyfin.roadtotech.me
|
href: https://jellyfin.example.test
|
||||||
description: Media Server & Streaming Hub
|
description: Media Server & Streaming Hub
|
||||||
server: my-docker
|
server: my-docker
|
||||||
container: jellyfin
|
container: jellyfin
|
||||||
+6
-5
@@ -106,11 +106,11 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
- TZ=America/Bogota
|
- TZ=America/Bogota
|
||||||
- LLDAP_HTTP_URL=https://users.${DOMAIN}
|
- 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_JWT_SECRET=${LLDAP_JWT_SECRET}
|
||||||
- LLDAP_KEY_SEED=${LLDAP_KEY_SEED}
|
- LLDAP_KEY_SEED=${LLDAP_KEY_SEED}
|
||||||
- LLDAP_LDAP_USER_PASS=${LLDAP_LDAP_USER_PASS}
|
- 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
|
- LLDAP_DATABASE_URL=sqlite:///data/users.db?mode=rwc
|
||||||
volumes:
|
volumes:
|
||||||
- ./config/lldap/data:/data
|
- ./config/lldap/data:/data
|
||||||
@@ -142,6 +142,7 @@ services:
|
|||||||
- ./config/authelia:/config
|
- ./config/authelia:/config
|
||||||
environment:
|
environment:
|
||||||
- DOMAIN=${DOMAIN}
|
- DOMAIN=${DOMAIN}
|
||||||
|
- LLDAP_LDAP_BASE_DN=${LLDAP_LDAP_BASE_DN}
|
||||||
- AUTHELIA_SESSION_SECRET=${AUTHELIA_SESSION_SECRET}
|
- AUTHELIA_SESSION_SECRET=${AUTHELIA_SESSION_SECRET}
|
||||||
- AUTHELIA_STORAGE_ENCRYPTION_KEY=${AUTHELIA_STORAGE_ENCRYPTION_KEY}
|
- AUTHELIA_STORAGE_ENCRYPTION_KEY=${AUTHELIA_STORAGE_ENCRYPTION_KEY}
|
||||||
- AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET=${AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET}
|
- AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET=${AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET}
|
||||||
@@ -222,12 +223,12 @@ services:
|
|||||||
- DIUN_PROVIDERS_DOCKER_APIVERSION=${DOCKER_API_VERSION:-1.40}
|
- DIUN_PROVIDERS_DOCKER_APIVERSION=${DOCKER_API_VERSION:-1.40}
|
||||||
- DIUN_NOTIF_MAIL_HOST=stalwart
|
- DIUN_NOTIF_MAIL_HOST=stalwart
|
||||||
- DIUN_NOTIF_MAIL_PORT=465
|
- 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_PASSWORD=${DIUN_SMTP_PASSWORD}
|
||||||
- DIUN_NOTIF_MAIL_SSL=true
|
- DIUN_NOTIF_MAIL_SSL=true
|
||||||
- DIUN_NOTIF_MAIL_INSECURESKIPVERIFY=true
|
- DIUN_NOTIF_MAIL_INSECURESKIPVERIFY=true
|
||||||
- DIUN_NOTIF_MAIL_FROM=notifier@${DOMAIN:-roadtotech.me}
|
- DIUN_NOTIF_MAIL_FROM=${DIUN_NOTIF_MAIL_FROM:-notifier@${DOMAIN:-example.test}}
|
||||||
- DIUN_NOTIF_MAIL_TO=kiskaadee@${DOMAIN:-roadtotech.me}
|
- DIUN_NOTIF_MAIL_TO=${DIUN_NOTIF_MAIL_TO:-operator@${DOMAIN:-example.test}}
|
||||||
volumes:
|
volumes:
|
||||||
- ./config/diun:/data
|
- ./config/diun:/data
|
||||||
networks:
|
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`.
|
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]
|
> [!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`).
|
> **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 planned Milestone P4 control-plane daemon transition and phased engineering roadmap, see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md).
|
> For the platform's phased engineering roadmap, see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. How `appctl` Works
|
## 1. How `appctl` Works
|
||||||
|
|
||||||
`appctl` consists of three cooperating modules in `scripts/`:
|
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)** (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.
|
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`).
|
||||||
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.).
|
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
|
```text
|
||||||
┌───────────────────────────────┐
|
┌──────────────────────────┐ ┌──────────────────────────┐
|
||||||
│ appctl <command> │
|
│ appctl <cmd> (CLI) │ │ homelab-gitops.service │
|
||||||
└───────────────┬───────────────┘
|
└────────────┬─────────────┘ └────────────┬─────────────┘
|
||||||
│
|
│ UDS (/run/homelab/appctl.sock) │ Bearer Token (homelab-operator)
|
||||||
|
└─────────────────┬─────────────────┘
|
||||||
▼
|
▼
|
||||||
┌───────────────────────────┐
|
┌────────────────────────────────────────────────┐
|
||||||
│ setup_app_env() │
|
│ homelab-appctl.service (appctl_daemon.py) │
|
||||||
└─────────────┬─────────────┘
|
│ • POST /v1/operations & GET /v1/health │
|
||||||
│
|
│ • Auth: SHA-256 tokens.json + SO_PEERCRED │
|
||||||
┌──────────────────────────┴──────────────────────────┐
|
│ • RBAC: admin / operator / viewer │
|
||||||
▼ ▼
|
└────────────────────────┬───────────────────────┘
|
||||||
[ 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
|
|
||||||
│ │
|
|
||||||
└──────────────────────────┬──────────────────────────┘
|
|
||||||
▼
|
▼
|
||||||
┌─────────────────────────────┐
|
┌────────────────────────────────────────────────┐
|
||||||
│ Injected Compose Context │
|
│ OperationalRouter (appctl_router.py) │
|
||||||
│ • PROXY_NETWORK │
|
│ • Per-target flock + Fail-closed DISPATCHED │
|
||||||
│ • SERVICE_DOMAIN / DOMAIN │
|
│ audit write (/var/log/homelab/appctl/...) │
|
||||||
│ • CONTAINER_NAME │
|
│ • Pre-flight: parse_manifest() + Compose AST │
|
||||||
│ • Validated manifest env │
|
│ • 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
|
## 2. CLI Command Reference
|
||||||
@@ -100,11 +193,13 @@ appctl info docs --ssl
|
|||||||
|
|
||||||
### Lifecycle Management
|
### Lifecycle Management
|
||||||
|
|
||||||
#### `appctl up <service|core>`
|
#### `appctl up <service|core> [--build] [--no-cache]`
|
||||||
Starts the specified service stack in detached mode (`--remove-orphans`).
|
Starts the specified service stack in detached mode (`--remove-orphans`).
|
||||||
* For a workload in `~/Sites`: starts containers and triggers `appctl sync`.
|
* 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 `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.
|
* 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>`
|
#### `appctl down <service|core>`
|
||||||
Stops and removes containers defined in the target's Compose file (or stops the targeted Core container).
|
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 core`: Restarts all Core Compose services.
|
||||||
* `appctl restart traefik`: Restarts only the Traefik container.
|
* `appctl restart traefik`: Restarts only the Traefik container.
|
||||||
|
|
||||||
#### `appctl update <service|core>`
|
#### `appctl update <service> [--branch <branch>] [--build] [--no-cache]`
|
||||||
Performs a sequential update workflow:
|
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).
|
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.
|
2. Runs `git pull --ff-only [origin <expected_branch>]` to fast-forward the current branch.
|
||||||
3. Runs `docker compose pull` to fetch updated container images.
|
3. Re-validates `app.yaml`, expected branch declaration, and Compose security rules against the newly pulled working tree.
|
||||||
4. Runs `docker compose up -d --remove-orphans` to recreate containers.
|
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.
|
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>`
|
#### `appctl pull <service|core>`
|
||||||
Pulls latest container images and recreates the target service.
|
Pulls latest container images and recreates the target service.
|
||||||
|
|
||||||
#### `appctl logs <service|core>`
|
#### `appctl logs <service|core> [--tail N]`
|
||||||
Streams container logs (`docker compose logs -f`). Supports passing specific container names (`appctl logs core traefik` or `appctl logs stalwart`).
|
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>`
|
#### `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.
|
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
|
## 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).
|
1. **Base System Path & Docker Config**: `PATH` and `DOCKER_CONFIG`.
|
||||||
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.
|
2. **Global Secrets & Templates**: Parsed inertly from `/run/secrets/rendered/homeserver.env` and `/run/secrets/rendered/traefik-deployments.env` (with `/run/secrets/*` fallbacks).
|
||||||
3. **Infrastructure Defaults**:
|
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`)
|
- `PROXY_NETWORK` (defaults to `proxy-net`)
|
||||||
- `CERT_RESOLVER` (defaults to `myresolver`)
|
- `CERT_RESOLVER` (defaults to `myresolver`)
|
||||||
- `DOMAIN_SUFFIX` (defaults to `$HOMELAB_DOMAIN`)
|
- `DOMAIN_SUFFIX` (`$HOMELAB_DOMAIN`)
|
||||||
4. **Application Identity**:
|
|
||||||
- `SERVICE_NAME` = `<canonical-name>`
|
- `SERVICE_NAME` = `<canonical-name>`
|
||||||
- `CONTAINER_NAME` = `<canonical-name>`
|
- `CONTAINER_NAME` = `<canonical-name>`
|
||||||
- `SERVICE_DOMAIN` = `<resolved-domain>`
|
- `SERVICE_DOMAIN` = `<canonical-name>.<HOMELAB_DOMAIN>`
|
||||||
- `DOMAIN` = `<resolved-domain>`
|
- `DOMAIN` = `<HOMELAB_DOMAIN>`
|
||||||
5. **Manifest Variables**: Validated key-value pairs from the `env:` block in `app.yaml` (emitted via null-delimited stream without shell `eval`).
|
5. **Manifest Variables**: Validated key-value pairs from the `env:` block in `app.yaml`.
|
||||||
6. **Local Repository Files**: Sourced from `$APP_DIR/.env` and `$APP_DIR/app.env` if present.
|
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`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
This document details the architectural structure, component roles, networking models, and security controls of the **Homelab Core** platform.
|
This document details the architectural structure, component roles, networking models, and security controls of the **Homelab Core** platform.
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> **Implementation Scope**: This document details the **current runtime architecture (Milestone P3)**, edge routing, container topologies, and network isolation models of Homelab Core.
|
> **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 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).
|
> For phased engineering milestones (P5–P7), see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -42,16 +42,17 @@ The runtime environment consists of four functional layers:
|
|||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
┌────────────────────────────────────────────────────────────────────────┐
|
┌────────────────────────────────────────────────────────────────────────┐
|
||||||
│ 4. HOST FOUNDATION │
|
│ 4. HOST FOUNDATION & CONTROL PLANE DAEMONS │
|
||||||
│ NixOS Linux · sops-nix Secrets · Docker Engine · Systemd Units │
|
│ 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 │
|
│ Smart Dynu DDNS Monitor · Host Firewall · /run Secret Projections │
|
||||||
└────────────────────────────────────────────────────────────────────────┘
|
└────────────────────────────────────────────────────────────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
### C. Cross-Cutting Orchestration
|
### C. Cross-Cutting Orchestration
|
||||||
Orchestration coordinates operations across the runtime layers:
|
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`).
|
* **`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, 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 `config/deployments.yaml` allowlist and Compose AST security checks, and dispatches serialized deployment actions for `~/Sites` workloads.
|
* **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 delegates serialized `workload.update` execution to `homelab-appctl.service` over `/run/homelab/appctl.sock` using its `homelab-operator` Bearer token.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -91,7 +92,8 @@ Orchestration coordinates operations across the runtime layers:
|
|||||||
|
|
||||||
### F. Host Foundation & Daemons
|
### 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`.
|
* **`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`.
|
* **`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`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -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)
|
||||||
+22
-28
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
This document serves as the authoritative repository index for Architectural Decision Records (ADRs) governing **Homelab Core** and the **`appctl` Operational Control Plane**.
|
This document serves as the authoritative repository index for Architectural Decision Records (ADRs) governing **Homelab Core** and the **`appctl` Operational Control Plane**.
|
||||||
|
|
||||||
Repository-level architectural decisions are recorded in `docs/decisions/` using the MADR 4.0 specification. Foundational platform ADRs (0001 and 0002) are summarized inline below alongside full MADR records (0003+).
|
Repository-level architectural decisions are recorded in `docs/decisions/` using the MADR 4.0 specification (`NNNN-slug.md`).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -11,15 +11,14 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
|
|||||||
| Decision Record | Status | Date | Scope & One-Line Purpose |
|
| Decision Record | Status | Date | Scope & One-Line Purpose |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| [**ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. |
|
| [**ADR-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-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**](#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-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
|
## 🧭 Summaries of Governing Decisions
|
||||||
|
|
||||||
### Centralized Runtime Validation & Serialization via Pydantic v2
|
### [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md)
|
||||||
* **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md)
|
* **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md)
|
||||||
* **Status**: `accepted` (Active)
|
* **Status**: `accepted` (Active)
|
||||||
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Milestone P4)
|
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Milestone P4)
|
||||||
@@ -30,27 +29,21 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
|
|||||||
4. **Secret-Safe Error Transformation**: Transport-level conversion of `ValidationError` into standard `ERR_VALIDATION_FAILED` (400) with raw input values redacted.
|
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.
|
5. **Dual-Transport Parity**: Identical validated models across Unix domain socket and HTTP transports.
|
||||||
|
|
||||||
### Homelab Operational Control Plane & Deployment Model Architecture
|
### [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)
|
||||||
* **Decision ID**: `ADR-0002`
|
* **Status**: `accepted` (Active — Reconciled with Pre-P4 Locked Decisions `DEC-01`–`DEC-05`)
|
||||||
* **Status**: `accepted` (Active)
|
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v6)
|
||||||
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v5)
|
|
||||||
* **Core Commitments**:
|
* **Core Commitments**:
|
||||||
1. **Control Plane Daemon**: `appctl` transitions from a collection of local shell scripts into the authoritative platform service (`homelab-appctl.service`).
|
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. **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.
|
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. **Explicit Token Authentication Everywhere**: Host SSH access does not confer appctl authority; every mutating operation requires an explicit, authenticated user-scoped token.
|
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. **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.
|
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. **Five-Stage Deployment Model Lifecycle**: Separates factual `ApplicationProfile`, candidate `DeploymentProposal`, validated `DeploymentModel` (in Git), materialized `Deployment Definition`, and runtime `Reconciliation`.
|
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`).
|
||||||
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`.
|
|
||||||
|
|
||||||
---
|
### [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)
|
||||||
### Homelab 3-Tier Architecture & Deployment Provenance Model
|
|
||||||
* **Decision ID**: `ADR-0001`
|
|
||||||
* **Status**: `accepted` (Active)
|
* **Status**: `accepted` (Active)
|
||||||
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v5)
|
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v6)
|
||||||
* **Core Commitments**:
|
* **Core Commitments**:
|
||||||
1. **3-Tier Separation of Concerns**:
|
1. **3-Tier Separation of Concerns**:
|
||||||
* *Tier 1 (Software Layer)*: Upstream application repositories owning code, tests, and CI. Zero Homelab infrastructure coupling.
|
* *Tier 1 (Software Layer)*: Upstream application repositories owning code, tests, and CI. Zero Homelab infrastructure coupling.
|
||||||
@@ -67,9 +60,10 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
|
|||||||
|
|
||||||
## 📜 Superseded Historical Decisions & Lineage
|
## 📜 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.
|
* **Roadmap v5 (`architecture-consolidation-roadmap-v5.md`)**: Superseded by Roadmap v6 (`DEC-01`–`DEC-05` pre-P4 boundary lock).
|
||||||
* **appctl-v2 Modernization Plan** (`appctl-engine-v2-refactoring.md`): Scaffolded and absorbed into Roadmap v5 Phases P0 and P3.
|
* **Roadmap v4, v3, v2 & v1** (`architecture-consolidation-roadmap-v4.md`): Superseded by Roadmap v5/v6.
|
||||||
* **Smart Selective Deployment Pipeline Plan** (`smart-deployment-pipeline.md`): Absorbed into Roadmap v5 Phase P4 control-plane reconciliation.
|
* **appctl-v2 Modernization Plan** (`appctl-engine-v2-refactoring.md`): Scaffolded and absorbed into Roadmap Phases P0 and P3.
|
||||||
* **Architecture Implementation Guide v3** (`architecture-consolidation-implementation-guide-v3.md`): Superseded by Roadmap v5.
|
* **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.
|
||||||
+1
-1
@@ -106,7 +106,7 @@ Before executing `docker compose up -d`, `validate_compose_security()` parses th
|
|||||||
To avoid blocking HTTP connections and handle overlapping pushes:
|
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.
|
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**:
|
3. **Commit Superseding**:
|
||||||
- Commit A begins deploying.
|
- Commit A begins deploying.
|
||||||
- Commit B arrives and is written to the pending file.
|
- Commit B arrives and is written to the pending file.
|
||||||
|
|||||||
+311
-3
@@ -16,9 +16,15 @@ After modifying any file in `nixos/` (including `configuration.nix`, `hardware-c
|
|||||||
nix-switch
|
nix-switch
|
||||||
|
|
||||||
# Or using the explicit command:
|
# 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
|
### Dry Build Validation & Rollback
|
||||||
```bash
|
```bash
|
||||||
# Validate build without activating (catches evaluation and syntax errors)
|
# Validate build without activating (catches evaluation and syntax errors)
|
||||||
@@ -139,9 +145,8 @@ appctl restart docs
|
|||||||
appctl restart traefik
|
appctl restart traefik
|
||||||
appctl restart authelia
|
appctl restart authelia
|
||||||
|
|
||||||
# Sequential stack update (clean working tree check -> git pull -> compose pull -> up -> sync)
|
# Sequential stack update for independent Sites workloads (clean tree check -> git pull -> compose pull -> up -> sync)
|
||||||
appctl update docs
|
appctl update docs
|
||||||
appctl update core
|
|
||||||
|
|
||||||
# Stream live container logs
|
# Stream live container logs
|
||||||
appctl logs docs
|
appctl logs docs
|
||||||
@@ -151,6 +156,37 @@ appctl logs -f stalwart
|
|||||||
appctl config docs
|
appctl config docs
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Workload vs. Core Update Policy
|
||||||
|
|
||||||
|
Homelab enforces a strict architectural boundary between independent application workloads (`~/Sites/<app>`) and Homelab Core (`~/Core`):
|
||||||
|
|
||||||
|
#### 1. Independent Sites Workloads (`~/Sites/<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 `config/deployments.yaml` can be triggered automatically via authenticated GitOps webhooks on Gitea push events.
|
||||||
|
- **Daemon Permissions**: `homelab-appctl.service` holds read-write permissions over `~/Sites` 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 `config/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)
|
## 4. User Identity & Access Management (LLDAP & Authelia)
|
||||||
@@ -279,3 +315,275 @@ To bring up a replacement host from version control:
|
|||||||
```bash
|
```bash
|
||||||
sudo systemctl start homeserver-core
|
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.
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
**Status**: ✅ **Approved & Locked (Pre-P4 Security Gate Complete; Ready for Daemon Implementation)**
|
**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)
|
**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).
|
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**:
|
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`.
|
- `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.
|
- 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.
|
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.
|
||||||
|
|||||||
@@ -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 │
|
│ 3. /run/secrets/gitops/webhook_secret │
|
||||||
│ -> Consumed by homelab-gitops.service for HMAC verification │
|
│ -> 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 │
|
│ -> Consumed by systemd ddclient service │
|
||||||
│ │
|
│ │
|
||||||
│ 5. /run/secrets/pdf_decrypt_password │
|
│ 7. /run/secrets/pdf_decrypt_password │
|
||||||
│ -> Consumed by shell pdf_dc utility │
|
│ -> Consumed by shell pdf_dc utility │
|
||||||
└────────────────────────────────────────────────────────────────────────┘
|
└────────────────────────────────────────────────────────────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Projected Secret Templates
|
## 3. Projected Secret Templates & Token Store
|
||||||
|
|
||||||
### A. Core Platform Environment (`/run/secrets/homeserver.env`)
|
### A. Core Platform Environment (`/run/secrets/homeserver.env`)
|
||||||
Generated by `nixos/modules/homeserver.nix`. Supplies credentials to the Core Compose stack:
|
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.
|
* `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`)
|
### 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: "..."
|
admin_password: "..."
|
||||||
gitops:
|
gitops:
|
||||||
webhook_secret: "..."
|
webhook_secret: "..."
|
||||||
|
appctl_token: "..."
|
||||||
|
appctl:
|
||||||
|
tokens_json: "[...]"
|
||||||
brevo:
|
brevo:
|
||||||
smtp_login: "..."
|
smtp_login: "..."
|
||||||
smtp_key: "..."
|
smtp_key: "..."
|
||||||
@@ -88,7 +103,7 @@ brevo:
|
|||||||
### 3. Save and Apply Changes
|
### 3. Save and Apply Changes
|
||||||
Saving the file in your editor automatically re-encrypts it with Age. Apply the updated templates to running services:
|
Saving the file in your editor automatically re-encrypts it with Age. Apply the updated templates to running services:
|
||||||
```bash
|
```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**:
|
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.
|
* **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`.
|
* **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 |
|
| **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 |
|
| **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) |
|
| **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`) |
|
| **User Directory** | `~/Core/config/lldap/data/` | ❌ No | LLDAP SQLite database (`users.db`) |
|
||||||
| **Auth Database** | `~/Core/config/authelia/db.sqlite3` | ❌ No | Authelia session database |
|
| **Auth Database** | `~/Core/config/authelia/db.sqlite3` | ❌ No | Authelia session database |
|
||||||
|
|||||||
+47
-7
@@ -32,24 +32,64 @@ sudo ls -l /etc/ssh/ssh_host_ed25519_key
|
|||||||
sudo chmod 600 /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
|
```bash
|
||||||
cd ~/Core
|
cd ~/Core
|
||||||
sudo nixos-rebuild switch --flake ~/Core#server
|
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
|
||||||
```
|
```
|
||||||
This configures:
|
This configures:
|
||||||
* Docker daemon, host firewall rules, and system packages.
|
* Docker daemon, host firewall rules, and system packages.
|
||||||
* Decrypted secret files in `/run/secrets/homeserver.env` and `/run/secrets/traefik-deployments.env`.
|
* 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:
|
The Core Compose stack and workloads require the `proxy-net` and `socket-net` bridge networks:
|
||||||
```bash
|
```bash
|
||||||
docker network create proxy-net 2>/dev/null || true
|
docker network create proxy-net 2>/dev/null || true
|
||||||
docker network create socket-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
|
```bash
|
||||||
sudo systemctl start homeserver-core
|
sudo systemctl start homeserver-core
|
||||||
```
|
```
|
||||||
@@ -58,7 +98,7 @@ Check running containers:
|
|||||||
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
|
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:
|
1. Trigger an immediate DDNS update:
|
||||||
```bash
|
```bash
|
||||||
sudo systemctl start dynu-monitor
|
sudo systemctl start dynu-monitor
|
||||||
@@ -68,7 +108,7 @@ docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
|
|||||||
appctl ssl traefik
|
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`).
|
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`).
|
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.
|
3. Create standard user accounts and assign them to required groups.
|
||||||
|
|||||||
@@ -52,6 +52,7 @@
|
|||||||
git
|
git
|
||||||
pythonEnv
|
pythonEnv
|
||||||
ruff
|
ruff
|
||||||
|
pyright
|
||||||
];
|
];
|
||||||
} ''
|
} ''
|
||||||
mkdir -p $out
|
mkdir -p $out
|
||||||
@@ -59,6 +60,7 @@
|
|||||||
chmod -R u+w source
|
chmod -R u+w source
|
||||||
cd source
|
cd source
|
||||||
HOME=/tmp ruff check --no-cache .
|
HOME=/tmp ruff check --no-cache .
|
||||||
|
HOME=/tmp pyright
|
||||||
HOME=/tmp pytest -o cache_dir=/tmp/.pytest_cache tests/
|
HOME=/tmp pytest -o cache_dir=/tmp/.pytest_cache tests/
|
||||||
'';
|
'';
|
||||||
};
|
};
|
||||||
|
|||||||
+17
-2
@@ -1,5 +1,5 @@
|
|||||||
# 🌐 Server NixOS Configuration — Turnkey Headless Homelab Appliance
|
# 🌐 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.
|
# No Home Manager. No shared desktop modules.
|
||||||
# Goal: wipe & restore from any NixOS installation via `nixos-install --flake ~/Core#server`
|
# Goal: wipe & restore from any NixOS installation via `nixos-install --flake ~/Core#server`
|
||||||
|
|
||||||
@@ -12,7 +12,20 @@
|
|||||||
./modules/traefik-deployments.nix # Traefik deployment secrets and env templates
|
./modules/traefik-deployments.nix # Traefik deployment secrets and env templates
|
||||||
./modules/dynu.nix # Dynu DDNS smart IP monitor service
|
./modules/dynu.nix # Dynu DDNS smart IP monitor service
|
||||||
./modules/shell.nix # Declarative bash environment for the server
|
./modules/shell.nix # Declarative bash environment for the server
|
||||||
|
] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix
|
||||||
|
++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-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}/Sites/*"
|
||||||
];
|
];
|
||||||
|
};
|
||||||
|
|
||||||
# ── SOPS secrets configuration ──────────────────────────────────────────────
|
# ── SOPS secrets configuration ──────────────────────────────────────────────
|
||||||
# Set once here to avoid duplicate-option conflicts across submodules
|
# Set once here to avoid duplicate-option conflicts across submodules
|
||||||
@@ -54,14 +67,16 @@
|
|||||||
networking.networkmanager.enable = true;
|
networking.networkmanager.enable = true;
|
||||||
|
|
||||||
# ── User account ─────────────────────────────────────────────────────────────
|
# ── User account ─────────────────────────────────────────────────────────────
|
||||||
users.users.kiskaadee = {
|
users.users.${config.homelab.operatorUser} = {
|
||||||
isNormalUser = true;
|
isNormalUser = true;
|
||||||
|
description = "Primary server administrator";
|
||||||
openssh.authorizedKeys.keys = [
|
openssh.authorizedKeys.keys = [
|
||||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICAVPPMk+WApUd/fo78+lsRGnLKSlY4GDZiNGKwBAifD"
|
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICAVPPMk+WApUd/fo78+lsRGnLKSlY4GDZiNGKwBAifD"
|
||||||
];
|
];
|
||||||
extraGroups = [
|
extraGroups = [
|
||||||
"wheel" # sudo access
|
"wheel" # sudo access
|
||||||
"docker" # run docker without sudo
|
"docker" # run docker without sudo
|
||||||
|
"homelab-operators" # access /run/homelab/appctl.sock
|
||||||
"networkmanager" # modify network settings
|
"networkmanager" # modify network settings
|
||||||
];
|
];
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ in
|
|||||||
sops.secrets."dynu/domain" = { };
|
sops.secrets."dynu/domain" = { };
|
||||||
sops.secrets."dynu/password" = { };
|
sops.secrets."dynu/password" = { };
|
||||||
sops.secrets."system/pdf_decrypt_password" = {
|
sops.secrets."system/pdf_decrypt_password" = {
|
||||||
owner = "kiskaadee";
|
owner = config.homelab.operatorUser;
|
||||||
};
|
};
|
||||||
|
|
||||||
# Assemble the ddclient config file securely at boot time in /run/secrets/
|
# Assemble the ddclient config file securely at boot time in /run/secrets/
|
||||||
|
|||||||
+158
-31
@@ -4,8 +4,36 @@
|
|||||||
{ config, lib, pkgs, ... }:
|
{ 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}/Sites";
|
||||||
|
description = "Path to Sites directory";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
config = let
|
||||||
|
domainParts = lib.splitString "." config.homelab.domain;
|
||||||
|
ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts);
|
||||||
|
in {
|
||||||
# Define the keys to decrypt from secrets.yaml
|
# Define the keys to decrypt from secrets.yaml
|
||||||
sops.secrets = lib.genAttrs [
|
sops.secrets = (lib.genAttrs [
|
||||||
"dynu/api_key"
|
"dynu/api_key"
|
||||||
"traefik/acme_email"
|
"traefik/acme_email"
|
||||||
"authelia/session_secret"
|
"authelia/session_secret"
|
||||||
@@ -18,13 +46,26 @@
|
|||||||
"brevo/smtp_login"
|
"brevo/smtp_login"
|
||||||
"brevo/smtp_key"
|
"brevo/smtp_key"
|
||||||
"diun/smtp_password"
|
"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
|
# Generate the unified environment file at runtime in /run/secrets/homeserver.env
|
||||||
sops.templates."homeserver.env" = {
|
sops.templates."homeserver.env" = {
|
||||||
owner = "kiskaadee";
|
owner = config.homelab.operatorUser;
|
||||||
content = lib.generators.toKeyValue {} {
|
content = lib.generators.toKeyValue {} {
|
||||||
DOMAIN = "roadtotech.me";
|
DOMAIN = config.homelab.domain;
|
||||||
|
LLDAP_LDAP_BASE_DN = ldapBaseDn;
|
||||||
DOCKER_API_VERSION = "1.40";
|
DOCKER_API_VERSION = "1.40";
|
||||||
DYNU_API_KEY = config.sops.placeholder."dynu/api_key";
|
DYNU_API_KEY = config.sops.placeholder."dynu/api_key";
|
||||||
ACME_EMAIL = config.sops.placeholder."traefik/acme_email";
|
ACME_EMAIL = config.sops.placeholder."traefik/acme_email";
|
||||||
@@ -53,7 +94,7 @@
|
|||||||
serviceConfig = {
|
serviceConfig = {
|
||||||
Type = "oneshot";
|
Type = "oneshot";
|
||||||
RemainAfterExit = true;
|
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";
|
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";
|
ExecStop = "${pkgs.docker-compose}/bin/docker-compose down";
|
||||||
};
|
};
|
||||||
@@ -62,6 +103,74 @@
|
|||||||
# Declarative Dynamic GitOps Webhook Service (Internal Port 9000)
|
# Declarative Dynamic GitOps Webhook Service (Internal Port 9000)
|
||||||
systemd.services.homelab-gitops = {
|
systemd.services.homelab-gitops = {
|
||||||
description = "Dynamic Homelab GitOps Webhook Dispatcher";
|
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";
|
||||||
|
};
|
||||||
|
|
||||||
|
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" ];
|
after = [ "network-online.target" "docker.service" ];
|
||||||
wants = [ "network-online.target" ];
|
wants = [ "network-online.target" ];
|
||||||
wantedBy = [ "multi-user.target" ];
|
wantedBy = [ "multi-user.target" ];
|
||||||
@@ -77,32 +186,38 @@
|
|||||||
];
|
];
|
||||||
|
|
||||||
environment = {
|
environment = {
|
||||||
GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path;
|
HOME = "/var/lib/homelab/appctl";
|
||||||
DOCKER_CONFIG = "/home/kiskaadee/.local/state/homelab/docker";
|
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;
|
||||||
|
SITES_DIR = config.homelab.sitesDir;
|
||||||
|
CORE_DIR = config.homelab.coreDir;
|
||||||
|
HOMELAB_CONFIG_DIR = "/home/${config.homelab.operatorUser}/.config/homelab";
|
||||||
|
HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.coreDir}/config/deployments.yaml";
|
||||||
};
|
};
|
||||||
|
|
||||||
serviceConfig = {
|
serviceConfig = {
|
||||||
Type = "simple";
|
Type = "simple";
|
||||||
User = "kiskaadee";
|
User = "homelab-appctl";
|
||||||
|
Group = "homelab-operators";
|
||||||
SupplementaryGroups = [ "docker" ];
|
SupplementaryGroups = [ "docker" ];
|
||||||
WorkingDirectory = "/home/kiskaadee/Core";
|
WorkingDirectory = config.homelab.coreDir;
|
||||||
ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [
|
ExecStart = "${(pkgs.python3.withPackages (ps: with ps; [ pyyaml pydantic ]))}/bin/python3 ${config.homelab.coreDir}/scripts/appctl_daemon.py";
|
||||||
{
|
Restart = "always";
|
||||||
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";
|
|
||||||
RestartSec = "5s";
|
RestartSec = "5s";
|
||||||
|
|
||||||
# Privilege separation & Systemd sandboxing
|
RuntimeDirectory = "homelab";
|
||||||
|
RuntimeDirectoryMode = "0750";
|
||||||
|
StateDirectory = "homelab/appctl";
|
||||||
|
StateDirectoryMode = "0700";
|
||||||
|
LogsDirectory = "homelab/appctl";
|
||||||
|
LogsDirectoryMode = "0700";
|
||||||
|
|
||||||
NoNewPrivileges = true;
|
NoNewPrivileges = true;
|
||||||
PrivateTmp = true;
|
PrivateTmp = true;
|
||||||
ProtectSystem = "strict";
|
ProtectSystem = "strict";
|
||||||
@@ -110,21 +225,33 @@
|
|||||||
ProtectKernelTunables = true;
|
ProtectKernelTunables = true;
|
||||||
ProtectControlGroups = true;
|
ProtectControlGroups = true;
|
||||||
ReadWritePaths = [
|
ReadWritePaths = [
|
||||||
"/home/kiskaadee/Sites"
|
config.homelab.sitesDir
|
||||||
"/home/kiskaadee/.local/state/homelab"
|
"-/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
|
# Ensure persistent directories have proper permissions for container runtimes
|
||||||
systemd.tmpfiles.rules = [
|
systemd.tmpfiles.rules = [
|
||||||
"d /home/kiskaadee/Core/config/stalwart/data 0777 kiskaadee users -"
|
"d ${config.homelab.coreDir}/config/stalwart/data 0777 ${config.homelab.operatorUser} users -"
|
||||||
"d /home/kiskaadee/Core/config/stalwart/etc 0777 kiskaadee users -"
|
"d ${config.homelab.coreDir}/config/stalwart/etc 0777 ${config.homelab.operatorUser} users -"
|
||||||
"d /home/kiskaadee/Sites 0755 kiskaadee users -"
|
"d ${config.homelab.sitesDir} 0755 ${config.homelab.operatorUser} users -"
|
||||||
"d /home/kiskaadee/.local/state/homelab/gitops 0755 kiskaadee users -"
|
"d /home/${config.homelab.operatorUser}/.local/state/homelab/gitops 0755 ${config.homelab.operatorUser} users -"
|
||||||
"d /home/kiskaadee/.local/state/homelab/docker 0755 kiskaadee 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 traverse and access to operator sites & homepage config
|
||||||
|
"a+ /home/${config.homelab.operatorUser} - - - - u:homelab-appctl:x"
|
||||||
|
"a+ ${config.homelab.coreDir} - - - - u:homelab-appctl:x"
|
||||||
|
"A+ ${config.homelab.sitesDir} - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
|
||||||
|
"A+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
|
||||||
|
"A+ ${config.homelab.coreDir}/config/homepage - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
|
||||||
];
|
];
|
||||||
|
|
||||||
# Open ports in the firewall for Traefik, Gitea SSH, GitOps Webhook Receiver, and Mail (SMTP, Submission, SMTPS, IMAPS, ManageSieve)
|
# 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 ];
|
networking.firewall.allowedTCPPorts = [ 80 443 2223 9000 25 465 587 993 4190 ];
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -62,8 +62,8 @@
|
|||||||
reload = "exec bash";
|
reload = "exec bash";
|
||||||
pgoog = "ping google.com -c 3";
|
pgoog = "ping google.com -c 3";
|
||||||
wifi = "nmtui";
|
wifi = "nmtui";
|
||||||
# NixOS rebuild targeting this flake
|
# NixOS rebuild targeting this flake (path scheme + impure required for instance.nix)
|
||||||
nix-switch = "sudo nixos-rebuild switch --flake ~/Core#server";
|
nix-switch = "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure";
|
||||||
};
|
};
|
||||||
|
|
||||||
interactiveShellInit = ''
|
interactiveShellInit = ''
|
||||||
|
|||||||
@@ -15,31 +15,31 @@
|
|||||||
"postgres/password"
|
"postgres/password"
|
||||||
"postgres/db"
|
"postgres/db"
|
||||||
"gitea/runner_token"
|
"gitea/runner_token"
|
||||||
] (name: { owner = "kiskaadee"; });
|
] (name: { owner = config.homelab.operatorUser; });
|
||||||
|
|
||||||
# Generate the unified environment file at runtime in /run/secrets/traefik-deployments.env
|
# Generate the unified environment file at runtime in /run/secrets/traefik-deployments.env
|
||||||
sops.templates."traefik-deployments.env" = {
|
sops.templates."traefik-deployments.env" = {
|
||||||
owner = "kiskaadee";
|
owner = config.homelab.operatorUser;
|
||||||
content = lib.generators.toKeyValue {} {
|
content = lib.generators.toKeyValue {} {
|
||||||
# --- Core / Infrastructure Settings ---
|
# --- Core / Infrastructure Settings ---
|
||||||
PROXY_NETWORK = "proxy-net";
|
PROXY_NETWORK = "proxy-net";
|
||||||
CERT_RESOLVER = "myresolver";
|
CERT_RESOLVER = "myresolver";
|
||||||
DOMAIN_SUFFIX = "roadtotech.me";
|
DOMAIN_SUFFIX = config.homelab.domain;
|
||||||
|
|
||||||
# --- Dashboard & Landing ---
|
# --- Dashboard & Landing ---
|
||||||
DASHBOARD_DOMAIN = "dashboard.roadtotech.me";
|
DASHBOARD_DOMAIN = "dashboard.${config.homelab.domain}";
|
||||||
LANDING_DOMAIN = "roadtotech.me";
|
LANDING_DOMAIN = config.homelab.domain;
|
||||||
|
|
||||||
# --- Docs ---
|
# --- Docs ---
|
||||||
DOCS_DOMAIN = "docs.roadtotech.me";
|
DOCS_DOMAIN = "docs.${config.homelab.domain}";
|
||||||
DOCS_PROJECT_PATH = "/home/kiskaadee/Brain";
|
DOCS_PROJECT_PATH = "/home/${config.homelab.operatorUser}/Brain";
|
||||||
|
|
||||||
# --- Excalidraw ---
|
# --- Excalidraw ---
|
||||||
EXCALIDRAW_DOMAIN = "excalidraw.roadtotech.me";
|
EXCALIDRAW_DOMAIN = "excalidraw.${config.homelab.domain}";
|
||||||
|
|
||||||
# --- Gitea ---
|
# --- Gitea ---
|
||||||
GITEA_DOMAIN = "gitea.roadtotech.me";
|
GITEA_DOMAIN = "gitea.${config.homelab.domain}";
|
||||||
GITEA_SSH_DOMAIN = "gitea.roadtotech.me";
|
GITEA_SSH_DOMAIN = "gitea.${config.homelab.domain}";
|
||||||
GITEA_SSH_PORT = "2223";
|
GITEA_SSH_PORT = "2223";
|
||||||
GITEA_AUTH_MIDDLEWARE = "https-redirect@docker";
|
GITEA_AUTH_MIDDLEWARE = "https-redirect@docker";
|
||||||
GITEA_RUNNER_TOKEN = config.sops.placeholder."gitea/runner_token";
|
GITEA_RUNNER_TOKEN = config.sops.placeholder."gitea/runner_token";
|
||||||
@@ -48,7 +48,7 @@
|
|||||||
JELLYFIN_SERVICE_NAME = "jellyfin";
|
JELLYFIN_SERVICE_NAME = "jellyfin";
|
||||||
JELLYFIN_CONTAINER_NAME = "jellyfin";
|
JELLYFIN_CONTAINER_NAME = "jellyfin";
|
||||||
JELLYFIN_IMAGE_TAG = "latest";
|
JELLYFIN_IMAGE_TAG = "latest";
|
||||||
JELLYFIN_DOMAIN = "jellyfin.roadtotech.me";
|
JELLYFIN_DOMAIN = "jellyfin.${config.homelab.domain}";
|
||||||
JELLYFIN_TZ = "UTC";
|
JELLYFIN_TZ = "UTC";
|
||||||
JELLYFIN_PUID = "1000";
|
JELLYFIN_PUID = "1000";
|
||||||
JELLYFIN_PGID = "1000";
|
JELLYFIN_PGID = "1000";
|
||||||
@@ -60,7 +60,7 @@
|
|||||||
|
|
||||||
# --- Learning Dashboard ---
|
# --- Learning Dashboard ---
|
||||||
LEARNING_SERVICE_NAME = "learning-hub";
|
LEARNING_SERVICE_NAME = "learning-hub";
|
||||||
LEARNING_DOMAIN = "learning.roadtotech.me";
|
LEARNING_DOMAIN = "learning.${config.homelab.domain}";
|
||||||
LEARNING_APP_PORT = "8000";
|
LEARNING_APP_PORT = "8000";
|
||||||
LEARNING_SOCKET_PROXY_NETWORK = "socket-net";
|
LEARNING_SOCKET_PROXY_NETWORK = "socket-net";
|
||||||
LEARNING_DOCKER_HOST = "tcp://socket-proxy:2375";
|
LEARNING_DOCKER_HOST = "tcp://socket-proxy:2375";
|
||||||
@@ -68,25 +68,25 @@
|
|||||||
TURSO_AUTH_TOKEN = config.sops.placeholder."learning/turso_auth_token";
|
TURSO_AUTH_TOKEN = config.sops.placeholder."learning/turso_auth_token";
|
||||||
|
|
||||||
# --- Mermaid ---
|
# --- Mermaid ---
|
||||||
MERMAID_DOMAIN = "mermaid.roadtotech.me";
|
MERMAID_DOMAIN = "mermaid.${config.homelab.domain}";
|
||||||
MERMAID_SERVICE_NAME = "mermaid";
|
MERMAID_SERVICE_NAME = "mermaid";
|
||||||
|
|
||||||
# --- Minecraft ---
|
# --- Minecraft ---
|
||||||
MINECRAFT_DOMAIN = "minecraft.roadtotech.me";
|
MINECRAFT_DOMAIN = "minecraft.${config.homelab.domain}";
|
||||||
|
|
||||||
# --- MongoDB ---
|
# --- MongoDB ---
|
||||||
MONGO_ROOT_USERNAME = config.sops.placeholder."mongo/root_username";
|
MONGO_ROOT_USERNAME = config.sops.placeholder."mongo/root_username";
|
||||||
MONGO_ROOT_PASSWORD = config.sops.placeholder."mongo/root_password";
|
MONGO_ROOT_PASSWORD = config.sops.placeholder."mongo/root_password";
|
||||||
MONGO_DOMAIN = "mongodb.roadtotech.me";
|
MONGO_DOMAIN = "mongodb.${config.homelab.domain}";
|
||||||
|
|
||||||
# --- PostgreSQL ---
|
# --- PostgreSQL ---
|
||||||
POSTGRES_USER = config.sops.placeholder."postgres/user";
|
POSTGRES_USER = config.sops.placeholder."postgres/user";
|
||||||
POSTGRES_PASSWORD = config.sops.placeholder."postgres/password";
|
POSTGRES_PASSWORD = config.sops.placeholder."postgres/password";
|
||||||
POSTGRES_DB = config.sops.placeholder."postgres/db";
|
POSTGRES_DB = config.sops.placeholder."postgres/db";
|
||||||
POSTGRES_DOMAIN = "pgsql.roadtotech.me";
|
POSTGRES_DOMAIN = "pgsql.${config.homelab.domain}";
|
||||||
|
|
||||||
# --- Ollama ---
|
# --- Ollama ---
|
||||||
OLLAMA_DOMAIN = "ollama.roadtotech.me";
|
OLLAMA_DOMAIN = "ollama.${config.homelab.domain}";
|
||||||
OLLAMA_API_KEY = config.sops.placeholder."ollama/api_key";
|
OLLAMA_API_KEY = config.sops.placeholder."ollama/api_key";
|
||||||
OLLAMA_REPLICAS = "1";
|
OLLAMA_REPLICAS = "1";
|
||||||
OLLAMA_DATA_VOLUME = "ollama_data";
|
OLLAMA_DATA_VOLUME = "ollama_data";
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ PROVIDERS = [
|
|||||||
"https://api.ipify.org",
|
"https://api.ipify.org",
|
||||||
"https://ifconfig.me/ip",
|
"https://ifconfig.me/ip",
|
||||||
"https://icanhazip.com",
|
"https://icanhazip.com",
|
||||||
"https://wtfismyip.com/text"
|
"https://wtfismyip.com/text",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -78,14 +78,11 @@ def get_public_ip():
|
|||||||
for provider in PROVIDERS:
|
for provider in PROVIDERS:
|
||||||
try:
|
try:
|
||||||
req = urllib.request.Request(
|
req = urllib.request.Request(
|
||||||
provider,
|
provider, headers={"User-Agent": "Mozilla/5.0 (NixOS WAN Monitor)"}
|
||||||
headers={
|
|
||||||
'User-Agent': 'Mozilla/5.0 (NixOS WAN Monitor)'
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
# Fetch with 5s timeout to avoid hanging the systemd service
|
# Fetch with 5s timeout to avoid hanging the systemd service
|
||||||
with urllib.request.urlopen(req, timeout=5) as response:
|
with urllib.request.urlopen(req, timeout=5) as response:
|
||||||
ip = response.read().decode('utf-8').strip()
|
ip = response.read().decode("utf-8").strip()
|
||||||
if is_valid_public_ipv4(ip):
|
if is_valid_public_ipv4(ip):
|
||||||
return ip
|
return ip
|
||||||
else:
|
else:
|
||||||
@@ -94,8 +91,7 @@ def get_public_ip():
|
|||||||
errors.append(f"{provider}: {e!s}")
|
errors.append(f"{provider}: {e!s}")
|
||||||
|
|
||||||
print(
|
print(
|
||||||
f"Error: All IP discovery providers failed. Details: {errors}",
|
f"Error: All IP discovery providers failed. Details: {errors}", file=sys.stderr
|
||||||
file=sys.stderr
|
|
||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -132,11 +128,7 @@ def record_ip(ip, status, details=None):
|
|||||||
Appends a new event entry into the JSONLines history registry.
|
Appends a new event entry into the JSONLines history registry.
|
||||||
"""
|
"""
|
||||||
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
|
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
|
||||||
entry = {
|
entry = {"timestamp": datetime.now(tz=UTC).isoformat(), "ip": ip, "status": status}
|
||||||
"timestamp": datetime.now(tz=UTC).isoformat(),
|
|
||||||
"ip": ip,
|
|
||||||
"status": status
|
|
||||||
}
|
|
||||||
if details:
|
if details:
|
||||||
entry["details"] = details
|
entry["details"] = details
|
||||||
try:
|
try:
|
||||||
@@ -164,10 +156,7 @@ def trigger_ddclient():
|
|||||||
if res.returncode == 0:
|
if res.returncode == 0:
|
||||||
return True, None
|
return True, None
|
||||||
else:
|
else:
|
||||||
err_msg = (
|
err_msg = f"systemctl exited with {res.returncode}: {res.stderr.strip()}"
|
||||||
f"systemctl exited with {res.returncode}: "
|
|
||||||
f"{res.stderr.strip()}"
|
|
||||||
)
|
|
||||||
return False, err_msg
|
return False, err_msg
|
||||||
except (OSError, subprocess.SubprocessError) as e:
|
except (OSError, subprocess.SubprocessError) as e:
|
||||||
return False, str(e)
|
return False, str(e)
|
||||||
|
|||||||
+5
-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]
|
pdf_decrypt_password: ENC[AES256_GCM,data:n3XTANd+PbejUw==,iv:y2VIabyv/DfTgztbjS6M/xIfRNKOL+U+r3eXsal32OQ=,tag:oFpXg2E9dDM5dwkjSZkLgw==,type:str]
|
||||||
gitops:
|
gitops:
|
||||||
webhook_secret: ENC[AES256_GCM,data:Kj3d0Repa3OOvjCkW6+kakQEfsCdpdVJQd71Am6zQHBt7QkLtxlnovUmmS+zJ+jChQBbCc9/7LunFvFT2pL36w==,iv:qh1pEIVtvB/fxbMv+a9pworhbXsIpfF5gKWS22Zn0GU=,tag:D4RNXkWhg9l3BJFp7MMloA==,type:str]
|
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:
|
lldap:
|
||||||
jwt_secret: ENC[AES256_GCM,data:RHtVgZJzNK7PFFvYO4jSsv+3928PYG2RdajG3ETEfN5eh0FwAmqcC98X2scT8H2JAeDV+bRI6QMZ3FoNRNcOHw==,iv:YGYImZJQzf1ONkc9lq2bEV/eWKIPfTyH+2hKzObaY08=,tag:jcUYKHrYSPYvHjQ86hLl0g==,type:str]
|
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]
|
key_seed: ENC[AES256_GCM,data:8Jf/xyMMXQFYxSO9RezTQRcS+Amm9hYOf97K03H/8cI=,iv:D5BJ4I12cMp2HAdCJC8MD/LnrBskbX7X/a6TnyisuMk=,tag:fhxge0iBSPllyrGQfCkw7w==,type:str]
|
||||||
@@ -37,6 +38,8 @@ lldap:
|
|||||||
brevo:
|
brevo:
|
||||||
smtp_login: ENC[AES256_GCM,data:zfqKsAtoAOWCrSqx38sknwcJZT2m8W2J,iv:tMwTNDf+2CE3/8rKqWTWLl5Zp4LUVNSFV90QN94VXxo=,tag:XYXz9w3oIa0qkcfjCcgcYg==,type:str]
|
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]
|
smtp_key: ENC[AES256_GCM,data:YulXyaVF/sLWE9x12yxdBAj9KMbfP/CK/7FS3XkYO8sCj3GWgPbNoSaUT/9quLWHPtCsBxxdLeLoDNa1jE2WRyHP1W+Ioyyx5sAzdzevzHIBmfP+fdw0rKhe,iv:QT0HfzNPsTqXlN3IC/+bBzJfUzN9YkXYiv/3uqkXHBw=,tag:vBetkZPDYoh0Yy3BpMT9BQ==,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:
|
sops:
|
||||||
age:
|
age:
|
||||||
- enc: |
|
- enc: |
|
||||||
@@ -57,7 +60,7 @@ sops:
|
|||||||
yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A==
|
yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A==
|
||||||
-----END AGE ENCRYPTED FILE-----
|
-----END AGE ENCRYPTED FILE-----
|
||||||
recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg
|
recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg
|
||||||
lastmodified: "2026-09-25T00:49:38Z"
|
lastmodified: "2026-10-19T20:40:13Z"
|
||||||
mac: ENC[AES256_GCM,data:EyJ9V0aYo7isyqnW6HWBz4hD2X6xa+VRNg3TaK88gkX6YCG/H0htBfMf/VYl/hOA/eEZW+uMVys8Ocula9zpY1Pd1gUbWt5FrXQvooYNhtCFCFUAJdsrmif8Ru7AXazFbyhhaeBSBjSQURM0qi69XqllVvfmiSz32WlX/QIOZ/c=,iv:znmm8JuFKSFl2IGGhRG77SE9kqy3uFWUK8VjocJ18n4=,tag:tG000kt5a6W1fa0IEfvLLQ==,type:str]
|
mac: ENC[AES256_GCM,data:rui8qF/l3ucq8vrZniHtGjlLGPq7ihteKK7rcaz2prRvmo7nHd97Axt7oElo050HFuoaJB1/coVPzYcAUozjZNsNx3TQYABGFWvxF5Y0SxjdLc1rqAjGR/j2Cf5wmvF9H457KBHfij2gQHY/ZZ2Nyd9aEpAKSFtKkn3aYkmTvW4=,iv:RdQWUpkahFEYEhd9kTpPG0GMJaHr7b+wbhf5MBhk6mo=,tag:1E3mcFk/EMnJNNxuZ6AXAw==,type:str]
|
||||||
unencrypted_suffix: _unencrypted
|
unencrypted_suffix: _unencrypted
|
||||||
version: 3.13.3
|
version: 3.13.3
|
||||||
@@ -14,3 +14,11 @@ extraPaths = ["scripts"]
|
|||||||
venvPath = "."
|
venvPath = "."
|
||||||
venv = ".venv"
|
venv = ".venv"
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
# Automatically adds app modules and script hooks to the sys.venvPath
|
||||||
|
pythonpath = [
|
||||||
|
".",
|
||||||
|
"scripts"
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
+36
-291
@@ -1,174 +1,26 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
# appctl - Unified, Manifest-Driven Container Orchestrator
|
# appctl - Unified, Manifest-Driven Container Orchestrator
|
||||||
# Discovers individual application repositories located in ~/Sites/*/
|
# Thin CLI wrapper delegating operational commands to homelab-appctl.service over UDS
|
||||||
# Injects global homelab secrets, per-app metadata from app.yaml, and monitors Git sync
|
|
||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
ENGINE="$SCRIPT_DIR/appctl_engine.py"
|
ENGINE="$SCRIPT_DIR/appctl_engine.py"
|
||||||
PYTHON_BIN="${PYTHON_BIN:-python3}"
|
if [ -z "$PYTHON_BIN" ]; then
|
||||||
ENV_FILE="/run/secrets/rendered/traefik-deployments.env"
|
if [ -x "$SCRIPT_DIR/../.venv/bin/python3" ]; then
|
||||||
if [ ! -f "$ENV_FILE" ] && [ -f "/run/secrets/traefik-deployments.env" ]; then
|
PYTHON_BIN="$SCRIPT_DIR/../.venv/bin/python3"
|
||||||
ENV_FILE="/run/secrets/traefik-deployments.env"
|
else
|
||||||
|
PYTHON_BIN="python3"
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
export SITES_DIR="${SITES_DIR:-$HOME/Sites}"
|
SOCKET_PATH="${APPCTL_SOCKET_PATH:-/run/homelab/appctl.sock}"
|
||||||
export CORE_DIR="${CORE_DIR:-$HOME/Core}"
|
CLI_CLIENT="$SCRIPT_DIR/appctl_cli.py"
|
||||||
export ENV_FILE
|
|
||||||
|
|
||||||
# Source global secrets/environment if available
|
# Fast-path local shell completion helpers
|
||||||
HOMESERVER_ENV="/run/secrets/rendered/homeserver.env"
|
case "${1:-}" in
|
||||||
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
|
|
||||||
|
|
||||||
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}"
|
|
||||||
;;
|
|
||||||
complete)
|
complete)
|
||||||
"$PYTHON_BIN" "$ENGINE" complete "${@:2}"
|
exec "$PYTHON_BIN" "$ENGINE" complete "${@:2}"
|
||||||
;;
|
|
||||||
resolve)
|
|
||||||
"$PYTHON_BIN" "$ENGINE" resolve "${@:2}"
|
|
||||||
;;
|
;;
|
||||||
completion)
|
completion)
|
||||||
cat <<'EOF'
|
cat <<'EOF'
|
||||||
@@ -184,7 +36,7 @@ _appctl_completions() {
|
|||||||
cword=$COMP_CWORD
|
cword=$COMP_CWORD
|
||||||
fi
|
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
|
if [ "$cword" -eq 1 ]; then
|
||||||
COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
|
COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
|
||||||
@@ -218,7 +70,25 @@ _appctl_completions() {
|
|||||||
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
|
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
|
||||||
fi
|
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
|
local services
|
||||||
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
|
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
|
||||||
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
|
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
|
||||||
@@ -230,138 +100,13 @@ _appctl_completions() {
|
|||||||
}
|
}
|
||||||
complete -F _appctl_completions appctl
|
complete -F _appctl_completions appctl
|
||||||
EOF
|
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
|
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
|
exit 1
|
||||||
|
fi
|
||||||
|
exec "$PYTHON_BIN" "$CLI_CLIENT" "$@"
|
||||||
;;
|
;;
|
||||||
esac
|
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,388 @@
|
|||||||
|
"""
|
||||||
|
appctl_auth.py — Authentication & 3-Role RBAC Policy Enforcement (P4 Slice 3)
|
||||||
|
|
||||||
|
Implements the zero-trust authorization pipeline for homelab-appctl.service:
|
||||||
|
- SOPS-managed SHA-256 Bearer token store loader (mode 0400 check, constant-time compare)
|
||||||
|
- Unix domain socket SO_PEERCRED fallback to homelab-viewer for zero-friction local reads
|
||||||
|
- Mandatory Bearer tokens for all network (HTTP) operations and all mutations / sensitive reads
|
||||||
|
- 3-role RBAC enforcement (homelab-admin, homelab-operator, homelab-viewer)
|
||||||
|
- Workload scope gating against config/deployments.yaml for homelab-operator
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import stat
|
||||||
|
from enum import StrEnum
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Annotated, Any, Literal
|
||||||
|
|
||||||
|
from appctl_contracts import (
|
||||||
|
ErrorCode,
|
||||||
|
OperationType,
|
||||||
|
StrictModel,
|
||||||
|
)
|
||||||
|
from pydantic import BeforeValidator, ConfigDict, Field, StrictStr
|
||||||
|
|
||||||
|
try:
|
||||||
|
import yaml
|
||||||
|
except ImportError:
|
||||||
|
yaml = None # type: ignore[assignment]
|
||||||
|
|
||||||
|
DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json")
|
||||||
|
DEFAULT_DEPLOYMENTS_FILE = (
|
||||||
|
Path(__file__).resolve().parent.parent / "config" / "deployments.yaml"
|
||||||
|
)
|
||||||
|
|
||||||
|
CORE_TARGETS: frozenset[str] = frozenset(
|
||||||
|
{
|
||||||
|
"core",
|
||||||
|
"traefik",
|
||||||
|
"authelia",
|
||||||
|
"lldap",
|
||||||
|
"stalwart",
|
||||||
|
"dozzle",
|
||||||
|
"socket-proxy",
|
||||||
|
"homepage",
|
||||||
|
"diun",
|
||||||
|
"watchtower",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset(
|
||||||
|
{
|
||||||
|
OperationType.WORKLOAD_CONFIG,
|
||||||
|
OperationType.WORKLOAD_LOGS,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
MUTATING_OPERATIONS: frozenset[OperationType] = frozenset(
|
||||||
|
{
|
||||||
|
OperationType.WORKLOAD_DEPLOY,
|
||||||
|
OperationType.WORKLOAD_STOP,
|
||||||
|
OperationType.WORKLOAD_RESTART,
|
||||||
|
OperationType.WORKLOAD_UPDATE,
|
||||||
|
OperationType.WORKLOAD_PULL,
|
||||||
|
OperationType.PLATFORM_SYNC_HOMEPAGE,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset(
|
||||||
|
{
|
||||||
|
OperationType.WORKLOAD_LIST,
|
||||||
|
OperationType.WORKLOAD_GET,
|
||||||
|
OperationType.WORKLOAD_RESOLVE,
|
||||||
|
OperationType.PLATFORM_SSL,
|
||||||
|
OperationType.PLATFORM_HEALTH,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Role(StrEnum):
|
||||||
|
"""Hierarchical authorization roles for homelab-appctl.service."""
|
||||||
|
|
||||||
|
ADMIN = "homelab-admin"
|
||||||
|
OPERATOR = "homelab-operator"
|
||||||
|
VIEWER = "homelab-viewer"
|
||||||
|
|
||||||
|
|
||||||
|
def _coerce_role(v: Any) -> Any:
|
||||||
|
if isinstance(v, str):
|
||||||
|
try:
|
||||||
|
return Role(v)
|
||||||
|
except ValueError:
|
||||||
|
return v
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
FlexibleRole = Annotated[
|
||||||
|
Role,
|
||||||
|
BeforeValidator(_coerce_role),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class Principal(StrictModel):
|
||||||
|
"""Authenticated caller identity and operational role."""
|
||||||
|
|
||||||
|
model_config = ConfigDict(extra="forbid", strict=True)
|
||||||
|
|
||||||
|
identity: StrictStr
|
||||||
|
role: FlexibleRole
|
||||||
|
token_id: StrictStr | None = None
|
||||||
|
auth_method: Literal["bearer_token", "unix_peercred"]
|
||||||
|
|
||||||
|
|
||||||
|
class TokenDescriptor(StrictModel):
|
||||||
|
"""Internal model for token entries in SOPS tokens.json store."""
|
||||||
|
|
||||||
|
model_config = ConfigDict(extra="forbid", strict=True)
|
||||||
|
|
||||||
|
token_id: StrictStr
|
||||||
|
identity: StrictStr
|
||||||
|
role: FlexibleRole
|
||||||
|
sha256: Annotated[StrictStr, Field(pattern=r"^[0-9a-fA-F]{64}$")]
|
||||||
|
|
||||||
|
|
||||||
|
class AuthenticationError(Exception):
|
||||||
|
"""Raised when authentication fails (401 Unauthorized)."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str = "Authentication required",
|
||||||
|
code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED,
|
||||||
|
) -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
self.code = code
|
||||||
|
self.http_status = 401
|
||||||
|
|
||||||
|
|
||||||
|
class AuthorizationError(Exception):
|
||||||
|
"""Raised when an authenticated principal lacks required role or scope (403 Forbidden)."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str = "Permission denied",
|
||||||
|
code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED,
|
||||||
|
) -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
self.code = code
|
||||||
|
self.http_status = 403
|
||||||
|
|
||||||
|
|
||||||
|
class TokenStore:
|
||||||
|
"""Loads and validates SHA-256 Bearer tokens from a mode 0400 store."""
|
||||||
|
|
||||||
|
def __init__(self, tokens_path: Path | str | None = None) -> None:
|
||||||
|
if tokens_path is not None:
|
||||||
|
self.tokens_path = Path(tokens_path)
|
||||||
|
elif "APPCTL_TOKENS_FILE" in os.environ:
|
||||||
|
self.tokens_path = Path(os.environ["APPCTL_TOKENS_FILE"])
|
||||||
|
else:
|
||||||
|
self.tokens_path = DEFAULT_TOKENS_FILE
|
||||||
|
|
||||||
|
def _verify_permissions(self) -> None:
|
||||||
|
"""Enforce strict 0400 file mode: readable only by owner, no write/exec, no group/world."""
|
||||||
|
if not self.tokens_path.is_file():
|
||||||
|
raise AuthenticationError(
|
||||||
|
f"Token store '{self.tokens_path}' not found",
|
||||||
|
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||||
|
)
|
||||||
|
# Check permissions: reject if group/world readable or writable (must be 0400)
|
||||||
|
mode = stat.S_IMODE(self.tokens_path.stat().st_mode)
|
||||||
|
if (mode & 0o077) != 0 or (mode & 0o200) != 0:
|
||||||
|
raise AuthenticationError(
|
||||||
|
f"Token store '{self.tokens_path}' has insecure mode {oct(mode)}; mode 0400 required",
|
||||||
|
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||||
|
)
|
||||||
|
|
||||||
|
def load_tokens(self) -> list[TokenDescriptor]:
|
||||||
|
"""Load and parse token descriptors from the token store."""
|
||||||
|
self._verify_permissions()
|
||||||
|
try:
|
||||||
|
content = self.tokens_path.read_text(encoding="utf-8")
|
||||||
|
data = json.loads(content)
|
||||||
|
if not isinstance(data, list):
|
||||||
|
raise TypeError("Tokens payload must be an array of token descriptors")
|
||||||
|
return [TokenDescriptor.model_validate(item) for item in data]
|
||||||
|
except (OSError, json.JSONDecodeError, ValueError, TypeError) as err:
|
||||||
|
raise AuthenticationError(
|
||||||
|
f"Failed to load token store '{self.tokens_path}': {err}",
|
||||||
|
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||||
|
) from err
|
||||||
|
|
||||||
|
def authenticate_bearer(self, secret: str) -> Principal:
|
||||||
|
"""
|
||||||
|
Hash secret with SHA-256 and look up against stored token descriptors using
|
||||||
|
constant-time hmac.compare_digest.
|
||||||
|
"""
|
||||||
|
if not secret:
|
||||||
|
raise AuthenticationError(
|
||||||
|
"Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED
|
||||||
|
)
|
||||||
|
|
||||||
|
secret_hash = hashlib.sha256(secret.encode("utf-8")).hexdigest()
|
||||||
|
tokens = self.load_tokens()
|
||||||
|
|
||||||
|
for token in tokens:
|
||||||
|
if hmac.compare_digest(secret_hash, token.sha256.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 config/deployments.yaml.
|
||||||
|
Fails closed (empty set) if registry is missing or malformed.
|
||||||
|
"""
|
||||||
|
if deployments_path is not None:
|
||||||
|
reg_file = Path(deployments_path)
|
||||||
|
elif "HOMELAB_DEPLOYMENTS_FILE" in os.environ:
|
||||||
|
reg_file = Path(os.environ["HOMELAB_DEPLOYMENTS_FILE"])
|
||||||
|
else:
|
||||||
|
reg_file = DEFAULT_DEPLOYMENTS_FILE
|
||||||
|
|
||||||
|
if not reg_file.is_file():
|
||||||
|
return set()
|
||||||
|
|
||||||
|
yaml_errors = (yaml.YAMLError,) if yaml is not None else ()
|
||||||
|
try:
|
||||||
|
content = reg_file.read_text(encoding="utf-8")
|
||||||
|
if yaml is not None:
|
||||||
|
data = yaml.safe_load(content)
|
||||||
|
else:
|
||||||
|
data = json.loads(content)
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return set()
|
||||||
|
|
||||||
|
admitted: set[str] = set()
|
||||||
|
repos = data.get("repositories", {})
|
||||||
|
if isinstance(repos, dict):
|
||||||
|
for name, entry in repos.items():
|
||||||
|
admitted.add(name)
|
||||||
|
if isinstance(entry, dict):
|
||||||
|
aliases = entry.get("aliases", [])
|
||||||
|
if isinstance(aliases, list):
|
||||||
|
for alias in aliases:
|
||||||
|
if isinstance(alias, str) and alias.strip():
|
||||||
|
admitted.add(alias.strip())
|
||||||
|
return admitted
|
||||||
|
except (
|
||||||
|
OSError,
|
||||||
|
UnicodeDecodeError,
|
||||||
|
ValueError,
|
||||||
|
json.JSONDecodeError,
|
||||||
|
*yaml_errors,
|
||||||
|
):
|
||||||
|
return set()
|
||||||
|
|
||||||
|
|
||||||
|
def authenticate_request(
|
||||||
|
transport: Literal["unix_socket", "http"],
|
||||||
|
auth_header: str | None,
|
||||||
|
peer_uid: int | None = None,
|
||||||
|
token_store: TokenStore | None = None,
|
||||||
|
) -> Principal:
|
||||||
|
"""
|
||||||
|
Authenticate an incoming request across transports:
|
||||||
|
- If Authorization header present: parses Bearer secret and verifies against TokenStore.
|
||||||
|
- If Authorization header missing over HTTP: fails closed with 401 ERR_AUTH_REQUIRED.
|
||||||
|
- If Authorization header missing over Unix socket: falls back to homelab-viewer with peer_uid.
|
||||||
|
"""
|
||||||
|
store = token_store or TokenStore()
|
||||||
|
|
||||||
|
if auth_header is not None:
|
||||||
|
header_val = auth_header.strip()
|
||||||
|
if not header_val.startswith("Bearer "):
|
||||||
|
raise AuthenticationError(
|
||||||
|
"Malformed Authorization header: must start with 'Bearer '",
|
||||||
|
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||||
|
)
|
||||||
|
secret = header_val[7:].strip()
|
||||||
|
if not secret:
|
||||||
|
raise AuthenticationError(
|
||||||
|
"Missing token secret in Authorization header",
|
||||||
|
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||||
|
)
|
||||||
|
return store.authenticate_bearer(secret)
|
||||||
|
|
||||||
|
# Missing Authorization header
|
||||||
|
if transport == "unix_socket":
|
||||||
|
if peer_uid is not None:
|
||||||
|
return Principal(
|
||||||
|
identity=f"unix_uid_{peer_uid}",
|
||||||
|
role=Role.VIEWER,
|
||||||
|
token_id=None,
|
||||||
|
auth_method="unix_peercred",
|
||||||
|
)
|
||||||
|
raise AuthenticationError(
|
||||||
|
"Missing peer credentials over Unix socket",
|
||||||
|
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||||
|
)
|
||||||
|
|
||||||
|
# HTTP transport requires Bearer token strictly
|
||||||
|
raise AuthenticationError(
|
||||||
|
"Bearer token required over network transport",
|
||||||
|
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def enforce_rbac(
|
||||||
|
principal: Principal,
|
||||||
|
operation: OperationType,
|
||||||
|
target: str | None = None,
|
||||||
|
admitted_workloads: set[str] | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Enforce 3-role RBAC policy (homelab-admin, homelab-operator, homelab-viewer).
|
||||||
|
Raises AuthorizationError (403) on violation.
|
||||||
|
"""
|
||||||
|
# 1. homelab-admin has unrestricted access across all operations and targets
|
||||||
|
if principal.role == Role.ADMIN:
|
||||||
|
return
|
||||||
|
|
||||||
|
# 2. homelab-operator:
|
||||||
|
if principal.role == Role.OPERATOR:
|
||||||
|
# Platform homepage sync allowed
|
||||||
|
if operation == OperationType.PLATFORM_SYNC_HOMEPAGE:
|
||||||
|
return
|
||||||
|
|
||||||
|
# Target checks for operations targeting infrastructure
|
||||||
|
if target is not None and target.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,350 @@
|
|||||||
|
"""
|
||||||
|
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 6-code error taxonomy for homelab-appctl.service."""
|
||||||
|
|
||||||
|
ERR_VALIDATION_FAILED = "ERR_VALIDATION_FAILED"
|
||||||
|
ERR_AUTH_REQUIRED = "ERR_AUTH_REQUIRED"
|
||||||
|
ERR_PERMISSION_DENIED = "ERR_PERMISSION_DENIED"
|
||||||
|
ERR_TARGET_NOT_FOUND = "ERR_TARGET_NOT_FOUND"
|
||||||
|
ERR_CONCURRENT_MUTATION = "ERR_CONCURRENT_MUTATION"
|
||||||
|
ERR_EXECUTION_FAILED = "ERR_EXECUTION_FAILED"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def http_status(self) -> int:
|
||||||
|
return ERROR_HTTP_STATUS[self]
|
||||||
|
|
||||||
|
|
||||||
|
ERROR_HTTP_STATUS: dict[ErrorCode, int] = {
|
||||||
|
ErrorCode.ERR_VALIDATION_FAILED: 400,
|
||||||
|
ErrorCode.ERR_AUTH_REQUIRED: 401,
|
||||||
|
ErrorCode.ERR_PERMISSION_DENIED: 403,
|
||||||
|
ErrorCode.ERR_TARGET_NOT_FOUND: 404,
|
||||||
|
ErrorCode.ERR_CONCURRENT_MUTATION: 409,
|
||||||
|
ErrorCode.ERR_EXECUTION_FAILED: 500,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _coerce_error_code(v: Any) -> Any:
|
||||||
|
if isinstance(v, str):
|
||||||
|
try:
|
||||||
|
return ErrorCode(v)
|
||||||
|
except ValueError:
|
||||||
|
return v
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
FlexibleErrorCode = Annotated[
|
||||||
|
ErrorCode,
|
||||||
|
BeforeValidator(_coerce_error_code),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class DeployParams(StrictModel):
|
||||||
|
"""Parameters for workload.deploy."""
|
||||||
|
|
||||||
|
recreate: StrictBool = True
|
||||||
|
remove_orphans: StrictBool = True
|
||||||
|
build: StrictBool = False
|
||||||
|
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
+599
@@ -0,0 +1,599 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
appctl_daemon.py — Dual-Transport HTTP/1.1 Control Plane Daemon for Homelab
|
||||||
|
|
||||||
|
Implements Milestone P4 Control Plane Daemon:
|
||||||
|
- Multi-threaded Unix domain socket listener (/run/homelab/appctl.sock, mode 0660)
|
||||||
|
- Multi-threaded loopback HTTP listener (127.0.0.1:9001)
|
||||||
|
- Bounded 64 KiB request body enforcement
|
||||||
|
- Endpoints: GET /v1/health, POST /v1/operations
|
||||||
|
- Linux SO_PEERCRED credential extraction on UDS transport
|
||||||
|
- Bearer token authentication + RBAC gating + append-only audit logging
|
||||||
|
- Pure-Python Unix domain socket HTTP client helper
|
||||||
|
- Graceful SIGINT and SIGTERM shutdown unlinking socket file
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import http.client
|
||||||
|
import http.server
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
import socket
|
||||||
|
import socketserver
|
||||||
|
import struct
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, cast
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
from appctl_audit import (
|
||||||
|
AuditLogger,
|
||||||
|
PrincipalAudit,
|
||||||
|
TargetLockManager,
|
||||||
|
current_iso_timestamp,
|
||||||
|
generate_operation_id,
|
||||||
|
)
|
||||||
|
from appctl_auth import (
|
||||||
|
AuthenticationError,
|
||||||
|
TokenStore,
|
||||||
|
authenticate_request,
|
||||||
|
)
|
||||||
|
from appctl_contracts import (
|
||||||
|
ErrorCode,
|
||||||
|
OperationError,
|
||||||
|
OperationRequest,
|
||||||
|
OperationResponse,
|
||||||
|
OperationType,
|
||||||
|
sanitize_validation_error,
|
||||||
|
)
|
||||||
|
from appctl_router import OperationalRouter
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
logger = logging.getLogger("appctl_daemon")
|
||||||
|
|
||||||
|
CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent))
|
||||||
|
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
|
||||||
|
DEPLOYMENTS_FILE = Path(
|
||||||
|
os.environ.get("HOMELAB_DEPLOYMENTS_FILE", CORE_DIR / "config" / "deployments.yaml")
|
||||||
|
)
|
||||||
|
|
||||||
|
DEFAULT_SOCKET_PATH = Path(
|
||||||
|
os.environ.get("APPCTL_SOCKET_PATH", "/run/homelab/appctl.sock")
|
||||||
|
)
|
||||||
|
DEFAULT_HTTP_HOST = os.environ.get("APPCTL_HTTP_HOST", "127.0.0.1")
|
||||||
|
DEFAULT_HTTP_PORT = int(os.environ.get("APPCTL_HTTP_PORT", "9001"))
|
||||||
|
MAX_REQUEST_BODY = 64 * 1024 # 64 KiB
|
||||||
|
|
||||||
|
|
||||||
|
def extract_peer_credentials(sock: socket.socket) -> tuple[int, int, int] | None:
|
||||||
|
"""
|
||||||
|
Extract (pid, uid, gid) from a connected Unix domain socket on Linux via SO_PEERCRED.
|
||||||
|
Returns None if unsupported or on error.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
so_peercred = getattr(socket, "SO_PEERCRED", 17)
|
||||||
|
creds = sock.getsockopt(socket.SOL_SOCKET, so_peercred, struct.calcsize("3i"))
|
||||||
|
pid, uid, gid = struct.unpack("3i", creds)
|
||||||
|
return pid, uid, gid
|
||||||
|
except (OSError, struct.error, AttributeError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class UnixHTTPConnection(http.client.HTTPConnection):
|
||||||
|
"""HTTP client connection over a local Unix domain socket."""
|
||||||
|
|
||||||
|
def __init__(self, socket_path: str, timeout: float = 30.0) -> None:
|
||||||
|
super().__init__("localhost", timeout=timeout)
|
||||||
|
self.socket_path = socket_path
|
||||||
|
|
||||||
|
def connect(self) -> None:
|
||||||
|
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||||
|
if self.timeout is not None:
|
||||||
|
sock.settimeout(self.timeout)
|
||||||
|
sock.connect(self.socket_path)
|
||||||
|
self.sock = sock
|
||||||
|
|
||||||
|
|
||||||
|
def send_daemon_request(
|
||||||
|
endpoint: str | Path,
|
||||||
|
operation_request: OperationRequest | dict[str, Any],
|
||||||
|
token: str | None = None,
|
||||||
|
timeout: float = 30.0,
|
||||||
|
) -> OperationResponse:
|
||||||
|
"""
|
||||||
|
Client helper to send an OperationRequest over UDS or HTTP to the daemon.
|
||||||
|
Accepts:
|
||||||
|
- Path object or path ending in .sock -> UnixHTTPConnection
|
||||||
|
- URL starting with http:// or host:port -> standard HTTPConnection
|
||||||
|
"""
|
||||||
|
if isinstance(operation_request, OperationRequest):
|
||||||
|
req_body = operation_request.model_dump_json(exclude_none=True)
|
||||||
|
elif isinstance(operation_request, dict):
|
||||||
|
req_body = json.dumps(operation_request)
|
||||||
|
else:
|
||||||
|
raise TypeError("operation_request must be OperationRequest or dict")
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Host": "localhost",
|
||||||
|
}
|
||||||
|
if token:
|
||||||
|
headers["Authorization"] = f"Bearer {token}"
|
||||||
|
|
||||||
|
is_unix = False
|
||||||
|
endpoint_str = str(endpoint)
|
||||||
|
|
||||||
|
if (
|
||||||
|
isinstance(endpoint, Path)
|
||||||
|
or endpoint_str.endswith(".sock")
|
||||||
|
or ("/" in endpoint_str and not endpoint_str.startswith("http"))
|
||||||
|
):
|
||||||
|
is_unix = True
|
||||||
|
|
||||||
|
if is_unix:
|
||||||
|
conn = UnixHTTPConnection(endpoint_str, timeout=timeout)
|
||||||
|
else:
|
||||||
|
if endpoint_str.startswith(("http://", "https://")):
|
||||||
|
parsed = urlparse(endpoint_str)
|
||||||
|
host = parsed.hostname or "127.0.0.1"
|
||||||
|
port = parsed.port or (443 if parsed.scheme == "https" else 80)
|
||||||
|
elif ":" in endpoint_str:
|
||||||
|
host, port_str = endpoint_str.split(":", 1)
|
||||||
|
port = int(port_str)
|
||||||
|
else:
|
||||||
|
host = endpoint_str
|
||||||
|
port = DEFAULT_HTTP_PORT
|
||||||
|
conn = http.client.HTTPConnection(host, port, timeout=timeout)
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn.request("POST", "/v1/operations", body=req_body.encode("utf-8"), headers=headers)
|
||||||
|
res = conn.getresponse()
|
||||||
|
resp_data = res.read().decode("utf-8")
|
||||||
|
parsed_json = json.loads(resp_data)
|
||||||
|
return OperationResponse.model_validate(parsed_json)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
|
||||||
|
"""
|
||||||
|
HTTP/1.1 request handler for appctl control plane operations.
|
||||||
|
Supports both UDS and loopback TCP listeners.
|
||||||
|
"""
|
||||||
|
|
||||||
|
server_version = "AppctlDaemon/1.0"
|
||||||
|
protocol_version = "HTTP/1.1"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def appctl_server(self) -> ThreadingUnixStreamServer | ThreadingHTTPServer:
|
||||||
|
return cast("ThreadingUnixStreamServer | ThreadingHTTPServer", self.server)
|
||||||
|
|
||||||
|
def address_string(self) -> str:
|
||||||
|
"""Safely format client address avoiding slow DNS lookups or UDS unpack errors."""
|
||||||
|
client_addr = self.client_address
|
||||||
|
if isinstance(client_addr, tuple) and len(client_addr) >= 2:
|
||||||
|
return f"{client_addr[0]}:{client_addr[1]}"
|
||||||
|
if isinstance(client_addr, str) and client_addr:
|
||||||
|
return client_addr
|
||||||
|
return "unix_socket"
|
||||||
|
|
||||||
|
def log_message(self, format: str, *args: Any) -> None:
|
||||||
|
"""Forward access logs to Python standard logger."""
|
||||||
|
logger.info("%s - %s", self.address_string(), format % args)
|
||||||
|
|
||||||
|
def _send_json(self, status_code: int, data: dict[str, Any] | str) -> None:
|
||||||
|
"""Send formatted JSON HTTP response."""
|
||||||
|
body_bytes = data.encode("utf-8") if isinstance(data, str) else json.dumps(data, indent=2).encode("utf-8")
|
||||||
|
self.send_response(status_code)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Content-Length", str(len(body_bytes)))
|
||||||
|
self.send_header("Connection", "close")
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body_bytes)
|
||||||
|
|
||||||
|
def _send_operation_response(self, status_code: int, response: OperationResponse) -> None:
|
||||||
|
"""Serialize and send an OperationResponse payload."""
|
||||||
|
payload_str = response.model_dump_json(exclude_none=True)
|
||||||
|
self._send_json(status_code, payload_str)
|
||||||
|
|
||||||
|
def _send_operation_error(
|
||||||
|
self,
|
||||||
|
status_code: int,
|
||||||
|
error: OperationError,
|
||||||
|
operation: Any = None,
|
||||||
|
target: str | None = None,
|
||||||
|
op_id: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Send standardized OperationResponse representing a failure."""
|
||||||
|
resp = OperationResponse(
|
||||||
|
version="1.0",
|
||||||
|
success=False,
|
||||||
|
status="error",
|
||||||
|
operation_id=op_id or generate_operation_id(),
|
||||||
|
operation=operation if isinstance(operation, (OperationType, str)) else None,
|
||||||
|
target=target if isinstance(target, str) else None,
|
||||||
|
error=error,
|
||||||
|
timestamp=current_iso_timestamp(),
|
||||||
|
)
|
||||||
|
self._send_operation_response(status_code, resp)
|
||||||
|
|
||||||
|
def _send_error_response(
|
||||||
|
self,
|
||||||
|
status_code: int,
|
||||||
|
code: ErrorCode,
|
||||||
|
message: str,
|
||||||
|
details: list[dict[str, Any]] | None = None,
|
||||||
|
op_id: str | None = None,
|
||||||
|
operation: Any = None,
|
||||||
|
target: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Send structured error response with canonical error code."""
|
||||||
|
error = OperationError(code=code, message=message, details=details)
|
||||||
|
self._send_operation_error(
|
||||||
|
status_code=status_code,
|
||||||
|
error=error,
|
||||||
|
operation=operation,
|
||||||
|
target=target,
|
||||||
|
op_id=op_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
def do_GET(self) -> None:
|
||||||
|
"""Handle health check endpoint."""
|
||||||
|
if self.path in ("/v1/health", "/health"):
|
||||||
|
health = self.appctl_server.daemon_instance.get_health_status()
|
||||||
|
self._send_json(200, health)
|
||||||
|
return
|
||||||
|
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=404,
|
||||||
|
code=ErrorCode.ERR_TARGET_NOT_FOUND,
|
||||||
|
message=f"Endpoint '{self.path}' not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
def do_POST(self) -> None:
|
||||||
|
"""Handle operational dispatch requests."""
|
||||||
|
if self.path != "/v1/operations":
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=404,
|
||||||
|
code=ErrorCode.ERR_TARGET_NOT_FOUND,
|
||||||
|
message=f"Endpoint '{self.path}' not found. Supported endpoint: POST /v1/operations",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
cl_header = self.headers.get("Content-Length")
|
||||||
|
if cl_header is None:
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=400,
|
||||||
|
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||||
|
message="Missing Content-Length header",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
content_length = int(cl_header.strip())
|
||||||
|
except ValueError:
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=400,
|
||||||
|
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||||
|
message="Malformed Content-Length header",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if content_length < 0:
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=400,
|
||||||
|
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||||
|
message="Content-Length cannot be negative",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if content_length > MAX_REQUEST_BODY:
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=400,
|
||||||
|
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||||
|
message=f"Request body ({content_length} bytes) exceeds limit of {MAX_REQUEST_BODY} bytes",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
raw_body = self.rfile.read(content_length)
|
||||||
|
|
||||||
|
try:
|
||||||
|
body_dict = json.loads(raw_body.decode("utf-8"))
|
||||||
|
except (json.JSONDecodeError, UnicodeDecodeError) as e:
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=400,
|
||||||
|
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||||
|
message=f"Invalid JSON payload: {e}",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if not isinstance(body_dict, dict):
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=400,
|
||||||
|
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||||
|
message="Payload root must be a JSON object mapping",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
req = OperationRequest.model_validate(body_dict)
|
||||||
|
except ValidationError as exc:
|
||||||
|
sanitized = sanitize_validation_error(exc)
|
||||||
|
self._send_operation_error(
|
||||||
|
status_code=400,
|
||||||
|
error=sanitized,
|
||||||
|
operation=body_dict.get("operation") or body_dict.get("action"),
|
||||||
|
target=body_dict.get("target"),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Determine transport scheme and peer credentials
|
||||||
|
is_unix = getattr(self.connection, "family", None) == socket.AF_UNIX
|
||||||
|
transport = "unix_socket" if is_unix else "http"
|
||||||
|
peer_uid: int | None = None
|
||||||
|
|
||||||
|
if is_unix:
|
||||||
|
creds = extract_peer_credentials(self.connection)
|
||||||
|
if creds is not None:
|
||||||
|
_, peer_uid, _ = creds
|
||||||
|
origin = f"peer_uid_{peer_uid}" if peer_uid is not None else "unix_socket"
|
||||||
|
else:
|
||||||
|
origin = self.address_string()
|
||||||
|
|
||||||
|
client_header = self.headers.get("User-Agent", "appctl-client/1.0")
|
||||||
|
auth_header = self.headers.get("Authorization")
|
||||||
|
|
||||||
|
# Authenticate principal
|
||||||
|
try:
|
||||||
|
principal = authenticate_request(
|
||||||
|
auth_header=auth_header,
|
||||||
|
transport=transport,
|
||||||
|
peer_uid=peer_uid,
|
||||||
|
token_store=self.appctl_server.token_store,
|
||||||
|
)
|
||||||
|
except AuthenticationError as auth_err:
|
||||||
|
op_id = generate_operation_id()
|
||||||
|
auth_msg = str(auth_err)
|
||||||
|
self.appctl_server.audit_logger.log_denied(
|
||||||
|
operation_id=op_id,
|
||||||
|
principal=PrincipalAudit(
|
||||||
|
identity=f"peer_uid_{peer_uid}" if peer_uid is not None else "unknown",
|
||||||
|
role="homelab-viewer" if is_unix else "unknown",
|
||||||
|
token_id=None,
|
||||||
|
auth_method="unix_peercred" if is_unix and auth_header is None else "bearer_token",
|
||||||
|
),
|
||||||
|
action=req.operation.value,
|
||||||
|
target=req.target,
|
||||||
|
transport=transport,
|
||||||
|
origin=origin,
|
||||||
|
client=client_header,
|
||||||
|
parameters=req.parameters,
|
||||||
|
error_code=auth_err.code.value,
|
||||||
|
message=auth_msg,
|
||||||
|
)
|
||||||
|
self._send_operation_error(
|
||||||
|
status_code=auth_err.code.http_status,
|
||||||
|
error=OperationError(code=auth_err.code, message=auth_msg),
|
||||||
|
operation=req.operation,
|
||||||
|
target=req.target,
|
||||||
|
op_id=op_id,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Dispatch operation to OperationalRouter
|
||||||
|
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()
|
||||||
+173
-61
@@ -33,7 +33,8 @@ from provenance import (
|
|||||||
|
|
||||||
# Dynamic Environment Paths
|
# Dynamic Environment Paths
|
||||||
CORE_DIR = os.environ.get(
|
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.environ.get(
|
||||||
@@ -78,12 +79,19 @@ class App:
|
|||||||
name: str # Canonical identifier (e.g., "traefik", "jellyfin")
|
name: str # Canonical identifier (e.g., "traefik", "jellyfin")
|
||||||
description: str = "" # Human-readable summary for dashboards and CLI info
|
description: str = "" # Human-readable summary for dashboards and CLI info
|
||||||
domain: str = "" # Routing FQDN (e.g., "auth.example.com") or "internal".
|
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
|
@property
|
||||||
def is_internal(self) -> bool:
|
def is_internal(self) -> bool:
|
||||||
"""Returns True if the service does not expose a public TLS endpoint."""
|
"""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]:
|
def to_dict(self) -> dict[str, Any]:
|
||||||
"""Serialize for JSON consumption by scripts/appctl"""
|
"""Serialize for JSON consumption by scripts/appctl"""
|
||||||
@@ -100,16 +108,24 @@ class CoreService(App):
|
|||||||
app_type: str = "core_service"
|
app_type: str = "core_service"
|
||||||
dir_path: str = CORE_DIR
|
dir_path: str = CORE_DIR
|
||||||
|
|
||||||
|
@property
|
||||||
|
def container_name(self) -> str:
|
||||||
|
return self.container
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class SitesApp(App):
|
class SitesApp(App):
|
||||||
dir_name: str = "" # directory name in ~/Sites (e.g., "homelab-vaultwarden")
|
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
|
aliases: list[str] = field(default_factory=list) # CLI resolution aliases
|
||||||
visible: bool = True # Defines whether the icon is visible in Homepage
|
visible: bool = True # Defines whether the icon is visible in Homepage
|
||||||
auth: bool = True # Authelia protection guard indicator
|
auth: bool = True # Authelia protection guard indicator
|
||||||
has_compose: bool = False # Whether a docker-compose.yml exists
|
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
|
env: dict[str, Any] = field(default_factory=dict) # Environment variable overrides
|
||||||
homepage: HomepageConfig | None = None # Dashboard Card Configuration
|
homepage: HomepageConfig | None = None # Dashboard Card Configuration
|
||||||
manifest_error: str | None = None # Captured syntax/loading errors
|
manifest_error: str | None = None # Captured syntax/loading errors
|
||||||
@@ -121,15 +137,21 @@ class SitesApp(App):
|
|||||||
data = asdict(self)
|
data = asdict(self)
|
||||||
data.pop("manifest_obj", None)
|
data.pop("manifest_obj", None)
|
||||||
if self.source is not 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:
|
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")
|
data["type"] = getattr(self, "app_type", "app")
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def sites_app_from_manifest(
|
def sites_app_from_manifest(
|
||||||
app_dir: str,
|
app_dir: str,
|
||||||
manifest: Manifest | dict[str, Any] | None = None,
|
manifest: Manifest | dict[str, Any] | None = None,
|
||||||
@@ -139,10 +161,9 @@ def sites_app_from_manifest(
|
|||||||
raw_dir_name = os.path.basename(app_dir)
|
raw_dir_name = os.path.basename(app_dir)
|
||||||
|
|
||||||
if isinstance(manifest, Manifest):
|
if isinstance(manifest, Manifest):
|
||||||
has_compose = (
|
has_compose = os.path.isfile(
|
||||||
os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or
|
os.path.join(app_dir, "docker-compose.yaml")
|
||||||
os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
|
) or os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
|
||||||
)
|
|
||||||
canonical_name = manifest.name
|
canonical_name = manifest.name
|
||||||
domain = manifest.domain or f"{canonical_name}.{HOMELAB_DOMAIN}"
|
domain = manifest.domain or f"{canonical_name}.{HOMELAB_DOMAIN}"
|
||||||
return SitesApp(
|
return SitesApp(
|
||||||
@@ -169,7 +190,9 @@ def sites_app_from_manifest(
|
|||||||
return sites_app_from_manifest(app_dir, parsed, manifest_error)
|
return sites_app_from_manifest(app_dir, parsed, manifest_error)
|
||||||
except ManifestValidationError as err:
|
except ManifestValidationError as err:
|
||||||
manifest_error = f"{manifest_error}; {err}" if manifest_error else str(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(
|
return SitesApp(
|
||||||
name=canonical_name,
|
name=canonical_name,
|
||||||
dir_name=raw_dir_name,
|
dir_name=raw_dir_name,
|
||||||
@@ -217,13 +240,18 @@ def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]:
|
|||||||
try:
|
try:
|
||||||
manifest_obj = parse_manifest(manifest_file)
|
manifest_obj = parse_manifest(manifest_file)
|
||||||
apps.append(sites_app_from_manifest(app_dir=app_dir, manifest=manifest_obj))
|
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
|
raw_data = None
|
||||||
with (
|
with contextlib.suppress(Exception), open(manifest_path, "r", encoding="utf-8") as f:
|
||||||
contextlib.suppress(Exception),
|
|
||||||
open(manifest_path, "r", encoding="utf-8") as f,
|
|
||||||
):
|
|
||||||
raw_data = yaml.safe_load(f)
|
raw_data = yaml.safe_load(f)
|
||||||
|
|
||||||
|
|
||||||
app_dict = raw_data if isinstance(raw_data, dict) else {}
|
app_dict = raw_data if isinstance(raw_data, dict) else {}
|
||||||
apps.append(
|
apps.append(
|
||||||
sites_app_from_manifest(
|
sites_app_from_manifest(
|
||||||
@@ -322,14 +350,18 @@ def resolve_app(
|
|||||||
query: str,
|
query: str,
|
||||||
apps: list[SitesApp] | None = None,
|
apps: list[SitesApp] | None = None,
|
||||||
sites_dir: str | None = None,
|
sites_dir: str | None = None,
|
||||||
|
core_dir: str | None = None,
|
||||||
) -> App | None:
|
) -> App | None:
|
||||||
"""
|
"""
|
||||||
Resolve a query string to a SitesApp or CoreService.
|
Resolve a query string to a SitesApp or CoreService.
|
||||||
Priority: Canonical Name > Alias > Dir Name > Stripped 'homelab-' Prefix > Core Services.
|
Priority: Canonical Name > Alias > Dir Name > Stripped 'homelab-' Prefix > Core Services.
|
||||||
"""
|
"""
|
||||||
if apps is None:
|
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()
|
query_clean = query.strip().lower()
|
||||||
|
|
||||||
# 1. Exact match on canonical name
|
# 1. Exact match on canonical name
|
||||||
@@ -353,7 +385,7 @@ def resolve_app(
|
|||||||
return app
|
return app
|
||||||
|
|
||||||
# 5. Match Core services
|
# 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:
|
if svc.name.lower() == query_clean:
|
||||||
return svc
|
return svc
|
||||||
|
|
||||||
@@ -363,7 +395,7 @@ def resolve_app(
|
|||||||
domain=HOMELAB_DOMAIN,
|
domain=HOMELAB_DOMAIN,
|
||||||
container="",
|
container="",
|
||||||
description="Homelab Core Platform Stack",
|
description="Homelab Core Platform Stack",
|
||||||
dir_path=CORE_DIR,
|
dir_path=c_dir,
|
||||||
app_type="core",
|
app_type="core",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -383,13 +415,22 @@ def get_docker_status(
|
|||||||
text=True,
|
text=True,
|
||||||
check=False,
|
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()
|
state = inspect_res.stdout.strip()
|
||||||
if state.lower() == "true":
|
if state.lower() == "true":
|
||||||
return "🟢 Running (1)"
|
return "🟢 Running (1)"
|
||||||
return "🔴 Stopped"
|
return "🔴 Stopped"
|
||||||
|
|
||||||
path = Path(dir_path)
|
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"
|
return "⚪ Not Stack"
|
||||||
|
|
||||||
res = subprocess.run(
|
res = subprocess.run(
|
||||||
@@ -399,6 +440,9 @@ def get_docker_status(
|
|||||||
text=True,
|
text=True,
|
||||||
check=False,
|
check=False,
|
||||||
)
|
)
|
||||||
|
if res.returncode != 0:
|
||||||
|
return "❓ Unknown"
|
||||||
|
|
||||||
container_ids = [c for c in res.stdout.strip().splitlines() if c]
|
container_ids = [c for c in res.stdout.strip().splitlines() if c]
|
||||||
if not container_ids:
|
if not container_ids:
|
||||||
return "🔴 Stopped"
|
return "🔴 Stopped"
|
||||||
@@ -409,6 +453,9 @@ def get_docker_status(
|
|||||||
text=True,
|
text=True,
|
||||||
check=False,
|
check=False,
|
||||||
)
|
)
|
||||||
|
if inspect_res.returncode != 0:
|
||||||
|
return "❓ Unknown"
|
||||||
|
|
||||||
running_states = inspect_res.stdout.strip().splitlines()
|
running_states = inspect_res.stdout.strip().splitlines()
|
||||||
running_count = sum(1 for s in running_states if s.lower() == "true")
|
running_count = sum(1 for s in running_states if s.lower() == "true")
|
||||||
total_count = len(container_ids)
|
total_count = len(container_ids)
|
||||||
@@ -465,7 +512,9 @@ def get_docker_image_revision(
|
|||||||
return None
|
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."""
|
"""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:
|
if not domain or domain == "internal" or domain.endswith(".local") or ":" in domain:
|
||||||
return {
|
return {
|
||||||
@@ -481,10 +530,8 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
ctx = ssl.create_default_context()
|
ctx = ssl.create_default_context()
|
||||||
with (
|
with socket.create_connection((domain, port), timeout=timeout) as sock: # noqa: SIM117
|
||||||
socket.create_connection((domain, port), timeout=timeout) as sock,
|
with ctx.wrap_socket(sock, server_hostname=domain) as ssock:
|
||||||
ctx.wrap_socket(sock, server_hostname=domain) as ssock,
|
|
||||||
):
|
|
||||||
raw_cert = ssock.getpeercert()
|
raw_cert = ssock.getpeercert()
|
||||||
cert = raw_cert if isinstance(raw_cert, dict) else {}
|
cert = raw_cert if isinstance(raw_cert, dict) else {}
|
||||||
|
|
||||||
@@ -492,9 +539,9 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
|||||||
days_remaining = None
|
days_remaining = None
|
||||||
formatted_expiry = "-"
|
formatted_expiry = "-"
|
||||||
if not_after_str:
|
if not_after_str:
|
||||||
expiry_dt = datetime.datetime.strptime(not_after_str, "%b %d %H:%M:%S %Y %Z").replace(
|
expiry_dt = datetime.datetime.strptime(
|
||||||
tzinfo=datetime.UTC
|
not_after_str, "%b %d %H:%M:%S %Y %Z"
|
||||||
)
|
).replace(tzinfo=datetime.UTC)
|
||||||
now_dt = datetime.datetime.now(datetime.UTC)
|
now_dt = datetime.datetime.now(datetime.UTC)
|
||||||
days_remaining = (expiry_dt - now_dt).days
|
days_remaining = (expiry_dt - now_dt).days
|
||||||
formatted_expiry = expiry_dt.strftime("%Y-%m-%d")
|
formatted_expiry = expiry_dt.strftime("%Y-%m-%d")
|
||||||
@@ -507,7 +554,11 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
|||||||
entry = rdn[0]
|
entry = rdn[0]
|
||||||
if isinstance(entry, (list, tuple)) and len(entry) >= 2:
|
if isinstance(entry, (list, tuple)) and len(entry) >= 2:
|
||||||
issuer_dict[str(entry[0])] = str(entry[1])
|
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_dict: dict[str, str] = {}
|
||||||
subject_raw = cert.get("subject")
|
subject_raw = cert.get("subject")
|
||||||
@@ -519,7 +570,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_dict[str(entry[0])] = str(entry[1])
|
||||||
subject = str(subject_dict.get("commonName") or domain)
|
subject = str(subject_dict.get("commonName") or domain)
|
||||||
|
|
||||||
|
|
||||||
if days_remaining is not None:
|
if days_remaining is not None:
|
||||||
if days_remaining < 0:
|
if days_remaining < 0:
|
||||||
status = f"🔴 Expired ({abs(days_remaining)}d ago)"
|
status = f"🔴 Expired ({abs(days_remaining)}d ago)"
|
||||||
@@ -540,7 +590,14 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
|||||||
"formatted_expiry": formatted_expiry,
|
"formatted_expiry": formatted_expiry,
|
||||||
"error": None,
|
"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 {
|
return {
|
||||||
"domain": domain,
|
"domain": domain,
|
||||||
"status": "🔴 Failed",
|
"status": "🔴 Failed",
|
||||||
@@ -555,13 +612,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]]:
|
def check_all_ssl_certs(domains: list[str]) -> dict[str, dict[str, Any]]:
|
||||||
"""Check multiple domains concurrently with ThreadPoolExecutor."""
|
"""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]] = {}
|
results: dict[str, dict[str, Any]] = {}
|
||||||
if not valid_domains:
|
if not valid_domains:
|
||||||
return results
|
return results
|
||||||
|
|
||||||
with ThreadPoolExecutor(max_workers=min(len(valid_domains), 8)) as executor:
|
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():
|
for future, d in future_to_domain.items():
|
||||||
with contextlib.suppress(subprocess.SubprocessError, OSError):
|
with contextlib.suppress(subprocess.SubprocessError, OSError):
|
||||||
results[d] = future.result()
|
results[d] = future.result()
|
||||||
@@ -591,7 +654,8 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
|||||||
groups[core_group] = []
|
groups[core_group] = []
|
||||||
for svc in core_services:
|
for svc in core_services:
|
||||||
if not svc.is_internal:
|
if not svc.is_internal:
|
||||||
groups[core_group].append({
|
groups[core_group].append(
|
||||||
|
{
|
||||||
"title": svc.name.title(),
|
"title": svc.name.title(),
|
||||||
"icon": getattr(svc, "icon", "default.png"),
|
"icon": getattr(svc, "icon", "default.png"),
|
||||||
"href": f"https://{svc.domain}",
|
"href": f"https://{svc.domain}",
|
||||||
@@ -599,7 +663,8 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
|||||||
"server": "my-docker",
|
"server": "my-docker",
|
||||||
"container": getattr(svc, "container", svc.name),
|
"container": getattr(svc, "container", svc.name),
|
||||||
"weight": getattr(svc, "weight", 50),
|
"weight": getattr(svc, "weight", 50),
|
||||||
})
|
}
|
||||||
|
)
|
||||||
|
|
||||||
# 2. Add Sites applications
|
# 2. Add Sites applications
|
||||||
icons_dir = os.path.join(hp_dir, "icons")
|
icons_dir = os.path.join(hp_dir, "icons")
|
||||||
@@ -633,7 +698,8 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
|||||||
if matched_icon:
|
if matched_icon:
|
||||||
icon = f"/icons/{matched_icon}"
|
icon = f"/icons/{matched_icon}"
|
||||||
|
|
||||||
groups[group_name].append({
|
groups[group_name].append(
|
||||||
|
{
|
||||||
"title": card_title,
|
"title": card_title,
|
||||||
"icon": icon,
|
"icon": icon,
|
||||||
"href": f"https://{app.domain}",
|
"href": f"https://{app.domain}",
|
||||||
@@ -641,7 +707,8 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
|||||||
"server": "my-docker",
|
"server": "my-docker",
|
||||||
"container": container,
|
"container": container,
|
||||||
"weight": weight,
|
"weight": weight,
|
||||||
})
|
}
|
||||||
|
)
|
||||||
|
|
||||||
# Preferred group order
|
# Preferred group order
|
||||||
preferred_order = [
|
preferred_order = [
|
||||||
@@ -675,10 +742,16 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
|||||||
lines.append("")
|
lines.append("")
|
||||||
|
|
||||||
content = "\n".join(lines).strip() + "\n"
|
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.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}")
|
print(f"📄 Generated {services_yaml_path}")
|
||||||
|
|
||||||
|
|
||||||
@@ -699,11 +772,19 @@ def cmd_list(args: list[str]) -> None:
|
|||||||
ssl_data = check_all_ssl_certs(domains_to_check)
|
ssl_data = check_all_ssl_certs(domains_to_check)
|
||||||
|
|
||||||
if show_ssl:
|
if show_ssl:
|
||||||
print(f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}")
|
print(
|
||||||
print(f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}")
|
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
print(f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}")
|
print(
|
||||||
print(f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}")
|
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}"
|
||||||
|
)
|
||||||
|
|
||||||
for app in apps:
|
for app in apps:
|
||||||
app_path = Path(app.dir_path)
|
app_path = Path(app.dir_path)
|
||||||
@@ -713,7 +794,9 @@ def cmd_list(args: list[str]) -> None:
|
|||||||
dep_str = "⚠️ Manifest Error"
|
dep_str = "⚠️ Manifest Error"
|
||||||
prov_str = "⚠️ Invalid Manifest"
|
prov_str = "⚠️ Invalid Manifest"
|
||||||
else:
|
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(
|
two_axis = inspect_workload_two_axis(
|
||||||
app_dir=app_path,
|
app_dir=app_path,
|
||||||
manifest=manifest_obj,
|
manifest=manifest_obj,
|
||||||
@@ -726,9 +809,13 @@ def cmd_list(args: list[str]) -> None:
|
|||||||
if show_ssl:
|
if show_ssl:
|
||||||
cert_info = ssl_data.get(app.domain, check_ssl_cert(app.domain))
|
cert_info = ssl_data.get(app.domain, check_ssl_cert(app.domain))
|
||||||
cert_badge = cert_info.get("status", "-")
|
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:
|
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:
|
if show_core:
|
||||||
core_path = Path(CORE_DIR)
|
core_path = Path(CORE_DIR)
|
||||||
@@ -736,11 +823,19 @@ def cmd_list(args: list[str]) -> None:
|
|||||||
core_dep_str = core_checkout.status_label
|
core_dep_str = core_checkout.status_label
|
||||||
print()
|
print()
|
||||||
if show_ssl:
|
if show_ssl:
|
||||||
print(f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}")
|
print(
|
||||||
print(f"{'------------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}")
|
f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
f"{'------------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
print(f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}")
|
print(
|
||||||
print(f"{'------------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}")
|
f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
f"{'------------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}"
|
||||||
|
)
|
||||||
|
|
||||||
core_services = get_core_services()
|
core_services = get_core_services()
|
||||||
for i, svc in enumerate(core_services):
|
for i, svc in enumerate(core_services):
|
||||||
@@ -749,9 +844,13 @@ def cmd_list(args: list[str]) -> None:
|
|||||||
if show_ssl:
|
if show_ssl:
|
||||||
cert_info = ssl_data.get(svc.domain, check_ssl_cert(svc.domain))
|
cert_info = ssl_data.get(svc.domain, check_ssl_cert(svc.domain))
|
||||||
cert_badge = cert_info.get("status", "-")
|
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:
|
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:
|
def cmd_info(args: list[str]) -> None:
|
||||||
@@ -775,7 +874,9 @@ def cmd_info(args: list[str]) -> None:
|
|||||||
print(f"Directory: {app.dir_path}")
|
print(f"Directory: {app.dir_path}")
|
||||||
print(f"Domain: {app.domain}")
|
print(f"Domain: {app.domain}")
|
||||||
print(f"Container: {app.container}")
|
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}")
|
print(f"Description: {app.description}")
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -791,7 +892,9 @@ def cmd_info(args: list[str]) -> None:
|
|||||||
print(f"Description: {app.description}")
|
print(f"Description: {app.description}")
|
||||||
if app.aliases:
|
if app.aliases:
|
||||||
print(f"Aliases: {', '.join(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"Networks: {', '.join(app.networks)}")
|
||||||
print(f"Auth Protected: {app.auth}")
|
print(f"Auth Protected: {app.auth}")
|
||||||
print(f"Dashboard: {'Visible' if app.visible else 'Hidden'}")
|
print(f"Dashboard: {'Visible' if app.visible else 'Hidden'}")
|
||||||
@@ -816,7 +919,9 @@ def cmd_info(args: list[str]) -> None:
|
|||||||
if two_axis.checkout.is_git:
|
if two_axis.checkout.is_git:
|
||||||
print(f" Branch: {two_axis.checkout.branch}")
|
print(f" Branch: {two_axis.checkout.branch}")
|
||||||
print(f" Commit SHA: {two_axis.checkout.commit_sha}")
|
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}")
|
print(f" Docker Status: {two_axis.docker_status}")
|
||||||
if two_axis.image_revision:
|
if two_axis.image_revision:
|
||||||
print(f" Image Revision:{two_axis.image_revision}")
|
print(f" Image Revision:{two_axis.image_revision}")
|
||||||
@@ -847,7 +952,10 @@ def cmd_resolve(args: list[str]) -> None:
|
|||||||
if not app:
|
if not app:
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
if isinstance(app, SitesApp) and app.manifest_error:
|
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)
|
sys.exit(1)
|
||||||
print(json.dumps(app.to_dict()))
|
print(json.dumps(app.to_dict()))
|
||||||
|
|
||||||
@@ -874,7 +982,9 @@ def cmd_ssl(args: list[str]) -> None:
|
|||||||
print(f"Subject: {cert_info['subject']}")
|
print(f"Subject: {cert_info['subject']}")
|
||||||
print(f"Expiration: {cert_info['not_after']}")
|
print(f"Expiration: {cert_info['not_after']}")
|
||||||
if cert_info["days_remaining"] is not None:
|
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"]:
|
if cert_info["error"]:
|
||||||
print(f"Details/Error: {cert_info['error']}")
|
print(f"Details/Error: {cert_info['error']}")
|
||||||
print()
|
print()
|
||||||
@@ -896,7 +1006,9 @@ def cmd_ssl(args: list[str]) -> None:
|
|||||||
|
|
||||||
for name, domain in services_to_check:
|
for name, domain in services_to_check:
|
||||||
info = ssl_results.get(domain, check_ssl_cert(domain))
|
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:
|
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())
|
||||||
+103
-36
@@ -36,9 +36,9 @@ class ManifestValidationError(Exception):
|
|||||||
"""Raised when an application manifest violates schema or security constraints."""
|
"""Raised when an application manifest violates schema or security constraints."""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class RefType(str, Enum):
|
class RefType(str, Enum):
|
||||||
"""Semantic classification of an upstream git reference."""
|
"""Semantic classification of an upstream git reference."""
|
||||||
|
|
||||||
BRANCH = "branch" # Moving branch (e.g. main, master, develop, release/v1)
|
BRANCH = "branch" # Moving branch (e.g. main, master, develop, release/v1)
|
||||||
TAG = "tag" # Pinned release tag (e.g. v1.0.0, 2.3.1)
|
TAG = "tag" # Pinned release tag (e.g. v1.0.0, 2.3.1)
|
||||||
COMMIT = "commit" # Immutable commit SHA (40-character hex)
|
COMMIT = "commit" # Immutable commit SHA (40-character hex)
|
||||||
@@ -47,6 +47,7 @@ class RefType(str, Enum):
|
|||||||
|
|
||||||
class TransportScheme(str, Enum):
|
class TransportScheme(str, Enum):
|
||||||
"""Supported secure git network transports."""
|
"""Supported secure git network transports."""
|
||||||
|
|
||||||
HTTPS = "https"
|
HTTPS = "https"
|
||||||
SSH = "ssh"
|
SSH = "ssh"
|
||||||
GIT_SCP = "git_scp"
|
GIT_SCP = "git_scp"
|
||||||
@@ -57,15 +58,39 @@ NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]*$")
|
|||||||
COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$")
|
COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$")
|
||||||
SHORT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,12}$")
|
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._-]*)$")
|
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_]*$")
|
ENV_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
|
||||||
RESERVED_ENV_KEYS = {
|
RESERVED_ENV_KEYS = {
|
||||||
"PATH", "LD_PRELOAD", "IFS", "SHELL", "USER",
|
"PATH",
|
||||||
"CORE_DIR", "SITES_DIR", "ENV_FILE", "HOMESERVER_ENV"
|
"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",
|
||||||
}
|
}
|
||||||
|
|
||||||
ALLOWED_STRATEGIES = {"compose"}
|
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]:
|
def validate_transport(url: str) -> tuple[TransportScheme, str]:
|
||||||
@@ -80,35 +105,49 @@ def validate_transport(url: str) -> tuple[TransportScheme, str]:
|
|||||||
|
|
||||||
# Reject path traversal / directory escapes
|
# Reject path traversal / directory escapes
|
||||||
if ".." in clean_url or "\\" in clean_url or clean_url.startswith(("/", "~")):
|
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
|
# 1. HTTPS transport
|
||||||
if clean_url.startswith("https://"):
|
if clean_url.startswith("https://"):
|
||||||
parsed = urlparse(clean_url)
|
parsed = urlparse(clean_url)
|
||||||
if not parsed.netloc:
|
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 == "/":
|
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
|
return TransportScheme.HTTPS, clean_url
|
||||||
|
|
||||||
# 2. Standard SSH transport (ssh://[user@]host[:port]/path)
|
# 2. Standard SSH transport (ssh://[user@]host[:port]/path)
|
||||||
if clean_url.startswith("ssh://"):
|
if clean_url.startswith("ssh://"):
|
||||||
parsed = urlparse(clean_url)
|
parsed = urlparse(clean_url)
|
||||||
if not parsed.netloc:
|
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 == "/":
|
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
|
return TransportScheme.SSH, clean_url
|
||||||
|
|
||||||
# 3. SCP-style SSH transport (git@host:owner/repo.git)
|
# 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):
|
if SCP_URL_RE.match(clean_url):
|
||||||
return TransportScheme.GIT_SCP, clean_url
|
return TransportScheme.GIT_SCP, clean_url
|
||||||
raise ManifestValidationError(f"Malformed SCP-style source URL: '{clean_url}'")
|
raise ManifestValidationError(f"Malformed SCP-style source URL: '{clean_url}'")
|
||||||
|
|
||||||
# Reject plaintext HTTP or unsupported schemes
|
# Reject plaintext HTTP or unsupported schemes
|
||||||
if clean_url.startswith("http://"):
|
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(
|
raise ManifestValidationError(
|
||||||
f"Invalid source.url scheme: '{clean_url}'. "
|
f"Invalid source.url scheme: '{clean_url}'. "
|
||||||
@@ -140,20 +179,14 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]:
|
|||||||
if SEMVER_TAG_RE.match(ref):
|
if SEMVER_TAG_RE.match(ref):
|
||||||
return RefType.TAG, ref
|
return RefType.TAG, ref
|
||||||
|
|
||||||
# Standard branch naming patterns
|
# Non-versioned arbitrary string treated as branch
|
||||||
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
|
|
||||||
return RefType.BRANCH, ref
|
return RefType.BRANCH, ref
|
||||||
|
|
||||||
|
|
||||||
class SourceConfig(BaseModel):
|
class SourceConfig(BaseModel):
|
||||||
"""Upstream source provenance descriptor."""
|
"""Upstream source provenance descriptor."""
|
||||||
model_config = ConfigDict(extra="forbid")
|
|
||||||
|
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||||
|
|
||||||
url: str
|
url: str
|
||||||
ref: str = "main"
|
ref: str = "main"
|
||||||
@@ -167,7 +200,9 @@ class SourceConfig(BaseModel):
|
|||||||
if isinstance(data, dict):
|
if isinstance(data, dict):
|
||||||
src_type = str(data.get("type", "git")).strip().lower()
|
src_type = str(data.get("type", "git")).strip().lower()
|
||||||
if src_type != "git":
|
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
|
data["type"] = src_type
|
||||||
|
|
||||||
raw_url = data.get("url")
|
raw_url = data.get("url")
|
||||||
@@ -198,7 +233,8 @@ class SourceConfig(BaseModel):
|
|||||||
|
|
||||||
class DeploymentConfig(BaseModel):
|
class DeploymentConfig(BaseModel):
|
||||||
"""Continuous deployment strategy and action policy."""
|
"""Continuous deployment strategy and action policy."""
|
||||||
model_config = ConfigDict(extra="forbid")
|
|
||||||
|
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||||
|
|
||||||
strategy: str = "compose"
|
strategy: str = "compose"
|
||||||
branch: str = "main"
|
branch: str = "main"
|
||||||
@@ -223,7 +259,7 @@ class DeploymentConfig(BaseModel):
|
|||||||
act_str = str(act).strip().lower()
|
act_str = str(act).strip().lower()
|
||||||
if act_str not in ALLOWED_ACTIONS:
|
if act_str not in ALLOWED_ACTIONS:
|
||||||
raise ManifestValidationError(
|
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)
|
actions.append(act_str)
|
||||||
if not actions:
|
if not actions:
|
||||||
@@ -237,7 +273,8 @@ class DeploymentConfig(BaseModel):
|
|||||||
|
|
||||||
class HomepageConfig(BaseModel):
|
class HomepageConfig(BaseModel):
|
||||||
"""Dashboard card metadata for Homepage."""
|
"""Dashboard card metadata for Homepage."""
|
||||||
model_config = ConfigDict(extra="forbid")
|
|
||||||
|
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||||
|
|
||||||
title: str
|
title: str
|
||||||
group: str = "Applications"
|
group: str = "Applications"
|
||||||
@@ -262,7 +299,12 @@ class Manifest(BaseModel):
|
|||||||
Authoritative Workload Manifest Model (Schema v1.0).
|
Authoritative Workload Manifest Model (Schema v1.0).
|
||||||
Represents the full contract declared in a workload's app.yaml.
|
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
|
name: str
|
||||||
schema_version: str = Field(default="1.0", alias="schemaVersion")
|
schema_version: str = Field(default="1.0", alias="schemaVersion")
|
||||||
@@ -282,8 +324,14 @@ class Manifest(BaseModel):
|
|||||||
def prepare_manifest(cls, data: Any) -> Any:
|
def prepare_manifest(cls, data: Any) -> Any:
|
||||||
if isinstance(data, dict):
|
if isinstance(data, dict):
|
||||||
raw_name = data.get("name")
|
raw_name = data.get("name")
|
||||||
if raw_name is None or not isinstance(raw_name, str) or not raw_name.strip():
|
if (
|
||||||
raise ManifestValidationError("Manifest is missing mandatory string field 'name'.")
|
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()
|
clean_name = raw_name.strip()
|
||||||
if not NAME_RE.match(clean_name):
|
if not NAME_RE.match(clean_name):
|
||||||
raise ManifestValidationError(
|
raise ManifestValidationError(
|
||||||
@@ -359,7 +407,12 @@ class Manifest(BaseModel):
|
|||||||
@property
|
@property
|
||||||
def is_internal(self) -> bool:
|
def is_internal(self) -> bool:
|
||||||
"""True if the workload does not expose a public TLS endpoint."""
|
"""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]:
|
def to_dict(self) -> dict[str, Any]:
|
||||||
data: dict[str, Any] = {
|
data: dict[str, Any] = {
|
||||||
@@ -401,23 +454,35 @@ def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest:
|
|||||||
try:
|
try:
|
||||||
content = raw_input.read_text(encoding="utf-8")
|
content = raw_input.read_text(encoding="utf-8")
|
||||||
except OSError as e:
|
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:
|
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:
|
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):
|
elif isinstance(raw_input, str):
|
||||||
try:
|
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:
|
except Exception as e:
|
||||||
raise ManifestValidationError(f"YAML parsing error: {e}") from e
|
raise ManifestValidationError(f"YAML parsing error: {e}") from e
|
||||||
elif isinstance(raw_input, dict):
|
elif isinstance(raw_input, dict):
|
||||||
data = raw_input
|
data = raw_input
|
||||||
else:
|
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):
|
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:
|
try:
|
||||||
return Manifest.model_validate(data)
|
return Manifest.model_validate(data)
|
||||||
@@ -433,7 +498,9 @@ def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest:
|
|||||||
msg = msg.removeprefix("Value error, ")
|
msg = msg.removeprefix("Value error, ")
|
||||||
loc = ".".join(str(p) for p in first_error.get("loc", []))
|
loc = ".".join(str(p) for p in first_error.get("loc", []))
|
||||||
if loc and first_error.get("type") == "extra_forbidden":
|
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
|
raise ManifestValidationError(msg) from e
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+501
-123
File diff suppressed because it is too large.
Load diff
+24
-10
@@ -19,6 +19,7 @@ from core_manifest import Manifest, RefType, SourceConfig
|
|||||||
|
|
||||||
class ProvenanceStatus(str, Enum):
|
class ProvenanceStatus(str, Enum):
|
||||||
"""Evaluation result of local state vs. upstream software provenance."""
|
"""Evaluation result of local state vs. upstream software provenance."""
|
||||||
|
|
||||||
SYNCED = "✓ Synced"
|
SYNCED = "✓ Synced"
|
||||||
UPDATE_AVAILABLE = "↓ Update Available"
|
UPDATE_AVAILABLE = "↓ Update Available"
|
||||||
IMAGE_ONLY = "— Image-Only (Class B)"
|
IMAGE_ONLY = "— Image-Only (Class B)"
|
||||||
@@ -32,6 +33,7 @@ class ProvenanceStatus(str, Enum):
|
|||||||
@dataclass
|
@dataclass
|
||||||
class CheckoutStatus:
|
class CheckoutStatus:
|
||||||
"""Axis 1: Local deployment checkout state."""
|
"""Axis 1: Local deployment checkout state."""
|
||||||
|
|
||||||
is_git: bool
|
is_git: bool
|
||||||
is_dirty: bool
|
is_dirty: bool
|
||||||
branch: str
|
branch: str
|
||||||
@@ -51,6 +53,7 @@ class CheckoutStatus:
|
|||||||
@dataclass
|
@dataclass
|
||||||
class UpstreamProvenance:
|
class UpstreamProvenance:
|
||||||
"""Axis 2: Upstream software provenance state."""
|
"""Axis 2: Upstream software provenance state."""
|
||||||
|
|
||||||
status: ProvenanceStatus
|
status: ProvenanceStatus
|
||||||
remote_sha: str = ""
|
remote_sha: str = ""
|
||||||
target_ref: str = ""
|
target_ref: str = ""
|
||||||
@@ -68,6 +71,7 @@ class UpstreamProvenance:
|
|||||||
@dataclass
|
@dataclass
|
||||||
class TwoAxisStatus:
|
class TwoAxisStatus:
|
||||||
"""Unified inspection combining local deployment and upstream provenance."""
|
"""Unified inspection combining local deployment and upstream provenance."""
|
||||||
|
|
||||||
app_name: str
|
app_name: str
|
||||||
checkout: CheckoutStatus
|
checkout: CheckoutStatus
|
||||||
provenance: UpstreamProvenance
|
provenance: UpstreamProvenance
|
||||||
@@ -105,6 +109,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
|
|||||||
|
|
||||||
# 1. Check cleanliness
|
# 1. Check cleanliness
|
||||||
is_dirty = False
|
is_dirty = False
|
||||||
|
git_error: str | None = None
|
||||||
try:
|
try:
|
||||||
status_res = subprocess.run(
|
status_res = subprocess.run(
|
||||||
["git", "-C", str(path), "status", "--porcelain"],
|
["git", "-C", str(path), "status", "--porcelain"],
|
||||||
@@ -114,10 +119,14 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
|
|||||||
timeout=5.0,
|
timeout=5.0,
|
||||||
env=git_env,
|
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
|
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
|
is_dirty = False
|
||||||
|
git_error = f"⚠️ Git Error ({exc.__class__.__name__})"
|
||||||
|
|
||||||
# 2. Get active branch
|
# 2. Get active branch
|
||||||
branch = ""
|
branch = ""
|
||||||
@@ -164,6 +173,9 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
|
|||||||
commit_sha = ""
|
commit_sha = ""
|
||||||
|
|
||||||
# 4. Format status label
|
# 4. Format status label
|
||||||
|
if git_error:
|
||||||
|
status_label = git_error
|
||||||
|
else:
|
||||||
state_symbol = "* Dirty" if is_dirty else "✓ Clean"
|
state_symbol = "* Dirty" if is_dirty else "✓ Clean"
|
||||||
ref_desc = f"{branch}@{commit_sha}" if commit_sha else branch
|
ref_desc = f"{branch}@{commit_sha}" if commit_sha else branch
|
||||||
status_label = f"{state_symbol} ({ref_desc})" if ref_desc else state_symbol
|
status_label = f"{state_symbol} ({ref_desc})" if ref_desc else state_symbol
|
||||||
@@ -198,12 +210,12 @@ def resolve_upstream_provenance(
|
|||||||
|
|
||||||
# Commits pinned directly in manifest cannot be checked via ls-remote ref matching
|
# Commits pinned directly in manifest cannot be checked via ls-remote ref matching
|
||||||
if source.ref_type == RefType.COMMIT:
|
if source.ref_type == RefType.COMMIT:
|
||||||
is_match = (
|
is_match = local_commit and (
|
||||||
local_commit and (
|
|
||||||
source.ref.startswith(local_commit) or local_commit.startswith(source.ref)
|
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(
|
return UpstreamProvenance(
|
||||||
status=status,
|
status=status,
|
||||||
remote_sha=source.ref,
|
remote_sha=source.ref,
|
||||||
@@ -248,10 +260,10 @@ def resolve_upstream_provenance(
|
|||||||
for line in proc.stdout.splitlines():
|
for line in proc.stdout.splitlines():
|
||||||
parts = line.strip().split()
|
parts = line.strip().split()
|
||||||
if len(parts) >= 2 and (
|
if len(parts) >= 2 and (
|
||||||
parts[1] == target_ref or
|
parts[1] == target_ref
|
||||||
parts[1] == f"refs/heads/{target_ref}" or
|
or parts[1] == f"refs/heads/{target_ref}"
|
||||||
parts[1] == f"refs/tags/{target_ref}" or
|
or parts[1] == f"refs/tags/{target_ref}"
|
||||||
parts[1] == f"refs/tags/{target_ref}^{{}}"
|
or parts[1] == f"refs/tags/{target_ref}^{{}}"
|
||||||
):
|
):
|
||||||
remote_sha = parts[0]
|
remote_sha = parts[0]
|
||||||
# Peaked tags (^{}) take precedence over lightweight tag refs
|
# Peaked tags (^{}) take precedence over lightweight tag refs
|
||||||
@@ -271,7 +283,9 @@ def resolve_upstream_provenance(
|
|||||||
|
|
||||||
# Compare local commit with remote SHA
|
# Compare local commit with remote SHA
|
||||||
is_synced = False
|
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
|
is_synced = True
|
||||||
|
|
||||||
status = ProvenanceStatus.SYNCED if is_synced else ProvenanceStatus.UPDATE_AVAILABLE
|
status = ProvenanceStatus.SYNCED if is_synced else ProvenanceStatus.UPDATE_AVAILABLE
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
[mutmut]
|
||||||
|
also_copy=
|
||||||
|
pyproject.toml
|
||||||
|
docker-compose.yml
|
||||||
|
config
|
||||||
|
scripts
|
||||||
@@ -3,44 +3,41 @@ Security invariant tests for homelab GitOps execution and admission.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import gitops_dispatcher
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
# Add Core to path so scripts can be imported
|
# Add Core to path so scripts can be imported
|
||||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
# Comment-out reason: testing pyproject-level pythonpath definition
|
||||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||||
|
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||||
import gitops_dispatcher
|
|
||||||
|
|
||||||
|
|
||||||
def test_custom_shell_action_is_rejected_without_execution(tmp_path: Path):
|
def test_custom_shell_action_is_rejected_without_execution(tmp_path: Path):
|
||||||
"""Ensure that arbitrary 'custom' actions fail closed and never invoke a shell."""
|
"""Ensure that arbitrary 'custom' actions fail closed and never invoke a shell."""
|
||||||
deployment_config = {
|
deployment_config = {"branch": "main", "actions": [{"custom": "touch /tmp/pwned"}]}
|
||||||
"branch": "main",
|
|
||||||
"actions": [
|
|
||||||
{"custom": "touch /tmp/pwned"}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
with patch("subprocess.run") as mock_run:
|
with patch("subprocess.run") as mock_run:
|
||||||
success = gitops_dispatcher.execute_deployment(tmp_path, deployment_config, branch="main")
|
success = gitops_dispatcher.execute_deployment(
|
||||||
|
tmp_path, deployment_config, branch="main"
|
||||||
|
)
|
||||||
|
|
||||||
assert success is False, "execute_deployment must fail closed on 'custom' action"
|
assert success is False, (
|
||||||
|
"execute_deployment must fail closed on 'custom' action"
|
||||||
|
)
|
||||||
mock_run.assert_not_called()
|
mock_run.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
def test_unknown_action_is_rejected(tmp_path: Path):
|
def test_unknown_action_is_rejected(tmp_path: Path):
|
||||||
"""Ensure that unknown action strings fail closed and abort deployment."""
|
"""Ensure that unknown action strings fail closed and abort deployment."""
|
||||||
deployment_config = {
|
deployment_config = {"branch": "main", "actions": ["malicious_or_unknown_action"]}
|
||||||
"branch": "main",
|
|
||||||
"actions": ["malicious_or_unknown_action"]
|
|
||||||
}
|
|
||||||
|
|
||||||
with patch("subprocess.run") as mock_run:
|
with patch("subprocess.run") as mock_run:
|
||||||
success = gitops_dispatcher.execute_deployment(tmp_path, deployment_config, branch="main")
|
success = gitops_dispatcher.execute_deployment(
|
||||||
|
tmp_path, deployment_config, branch="main"
|
||||||
|
)
|
||||||
|
|
||||||
assert success is False, "execute_deployment must reject unknown actions"
|
assert success is False, "execute_deployment must reject unknown actions"
|
||||||
mock_run.assert_not_called()
|
mock_run.assert_not_called()
|
||||||
@@ -48,14 +45,13 @@ def test_unknown_action_is_rejected(tmp_path: Path):
|
|||||||
|
|
||||||
def test_allowed_actions_use_safe_argument_lists(tmp_path: Path):
|
def test_allowed_actions_use_safe_argument_lists(tmp_path: Path):
|
||||||
"""Ensure that allowed actions execute safely via argument lists without shell=True."""
|
"""Ensure that allowed actions execute safely via argument lists without shell=True."""
|
||||||
deployment_config = {
|
deployment_config = {"branch": "main", "actions": ["git_pull"]}
|
||||||
"branch": "main",
|
|
||||||
"actions": ["git_pull"]
|
|
||||||
}
|
|
||||||
|
|
||||||
with patch("subprocess.run") as mock_run:
|
with patch("subprocess.run") as mock_run:
|
||||||
mock_run.return_value = MagicMock(returncode=0)
|
mock_run.return_value = MagicMock(returncode=0)
|
||||||
success = gitops_dispatcher.execute_deployment(tmp_path, deployment_config, branch="main")
|
success = gitops_dispatcher.execute_deployment(
|
||||||
|
tmp_path, deployment_config, branch="main"
|
||||||
|
)
|
||||||
|
|
||||||
assert success is True
|
assert success is True
|
||||||
mock_run.assert_called_once()
|
mock_run.assert_called_once()
|
||||||
@@ -82,7 +78,9 @@ def test_resolve_repository_rejects_path_traversal(tmp_path: Path, monkeypatch):
|
|||||||
]
|
]
|
||||||
|
|
||||||
for payload in traversal_payloads:
|
for payload in traversal_payloads:
|
||||||
assert gitops_dispatcher.resolve_repository(payload) is None, f"Expected {payload} to be rejected"
|
assert gitops_dispatcher.resolve_repository(payload) is None, (
|
||||||
|
f"Expected {payload} to be rejected"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_resolve_repository_rejects_unknown_repositories(tmp_path: Path, monkeypatch):
|
def test_resolve_repository_rejects_unknown_repositories(tmp_path: Path, monkeypatch):
|
||||||
@@ -120,14 +118,13 @@ def test_resolve_repository_resolves_valid_manifest(tmp_path: Path, monkeypatch)
|
|||||||
app_dir = sites_dir / "homelab-docs"
|
app_dir = sites_dir / "homelab-docs"
|
||||||
app_dir.mkdir(parents=True)
|
app_dir.mkdir(parents=True)
|
||||||
(app_dir / "app.yaml").write_text(
|
(app_dir / "app.yaml").write_text(
|
||||||
"name: docs\naliases:\n - doc2site\n - notes\n",
|
"name: docs\naliases:\n - doc2site\n - notes\n", encoding="utf-8"
|
||||||
encoding="utf-8"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
registry = tmp_path / "deployments.yaml"
|
registry = tmp_path / "deployments.yaml"
|
||||||
registry.write_text(
|
registry.write_text(
|
||||||
f'schemaVersion: "1.0"\nrepositories:\n homelab-docs:\n path: "{app_dir}"\n aliases:\n - docs\n - doc2site\n - notes\n',
|
f'schemaVersion: "1.0"\nrepositories:\n homelab-docs:\n path: "{app_dir}"\n aliases:\n - docs\n - doc2site\n - notes\n',
|
||||||
encoding="utf-8"
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
|
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
@@ -140,7 +137,6 @@ def test_resolve_repository_resolves_valid_manifest(tmp_path: Path, monkeypatch)
|
|||||||
assert gitops_dispatcher.resolve_repository("notes") == canonical
|
assert gitops_dispatcher.resolve_repository("notes") == canonical
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_resolve_repository_rejects_vault(tmp_path: Path, monkeypatch):
|
def test_resolve_repository_rejects_vault(tmp_path: Path, monkeypatch):
|
||||||
"""Ensure data vault identities (Brain / second-brain) are not recognized by GitOps."""
|
"""Ensure data vault identities (Brain / second-brain) are not recognized by GitOps."""
|
||||||
sites_dir = tmp_path / "Sites"
|
sites_dir = tmp_path / "Sites"
|
||||||
@@ -189,7 +185,9 @@ repositories:
|
|||||||
assert "escaped-app" not in mapping
|
assert "escaped-app" not in mapping
|
||||||
|
|
||||||
|
|
||||||
def test_unregistered_sites_directory_rejected_when_registry_active(tmp_path: Path, monkeypatch):
|
def test_unregistered_sites_directory_rejected_when_registry_active(
|
||||||
|
tmp_path: Path, monkeypatch
|
||||||
|
):
|
||||||
"""Ensure unregistered directories in ~/Sites cannot be resolved when deployments.yaml is active."""
|
"""Ensure unregistered directories in ~/Sites cannot be resolved when deployments.yaml is active."""
|
||||||
sites_dir = tmp_path / "Sites"
|
sites_dir = tmp_path / "Sites"
|
||||||
registered_dir = sites_dir / "homelab-docs"
|
registered_dir = sites_dir / "homelab-docs"
|
||||||
@@ -224,7 +222,9 @@ def test_missing_or_corrupt_registry_fails_closed(tmp_path: Path, monkeypatch):
|
|||||||
missing_registry = tmp_path / "nonexistent-deployments.yaml"
|
missing_registry = tmp_path / "nonexistent-deployments.yaml"
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", missing_registry)
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", missing_registry)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "CONFIG_DIR", tmp_path / "nonexistent-config")
|
monkeypatch.setattr(
|
||||||
|
gitops_dispatcher, "CONFIG_DIR", tmp_path / "nonexistent-config"
|
||||||
|
)
|
||||||
|
|
||||||
# Missing registry must fail closed: empty mapping, no resolution
|
# Missing registry must fail closed: empty mapping, no resolution
|
||||||
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
|
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
|
||||||
@@ -232,14 +232,15 @@ def test_missing_or_corrupt_registry_fails_closed(tmp_path: Path, monkeypatch):
|
|||||||
|
|
||||||
# Corrupt YAML registry must also fail closed
|
# Corrupt YAML registry must also fail closed
|
||||||
corrupt_registry = tmp_path / "corrupt-deployments.yaml"
|
corrupt_registry = tmp_path / "corrupt-deployments.yaml"
|
||||||
corrupt_registry.write_text("schemaVersion: 1.0\nrepositories: [bad list syntax", encoding="utf-8")
|
corrupt_registry.write_text(
|
||||||
|
"schemaVersion: 1.0\nrepositories: [bad list syntax", encoding="utf-8"
|
||||||
|
)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", corrupt_registry)
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", corrupt_registry)
|
||||||
|
|
||||||
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
|
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
|
||||||
assert gitops_dispatcher.resolve_repository("valid") is None
|
assert gitops_dispatcher.resolve_repository("valid") is None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_webhook_verification_valid_signature():
|
def test_webhook_verification_valid_signature():
|
||||||
"""Ensure valid HMAC-SHA256 signature passes verification."""
|
"""Ensure valid HMAC-SHA256 signature passes verification."""
|
||||||
import hashlib
|
import hashlib
|
||||||
@@ -251,7 +252,10 @@ def test_webhook_verification_valid_signature():
|
|||||||
|
|
||||||
assert gitops_dispatcher.verify_signature(body, expected_hex, secret) is True
|
assert gitops_dispatcher.verify_signature(body, expected_hex, secret) is True
|
||||||
# Support sha256= prefix as well
|
# Support sha256= prefix as well
|
||||||
assert gitops_dispatcher.verify_signature(body, f"sha256={expected_hex}", secret) is True
|
assert (
|
||||||
|
gitops_dispatcher.verify_signature(body, f"sha256={expected_hex}", secret)
|
||||||
|
is True
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_webhook_verification_invalid_signature():
|
def test_webhook_verification_invalid_signature():
|
||||||
@@ -316,7 +320,10 @@ def test_webhook_verification_malformed_signature():
|
|||||||
secret = b"supersecrettoken123"
|
secret = b"supersecrettoken123"
|
||||||
body = b'{"repository": {"name": "docs"}}'
|
body = b'{"repository": {"name": "docs"}}'
|
||||||
|
|
||||||
assert gitops_dispatcher.verify_signature(body, "not-a-valid-hex-digest", secret) is False
|
assert (
|
||||||
|
gitops_dispatcher.verify_signature(body, "not-a-valid-hex-digest", secret)
|
||||||
|
is False
|
||||||
|
)
|
||||||
assert gitops_dispatcher.verify_signature(body, "deadbeef", secret) is False
|
assert gitops_dispatcher.verify_signature(body, "deadbeef", secret) is False
|
||||||
assert gitops_dispatcher.verify_signature(body, "z" * 64, secret) is False
|
assert gitops_dispatcher.verify_signature(body, "z" * 64, secret) is False
|
||||||
|
|
||||||
@@ -326,36 +333,35 @@ def test_admission_rejects_non_push_events(tmp_path: Path):
|
|||||||
payload_pr = {
|
payload_pr = {
|
||||||
"ref": "refs/heads/main",
|
"ref": "refs/heads/main",
|
||||||
"repository": {"name": "docs"},
|
"repository": {"name": "docs"},
|
||||||
"pull_request": {"id": 1}
|
"pull_request": {"id": 1},
|
||||||
}
|
}
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload_pr, event_type="push")
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
|
payload_pr, event_type="push"
|
||||||
|
)
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "non-push event" in reason
|
assert "non-push event" in reason
|
||||||
|
|
||||||
payload_normal = {
|
payload_normal = {"ref": "refs/heads/main", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/heads/main",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
payload_normal, event_type="pull_request"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload_normal, event_type="pull_request")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "Only 'push' is allowed" in reason
|
assert "Only 'push' is allowed" in reason
|
||||||
|
|
||||||
|
|
||||||
def test_admission_rejects_tags_and_invalid_refs():
|
def test_admission_rejects_tags_and_invalid_refs():
|
||||||
"""Ensure tags or invalid ref structures are rejected from deployment."""
|
"""Ensure tags or invalid ref structures are rejected from deployment."""
|
||||||
tag_payload = {
|
tag_payload = {"ref": "refs/tags/v1.0.0", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/tags/v1.0.0",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
tag_payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(tag_payload, event_type="push")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "Tag push" in reason
|
assert "Tag push" in reason
|
||||||
|
|
||||||
non_head_payload = {
|
non_head_payload = {"ref": "refs/pull/42/head", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/pull/42/head",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
non_head_payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(non_head_payload, event_type="push")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "not a head branch" in reason
|
assert "not a head branch" in reason
|
||||||
|
|
||||||
@@ -366,11 +372,10 @@ def test_admission_rejects_unknown_repository(tmp_path: Path, monkeypatch):
|
|||||||
sites_dir.mkdir()
|
sites_dir.mkdir()
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
|
||||||
payload = {
|
payload = {"ref": "refs/heads/main", "repository": {"name": "unregistered-app"}}
|
||||||
"ref": "refs/heads/main",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "unregistered-app"}
|
payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "not recognized" in reason
|
assert "not recognized" in reason
|
||||||
|
|
||||||
@@ -381,8 +386,7 @@ def test_admission_rejects_branch_mismatch(tmp_path: Path, monkeypatch):
|
|||||||
app_dir = sites_dir / "homelab-docs"
|
app_dir = sites_dir / "homelab-docs"
|
||||||
app_dir.mkdir(parents=True)
|
app_dir.mkdir(parents=True)
|
||||||
(app_dir / "app.yaml").write_text(
|
(app_dir / "app.yaml").write_text(
|
||||||
"name: docs\ndeployment:\n branch: production\n",
|
"name: docs\ndeployment:\n branch: production\n", encoding="utf-8"
|
||||||
encoding="utf-8"
|
|
||||||
)
|
)
|
||||||
registry = tmp_path / "deployments.yaml"
|
registry = tmp_path / "deployments.yaml"
|
||||||
registry.write_text(
|
registry.write_text(
|
||||||
@@ -392,11 +396,10 @@ def test_admission_rejects_branch_mismatch(tmp_path: Path, monkeypatch):
|
|||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {"ref": "refs/heads/staging", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/heads/staging",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "Branch mismatch" in reason
|
assert "Branch mismatch" in reason
|
||||||
|
|
||||||
@@ -408,7 +411,7 @@ def test_admission_rejects_unsupported_strategy(tmp_path: Path, monkeypatch):
|
|||||||
app_dir.mkdir(parents=True)
|
app_dir.mkdir(parents=True)
|
||||||
(app_dir / "app.yaml").write_text(
|
(app_dir / "app.yaml").write_text(
|
||||||
"name: docs\ndeployment:\n branch: main\n strategy: kubernetes\n",
|
"name: docs\ndeployment:\n branch: main\n strategy: kubernetes\n",
|
||||||
encoding="utf-8"
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
registry = tmp_path / "deployments.yaml"
|
registry = tmp_path / "deployments.yaml"
|
||||||
registry.write_text(
|
registry.write_text(
|
||||||
@@ -418,11 +421,10 @@ def test_admission_rejects_unsupported_strategy(tmp_path: Path, monkeypatch):
|
|||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {"ref": "refs/heads/main", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/heads/main",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "Unsupported deployment strategy" in reason
|
assert "Unsupported deployment strategy" in reason
|
||||||
|
|
||||||
@@ -434,7 +436,7 @@ def test_admission_rejects_unsupported_actions(tmp_path: Path, monkeypatch):
|
|||||||
app_dir.mkdir(parents=True)
|
app_dir.mkdir(parents=True)
|
||||||
(app_dir / "app.yaml").write_text(
|
(app_dir / "app.yaml").write_text(
|
||||||
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n",
|
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n",
|
||||||
encoding="utf-8"
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
registry = tmp_path / "deployments.yaml"
|
registry = tmp_path / "deployments.yaml"
|
||||||
registry.write_text(
|
registry.write_text(
|
||||||
@@ -444,11 +446,10 @@ def test_admission_rejects_unsupported_actions(tmp_path: Path, monkeypatch):
|
|||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {"ref": "refs/heads/main", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/heads/main",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "Unsupported deployment action" in reason
|
assert "Unsupported deployment action" in reason
|
||||||
|
|
||||||
@@ -460,7 +461,7 @@ def test_admission_admits_valid_push(tmp_path: Path, monkeypatch):
|
|||||||
app_dir.mkdir(parents=True)
|
app_dir.mkdir(parents=True)
|
||||||
(app_dir / "app.yaml").write_text(
|
(app_dir / "app.yaml").write_text(
|
||||||
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n",
|
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n",
|
||||||
encoding="utf-8"
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
registry = tmp_path / "deployments.yaml"
|
registry = tmp_path / "deployments.yaml"
|
||||||
registry.write_text(
|
registry.write_text(
|
||||||
@@ -470,11 +471,10 @@ def test_admission_admits_valid_push(tmp_path: Path, monkeypatch):
|
|||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {"ref": "refs/heads/main", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/heads/main",
|
admitted, target_dir, config, branch, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, target_dir, config, branch, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
|
||||||
assert admitted is True
|
assert admitted is True
|
||||||
|
|
||||||
assert "Admitted" in reason
|
assert "Admitted" in reason
|
||||||
@@ -492,16 +492,22 @@ def test_enqueue_supersedes_pending_revision(tmp_path: Path, monkeypatch):
|
|||||||
target_dir.mkdir()
|
target_dir.mkdir()
|
||||||
|
|
||||||
# Enqueue revision A
|
# Enqueue revision A
|
||||||
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "A"}, "main")
|
gitops_dispatcher.enqueue_deployment(
|
||||||
|
target_dir, {"branch": "main", "rev": "A"}, "main"
|
||||||
|
)
|
||||||
pending_file = gitops_dispatcher.get_pending_file("app")
|
pending_file = gitops_dispatcher.get_pending_file("app")
|
||||||
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "A"
|
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "A"
|
||||||
|
|
||||||
# Enqueue revision B (supersedes A)
|
# Enqueue revision B (supersedes A)
|
||||||
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "B"}, "main")
|
gitops_dispatcher.enqueue_deployment(
|
||||||
|
target_dir, {"branch": "main", "rev": "B"}, "main"
|
||||||
|
)
|
||||||
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "B"
|
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "B"
|
||||||
|
|
||||||
# Enqueue revision C (supersedes B)
|
# Enqueue revision C (supersedes B)
|
||||||
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "C"}, "main")
|
gitops_dispatcher.enqueue_deployment(
|
||||||
|
target_dir, {"branch": "main", "rev": "C"}, "main"
|
||||||
|
)
|
||||||
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "C"
|
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "C"
|
||||||
|
|
||||||
|
|
||||||
@@ -538,20 +544,28 @@ def test_serialized_worker_race_superseding(tmp_path: Path, monkeypatch):
|
|||||||
monkeypatch.setattr(gitops_dispatcher, "execute_deployment", mock_execute)
|
monkeypatch.setattr(gitops_dispatcher, "execute_deployment", mock_execute)
|
||||||
|
|
||||||
# 1. Enqueue A
|
# 1. Enqueue A
|
||||||
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "A"}, "main")
|
gitops_dispatcher.enqueue_deployment(
|
||||||
|
target_dir, {"branch": "main", "rev": "A"}, "main"
|
||||||
|
)
|
||||||
|
|
||||||
# Start worker in thread (takes A)
|
# Start worker in thread (takes A)
|
||||||
worker_thread = threading.Thread(target=gitops_dispatcher.run_target_worker, args=("app",))
|
worker_thread = threading.Thread(
|
||||||
|
target=gitops_dispatcher.run_target_worker, args=("app",)
|
||||||
|
)
|
||||||
worker_thread.start()
|
worker_thread.start()
|
||||||
|
|
||||||
# Wait for A to start executing
|
# Wait for A to start executing
|
||||||
assert a_started_event.wait(timeout=2.0) is True
|
assert a_started_event.wait(timeout=2.0) is True
|
||||||
|
|
||||||
# 2. B arrives while A is running
|
# 2. B arrives while A is running
|
||||||
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "B"}, "main")
|
gitops_dispatcher.enqueue_deployment(
|
||||||
|
target_dir, {"branch": "main", "rev": "B"}, "main"
|
||||||
|
)
|
||||||
|
|
||||||
# 3. C arrives while A is running (supersedes B)
|
# 3. C arrives while A is running (supersedes B)
|
||||||
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "C"}, "main")
|
gitops_dispatcher.enqueue_deployment(
|
||||||
|
target_dir, {"branch": "main", "rev": "C"}, "main"
|
||||||
|
)
|
||||||
|
|
||||||
# Let A complete
|
# Let A complete
|
||||||
b_and_c_enqueued_event.set()
|
b_and_c_enqueued_event.set()
|
||||||
@@ -559,7 +573,9 @@ def test_serialized_worker_race_superseding(tmp_path: Path, monkeypatch):
|
|||||||
worker_thread.join(timeout=3.0)
|
worker_thread.join(timeout=3.0)
|
||||||
|
|
||||||
# Verification: A was executed, B was superseded/skipped, C was executed!
|
# Verification: A was executed, B was superseded/skipped, C was executed!
|
||||||
assert executed_revisions == ["A", "C"], f"Expected ['A', 'C'] but got {executed_revisions}"
|
assert executed_revisions == ["A", "C"], (
|
||||||
|
f"Expected ['A', 'C'] but got {executed_revisions}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_post_pull_manifest_validation_rejects_unsupported_action(tmp_path: Path):
|
def test_post_pull_manifest_validation_rejects_unsupported_action(tmp_path: Path):
|
||||||
@@ -570,24 +586,31 @@ def test_post_pull_manifest_validation_rejects_unsupported_action(tmp_path: Path
|
|||||||
app_dir = tmp_path / "app"
|
app_dir = tmp_path / "app"
|
||||||
app_dir.mkdir()
|
app_dir.mkdir()
|
||||||
manifest_file = app_dir / "app.yaml"
|
manifest_file = app_dir / "app.yaml"
|
||||||
manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n")
|
manifest_file.write_text(
|
||||||
(app_dir / "docker-compose.yml").write_text("version: '3'\nservices:\n web:\n image: nginx\n")
|
"name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n"
|
||||||
|
)
|
||||||
|
(app_dir / "docker-compose.yml").write_text(
|
||||||
|
"version: '3'\nservices:\n web:\n image: nginx\n"
|
||||||
|
)
|
||||||
|
|
||||||
initial_config = {
|
initial_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
|
||||||
"branch": "main",
|
|
||||||
"actions": ["git_pull", "compose_up"]
|
|
||||||
}
|
|
||||||
|
|
||||||
def mock_pull(cmd, check=True):
|
def mock_pull(cmd, check=True):
|
||||||
if "pull" in cmd:
|
if "pull" in cmd:
|
||||||
# Simulate git pull bringing in an invalid action in app.yaml
|
# Simulate git pull bringing in an invalid action in app.yaml
|
||||||
manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n")
|
manifest_file.write_text(
|
||||||
|
"name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n"
|
||||||
|
)
|
||||||
return MagicMock(returncode=0)
|
return MagicMock(returncode=0)
|
||||||
|
|
||||||
with patch("subprocess.run", side_effect=mock_pull) as mock_run:
|
with patch("subprocess.run", side_effect=mock_pull) as mock_run:
|
||||||
success = gitops_dispatcher.execute_deployment(app_dir, initial_config, branch="main")
|
success = gitops_dispatcher.execute_deployment(
|
||||||
|
app_dir, initial_config, branch="main"
|
||||||
|
)
|
||||||
|
|
||||||
assert success is False, "Deployment must fail closed when pulled revision has invalid actions"
|
assert success is False, (
|
||||||
|
"Deployment must fail closed when pulled revision has invalid actions"
|
||||||
|
)
|
||||||
# Only git pull was called; compose_up was never reached!
|
# Only git pull was called; compose_up was never reached!
|
||||||
calls = [c[0][0] for c in mock_run.call_args_list]
|
calls = [c[0][0] for c in mock_run.call_args_list]
|
||||||
assert len(calls) == 1
|
assert len(calls) == 1
|
||||||
@@ -602,24 +625,31 @@ def test_post_pull_manifest_validation_rejects_branch_policy_mismatch(tmp_path:
|
|||||||
app_dir = tmp_path / "app"
|
app_dir = tmp_path / "app"
|
||||||
app_dir.mkdir()
|
app_dir.mkdir()
|
||||||
manifest_file = app_dir / "app.yaml"
|
manifest_file = app_dir / "app.yaml"
|
||||||
manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n")
|
manifest_file.write_text(
|
||||||
(app_dir / "docker-compose.yml").write_text("version: '3'\nservices:\n web:\n image: nginx\n")
|
"name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n"
|
||||||
|
)
|
||||||
|
(app_dir / "docker-compose.yml").write_text(
|
||||||
|
"version: '3'\nservices:\n web:\n image: nginx\n"
|
||||||
|
)
|
||||||
|
|
||||||
initial_config = {
|
initial_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
|
||||||
"branch": "main",
|
|
||||||
"actions": ["git_pull", "compose_up"]
|
|
||||||
}
|
|
||||||
|
|
||||||
def mock_pull(cmd, check=True):
|
def mock_pull(cmd, check=True):
|
||||||
if "pull" in cmd:
|
if "pull" in cmd:
|
||||||
# Simulate git pull bringing in an app.yaml that targets 'staging', not 'main'
|
# Simulate git pull bringing in an app.yaml that targets 'staging', not 'main'
|
||||||
manifest_file.write_text("name: app\ndeployment:\n branch: staging\n actions:\n - git_pull\n - compose_up\n")
|
manifest_file.write_text(
|
||||||
|
"name: app\ndeployment:\n branch: staging\n actions:\n - git_pull\n - compose_up\n"
|
||||||
|
)
|
||||||
return MagicMock(returncode=0)
|
return MagicMock(returncode=0)
|
||||||
|
|
||||||
with patch("subprocess.run", side_effect=mock_pull) as mock_run:
|
with patch("subprocess.run", side_effect=mock_pull) as mock_run:
|
||||||
success = gitops_dispatcher.execute_deployment(app_dir, initial_config, branch="main")
|
success = gitops_dispatcher.execute_deployment(
|
||||||
|
app_dir, initial_config, branch="main"
|
||||||
|
)
|
||||||
|
|
||||||
assert success is False, "Deployment must fail closed on post-pull branch mismatch"
|
assert success is False, (
|
||||||
|
"Deployment must fail closed on post-pull branch mismatch"
|
||||||
|
)
|
||||||
calls = [c[0][0] for c in mock_run.call_args_list]
|
calls = [c[0][0] for c in mock_run.call_args_list]
|
||||||
assert len(calls) == 1
|
assert len(calls) == 1
|
||||||
assert "pull" in calls[0]
|
assert "pull" in calls[0]
|
||||||
@@ -633,22 +663,27 @@ def test_post_pull_manifest_adopts_updated_actions(tmp_path: Path):
|
|||||||
app_dir = tmp_path / "app"
|
app_dir = tmp_path / "app"
|
||||||
app_dir.mkdir()
|
app_dir.mkdir()
|
||||||
manifest_file = app_dir / "app.yaml"
|
manifest_file = app_dir / "app.yaml"
|
||||||
manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n")
|
manifest_file.write_text(
|
||||||
(app_dir / "docker-compose.yml").write_text("version: '3'\nservices:\n web:\n image: nginx\n")
|
"name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n"
|
||||||
|
)
|
||||||
|
(app_dir / "docker-compose.yml").write_text(
|
||||||
|
"version: '3'\nservices:\n web:\n image: nginx\n"
|
||||||
|
)
|
||||||
|
|
||||||
initial_config = {
|
initial_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
|
||||||
"branch": "main",
|
|
||||||
"actions": ["git_pull", "compose_up"]
|
|
||||||
}
|
|
||||||
|
|
||||||
def mock_pull(cmd, check=True):
|
def mock_pull(cmd, check=True):
|
||||||
if "pull" in cmd:
|
if "pull" in cmd:
|
||||||
# Revision updates action to compose_build
|
# Revision updates action to compose_build
|
||||||
manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_build\n")
|
manifest_file.write_text(
|
||||||
|
"name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_build\n"
|
||||||
|
)
|
||||||
return MagicMock(returncode=0)
|
return MagicMock(returncode=0)
|
||||||
|
|
||||||
with patch("subprocess.run", side_effect=mock_pull) as mock_run:
|
with patch("subprocess.run", side_effect=mock_pull) as mock_run:
|
||||||
success = gitops_dispatcher.execute_deployment(app_dir, initial_config, branch="main")
|
success = gitops_dispatcher.execute_deployment(
|
||||||
|
app_dir, initial_config, branch="main"
|
||||||
|
)
|
||||||
|
|
||||||
assert success is True
|
assert success is True
|
||||||
calls = [c[0][0] for c in mock_run.call_args_list]
|
calls = [c[0][0] for c in mock_run.call_args_list]
|
||||||
@@ -668,10 +703,7 @@ def test_worker_records_status_file(tmp_path: Path, monkeypatch):
|
|||||||
monkeypatch.setattr(gitops_dispatcher, "execute_deployment", lambda t, c, b: True)
|
monkeypatch.setattr(gitops_dispatcher, "execute_deployment", lambda t, c, b: True)
|
||||||
|
|
||||||
gitops_dispatcher.enqueue_deployment(
|
gitops_dispatcher.enqueue_deployment(
|
||||||
target_dir,
|
target_dir, {"branch": "main"}, "main", commit_sha="abcdef123456"
|
||||||
{"branch": "main"},
|
|
||||||
"main",
|
|
||||||
commit_sha="abcdef123456"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
success = gitops_dispatcher.run_target_worker("app")
|
success = gitops_dispatcher.run_target_worker("app")
|
||||||
@@ -690,12 +722,15 @@ def test_worker_records_status_file(tmp_path: Path, monkeypatch):
|
|||||||
def test_validate_compose_security_rejects_privileged(tmp_path: Path):
|
def test_validate_compose_security_rejects_privileged(tmp_path: Path):
|
||||||
"""Ensure docker-compose with privileged: true fails pre-flight validation."""
|
"""Ensure docker-compose with privileged: true fails pre-flight validation."""
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine:latest
|
image: alpine:latest
|
||||||
privileged: true
|
privileged: true
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "privileged: true" in err
|
assert err is not None and "privileged: true" in err
|
||||||
@@ -705,19 +740,23 @@ def test_validate_compose_security_rejects_docker_socket_mount(tmp_path: Path):
|
|||||||
"""Ensure docker-compose with /var/run/docker.sock mount fails validation."""
|
"""Ensure docker-compose with /var/run/docker.sock mount fails validation."""
|
||||||
# Test string syntax
|
# Test string syntax
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine:latest
|
image: alpine:latest
|
||||||
volumes:
|
volumes:
|
||||||
- /var/run/docker.sock:/var/run/docker.sock
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "Docker socket" in err
|
assert err is not None and "Docker socket" in err
|
||||||
|
|
||||||
# Test dict / long syntax
|
# Test dict / long syntax
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine:latest
|
image: alpine:latest
|
||||||
@@ -725,7 +764,9 @@ services:
|
|||||||
- type: bind
|
- type: bind
|
||||||
source: /var/run/docker.sock
|
source: /var/run/docker.sock
|
||||||
target: /var/run/docker.sock
|
target: /var/run/docker.sock
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "Docker socket" in err
|
assert err is not None and "Docker socket" in err
|
||||||
@@ -734,12 +775,15 @@ services:
|
|||||||
def test_validate_compose_security_rejects_host_network(tmp_path: Path):
|
def test_validate_compose_security_rejects_host_network(tmp_path: Path):
|
||||||
"""Ensure docker-compose with network_mode: host fails pre-flight validation."""
|
"""Ensure docker-compose with network_mode: host fails pre-flight validation."""
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine:latest
|
image: alpine:latest
|
||||||
network_mode: host
|
network_mode: host
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "network_mode: host" in err
|
assert err is not None and "network_mode: host" in err
|
||||||
@@ -748,13 +792,16 @@ services:
|
|||||||
def test_validate_compose_security_rejects_out_of_bounds_host_bind(tmp_path: Path):
|
def test_validate_compose_security_rejects_out_of_bounds_host_bind(tmp_path: Path):
|
||||||
"""Ensure host bind mounts outside workload directory or state root are rejected."""
|
"""Ensure host bind mounts outside workload directory or state root are rejected."""
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine:latest
|
image: alpine:latest
|
||||||
volumes:
|
volumes:
|
||||||
- /etc/shadow:/etc/shadow:ro
|
- /etc/shadow:/etc/shadow:ro
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "prohibited host bind mount" in err
|
assert err is not None and "prohibited host bind mount" in err
|
||||||
@@ -765,7 +812,8 @@ def test_validate_compose_security_allows_safe_compose(tmp_path: Path):
|
|||||||
data_dir = tmp_path / "data"
|
data_dir = tmp_path / "data"
|
||||||
data_dir.mkdir()
|
data_dir.mkdir()
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text(f"""
|
compose_file.write_text(
|
||||||
|
f"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine:latest
|
image: alpine:latest
|
||||||
@@ -774,7 +822,9 @@ services:
|
|||||||
- named_vol:/var/log
|
- named_vol:/var/log
|
||||||
volumes:
|
volumes:
|
||||||
named_vol:
|
named_vol:
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
||||||
assert valid is True
|
assert valid is True
|
||||||
assert err is None
|
assert err is None
|
||||||
@@ -788,11 +838,14 @@ def test_validate_compose_security_nonexistent_file(tmp_path: Path):
|
|||||||
assert err is None
|
assert err is None
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("malicious_volume", [
|
@pytest.mark.parametrize(
|
||||||
|
"malicious_volume",
|
||||||
|
[
|
||||||
"../../etc/passwd:/mnt/passwd:ro",
|
"../../etc/passwd:/mnt/passwd:ro",
|
||||||
"./../../Core/nixos/secrets.yaml:/secrets.yaml",
|
"./../../Core/nixos/secrets.yaml:/secrets.yaml",
|
||||||
"../other-workload/data:/data",
|
"../other-workload/data:/data",
|
||||||
])
|
],
|
||||||
|
)
|
||||||
def test_validate_compose_security_blocks_relative_traversal(
|
def test_validate_compose_security_blocks_relative_traversal(
|
||||||
tmp_path: Path, malicious_volume: str
|
tmp_path: Path, malicious_volume: str
|
||||||
):
|
):
|
||||||
@@ -806,8 +859,12 @@ def test_validate_compose_security_blocks_relative_traversal(
|
|||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
|
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
assert valid is False, f"Expected relative traversal '{malicious_volume}' to be rejected!"
|
compose_file, app_dir, app_name="my-app"
|
||||||
|
)
|
||||||
|
assert valid is False, (
|
||||||
|
f"Expected relative traversal '{malicious_volume}' to be rejected!"
|
||||||
|
)
|
||||||
assert err is not None and "prohibited host bind mount" in err
|
assert err is not None and "prohibited host bind mount" in err
|
||||||
|
|
||||||
|
|
||||||
@@ -831,27 +888,38 @@ def test_validate_compose_security_blocks_cross_tenant_state_mounts(
|
|||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
|
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, app_dir, app_name="my-app"
|
||||||
|
)
|
||||||
assert valid is False, "Expected cross-tenant state mount to be rejected!"
|
assert valid is False, "Expected cross-tenant state mount to be rejected!"
|
||||||
assert err is not None and ("prohibited host bind mount" in err or "cross-tenant" in err.lower())
|
assert err is not None and (
|
||||||
|
"prohibited host bind mount" in err or "cross-tenant" in err.lower()
|
||||||
|
)
|
||||||
|
|
||||||
# Authorized own state mount must pass
|
# Authorized own state mount must pass
|
||||||
compose_file.write_text(
|
compose_file.write_text(
|
||||||
f"services:\n web:\n image: nginx\n volumes:\n - '{state_root}/my-app:/data'\n",
|
f"services:\n web:\n image: nginx\n volumes:\n - '{state_root}/my-app:/data'\n",
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
valid_own, err_own = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
|
valid_own, err_own = gitops_dispatcher.validate_compose_security(
|
||||||
assert valid_own is True, f"Own state mount should be permitted, got error: {err_own}"
|
compose_file, app_dir, app_name="my-app"
|
||||||
|
)
|
||||||
|
assert valid_own is True, (
|
||||||
|
f"Own state mount should be permitted, got error: {err_own}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("unsafe_directive", [
|
@pytest.mark.parametrize(
|
||||||
|
"unsafe_directive",
|
||||||
|
[
|
||||||
"cap_add:\n - SYS_ADMIN",
|
"cap_add:\n - SYS_ADMIN",
|
||||||
"pid: host",
|
"pid: host",
|
||||||
"ipc: host",
|
"ipc: host",
|
||||||
"userns_mode: host",
|
"userns_mode: host",
|
||||||
"devices:\n - /dev/sda:/dev/sda",
|
"devices:\n - /dev/sda:/dev/sda",
|
||||||
"security_opt:\n - apparmor:unconfined",
|
"security_opt:\n - apparmor:unconfined",
|
||||||
])
|
],
|
||||||
|
)
|
||||||
def test_validate_compose_security_blocks_privilege_escalation_primitives(
|
def test_validate_compose_security_blocks_privilege_escalation_primitives(
|
||||||
tmp_path: Path, unsafe_directive: str
|
tmp_path: Path, unsafe_directive: str
|
||||||
):
|
):
|
||||||
@@ -861,7 +929,9 @@ def test_validate_compose_security_blocks_privilege_escalation_primitives(
|
|||||||
f"services:\n app:\n image: alpine\n {unsafe_directive}\n",
|
f"services:\n app:\n image: alpine\n {unsafe_directive}\n",
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="app")
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, tmp_path, app_name="app"
|
||||||
|
)
|
||||||
assert valid is False, f"Directive should be blocked:\n{unsafe_directive}"
|
assert valid is False, f"Directive should be blocked:\n{unsafe_directive}"
|
||||||
assert err is not None
|
assert err is not None
|
||||||
|
|
||||||
@@ -869,14 +939,19 @@ def test_validate_compose_security_blocks_privilege_escalation_primitives(
|
|||||||
def test_validate_compose_security_rejects_top_level_include(tmp_path: Path):
|
def test_validate_compose_security_rejects_top_level_include(tmp_path: Path):
|
||||||
"""Ensure top-level Compose include directives are rejected to prevent out-of-tree includes."""
|
"""Ensure top-level Compose include directives are rejected to prevent out-of-tree includes."""
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
include:
|
include:
|
||||||
- /etc/shadow
|
- /etc/shadow
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine
|
image: alpine
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="app")
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, tmp_path, app_name="app"
|
||||||
|
)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "include" in err.lower()
|
assert err is not None and "include" in err.lower()
|
||||||
|
|
||||||
@@ -891,7 +966,9 @@ def test_validate_compose_security_rejects_symlink_escape(tmp_path: Path):
|
|||||||
compose_link = app_dir / "docker-compose.yml"
|
compose_link = app_dir / "docker-compose.yml"
|
||||||
compose_link.symlink_to(outside_file)
|
compose_link.symlink_to(outside_file)
|
||||||
|
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_link, app_dir, app_name="my-app")
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_link, app_dir, app_name="my-app"
|
||||||
|
)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "symlink" in err.lower()
|
assert err is not None and "symlink" in err.lower()
|
||||||
|
|
||||||
@@ -904,37 +981,52 @@ def test_validate_compose_security_rejects_escaping_env_file(tmp_path: Path):
|
|||||||
|
|
||||||
# 1. Escaping absolute path
|
# 1. Escaping absolute path
|
||||||
compose_file = app_dir / "docker-compose.yml"
|
compose_file = app_dir / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine
|
image: alpine
|
||||||
env_file: /run/secrets/homeserver.env
|
env_file: /run/secrets/homeserver.env
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, app_dir, app_name="my-app"
|
||||||
|
)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "env_file" in err.lower()
|
assert err is not None and "env_file" in err.lower()
|
||||||
|
|
||||||
# 2. Escaping relative path in list
|
# 2. Escaping relative path in list
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine
|
image: alpine
|
||||||
env_file:
|
env_file:
|
||||||
- valid.env
|
- valid.env
|
||||||
- ../../Core/.env
|
- ../../Core/.env
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, app_dir, app_name="my-app"
|
||||||
|
)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "env_file" in err.lower()
|
assert err is not None and "env_file" in err.lower()
|
||||||
|
|
||||||
# 3. Valid local env_file
|
# 3. Valid local env_file
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine
|
image: alpine
|
||||||
env_file: valid.env
|
env_file: valid.env
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, app_dir, app_name="my-app"
|
||||||
|
)
|
||||||
assert valid is True
|
assert valid is True
|
||||||
assert err is None
|
assert err is None
|
||||||
|
|
||||||
@@ -942,14 +1034,19 @@ services:
|
|||||||
def test_validate_compose_security_rejects_undeclared_named_volumes(tmp_path: Path):
|
def test_validate_compose_security_rejects_undeclared_named_volumes(tmp_path: Path):
|
||||||
"""Ensure ambiguous volume paths not declared in top-level volumes are rejected."""
|
"""Ensure ambiguous volume paths not declared in top-level volumes are rejected."""
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine
|
image: alpine
|
||||||
volumes:
|
volumes:
|
||||||
- rogue_named_volume:/data
|
- rogue_named_volume:/data
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="my-app")
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, tmp_path, app_name="my-app"
|
||||||
|
)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "undeclared" in err.lower()
|
assert err is not None and "undeclared" in err.lower()
|
||||||
|
|
||||||
@@ -957,20 +1054,109 @@ services:
|
|||||||
def test_validate_compose_security_handles_string_security_opt(tmp_path: Path):
|
def test_validate_compose_security_handles_string_security_opt(tmp_path: Path):
|
||||||
"""Ensure security_opt specified as string instead of list is strictly checked."""
|
"""Ensure security_opt specified as string instead of list is strictly checked."""
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine
|
image: alpine
|
||||||
security_opt: "apparmor:unconfined"
|
security_opt: "apparmor:unconfined"
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="my-app")
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, tmp_path, app_name="my-app"
|
||||||
|
)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "security_opt" in err.lower()
|
assert err is not None and "security_opt" in err.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_compose_security_rejects_dict_volume_without_type_bind(
|
||||||
|
tmp_path: Path,
|
||||||
|
):
|
||||||
|
"""Ensure dictionary volume declarations without explicit type: bind enforce host containment (CR-DI-01)."""
|
||||||
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: alpine
|
||||||
|
volumes:
|
||||||
|
- source: /etc/shadow
|
||||||
|
target: /app/shadow
|
||||||
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, tmp_path, app_name="my-app"
|
||||||
|
)
|
||||||
|
assert valid is False
|
||||||
|
assert err is not None and "prohibited host bind mount" in err.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_compose_security_rejects_variable_interpolation_in_volume_host_path(
|
||||||
|
tmp_path: Path,
|
||||||
|
):
|
||||||
|
"""Ensure volume host paths containing variable interpolation (${...}) fail closed (CR-DI-02)."""
|
||||||
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: alpine
|
||||||
|
volumes:
|
||||||
|
- "${HOST_DIR}/data:/data"
|
||||||
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, tmp_path, app_name="my-app"
|
||||||
|
)
|
||||||
|
assert valid is False
|
||||||
|
assert err is not None and "variable interpolation" in err.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_compose_security_rejects_variable_interpolation_in_dict_volume_source(
|
||||||
|
tmp_path: Path,
|
||||||
|
):
|
||||||
|
"""Ensure dictionary volume source containing variable interpolation (${...}) fails closed (CR-DI-02)."""
|
||||||
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: alpine
|
||||||
|
volumes:
|
||||||
|
- source: "${HOST_DIR}/data"
|
||||||
|
target: /data
|
||||||
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, tmp_path, app_name="my-app"
|
||||||
|
)
|
||||||
|
assert valid is False
|
||||||
|
assert err is not None and "variable interpolation" in err.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_compose_security_allows_valid_dict_volume_within_workload(
|
||||||
|
tmp_path: Path,
|
||||||
|
):
|
||||||
|
"""Ensure valid dictionary volume within workload root is accepted even without type: bind."""
|
||||||
|
(tmp_path / "data").mkdir()
|
||||||
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: alpine
|
||||||
|
volumes:
|
||||||
|
- source: ./data
|
||||||
|
target: /data
|
||||||
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
valid, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, tmp_path, app_name="my-app"
|
||||||
|
)
|
||||||
|
assert valid is True
|
||||||
|
assert err is None
|
||||||
@@ -2,19 +2,24 @@
|
|||||||
Security invariant tests for Docker Compose and container isolation.
|
Security invariant tests for Docker Compose and container isolation.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import yaml
|
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
|
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||||
|
|
||||||
|
|
||||||
def test_socket_proxy_is_strictly_read_only():
|
def test_socket_proxy_is_strictly_read_only():
|
||||||
|
|
||||||
"""Ensure socket-proxy container blocks state-modifying requests (POST=0, DELETE=0)."""
|
"""Ensure socket-proxy container blocks state-modifying requests (POST=0, DELETE=0)."""
|
||||||
compose_path = CORE_ROOT / "docker-compose.yml"
|
compose_path = CORE_ROOT / "docker-compose.yml"
|
||||||
with open(compose_path, encoding="utf-8") as f:
|
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", [])
|
volumes = svc.get("volumes", [])
|
||||||
for vol in volumes:
|
for vol in volumes:
|
||||||
if isinstance(vol, str) and "/var/run/docker.sock" in vol:
|
if isinstance(vol, str) and "/var/run/docker.sock" in vol:
|
||||||
assert name == "socket-proxy", f"Service '{name}' directly mounts docker.sock!"
|
assert name == "socket-proxy", (
|
||||||
assert vol.endswith(":ro"), "socket-proxy docker.sock mount must be read-only (:ro)"
|
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():
|
def test_no_privileged_containers():
|
||||||
@@ -60,7 +69,9 @@ def test_no_privileged_containers():
|
|||||||
services = compose.get("services", {})
|
services = compose.get("services", {})
|
||||||
for name, svc in services.items():
|
for name, svc in services.items():
|
||||||
privileged = svc.get("privileged", False)
|
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():
|
def test_no_shell_true_in_core_scripts():
|
||||||
@@ -78,10 +89,14 @@ def test_portainer_is_deprecated_and_absent():
|
|||||||
compose = yaml.safe_load(f)
|
compose = yaml.safe_load(f)
|
||||||
|
|
||||||
services = compose.get("services", {})
|
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 {}
|
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():
|
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!"
|
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
|
"""Ensure environment values from app.yaml cannot execute shell commands via command substitution
|
||||||
|
during P4 production environment assembly and router dispatch. Executes OperationalRouter with a mock docker binary.
|
||||||
in scripts/appctl during environment setup. Executes scripts/appctl directly with a mock docker binary.
|
|
||||||
"""
|
"""
|
||||||
canary = tmp_path / "pwned.txt"
|
canary = tmp_path / "pwned.txt"
|
||||||
payload = f"$(touch {canary})"
|
payload = f"$(touch {canary})"
|
||||||
@@ -113,16 +127,26 @@ env:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
(app_dir / "app.yaml").write_text(app_yaml.strip(), encoding="utf-8")
|
(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 = tmp_path / "bin"
|
||||||
mock_bin.mkdir()
|
mock_bin.mkdir()
|
||||||
mock_docker = mock_bin / "docker"
|
mock_docker = mock_bin / "docker"
|
||||||
bash_bin = shutil.which("bash") or "bash"
|
bash_bin = shutil.which("bash") or "bash"
|
||||||
|
|
||||||
mock_docker_script = f"""#!{bash_bin}
|
mock_docker_script = f"""#!{bash_bin}
|
||||||
if [ "$1" = "compose" ] && [ "$2" = "config" ]; then
|
if [ "$1" = "compose" ] && [ "$4" = "config" ]; then
|
||||||
echo "MOCK_DOCKER_COMPOSE_CONFIG"
|
echo "MOCK_DOCKER_COMPOSE_CONFIG"
|
||||||
echo "CAPTURED_INJECTION=$INJECTION_TEST"
|
echo "CAPTURED_INJECTION=$INJECTION_TEST"
|
||||||
echo "CAPTURED_NORMAL=$NORMAL_VAR"
|
echo "CAPTURED_NORMAL=$NORMAL_VAR"
|
||||||
@@ -133,45 +157,59 @@ exit 0
|
|||||||
mock_docker.write_text(mock_docker_script, encoding="utf-8")
|
mock_docker.write_text(mock_docker_script, encoding="utf-8")
|
||||||
mock_docker.chmod(0o755)
|
mock_docker.chmod(0o755)
|
||||||
|
|
||||||
# 3. Execute scripts/appctl config vuln-app directly
|
# 4. Dispatch workload.config through OperationalRouter
|
||||||
appctl_path = CORE_ROOT / "scripts" / "appctl"
|
monkeypatch.setenv("PATH", f"{mock_bin}:{os.environ.get('PATH', '')}")
|
||||||
env = os.environ.copy()
|
router = OperationalRouter(
|
||||||
if "NIX_PYTHONPATH" in env and "PYTHONPATH" not in env:
|
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||||
env["PYTHONPATH"] = env["NIX_PYTHONPATH"]
|
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||||
env["PATH"] = f"{mock_bin}:{Path(sys.executable).parent}:{env['PATH']}"
|
sites_dir=sites_dir,
|
||||||
env["PYTHON_BIN"] = sys.executable
|
core_dir=CORE_ROOT,
|
||||||
env["SITES_DIR"] = str(sites_dir)
|
)
|
||||||
env["HOMELAB_DOMAIN"] = "example.test"
|
req = OperationRequest.model_validate({
|
||||||
env["CORE_DIR"] = str(CORE_ROOT)
|
"operation": "workload.config",
|
||||||
|
"target": "vuln-app",
|
||||||
res = subprocess.run(
|
})
|
||||||
[bash_bin, str(appctl_path), "config", "vuln-app"],
|
admin_principal = Principal(
|
||||||
env=env,
|
identity="operator",
|
||||||
capture_output=True,
|
role=Role.ADMIN,
|
||||||
text=True,
|
token_id="tok_admin",
|
||||||
check=False,
|
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
|
# 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 not canary.exists(), (
|
||||||
assert res.returncode == 0, f"appctl config failed: {res.stderr}\nStdout: {res.stdout}"
|
"Command substitution was executed on the host during environment setup!"
|
||||||
assert "MOCK_DOCKER_COMPOSE_CONFIG" in res.stdout
|
)
|
||||||
assert f"CAPTURED_INJECTION={payload}" in res.stdout
|
assert resp.success is True, (
|
||||||
assert "CAPTURED_NORMAL=safe_value" in res.stdout
|
f"OperationalRouter dispatch failed: {resp.error}"
|
||||||
assert "/dangerous/override" not in res.stdout
|
)
|
||||||
|
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():
|
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."""
|
"""Ensure personal domains and operator usernames are absent from scripts, tests, and documentation."""
|
||||||
forbidden = ["roadtotech.me", "kiskaadee"]
|
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 = [
|
root_files = [
|
||||||
CORE_ROOT / "README.md",
|
CORE_ROOT / "README.md",
|
||||||
CORE_ROOT / "ROADMAP.md",
|
CORE_ROOT / "ROADMAP.md",
|
||||||
CORE_ROOT / "AGENTS.md",
|
CORE_ROOT / "AGENTS.md",
|
||||||
CORE_ROOT / "SECURITY.md",
|
CORE_ROOT / "SECURITY.md",
|
||||||
CORE_ROOT / "flake.nix",
|
CORE_ROOT / "flake.nix",
|
||||||
|
CORE_ROOT / "docker-compose.yml",
|
||||||
|
CORE_ROOT / "nixos" / "configuration.nix",
|
||||||
]
|
]
|
||||||
violations = []
|
violations = []
|
||||||
|
|
||||||
@@ -182,16 +220,310 @@ def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests(
|
|||||||
for file_path in candidate_files:
|
for file_path in candidate_files:
|
||||||
if (
|
if (
|
||||||
file_path.is_file()
|
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"
|
and file_path.name != "test_security_invariants.py"
|
||||||
):
|
):
|
||||||
content = file_path.read_text(encoding="utf-8", errors="ignore")
|
content = file_path.read_text(encoding="utf-8", errors="ignore")
|
||||||
for term in forbidden:
|
for term in forbidden:
|
||||||
if term in content:
|
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 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}/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/Sites/*" in safe_dirs, (
|
||||||
|
f"Expected '/home/operator/Sites/*' in git safe.directory, got {safe_dirs}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -36,7 +36,9 @@ def test_required_architectural_paths_exist():
|
|||||||
|
|
||||||
pre_commit = CORE_ROOT / ".githooks" / "pre-commit"
|
pre_commit = CORE_ROOT / ".githooks" / "pre-commit"
|
||||||
assert pre_commit.is_file(), ".githooks/pre-commit must be a regular file"
|
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():
|
def test_deprecated_legacy_structures_are_absent():
|
||||||
@@ -61,4 +63,7 @@ def test_unlicense_preserved():
|
|||||||
unlicense = CORE_ROOT / "UNLICENSE"
|
unlicense = CORE_ROOT / "UNLICENSE"
|
||||||
assert unlicense.is_file(), "UNLICENSE file must be present"
|
assert unlicense.is_file(), "UNLICENSE file must be present"
|
||||||
content = unlicense.read_text(encoding="utf-8")
|
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,494 @@
|
|||||||
|
"""
|
||||||
|
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
|
||||||
@@ -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,693 @@
|
|||||||
|
"""
|
||||||
|
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_6_canonical_codes():
|
||||||
|
assert len(ErrorCode) == 6
|
||||||
|
expected_codes = {
|
||||||
|
"ERR_VALIDATION_FAILED",
|
||||||
|
"ERR_AUTH_REQUIRED",
|
||||||
|
"ERR_PERMISSION_DENIED",
|
||||||
|
"ERR_TARGET_NOT_FOUND",
|
||||||
|
"ERR_CONCURRENT_MUTATION",
|
||||||
|
"ERR_EXECUTION_FAILED",
|
||||||
|
}
|
||||||
|
assert {code.value for code in ErrorCode} == expected_codes
|
||||||
|
|
||||||
|
|
||||||
|
def test_error_code_http_status_mapping():
|
||||||
|
assert ErrorCode.ERR_VALIDATION_FAILED.http_status == 400
|
||||||
|
assert ErrorCode.ERR_AUTH_REQUIRED.http_status == 401
|
||||||
|
assert ErrorCode.ERR_PERMISSION_DENIED.http_status == 403
|
||||||
|
assert ErrorCode.ERR_TARGET_NOT_FOUND.http_status == 404
|
||||||
|
assert ErrorCode.ERR_CONCURRENT_MUTATION.http_status == 409
|
||||||
|
assert ErrorCode.ERR_EXECUTION_FAILED.http_status == 500
|
||||||
|
|
||||||
|
|
||||||
|
def test_operation_error_accepts_valid_error_code():
|
||||||
|
err = OperationError(
|
||||||
|
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||||
|
message="Bearer token required",
|
||||||
|
)
|
||||||
|
assert err.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||||
|
assert err.message == "Bearer token required"
|
||||||
|
assert err.details is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_operation_error_accepts_string_error_code_coercion():
|
||||||
|
err = OperationError.model_validate({
|
||||||
|
"code": "ERR_CONCURRENT_MUTATION",
|
||||||
|
"message": "Operation locked by concurrent task",
|
||||||
|
})
|
||||||
|
assert err.code == ErrorCode.ERR_CONCURRENT_MUTATION
|
||||||
|
|
||||||
|
|
||||||
|
def test_operation_error_rejects_invalid_error_code():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
OperationError.model_validate({
|
||||||
|
"code": "ERR_CUSTOM_CODE",
|
||||||
|
"message": "Invalid code",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def test_operation_error_rejects_extra_fields():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
OperationError.model_validate({
|
||||||
|
"code": "ERR_VALIDATION_FAILED",
|
||||||
|
"message": "Failed",
|
||||||
|
"secret_leak": "value",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Error Sanitizer (Information Disclosure Prevention)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_sanitize_validation_error_strips_input_and_url():
|
||||||
|
# Create a model with secret value that fails validation
|
||||||
|
class SecretPayload(BaseModel):
|
||||||
|
token: str = "default"
|
||||||
|
|
||||||
|
try:
|
||||||
|
LogsParams.model_validate({
|
||||||
|
"tail": "SUPER_SECRET_TOKEN_DO_NOT_LEAK",
|
||||||
|
})
|
||||||
|
except ValidationError as exc:
|
||||||
|
op_err = sanitize_validation_error(exc)
|
||||||
|
|
||||||
|
assert op_err.code == ErrorCode.ERR_VALIDATION_FAILED
|
||||||
|
assert op_err.message == "Request payload validation failed"
|
||||||
|
assert op_err.details is not None
|
||||||
|
assert len(op_err.details) == 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,592 @@
|
|||||||
|
"""
|
||||||
|
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",
|
||||||
|
)
|
||||||
|
|
||||||
|
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
|
||||||
@@ -1,20 +1,19 @@
|
|||||||
import sys
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import MagicMock
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import appctl_engine as engine
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
# Import appctl engine
|
# Import appctl engine
|
||||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||||
|
|
||||||
import appctl_engine as engine
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class AppFactory:
|
class AppFactory:
|
||||||
"""Helper class to generate mock app directories and configurations"""
|
"""Helper class to generate mock app directories and configurations"""
|
||||||
|
|
||||||
sites_dir: Path
|
sites_dir: Path
|
||||||
|
|
||||||
def create(
|
def create(
|
||||||
@@ -28,9 +27,12 @@ class AppFactory:
|
|||||||
if manifest_yaml:
|
if manifest_yaml:
|
||||||
(app_dir / "app.yaml").write_text(manifest_yaml, encoding="utf-8")
|
(app_dir / "app.yaml").write_text(manifest_yaml, encoding="utf-8")
|
||||||
if has_compose:
|
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
|
return app_dir
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
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"""
|
"""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")
|
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "mydomain.test")
|
||||||
return sites
|
return sites
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def app_factory(mock_sites_dir: Path) -> AppFactory:
|
def app_factory(mock_sites_dir: Path) -> AppFactory:
|
||||||
"""Fixture that provides the AppFactory instance to test"""
|
"""Fixture that provides the AppFactory instance to test"""
|
||||||
return AppFactory(mock_sites_dir)
|
return AppFactory(mock_sites_dir)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def mock_core_dir(
|
def mock_core_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||||
tmp_path: Path,
|
|
||||||
monkeypatch: pytest.MonkeyPatch
|
|
||||||
) -> Path:
|
|
||||||
"""Fixture that creates an isolated Core directory and points engine.CORE_DIR to it"""
|
"""Fixture that creates an isolated Core directory and points engine.CORE_DIR to it"""
|
||||||
core = tmp_path / "CORE"
|
core = tmp_path / "CORE"
|
||||||
core.mkdir(parents=True, exist_ok=True)
|
core.mkdir(parents=True, exist_ok=True)
|
||||||
return core
|
return core
|
||||||
|
|
||||||
|
|
||||||
## GREEN TEST: Existing implementation should not break
|
## GREEN TEST: Existing implementation should not break
|
||||||
|
|
||||||
|
|
||||||
def test_resolve_app_hierarchy(app_factory: AppFactory):
|
def test_resolve_app_hierarchy(app_factory: AppFactory):
|
||||||
"""Ensure resolution follows: Canonical Name > Alias > Dir Name > Prefix"""
|
"""Ensure resolution follows: Canonical Name > Alias > Dir Name > Prefix"""
|
||||||
app_factory.create(
|
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("homelab-jellyfin", apps) is not None
|
||||||
assert engine.resolve_app("unknown", apps) is None
|
assert engine.resolve_app("unknown", apps) is None
|
||||||
|
|
||||||
|
|
||||||
def test_manifest_data_overrides_default_values(app_factory: AppFactory):
|
def test_manifest_data_overrides_default_values(app_factory: AppFactory):
|
||||||
"""Ensure app.yaml values successfully override the system defaults"""
|
"""Ensure app.yaml values successfully override the system defaults"""
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
dir_name="homelab-custom",
|
dir_name="homelab-custom",
|
||||||
manifest_yaml="""
|
manifest_yaml="""
|
||||||
name: custom-app
|
name: custom-app
|
||||||
domain: custom.roadtotech.local
|
domain: custom.example.test
|
||||||
auth: false
|
auth: false
|
||||||
visible: false
|
visible: false
|
||||||
networks:
|
networks:
|
||||||
- custom-net
|
- custom-net
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
apps = engine.get_sites_apps()
|
apps = engine.get_sites_apps()
|
||||||
app = engine.resolve_app("custom-app", apps)
|
app = engine.resolve_app("custom-app", apps)
|
||||||
|
|
||||||
assert app is not None
|
assert app is not None
|
||||||
assert app.domain == "custom.roadtotech.local"
|
assert app.domain == "custom.example.test"
|
||||||
assert app.auth is False
|
assert app.auth is False
|
||||||
assert app.networks == ["custom-net"]
|
assert app.networks == ["custom-net"]
|
||||||
|
|
||||||
|
|
||||||
def test_sites_app_normalization(app_factory: AppFactory):
|
def test_sites_app_normalization(app_factory: AppFactory):
|
||||||
"""Ensure missing or badly typed manifest fields are safely normalized"""
|
"""Ensure missing or badly typed manifest fields are safely normalized"""
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
@@ -106,7 +111,7 @@ def test_sites_app_normalization(app_factory: AppFactory):
|
|||||||
auth: "False" # should evaluate based on boolean casting
|
auth: "False" # should evaluate based on boolean casting
|
||||||
homepage:
|
homepage:
|
||||||
weight: "99" # this should be casted as an int
|
weight: "99" # this should be casted as an int
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
apps = engine.get_sites_apps()
|
apps = engine.get_sites_apps()
|
||||||
app = engine.resolve_app("testapp", apps)
|
app = engine.resolve_app("testapp", apps)
|
||||||
@@ -131,7 +136,7 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
|||||||
type: git
|
type: git
|
||||||
url: https://git.example.com/operator/bitetrack.git
|
url: https://git.example.com/operator/bitetrack.git
|
||||||
ref: v1.2.0
|
ref: v1.2.0
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
# 2. Source-backed app with default ref (main)
|
# 2. Source-backed app with default ref (main)
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
@@ -140,14 +145,14 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
|||||||
name: doc2site
|
name: doc2site
|
||||||
source:
|
source:
|
||||||
url: https://git.example.com/operator/doc2site.git
|
url: https://git.example.com/operator/doc2site.git
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
# 3. Image-only app (no source block)
|
# 3. Image-only app (no source block)
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
dir_name="homelab-jellyfin",
|
dir_name="homelab-jellyfin",
|
||||||
manifest_yaml="""
|
manifest_yaml="""
|
||||||
name: jellyfin
|
name: jellyfin
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
apps = engine.get_sites_apps()
|
apps = engine.get_sites_apps()
|
||||||
@@ -177,7 +182,7 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
|||||||
name: malformed
|
name: malformed
|
||||||
source:
|
source:
|
||||||
url: file:///etc/passwd
|
url: file:///etc/passwd
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
apps_updated = engine.get_sites_apps()
|
apps_updated = engine.get_sites_apps()
|
||||||
malformed = engine.resolve_app("malformed", apps_updated)
|
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
|
## RED TESTS: TDD Goals for next implementation
|
||||||
|
|
||||||
|
|
||||||
def test_docker_status_parser_running(monkeypatch):
|
def test_docker_status_parser_running(monkeypatch):
|
||||||
"""Ensure get_docker_status reports running compose stack when all containers are running."""
|
"""Ensure get_docker_status reports running compose stack when all containers are running."""
|
||||||
|
|
||||||
def mock_run(args, **kwargs):
|
def mock_run(args, **kwargs):
|
||||||
mock = MagicMock()
|
mock = MagicMock()
|
||||||
|
mock.returncode = 0
|
||||||
if "ps" in args:
|
if "ps" in args:
|
||||||
mock.stdout = "container123\n"
|
mock.stdout = "container123\n"
|
||||||
if "inspect" in args:
|
if "inspect" in args:
|
||||||
@@ -207,8 +215,10 @@ def test_docker_status_parser_running(monkeypatch):
|
|||||||
|
|
||||||
def test_docker_status_parser_stopped(monkeypatch):
|
def test_docker_status_parser_stopped(monkeypatch):
|
||||||
"""Ensure get_docker_status reports stopped when no containers exist."""
|
"""Ensure get_docker_status reports stopped when no containers exist."""
|
||||||
|
|
||||||
def mock_run(args, **kwargs):
|
def mock_run(args, **kwargs):
|
||||||
mock = MagicMock()
|
mock = MagicMock()
|
||||||
|
mock.returncode = 0
|
||||||
if "ps" in args:
|
if "ps" in args:
|
||||||
mock.stdout = ""
|
mock.stdout = ""
|
||||||
return mock
|
return mock
|
||||||
@@ -221,8 +231,10 @@ def test_docker_status_parser_stopped(monkeypatch):
|
|||||||
|
|
||||||
def test_docker_status_parser_degraded(monkeypatch):
|
def test_docker_status_parser_degraded(monkeypatch):
|
||||||
"""Ensure get_docker_status reports degraded when partial containers are running."""
|
"""Ensure get_docker_status reports degraded when partial containers are running."""
|
||||||
|
|
||||||
def mock_run(args, **kwargs):
|
def mock_run(args, **kwargs):
|
||||||
mock = MagicMock()
|
mock = MagicMock()
|
||||||
|
mock.returncode = 0
|
||||||
if "ps" in args:
|
if "ps" in args:
|
||||||
mock.stdout = "c1\nc2\n"
|
mock.stdout = "c1\nc2\n"
|
||||||
if "inspect" in args:
|
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):
|
def test_docker_status_single_container(monkeypatch):
|
||||||
"""Ensure get_docker_status inspects single Core container by name."""
|
"""Ensure get_docker_status inspects single Core container by name."""
|
||||||
|
|
||||||
def mock_run(args, **kwargs):
|
def mock_run(args, **kwargs):
|
||||||
mock = MagicMock()
|
mock = MagicMock()
|
||||||
|
mock.returncode = 0
|
||||||
if "authelia" in args:
|
if "authelia" in args:
|
||||||
mock.stdout = "true\n"
|
mock.stdout = "true\n"
|
||||||
else:
|
else:
|
||||||
@@ -258,8 +272,75 @@ def test_docker_status_single_container(monkeypatch):
|
|||||||
assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped"
|
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):
|
def test_docker_status_error_handling(monkeypatch):
|
||||||
"""Ensure get_docker_status handles subprocess failures gracefully."""
|
"""Ensure get_docker_status handles subprocess failures gracefully."""
|
||||||
|
|
||||||
def mock_err(*args, **kwargs):
|
def mock_err(*args, **kwargs):
|
||||||
raise OSError("Docker socket unreachable")
|
raise OSError("Docker socket unreachable")
|
||||||
|
|
||||||
@@ -269,6 +350,7 @@ def test_docker_status_error_handling(monkeypatch):
|
|||||||
|
|
||||||
def test_docker_image_revision_extraction(monkeypatch):
|
def test_docker_image_revision_extraction(monkeypatch):
|
||||||
"""Ensure get_docker_image_revision extracts org.opencontainers.image.revision."""
|
"""Ensure get_docker_image_revision extracts org.opencontainers.image.revision."""
|
||||||
|
|
||||||
def mock_run(args, **kwargs):
|
def mock_run(args, **kwargs):
|
||||||
mock = MagicMock()
|
mock = MagicMock()
|
||||||
if "ps" in args:
|
if "ps" in args:
|
||||||
@@ -278,7 +360,10 @@ def test_docker_image_revision_extraction(monkeypatch):
|
|||||||
return mock
|
return mock
|
||||||
|
|
||||||
monkeypatch.setattr("subprocess.run", mock_run)
|
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):
|
def mock_run_empty(args, **kwargs):
|
||||||
mock = MagicMock()
|
mock = MagicMock()
|
||||||
@@ -293,9 +378,8 @@ def test_docker_image_revision_extraction(monkeypatch):
|
|||||||
|
|
||||||
|
|
||||||
def test_homepage_sync_groups_and_sorts_correctly(
|
def test_homepage_sync_groups_and_sorts_correctly(
|
||||||
mock_core_dir: Path,
|
mock_core_dir: Path, app_factory: AppFactory, monkeypatch
|
||||||
app_factory: AppFactory,
|
):
|
||||||
monkeypatch):
|
|
||||||
"""
|
"""
|
||||||
TDD Goal: Port `cmd_sync_homepage` to V2 using the new Dataclass structure.
|
TDD Goal: Port `cmd_sync_homepage` to V2 using the new Dataclass structure.
|
||||||
It must group by `homepage.group` and sort by `homepage.weight`.
|
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
|
title: App1
|
||||||
group: Group B
|
group: Group B
|
||||||
weight: 20
|
weight: 20
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
@@ -324,7 +408,7 @@ def test_homepage_sync_groups_and_sorts_correctly(
|
|||||||
title: App2
|
title: App2
|
||||||
group: Group A
|
group: Group A
|
||||||
weight: 10
|
weight: 10
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
monkeypatch.setattr(engine, "get_core_services", list)
|
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"
|
assert output_file.exists(), "The services.yaml file must be generated"
|
||||||
|
|
||||||
content = output_file.read_text()
|
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
|
assert "App2" in content # App 2 is in the file
|
||||||
|
|
||||||
|
|
||||||
@@ -380,7 +466,9 @@ def test_resolve_core_stack_type():
|
|||||||
assert traefik.container == "traefik"
|
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."""
|
"""Ensure manifest parsing uses core_manifest and catches invalid env keys."""
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
dir_name="homelab-badenv",
|
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
|
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."""
|
"""Ensure cmd_resolve exits with non-zero on workload with manifest errors."""
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
dir_name="homelab-corrupt",
|
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
|
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."""
|
"""Ensure cmd_list flags workloads with manifest errors instead of swallowing them."""
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
dir_name="homelab-broken",
|
dir_name="homelab-broken",
|
||||||
@@ -462,4 +554,3 @@ def test_cmd_list_flags_manifest_error(app_factory: AppFactory, capsys: pytest.C
|
|||||||
engine.cmd_list([])
|
engine.cmd_list([])
|
||||||
captured = capsys.readouterr()
|
captured = capsys.readouterr()
|
||||||
assert "Manifest Error" in captured.out
|
assert "Manifest Error" in captured.out
|
||||||
|
|
||||||
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).
|
Unit test suite for scripts/core_manifest.py (Schema v1.0 & Parser Library).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
# Add scripts directory to path
|
# # Add scripts directory to path
|
||||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||||
|
|
||||||
from core_manifest import (
|
from core_manifest import (
|
||||||
Manifest,
|
Manifest,
|
||||||
ManifestValidationError,
|
ManifestValidationError,
|
||||||
@@ -24,13 +22,17 @@ from core_manifest import (
|
|||||||
|
|
||||||
def test_validate_transport_https():
|
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 scheme == TransportScheme.HTTPS
|
||||||
assert url == "https://git.example.com/operator/homelab-snappymail.git"
|
assert url == "https://git.example.com/operator/homelab-snappymail.git"
|
||||||
|
|
||||||
|
|
||||||
def test_validate_transport_ssh():
|
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 scheme == TransportScheme.SSH
|
||||||
assert url == "ssh://git@git.example.com:2223/operator/homelab-docs.git"
|
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"
|
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://insecure.example.com/repo.git",
|
||||||
"http://github.com/repo.git",
|
"http://github.com/repo.git",
|
||||||
])
|
],
|
||||||
|
)
|
||||||
def test_validate_transport_rejects_http(insecure_url: str):
|
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)
|
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",
|
"../../etc/shadow",
|
||||||
"/home/operator/secret",
|
"/home/operator/secret",
|
||||||
"~/vault",
|
"~/vault",
|
||||||
"file:///etc/passwd",
|
r"repo\windows\payload",
|
||||||
])
|
r"..\traversal",
|
||||||
|
],
|
||||||
|
)
|
||||||
def test_validate_transport_rejects_paths_and_traversal(traversal_url: str):
|
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)
|
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():
|
def test_classify_ref_branches():
|
||||||
assert classify_ref("main") == (RefType.BRANCH, "main")
|
assert classify_ref("main") == (RefType.BRANCH, "main")
|
||||||
assert classify_ref("refs/heads/develop") == (RefType.BRANCH, "develop")
|
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("release/v1.0") == (RefType.BRANCH, "release/v1.0")
|
||||||
|
assert classify_ref("custom-adhoc-branch") == (
|
||||||
|
RefType.BRANCH,
|
||||||
|
"custom-adhoc-branch",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_classify_ref_tags():
|
def test_classify_ref_tags():
|
||||||
@@ -145,7 +219,9 @@ deployment:
|
|||||||
|
|
||||||
|
|
||||||
def test_parse_manifest_rejects_missing_name():
|
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")
|
parse_manifest("domain: test.example.com\n")
|
||||||
|
|
||||||
|
|
||||||
@@ -162,7 +238,9 @@ deployment:
|
|||||||
- compose_up
|
- compose_up
|
||||||
- rm_rf_root
|
- 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)
|
parse_manifest(raw_yaml)
|
||||||
|
|
||||||
|
|
||||||
@@ -172,7 +250,9 @@ name: "app"
|
|||||||
deployment:
|
deployment:
|
||||||
strategy: "swarm"
|
strategy: "swarm"
|
||||||
"""
|
"""
|
||||||
with pytest.raises(ManifestValidationError, match="Unsupported deployment strategy 'swarm'"):
|
with pytest.raises(
|
||||||
|
ManifestValidationError, match="Unsupported deployment strategy 'swarm'"
|
||||||
|
):
|
||||||
parse_manifest(raw_yaml)
|
parse_manifest(raw_yaml)
|
||||||
|
|
||||||
|
|
||||||
@@ -185,7 +265,9 @@ def test_parse_manifest_from_path(tmp_path: Path):
|
|||||||
assert manifest.is_internal is True
|
assert manifest.is_internal is True
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("invalid_key", [
|
@pytest.mark.parametrize(
|
||||||
|
"invalid_key",
|
||||||
|
[
|
||||||
"123_BAD",
|
"123_BAD",
|
||||||
"INVALID-KEY",
|
"INVALID-KEY",
|
||||||
"FOO;BAR",
|
"FOO;BAR",
|
||||||
@@ -195,14 +277,26 @@ def test_parse_manifest_from_path(tmp_path: Path):
|
|||||||
"IFS",
|
"IFS",
|
||||||
"CORE_DIR",
|
"CORE_DIR",
|
||||||
"SITES_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):
|
def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str):
|
||||||
raw_yaml = f"""
|
raw_yaml = f"""
|
||||||
name: "app"
|
name: "app"
|
||||||
env:
|
env:
|
||||||
"{invalid_key}": "some_value"
|
"{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)
|
parse_manifest(raw_yaml)
|
||||||
|
|
||||||
|
|
||||||
@@ -226,7 +320,9 @@ def test_parse_manifest_rejects_extra_fields():
|
|||||||
name: "app"
|
name: "app"
|
||||||
unrecognized_field: "should_fail"
|
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)
|
parse_manifest(raw_yaml)
|
||||||
|
|
||||||
|
|
||||||
@@ -259,5 +355,3 @@ description: "Pydantic serialization test"
|
|||||||
assert dumped["name"] == "serialized-app"
|
assert dumped["name"] == "serialized-app"
|
||||||
assert dumped["schemaVersion"] == "1.0"
|
assert dumped["schemaVersion"] == "1.0"
|
||||||
assert manifest.to_dict()["name"] == "serialized-app"
|
assert manifest.to_dict()["name"] == "serialized-app"
|
||||||
|
|
||||||
|
|
||||||
@@ -4,14 +4,12 @@ Unit test suite for scripts/provenance.py (Two-Axis Inspection & Provenance Reso
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
# Add scripts directory to path
|
# # Add scripts directory to path
|
||||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||||
|
|
||||||
from core_manifest import Manifest, RefType, SourceConfig, TransportScheme
|
from core_manifest import Manifest, RefType, SourceConfig, TransportScheme
|
||||||
from provenance import (
|
from provenance import (
|
||||||
ProvenanceStatus,
|
ProvenanceStatus,
|
||||||
@@ -43,12 +41,28 @@ def test_get_local_checkout_status_clean_repo(tmp_path: Path):
|
|||||||
app_dir = tmp_path / "git_app"
|
app_dir = tmp_path / "git_app"
|
||||||
app_dir.mkdir()
|
app_dir.mkdir()
|
||||||
env = _clean_git_env()
|
env = _clean_git_env()
|
||||||
subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env)
|
subprocess.run(
|
||||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env)
|
["git", "-C", str(app_dir), "init", "-b", "main"],
|
||||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env)
|
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")
|
(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), "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)
|
status = get_local_checkout_status(app_dir)
|
||||||
assert status.is_git is True
|
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 = tmp_path / "git_dirty_app"
|
||||||
app_dir.mkdir()
|
app_dir.mkdir()
|
||||||
env = _clean_git_env()
|
env = _clean_git_env()
|
||||||
subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env)
|
subprocess.run(
|
||||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env)
|
["git", "-C", str(app_dir), "init", "-b", "main"],
|
||||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env)
|
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")
|
(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), "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
|
# Modify file to create dirty state
|
||||||
(app_dir / "file.txt").write_text("modified", encoding="utf-8")
|
(app_dir / "file.txt").write_text("modified", encoding="utf-8")
|
||||||
@@ -131,7 +161,10 @@ def test_resolve_upstream_provenance_timeout():
|
|||||||
transport=TransportScheme.HTTPS,
|
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)
|
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
|
||||||
|
|
||||||
assert prov.status == ProvenanceStatus.TIMEOUT
|
assert prov.status == ProvenanceStatus.TIMEOUT
|
||||||
@@ -183,13 +216,53 @@ def test_inspect_workload_two_axis(tmp_path: Path):
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Without fetch_upstream: Axis 2 returns UNKNOWN
|
# 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 status_no_fetch.provenance.status == ProvenanceStatus.UNKNOWN
|
||||||
assert "Pass --fetch" in status_no_fetch.provenance.message
|
assert "Pass --fetch" in status_no_fetch.provenance.message
|
||||||
|
|
||||||
# With fetch_upstream: Axis 2 queries remote
|
# With fetch_upstream: Axis 2 queries remote
|
||||||
with patch("provenance.resolve_upstream_provenance") as mock_resolve:
|
with patch("provenance.resolve_upstream_provenance") as mock_resolve:
|
||||||
mock_resolve.return_value = MagicMock(status=ProvenanceStatus.SYNCED)
|
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
|
assert status_fetch.provenance.status == ProvenanceStatus.SYNCED
|
||||||
mock_resolve.assert_called_once()
|
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)"
|
||||||
|
|
||||||
@@ -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) 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) Clarify Pydantic v2 target architecture, strict typing rules, and domain precedence in docs/plans/p4-readiness-plan.md +docs @p4-gate
|
||||||
x 2026-10-15 (A) Migrate core_manifest.py to Pydantic v2 models for strict type validation and serialization +manifest @schema
|
x 2026-10-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
|
x 2026-10-19 (A) Implement strict Pydantic v2 API contracts, error sanitizer, and compose_pull action in scripts/appctl_contracts.py and scripts/core_manifest.py +contracts @p4
|
||||||
(A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4
|
x 2026-10-19 (A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4
|
||||||
(A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4
|
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
|
||||||
(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 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
|
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
|
||||||
(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 (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
|
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
|
||||||
(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 (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