Compare commits
191
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49cded6122 | ||
|
|
90f3ca930c | ||
|
|
47d059ee8d | ||
|
|
a966244f08 | ||
|
|
ef42bfc801 | ||
|
|
6ba45961ae | ||
|
|
1eed45c301 | ||
|
|
1a8e3b5eae | ||
|
|
c9f3108805 | ||
|
|
4f40668536 | ||
|
|
ce969f4678 | ||
|
|
e807a90017 | ||
|
|
37d529848a | ||
|
|
f326b11986 | ||
|
|
8f3b98344a | ||
|
|
92333b017c | ||
|
|
131e5d75a1 | ||
|
|
158bbb0eed | ||
|
|
c104c69fbc | ||
|
|
11aaf6038b | ||
|
|
648dd49c82 | ||
|
|
365801a169 | ||
|
|
7d4cfe1c04 | ||
|
|
9306dae56b | ||
|
|
c337914fb3 | ||
|
|
df7c1f5292 | ||
|
|
33fda26dc1 | ||
|
|
f0db802f72 | ||
|
|
514409939d | ||
|
|
a5826e0e74 | ||
|
|
cdd2d562c3 | ||
|
|
2df95648d4 | ||
|
|
9d7114b547 | ||
|
|
9ac44d0baa | ||
|
|
88f8bace04 | ||
|
|
2882dc99b5 | ||
|
|
2b89ff44c3 | ||
|
|
99bda8740f | ||
|
|
de02b19861 | ||
|
|
99e9c130c0 | ||
|
|
9c9127b833 | ||
|
|
76df30747d | ||
|
|
c034afd0f8 | ||
|
|
af82d4b26d | ||
|
|
b7b19ad7f1 | ||
|
|
1fea9024f1 | ||
|
|
4622392ca5 | ||
|
|
c740ed8c71 | ||
|
|
55acf00c10 | ||
|
|
c8c79bef89 | ||
|
|
5156cf4306 | ||
|
|
5dfebac35c | ||
|
|
d0213d7209 | ||
|
|
178a0c8990 | ||
|
|
03c8fdcf8e | ||
|
|
3ba8e2b51d | ||
|
|
4f1a63160b | ||
|
|
e2dbc97b0e | ||
|
|
caa8140cd3 | ||
|
|
eb02543fa6 | ||
|
|
24508f8d92 | ||
|
|
8ad48a49db | ||
|
|
f631d5627c | ||
|
|
021c01171b | ||
|
|
7c1b9b75c5 | ||
|
|
c86faa8397 | ||
|
|
dae99af189 | ||
|
|
8da559381f | ||
|
|
c86103a14b | ||
|
|
ce7ffa8c46 | ||
|
|
3230e08bf9 | ||
|
|
b6ec909bb6 | ||
|
|
25e79898af | ||
|
|
528bd0d4bc | ||
|
|
2668dcc5a8 | ||
|
|
0b5ba58ecf | ||
|
|
154cde272b | ||
|
|
8cc06e2470 | ||
|
|
53404914c3 | ||
|
|
194d1bf3ff | ||
|
|
9e30e113a0 | ||
|
|
d092ca17b8 | ||
|
|
8ce74ff520 | ||
|
|
b5a3db6f1b | ||
|
|
e23ff941d8 | ||
|
|
dc880928a9 | ||
|
|
51c43f71ff | ||
|
|
d5ba44f676 | ||
|
|
dcacf976bf | ||
|
|
61a2798d4f | ||
|
|
2bf0635ba9 | ||
|
|
7d516579ef | ||
|
|
6997da3a58 | ||
|
|
1d196cbdd5 | ||
|
|
fe4111a628 | ||
|
|
fae36700b7 | ||
|
|
4786bbe1ca | ||
|
|
fbfbe9375f | ||
|
|
ea0ce0b1d6 | ||
|
|
66c5e4280a | ||
|
|
68c149d9af | ||
|
|
ec0a461b2e | ||
|
|
5ed61acf32 | ||
|
|
93feb0d3f2 | ||
|
|
8356819f08 | ||
|
|
0d9a2ce511 | ||
|
|
667f8d19b9 | ||
|
|
bbbf58a27c | ||
|
|
a9ada28c65 | ||
|
|
6052019f2c | ||
|
|
298ae728e1 | ||
|
|
ecacb1cc39 | ||
|
|
f261b80477 | ||
|
|
2c99e3e92e | ||
|
|
9381f3e070 | ||
|
|
f0e0fc41a1 | ||
|
|
c78550abea | ||
|
|
2779c06d8f | ||
|
|
c9b22af663 | ||
|
|
ccea8abb4a | ||
|
|
5d2aff3f90 | ||
|
|
6836233c95 | ||
|
|
61627cdd5d | ||
|
|
c549ada3b4 | ||
|
|
0312812c3b | ||
|
|
10468c4afa | ||
|
|
7ae03f2176 | ||
|
|
2297cd5cba | ||
|
|
82edd74aac | ||
|
|
964e633da2 | ||
|
|
aca5a71bca | ||
|
|
be954a1d39 | ||
|
|
e700e0d2b1 | ||
|
|
9d82577f48 | ||
|
|
9aeb67010f | ||
|
|
d6e5609a29 | ||
|
|
9db271b348 | ||
|
|
5fc5ad8656 | ||
|
|
619209fe4f | ||
|
|
246b5879d8 | ||
|
|
642ab32364 | ||
|
|
03b36b1b3a | ||
|
|
db1825832f | ||
|
|
2c8c7d969f | ||
|
|
22d3a649ea | ||
|
|
e0422a3795 | ||
|
|
c0cb71be2b | ||
|
|
2856c75092 | ||
|
|
f5e7c0b233 | ||
|
|
942bb1cc6d | ||
|
|
dd931a7c01 | ||
|
|
de7dcfc715 | ||
|
|
5f12e9e2a3 | ||
|
|
dc028934bd | ||
|
|
693733a324 | ||
|
|
90eed848e8 | ||
|
|
041d6d3434 | ||
|
|
d43848cf3b | ||
|
|
d119ca1ccd | ||
|
|
fabdacb274 | ||
|
|
abf8d8d7e0 | ||
|
|
3f8fb1756b | ||
|
|
35f7d564cc | ||
|
|
18c1a3f247 | ||
|
|
03ac2ae15e | ||
|
|
45d9271cbc | ||
|
|
8acbd66104 | ||
|
|
cc76a94890 | ||
|
|
0fac11c5d7 | ||
|
|
118da3dd84 | ||
|
|
8134070398 | ||
|
|
431413ec1a | ||
|
|
4c9e7a449d | ||
|
|
f8cbe082db | ||
|
|
534ea9ed11 | ||
|
|
33514663a3 | ||
|
|
f4b676be33 | ||
|
|
142697a19c | ||
|
|
5aae4ef0d6 | ||
|
|
c265c3e8f6 | ||
|
|
fa8054aad5 | ||
|
|
01acdb4f75 | ||
|
|
29dd186eb8 | ||
|
|
945e80206f | ||
|
|
9f71b32db9 | ||
|
|
96e935d319 | ||
|
|
a781e2c428 | ||
|
|
1a50c8a668 | ||
|
|
05ad9b2295 | ||
|
|
b6a23bd6b4 | ||
|
|
4d998f67f4 |
No files matched your search
@@ -1,13 +0,0 @@
|
||||
# DOMAIN AND DNS CONFIGURATION
|
||||
DOMAIN=yourdomain.com
|
||||
ACME_EMAIL=your-email@provider.com
|
||||
DYNU_API_KEY=your_dynu_api_key
|
||||
|
||||
# DOCKER CONFIGURATION
|
||||
DOCKER_API_VERSION=1.40
|
||||
|
||||
# AUTHELIA SECURITY SECRETS
|
||||
# Generate these using: openssl rand -hex 64
|
||||
AUTHELIA_SESSION_SECRET=session_secret_hex
|
||||
AUTHELIA_STORAGE_ENCRYPTION_KEY=storage_encryption_key_hex
|
||||
AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET=jwt_secret_hex
|
||||
@@ -0,0 +1 @@
|
||||
use flake
|
||||
@@ -0,0 +1,25 @@
|
||||
name: Core Architecture & Invariant CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Configure Git Safe Directory & Nix Flakes
|
||||
run: |
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||
mkdir -p ~/.config/nix
|
||||
echo "experimental-features = nix-command flakes" >> ~/.config/nix/nix.conf
|
||||
echo "build-users-group =" >> ~/.config/nix/nix.conf
|
||||
|
||||
- name: Run Architecture & Security Invariant Checks
|
||||
run: |
|
||||
nix flake check
|
||||
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# ==============================================================================
|
||||
# Homelab Core Pre-Commit Invariant & Quality Gate Hook
|
||||
# Runs linter (Ruff), static type checker (Pyright), and test suite (Pytest)
|
||||
# ==============================================================================
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
echo "🔍 [pre-commit] Executing Homelab Core invariant checks..."
|
||||
|
||||
# 1. Run Ruff Linter
|
||||
echo " ↳ Linting repository with Ruff..."
|
||||
if command -v ruff >/dev/null 2>&1; then
|
||||
ruff check .
|
||||
elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then
|
||||
nix develop --command ruff check .
|
||||
else
|
||||
echo "⚠️ [pre-commit] Neither ruff nor nix found; skipping ruff"
|
||||
fi
|
||||
|
||||
# 2. Run Pyright Type Checker
|
||||
echo " ↳ Checking static types with Pyright..."
|
||||
if command -v pyright >/dev/null 2>&1; then
|
||||
pyright
|
||||
elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then
|
||||
nix develop --command pyright
|
||||
else
|
||||
echo "⚠️ [pre-commit] Neither pyright nor nix found; skipping pyright"
|
||||
fi
|
||||
|
||||
# 3. Run Pytest Suite
|
||||
echo " ↳ Running structural and security test suite with Pytest..."
|
||||
if [ -x ".venv/bin/pytest" ]; then
|
||||
.venv/bin/pytest tests/
|
||||
elif command -v pytest >/dev/null 2>&1; then
|
||||
pytest tests/
|
||||
elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then
|
||||
nix develop --command pytest tests/
|
||||
else
|
||||
echo "⚠️ [pre-commit] Neither pytest nor nix found; skipping pytest"
|
||||
fi
|
||||
|
||||
echo "✅ [pre-commit] All repository checks passed successfully!"
|
||||
+31
-2
@@ -3,6 +3,10 @@
|
||||
.env.*
|
||||
secrets.txt
|
||||
backup.zip
|
||||
.envrc
|
||||
.direnv
|
||||
.venv
|
||||
nixos/instance.nix
|
||||
|
||||
# SSL / ACME Certificates & Keys
|
||||
config/letsencrypt/*
|
||||
@@ -11,21 +15,46 @@ config/letsencrypt/*
|
||||
**/*.pem
|
||||
**/*.bak
|
||||
|
||||
# Authelia Databases & Mail Logs
|
||||
# Authelia, LLDAP, Stalwart & SnappyMail Data
|
||||
config/authelia/db.sqlite3
|
||||
config/authelia/emails.txt
|
||||
config/authelia/users.yml
|
||||
config/authelia/users.yaml
|
||||
config/lldap/data/
|
||||
config/stalwart/data/
|
||||
config/stalwart/etc/*
|
||||
!config/stalwart/etc/.gitkeep
|
||||
config/snappymail/data/
|
||||
|
||||
|
||||
# Diun Databases
|
||||
config/diun/diun.db
|
||||
|
||||
# Homepage Logs
|
||||
# Homepage Logs & Generated Runtime State
|
||||
config/homepage/logs/
|
||||
config/homepage/services.yaml
|
||||
config/homepage/custom.css
|
||||
config/homepage/custom.js
|
||||
|
||||
# OS & Editor Metadata
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.vscode/
|
||||
.idea/
|
||||
.worktrees/
|
||||
|
||||
# Python & Testing Caches
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
mutants/
|
||||
.mutmut-cache/
|
||||
|
||||
# Local Bootstrap & Operational Scripts
|
||||
scripts/bootstrap_lldap_users.py
|
||||
scripts/bootstrap_*.py
|
||||
!scripts/bootstrap_token.py
|
||||
|
||||
# Worktrees & Slices
|
||||
.worktrees/
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
keys:
|
||||
- &server age18q3lr2z4yeg2f86my42ym4hx0dvcwgjshmchyhdkgwvf4k37dsyq3mcjse
|
||||
- &laptop age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg
|
||||
|
||||
creation_rules:
|
||||
- path_regex: nixos/secrets\.yaml$
|
||||
key_groups:
|
||||
- pgp: []
|
||||
age:
|
||||
- *server
|
||||
- *laptop
|
||||
@@ -1,25 +1,98 @@
|
||||
# 🤖 Antigravity Workspace Guidelines: Homelab Core & Infrastructure
|
||||
# Canopy NixOS Core — Agent Guidelines
|
||||
|
||||
This repository is the central control plane for the `roadtotech.me` homelab cluster. Follow these operational rules across all tasks.
|
||||
## 1. Project Overview & Architectural Boundaries
|
||||
|
||||
**Canopy NixOS Core** (`canopy-homelab/nixos-core`) defines the declarative NixOS host foundation, shared platform infrastructure services, security boundaries, and the `appctl` operational control plane for the **Canopy** ecosystem. Independent application workloads live in `~/Workloads/<app>` and integrate through declarative `app.yaml` manifests and workload-scoped Docker Compose files.
|
||||
|
||||
### Core vs. `~/Workloads` Ownership
|
||||
- **Core owns**: NixOS host configuration (`nixos/instance.example.nix` template for `/etc/nixos/homelab-instance.nix`), shared platform services (edge ingress, SSO/LDAP, mail, log/update monitors), platform-level ports and security policy (including `homelab.workloadGrants` -> `/etc/homelab/grants.json`), and orchestration/deployment mechanics (`appctl`, `gitops_dispatcher.py`, `workload_grants.py`).
|
||||
- **`~/Workloads` owns**: Independently deployed application workloads, workload-specific `docker-compose.yml` topologies, workload intent (`app.yaml`), and `deployments.yaml`.
|
||||
- **Boundary Rule**: Never hardcode *workload-specific* domains, ports, containers, environment variables, or deployment policies in Core (`scripts/appctl*`, GitOps, or Core `docker-compose.yml`), and never move Core platform services into `~/Workloads`. When ownership is ambiguous, consult [`docs/architecture.md`](docs/architecture.md) before changing the boundary.
|
||||
|
||||
### Context Discovery Hierarchy
|
||||
Before proposing or implementing changes, establish context in this order:
|
||||
1. **Architectural Decisions (`docs/decisions/`)**: Check [`docs/decisions/README.md`](docs/decisions/README.md) and local ADRs for binding design commitments.
|
||||
2. **Runtime Contracts (`docs/`)**: Consult [`docs/architecture.md`](docs/architecture.md), [`docs/appctl.md`](docs/appctl.md), [`docs/gitops.md`](docs/gitops.md), and [`docs/secrets-and-state.md`](docs/secrets-and-state.md) for current behavior.
|
||||
3. **Trajectory & Active Work (`ROADMAP.md`, `todo.txt`, `git log`)**: Verify whether a capability belongs to the current baseline or a planned milestone before modifying code.
|
||||
|
||||
When a requested change conflicts with an architectural invariant or accepted ADR, **stop and surface the conflict** before implementing a workaround.
|
||||
|
||||
---
|
||||
|
||||
## 🏛️ Architectural Invariants
|
||||
## 2. Build, Lint & Verification Commands
|
||||
|
||||
1. **Decentralized Manifests (`app.yaml`)**:
|
||||
- Never hardcode application environment variables, domains, or port maps inside `Core/scripts/appctl` or `Core/scripts/appctl_engine.py`.
|
||||
- Every application in `~/Sites` is self-describing via its own `app.yaml`.
|
||||
2. **Read-Only Socket Proxy**:
|
||||
- `socket-proxy` must remain restricted to read-only endpoints (`POST=0`, `DELETE=0`).
|
||||
3. **Zero Hardcoded Secrets**:
|
||||
- Never commit raw `.env` files, password strings, database files (`*.db`, `*.sqlite3`), or SSL certificates (`acme.json`, `*.key`).
|
||||
- All runtime secrets are managed declaratively in `~/Config/hosts/desktop/secrets.yaml` via SOPS and rendered to `/run/secrets/rendered/`.
|
||||
4. **License Invariant**:
|
||||
- Preserve and maintain `The Unlicense` (public domain) across all Core and Sites repositories.
|
||||
The Python environment (`python3`, `pytest`, `pydantic`, `pyyaml`, `types-pyyaml`) and static analysis tools (`ruff`, `pyright`) are provisioned hermetically by `flake.nix` and automatically symlinked to `.venv` via the Nix `devShell` hook (`.envrc`). Do not create separate `uv` or `pip` virtual environments that split from the Nix store environment.
|
||||
|
||||
Every implementation step must close with the automated verification gate before proposing a commit:
|
||||
|
||||
```bash
|
||||
# Full verification gate: Ruff + Pyright + Pytest (124+ tests) + nix flake check + NixOS drv eval
|
||||
./scripts/run-tests
|
||||
|
||||
# Targeted fast iteration commands (inside direnv / nix develop, or via .venv)
|
||||
ruff check .
|
||||
pyright
|
||||
.venv/bin/pytest tests/
|
||||
```
|
||||
|
||||
When modifying container or Compose definitions, also validate Compose syntax:
|
||||
|
||||
```bash
|
||||
docker compose config -q
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📚 Brain Vault & Continuous Learning
|
||||
## 3. Code Style & Contract Guidelines
|
||||
|
||||
* **Knowledge Capture**: Whenever architectural designs, threat analyses, debugging insights, or `/learn` commands are executed, ensure a clear, structured markdown note is persisted to [`/home/kiskaadee/Brain/homelab/`](/home/kiskaadee/Brain/homelab) or [`/home/kiskaadee/Brain/learning/`](/home/kiskaadee/Brain/learning) and indexed in its corresponding `README.md`.
|
||||
* **Obsidian & Docs Viewer Compatibility**: All documentation must be clean GitHub-flavored markdown compatible with Obsidian and the live docs viewer at `https://docs.roadtotech.me`.
|
||||
- **Fail-Closed Validation (`scripts/core_manifest.py`)**: All external inputs (`app.yaml` manifests, webhook payloads, CLI arguments, daemon payloads) must be validated through strict Pydantic v2 models (`ConfigDict(extra="forbid")`).
|
||||
- **Explicit Error Handling**: Never swallow diagnostic `stderr` silently (e.g., avoid blind `2>/dev/null` on engine or manifest commands). Surface actionable validation errors while redacting sensitive material.
|
||||
- **Platform Genericism**: Keep all code, templates, tests, and documentation strictly instance-agnostic:
|
||||
- Inject routing and service identities at runtime via environment variables (`HOMELAB_DOMAIN`, `DOMAIN_SUFFIX`).
|
||||
- Use RFC 2606 placeholders (`example.com`, `example.org`, `example.test`) in tests and configuration examples—never personal domains or operator usernames.
|
||||
- In historical documentation or milestone records, use descriptive phrasing (e.g., *"the configured `smtp.<domain>` endpoint"*) rather than fabricating placeholder domains as historical facts.
|
||||
|
||||
---
|
||||
|
||||
## 4. Testing Instructions (TDD)
|
||||
|
||||
- **TDD-First**: Write or update failing unit, structural, or security tests in `tests/` before or alongside implementation changes.
|
||||
- **No Tautological Tests**: Every test must import and execute real production modules or scripts (`core_manifest`, `appctl_engine`, `gitops_dispatcher`, `scripts/appctl`) and assert on observable outcomes. Never write tests that only inspect local mock strings, hardcode expected outputs into the fixture under test, or continue passing when the production invariant is broken.
|
||||
- **Protect Invariants**: Do not bypass failing tests by weakening or deleting an invariant assertion unless the architecture itself has intentionally changed via an approved ADR.
|
||||
|
||||
---
|
||||
|
||||
## 5. Security & State Invariants
|
||||
|
||||
1. **Workload Manifests (`app.yaml`)**: Describe declarative workload identity, routing metadata, and deployment intent only. Never introduce arbitrary command execution, host filesystem paths, privileged flags, or Docker control capabilities into `app.yaml`.
|
||||
2. **GitOps Trust Boundary (`scripts/gitops_dispatcher.py`)**:
|
||||
- Webhook admission requires cryptographic authentication (HMAC-SHA256).
|
||||
- Repository identity and filesystem paths must be resolved strictly through the trusted workloads registry (`~/Workloads/deployments.yaml` or `HOMELAB_DEPLOYMENTS_FILE`, templated by `config/deployments.yaml`)—never directly from webhook payloads.
|
||||
- Execution must remain allowlisted, serialized (`flock`), pre-validated by the Compose AST security checker, and free of shell interpolation (`shell=False`, no `eval`).
|
||||
3. **Docker & Privilege Isolation**:
|
||||
- `socket-proxy` is the **only** service permitted to mount `/var/run/docker.sock` (strictly `:ro`, read-only API capabilities only; `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`).
|
||||
- Never add `privileged: true`, host namespace sharing, or direct Docker socket mounts to workload or control-plane containers.
|
||||
4. **Declarative Configuration vs. Secrets & Runtime State**:
|
||||
- Git stores declarative configuration and reproducible definitions only. Never commit plaintext secrets, keys, password hashes, certificates, or runtime databases.
|
||||
- Host secrets are managed via SOPS (`sops-nix`) and projected to `/run/secrets/`.
|
||||
- Persistent mutable runtime state belongs in dedicated host state directories (`~/var/lib/homelab/<app>/`) or Docker volumes excluded from version control.
|
||||
|
||||
---
|
||||
|
||||
## 6. Documentation, Task Tracking & Git Workflow
|
||||
|
||||
- **Synchronize Documentation (`docs/`)**: Update repository documentation alongside code changes that alter behavior, contracts, or operations. Keep all Markdown formatted in GitHub-Flavored Markdown compatible with both Obsidian and the live documentation viewer.
|
||||
- **Architecture Decision Records (`docs/decisions/`)**: Record binding repository-level architectural decisions in MADR 4.0 format (`NNNN-slug.md`) and register them in [`docs/decisions/README.md`](docs/decisions/README.md).
|
||||
- **Live Task Tracking (`todo.txt`)**: Maintain a comment-free root `todo.txt` formatted for `tuxedo` / `todo.sh` (`(A)`–`(C)` priorities, `+<project>`, `@<context>`) reflecting the current milestone. Mark verified deliverables completed (`x YYYY-MM-DD ...`) immediately.
|
||||
- **Git & Commits**:
|
||||
- Never commit directly to `main`/`master`.
|
||||
- Never run destructive Git commands (`reset --hard`, `restore`, `clean -fd`, `push --force`) without explicit user confirmation.
|
||||
- Stage atomic changes and use Conventional Commits (`feat`, `fix`, `refactor`, `test`, `docs`, `chore`), waiting for user approval before committing.
|
||||
- Preserve [The Unlicense](UNLICENSE) across the repository.
|
||||
|
||||
### Organization Planning Sync Contract
|
||||
- **Ecosystem Hub**: Master roadmap and cross-repo plans live in `canopy-homelab/.profile` (`ROADMAP.md`, `docs/plans/`, `todo.txt`).
|
||||
- **Organization Kanban Board**: **Canopy Platform** (`https://gitea.<domain>/canopy-homelab/-/projects/7`, Project ID: `7`).
|
||||
- **Column IDs (Deep Signal)**: `Backlog` -> `30` (default), `Ready` -> `31`, `Work in Progress` -> `32`, `Review` -> `33`, `Completed` -> `34`.
|
||||
- **Mirror Policy**: Primary sovereign Gitea forge (`canopy-homelab/nixos-core`); GitHub (`canopy-homelab/nixos-core`) is an automated `sync_on_commit` push mirror.
|
||||
- **Re-sync Trigger**: Re-run `/gitea-plan` on scope shifts or before decomposing the next rolling milestone (P5/P6/P7).
|
||||
@@ -1,186 +1,185 @@
|
||||
# 🌐 Traefik Homelab Core
|
||||
# Canopy — NixOS Core (`canopy-homelab/nixos-core`)
|
||||
|
||||
Welcome to the **Traefik Homelab Core Control Plane** — the central orchestrator, security perimeter, and edge gateway for the `roadtotech.me` homelab cluster.
|
||||
**Canopy NixOS Core** is the declarative NixOS host foundation, shared platform infrastructure stack, and `appctl` operational control plane for the **Canopy** self-hosted homelab ecosystem.
|
||||
|
||||
This repository implements a **Hardened Hub** architecture where routing, SSL termination, identity management, container isolation, and orchestration are managed centrally, while user applications live in independent repositories in `~/Sites`.
|
||||
It is designed around a strict two-tier boundary:
|
||||
1. **Canopy NixOS Core (`canopy-homelab/nixos-core`, this repository)**: Owns NixOS operating system configuration, edge TLS ingress, SSO/LDAP directory identity, mail routing, read-only Docker socket isolation, and orchestration/deployment mechanics.
|
||||
2. **Canopy Workloads (`~/Workloads/<app>`, e.g. `<user>/canopy-workloads`)**: Independently deployed application stacks that integrate with Core through self-describing `app.yaml` manifests and workload-scoped `docker-compose.yml` definitions.
|
||||
|
||||
All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime.
|
||||
|
||||
> [!NOTE]
|
||||
> **Milestone P4 Control Plane Architecture**: Under [Milestone P4 in `ROADMAP.md`](ROADMAP.md), `appctl` operates as an operational control plane daemon service (`homelab-appctl.service`) exposing a unified logical API across a local Unix Domain Socket (`/run/homelab/appctl.sock`) and loopback HTTP (`127.0.0.1:9001`). The thin `appctl` CLI delegates commands to this daemon with automatic `SO_PEERCRED` identity inspection and token-based RBAC. See [`docs/appctl.md`](docs/appctl.md) and [`ROADMAP.md`](ROADMAP.md) for details.
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ Architectural Overview & Component Roles
|
||||
## System Architecture at a Glance
|
||||
|
||||
The infrastructure is strictly divided into two operational tiers:
|
||||
|
||||
```
|
||||
Internet (roadtotech.me)
|
||||
```text
|
||||
Internet
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────┐
|
||||
│ Traefik Edge Proxy (:443) │
|
||||
│ (Wildcard Let's Encrypt TLS) │
|
||||
│ Wildcard TLS (*.example.com) │
|
||||
└───────┬───────────────┬───────┘
|
||||
│ │
|
||||
Public Traffic │ │ Auth Guarded
|
||||
Public Traffic │ │ ForwardAuth Protected
|
||||
(e.g., SMTP, public) │ │ (authelia-auth@docker)
|
||||
▼ ▼
|
||||
[ Landing / Public ] [ Authelia SSO / 2FA ]
|
||||
│ │
|
||||
│ ▼
|
||||
└───────► [ Data Plane Apps ]
|
||||
(Sites: jellyfin, docs, etc.)
|
||||
[ Public Services ] [ Authelia SSO / 2FA ]
|
||||
│ │ (LDAP -> LLDAP)
|
||||
▼ ▼
|
||||
┌───────────────────────────────┐
|
||||
│ Docker proxy-net │
|
||||
├───────────────────────────────┤
|
||||
│ • Core Services (Homepage, │
|
||||
│ Dozzle, Stalwart, etc.) │
|
||||
│ • Workload Apps (~/Workloads/*) │
|
||||
└───────────────┬───────────────┘
|
||||
│ (Read-Only API via TCP:2375)
|
||||
▼
|
||||
┌───────────────────────────────┐
|
||||
│ Docker socket-proxy │
|
||||
│ (socket-net, Read-Only) │
|
||||
└───────────────┬───────────────┘
|
||||
│ (read-only mount :ro)
|
||||
▼
|
||||
/var/run/docker.sock
|
||||
▲
|
||||
│ (Host Orchestration & CD)
|
||||
┌───────────────┴───────────────┐
|
||||
│ Host Control Plane (P4) │
|
||||
│ • thin appctl CLI │
|
||||
│ • homelab-appctl.service │
|
||||
│ (UDS / HTTP daemon) │
|
||||
│ • homelab-gitops.service │
|
||||
└───────────────────────────────┘
|
||||
```
|
||||
|
||||
### 1. Control Plane Components (`~/Core`)
|
||||
* **`Traefik` (v3.6):** The edge reverse proxy and SSL terminator. Automatically obtains and maintains Let's Encrypt wildcard certificates (`*.roadtotech.me`, `roadtotech.me`) using the Dynu DNS-01 challenge. Routes incoming HTTP/HTTPS traffic to internal Docker containers over `proxy-net`.
|
||||
* **`socket-proxy` (tecnativa):** Security barrier. Prevents Traefik and other containers from having direct access to `/var/run/docker.sock`, restricting access exclusively to safe container read operations via TCP (`socket-net`).
|
||||
* **`Authelia`:** Single Sign-On (SSO) and Multi-Factor Authentication (2FA) identity gateway. Provides ForwardAuth middleware (`authelia-auth@docker`) that gates administrative dashboards and sensitive applications before traffic touches them.
|
||||
* **`Portainer CE`:** Visual GUI for container inspection, stack lifecycle management, and log tracking.
|
||||
* **`Dozzle`:** Lightweight real-time log viewer for all running containers, protected by Authelia SSO.
|
||||
* **`Watchtower` & `Diun`:** Background daemons responsible for container image update notifications and automated updates.
|
||||
For detailed runtime layers, network segmentation, and the P4 control-plane transport architecture, see [`docs/architecture.md`](docs/architecture.md) and [`ROADMAP.md`](ROADMAP.md).
|
||||
|
||||
### 2. Data Plane Applications (`~/Sites`)
|
||||
User and service applications (e.g. `dashboard`, `docs`, `jellyfin`, `excalidraw`, `gitea`, `mermaid`, `minecraft`, `ollama`, `pgsql`, `mongodb`) live in isolated, dedicated git repositories under `~/Sites`. They integrate with the Core control plane dynamically via the `proxy-net` Docker network and Traefik container labels.
|
||||
### Core Platform Services (`docker-compose.yml`)
|
||||
|
||||
| Service | Default Endpoint | Role | Access Policy |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **`traefik`** | `traefik.${HOMELAB_DOMAIN}` | Edge reverse proxy & DNS-01 ACME wildcard TLS | Authelia Guard |
|
||||
| **`socket-proxy`** | Internal (`socket-net:2375`) | Read-only Docker API security barrier (`POST=0`, `DELETE=0`) | Internal Only |
|
||||
| **`lldap`** | `users.${HOMELAB_DOMAIN}` | Central LDAP user directory | Authelia Guard |
|
||||
| **`authelia`** | `auth.${HOMELAB_DOMAIN}` | Single Sign-On (SSO), 2FA & ForwardAuth | Public (Auth Endpoint) |
|
||||
| **`stalwart`** | `smtp.${HOMELAB_DOMAIN}` | Mail server (SMTP/IMAP/JMAP/Sieve) | Native / LLDAP |
|
||||
| **`homepage`** | `dashboard.${HOMELAB_DOMAIN}` | Service portal dynamically synced via `appctl` | Authelia Guard |
|
||||
| **`dozzle`** | `logs.${HOMELAB_DOMAIN}` | Real-time container log viewer (via `socket-proxy`) | Authelia Guard |
|
||||
| **`watchtower`** | Internal | Automated container image updater | Internal Only |
|
||||
| **`diun`** | Internal | Container image update notifier | Internal Only |
|
||||
|
||||
---
|
||||
|
||||
## 🔒 Security Model & Secrets Architecture
|
||||
|
||||
The security model is built on zero hardcoded secrets and defense-in-depth:
|
||||
## Repository Structure
|
||||
|
||||
```text
|
||||
.
|
||||
├── flake.nix # NixOS host configuration, devShell (.venv symlink), and CI checks
|
||||
├── docker-compose.yml # Core platform service stack
|
||||
├── nixos/ # Declarative NixOS modules, systemd units, SOPS secret wiring & instance.example.nix
|
||||
├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml template)
|
||||
├── scripts/
|
||||
│ ├── appctl # Thin operational CLI delegating to control plane daemon
|
||||
│ ├── appctl_daemon.py # Async HTTP/UDS daemon server (homelab-appctl.service)
|
||||
│ ├── appctl_router.py # Operational router, locking, RBAC & dispatch
|
||||
│ ├── appctl_auth.py # SO_PEERCRED & Bearer token RBAC authentication
|
||||
│ ├── appctl_audit.py # Append-only fail-closed structured audit logger
|
||||
│ ├── appctl_contracts.py # Pydantic v2 schemas for daemon RPC requests & responses
|
||||
│ ├── appctl_cli.py # Unified CLI client with dual transport fallbacks
|
||||
│ ├── appctl_engine.py # Discovery, two-axis provenance, TLS inspection, and Homepage sync
|
||||
│ ├── bootstrap_token.py # Operator Bearer token provisioning helper
|
||||
│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for app.yaml
|
||||
│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST validation
|
||||
│ ├── workload_grants.py # Fail-closed Pydantic v2 loader for /etc/homelab/grants.json
|
||||
│ └── run-tests # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks)
|
||||
├── tests/ # Unit, structural, and security invariant test suites
|
||||
└── docs/ # Architecture references, operational runbooks, and MADR decisions
|
||||
```
|
||||
[~/Config/hosts/desktop/secrets.yaml] (Encrypted with SOPS + age keys)
|
||||
│
|
||||
▼ (Decrypted at boot by sops-nix using SSH host key)
|
||||
[/run/secrets/rendered/homeserver.env] & [/run/secrets/rendered/traefik-deployments.env]
|
||||
│
|
||||
▼ (Fed via --env-file and appctl)
|
||||
[Core & Sites Containers]
|
||||
```
|
||||
|
||||
1. **SOPS & sops-nix Integration:** All sensitive tokens (Dynu API key, Authelia session secrets, JWT keys, database passwords) are encrypted in `~/Config/hosts/desktop/secrets.yaml` and decrypted by NixOS at runtime into in-memory `/run/secrets/rendered/`.
|
||||
2. **Edge TLS & HSTS:** All external traffic is forced over HTTPS using Let's Encrypt wildcard certificates with strict redirect schemes (`https-redirect@docker`).
|
||||
3. **Authelia ForwardAuth:** Applications that require authentication declare `traefik.http.routers.<name>.middlewares=authelia-auth@docker`, delegating identity verification to Authelia.
|
||||
4. **Socket Isolation:** Direct Docker daemon sockets are completely hidden behind `socket-proxy`.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Orchestration with `appctl`
|
||||
## Quickstart & Operations (Control Plane Daemon & CLI)
|
||||
|
||||
Applications in `~/Sites` are managed using the custom `appctl` CLI tool located in `scripts/appctl`.
|
||||
### Development & Verification
|
||||
|
||||
Entering the directory via `direnv` (`use flake`) or `nix develop` provisions the hermetic Nix Python environment and symlinks `.venv` for IDE static analysis:
|
||||
|
||||
### Key Commands:
|
||||
```bash
|
||||
# List all application stacks with runtime container health and Git sync status
|
||||
# Run full automated verification (Ruff + Pyright + Pytest + nix flake check + NixOS drv eval)
|
||||
./scripts/run-tests
|
||||
|
||||
# Run individual checks directly
|
||||
ruff check .
|
||||
pyright
|
||||
.venv/bin/pytest tests/
|
||||
```
|
||||
|
||||
### Workload Management (`appctl` CLI)
|
||||
|
||||
The thin `appctl` CLI connects directly to `homelab-appctl.service` via Unix Domain Socket (`/run/homelab/appctl.sock`) or loopback HTTP (`127.0.0.1:9876`). Local operators in `homelab-operators` or `wheel` receive read-only viewer access via kernel `SO_PEERCRED` without tokens, while mutating actions consume Bearer tokens from `~/.config/homelab/token`:
|
||||
|
||||
```bash
|
||||
# Check daemon health status
|
||||
appctl health
|
||||
|
||||
# List all workloads with container health and local Git checkout status
|
||||
appctl list
|
||||
|
||||
# Fetch upstream git changes across all repositories before rendering status
|
||||
appctl list --fetch
|
||||
# Include upstream Git provenance (--fetch), TLS certificate expiry (--ssl), and Core services (--core)
|
||||
appctl list --fetch --ssl --core
|
||||
|
||||
# List all applications AND core control plane services
|
||||
appctl list --core
|
||||
# Inspect detailed manifest, provenance, and container diagnostics for a workload
|
||||
appctl info <service>
|
||||
|
||||
# Display comprehensive metadata, routing, environment, and Git diagnostics
|
||||
appctl info docs
|
||||
appctl info jellyfin
|
||||
# Manage workload or Core service lifecycle (dispatched via homelab-appctl daemon)
|
||||
appctl up <service|core>
|
||||
appctl down <service|core>
|
||||
appctl restart <service|core>
|
||||
|
||||
# Start, stop, or restart an application stack
|
||||
appctl up docs
|
||||
appctl down jellyfin
|
||||
appctl restart dash
|
||||
# Full stack update (clean tree check -> git pull --ff-only -> compose pull -> recreate -> sync)
|
||||
appctl update <service|core>
|
||||
|
||||
# Full atomic stack upgrade (clean check -> git pull --ff-only -> docker compose pull -> docker compose up -d -> appctl sync)
|
||||
appctl update docs
|
||||
appctl update core
|
||||
appctl update all
|
||||
|
||||
# Validate resolved docker compose configuration
|
||||
appctl config docs
|
||||
|
||||
# Synchronize Homepage dashboard services.yaml from app.yaml manifests
|
||||
# Recompile Homepage dashboard configuration from discovered app.yaml manifests
|
||||
appctl sync
|
||||
```
|
||||
|
||||
---
|
||||
### Host System Management
|
||||
|
||||
## 📦 Adding a New Application Stack
|
||||
|
||||
Adding a new application to the homelab is completely decentralized:
|
||||
|
||||
### 1. Create the App Directory
|
||||
```bash
|
||||
mkdir -p ~/Sites/homelab-myapp
|
||||
cd ~/Sites/homelab-myapp
|
||||
git init
|
||||
```
|
||||
# Rebuild and activate the NixOS host configuration (or use the 'nix-switch' alias)
|
||||
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
|
||||
|
||||
### 2. Create `app.yaml` Manifest
|
||||
Define the application metadata:
|
||||
```yaml
|
||||
name: "myapp"
|
||||
aliases:
|
||||
- "app"
|
||||
domain: "myapp.roadtotech.me"
|
||||
description: "My Awesome New Homelab App"
|
||||
visible: true
|
||||
auth: false
|
||||
networks:
|
||||
- proxy-net
|
||||
env:
|
||||
CUSTOM_VAR: "value"
|
||||
homepage:
|
||||
title: "My App"
|
||||
group: "Knowledge & Notes"
|
||||
icon: "custom.png"
|
||||
container: "myapp"
|
||||
weight: 50
|
||||
# Inspect platform systemd units
|
||||
systemctl status homeserver-core.service
|
||||
systemctl status homelab-appctl.service
|
||||
systemctl status homelab-gitops.service
|
||||
systemctl status dynu-monitor.service
|
||||
```
|
||||
|
||||
### 3. Create `docker-compose.yml`
|
||||
```yaml
|
||||
services:
|
||||
myapp:
|
||||
image: myapp/image:latest
|
||||
container_name: ${CONTAINER_NAME:-myapp}
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- proxy-net
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
# HTTPS Router
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.rule=Host(`${SERVICE_DOMAIN}`)"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.entrypoints=websecure"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.tls=true"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.service=${CONTAINER_NAME:-myapp}-svc"
|
||||
# HTTP to HTTPS Redirect
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}-red.rule=Host(`${SERVICE_DOMAIN}`)"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}-red.entrypoints=web"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}-red.middlewares=https-redirect@docker"
|
||||
# Service Target Port
|
||||
- "traefik.http.services.${CONTAINER_NAME:-myapp}-svc.loadbalancer.server.port=8080"
|
||||
|
||||
networks:
|
||||
proxy-net:
|
||||
name: ${PROXY_NETWORK:-proxy-net}
|
||||
external: true
|
||||
```
|
||||
|
||||
### 4. Deploy and Sync
|
||||
```bash
|
||||
appctl up myapp
|
||||
```
|
||||
`appctl` will start the container, inject standard environment variables, and automatically recompile [`homelab-dashboard/config/services.yaml`](file:///home/kiskaadee/Sites/homelab-dashboard/config/services.yaml).
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ NixOS Service Management
|
||||
## Documentation Index
|
||||
|
||||
The Core Control Plane runs as a native systemd unit managed declaratively by NixOS:
|
||||
|
||||
* **Service Unit:** `homeserver-core.service`
|
||||
* **Nix Module:** [`~/Config/hosts/desktop/homeserver.nix`](file:///home/kiskaadee/Config/hosts/desktop/homeserver.nix)
|
||||
* **Status Inspection:** `systemctl status homeserver-core`
|
||||
* **Logs:** `journalctl -u homeserver-core -f`
|
||||
* **Restart:** `sudo systemctl restart homeserver-core`
|
||||
| Document | Scope |
|
||||
| :--- | :--- |
|
||||
| [**`docs/architecture.md`**](docs/architecture.md) | Runtime layers, network segmentation, and Core / `~/Workloads` boundaries. |
|
||||
| [**`docs/decisions/README.md`**](docs/decisions/README.md) | Architecture Decision Records (MADR 4.0) governing platform evolution. |
|
||||
| [**`ROADMAP.md`**](ROADMAP.md) | Phased engineering milestones (P0–P7) and baseline-to-target architecture matrix. |
|
||||
| [**`docs/appctl.md`**](docs/appctl.md) | Current `appctl` CLI commands, resolution hierarchy, and `app.yaml` schema v1.0 contract. |
|
||||
| [**`docs/gitops.md`**](docs/gitops.md) | Webhook admission pipeline, HMAC verification, Compose AST validation, and locking. |
|
||||
| [**`docs/secrets-and-state.md`**](docs/secrets-and-state.md) | SOPS secret management, `/run/secrets/` projections, and persistent state paths. |
|
||||
| [**`docs/operations.md`**](docs/operations.md) | Day-2 operational runbook, updates, backups, and recovery procedures. |
|
||||
| [**`docs/setup_guide.md`**](docs/setup_guide.md) | Bare-metal NixOS installation and host bootstrapping guide. |
|
||||
| [**`SECURITY.md`**](SECURITY.md) | Security controls, Docker socket isolation, and threat model. |
|
||||
| [**`AGENTS.md`**](AGENTS.md) | Architectural invariants, TDD rules, and verification gates for contributors and agents. |
|
||||
|
||||
---
|
||||
|
||||
## 📄 License
|
||||
This repository is released into the public domain under the [Unlicense](LICENSE).
|
||||
## License
|
||||
|
||||
This repository is released into the public domain under [The Unlicense](UNLICENSE).
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
# 🗺️ Canopy — NixOS Core & Appctl Engineering Roadmap
|
||||
|
||||
This document serves as the repository-facing projection of the authoritative **Canopy Architecture Consolidation & Control Plane Roadmap (v6)** and the locked Milestone P4 boundary specification ([`docs/plans/p4-readiness-plan.md`](docs/plans/p4-readiness-plan.md)).
|
||||
|
||||
It describes the implementation trajectory and phased engineering milestones for evolving the **Canopy** platform (`canopy-homelab/nixos-core`) around a unified `appctl` Operational Control Plane.
|
||||
|
||||
> **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index ([ADR-0001: 3-Tier Provenance Model](docs/decisions/0001-3tier-architecture-and-provenance.md), [ADR-0002: Operational Control Plane Architecture](docs/decisions/0002-appctl-control-plane-architecture.md), [ADR-0003: Pydantic v2 Runtime Validation](docs/decisions/0003-pydantic-v2-runtime-validation.md), [ADR-0004: Unified ~/Workloads Monorepo](docs/decisions/0004-unified-workloads-monorepo.md), and [ADR-0005: Host-Granted Workload Capabilities](docs/decisions/0005-workload-capability-grants.md)).
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Architectural Invariants Governing Execution
|
||||
|
||||
1. **Git is the Authoritative Source of Deployment State**: All workload configurations are versioned in Git. `appctl` reconciles desired Git state into running containers.
|
||||
2. **One Logical API Across Dual Transports (`DEC-01`)**: The control-plane API is a single logical HTTP/1.1 command contract (`POST /v1/operations` + `GET /v1/health`) served identically over Unix domain socket (`/run/homelab/appctl.sock`) and loopback TCP (`127.0.0.1:9001`).
|
||||
3. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**: Entering via SSH does not bypass authentication. Every mutating operation and sensitive read (`workload.config`, `workload.logs`) requires an explicit Bearer token; tokenless local UDS calls fall back via `SO_PEERCRED` strictly to `homelab-viewer` read-only inspection.
|
||||
4. **Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)**: `homelab-appctl.service` executes as isolated user `homelab-appctl:homelab-operators` with mode `0600` append-only `/var/log/homelab/appctl/audit.jsonl`. Mutating operations abort immediately (`500 ERR_EXECUTION_FAILED`) if the pre-execution `DISPATCHED` audit write fails.
|
||||
5. **Unified Execution, Pre-Flight & Pure-Python Environment (`DEC-04`, `DEC-05`)**: Both CLI and GitOps worker paths execute through the daemon, enforcing Pydantic v2 manifest validation, `validate_compose_security()` AST checks, and inert pure-Python `.env` assembly (no shell `source` or `eval`).
|
||||
6. **Separation of Intent from Implementation**: Declarative manifests (`app.yaml` + Compose) versioned in Git capture workload intent and platform descriptors, materialized and enforced deterministically by `appctl`.
|
||||
7. **AI Authoring Boundary & External MCP Gateway**: AI agents operate externally as proposal generators via client-side Model Context Protocol (MCP) tool integrations. Humans approve intent before any mutation is applied in Git. The server appliance hosts zero autonomous agent loops or on-server compilers.
|
||||
8. **Secret Reference Invariant**: Deployment definitions store secret references (`secretKeyRef`), never plaintext material, resolved at runtime via `SecretProvider`.
|
||||
9. **Clean State Root**: Mutable application runtime data resides strictly under `~/var/lib/homelab/<app>/`, isolated from Git repositories.
|
||||
|
||||
---
|
||||
|
||||
## 🔍 Current Implementation Baseline vs. Target Architecture
|
||||
|
||||
| Architectural Area | Current Implementation Baseline (Milestone P4) | Target Architecture (Roadmap v6) |
|
||||
| :--- | :--- | :--- |
|
||||
| **`appctl` Architecture** | Dedicated daemon service (`homelab-appctl.service`, user `homelab-appctl`) exposing `POST /v1/operations` over Unix socket and loopback HTTP, with thin-client CLI (`scripts/appctl_cli.py`). | Expand with Operations UI and external ForwardAuth integration (P5–P7). |
|
||||
| **Operational Auth** | Mandatory SHA-256 Bearer token + 3-role RBAC + UDS `SO_PEERCRED` viewer fallback (`/run/secrets/appctl/tokens.json`). | LLDAP directory RBAC & Authelia ForwardAuth (P5). |
|
||||
| **Metadata & Schema Engine** | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | Standardized JSON-RPC Model Context Protocol tools over Pydantic v2 schemas (P6). |
|
||||
| **Deployment Model** | Authoritative declarative Git state (`app.yaml`, `docker-compose.yml`, `deployments.yaml`) in `~/Workloads/<app>/`, bounded by `homelab.workloadGrants` (`/etc/homelab/grants.json`). | Standardized JSON-RPC MCP tools (`P6`) and Operations UI (`P7`). |
|
||||
| **GitOps Engine** | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | Unified continuous deployment worker driven by Git webhooks delegating to control plane daemon (P4 baseline consolidated). |
|
||||
| **Secret Distribution** | Age-encrypted `nixos/secrets.yaml` decrypted by `sops-nix` to tmpfs `/run/secrets/`. | Host secrets remain in `sops-nix`; workload secrets referenced by key and projected via `SecretProvider` (planned in P5). |
|
||||
| **Dashboard** | `appctl sync` compiles `config/homepage/services.yaml` from `app.yaml` manifests under `_homepage_sync.lock`. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for management (planned in P7). |
|
||||
|
||||
---
|
||||
|
||||
## 📊 Milestone Overview
|
||||
|
||||
| Milestone | Title | Focus Area | Status | Deliverables Summary |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| **P0** | **Baseline Consolidation** | Git & Architecture | ✅ **Completed** | Synchronized `refactor/appctl-rework` with `main`, recorded control plane ADR, scaffolded v2 metadata engine. |
|
||||
| **P1** | **Mail Topology Realignment** | Topology & State | ✅ **Completed** | Re-homed Stalwart to the dedicated `smtp.` subdomain; migrated SnappyMail to `~/Sites/snappymail` with zero data loss. |
|
||||
| **P2** | **GitOps Hardening** | Ingress Security | ✅ **Completed** | Authoritative Core repository registry (`deployments.yaml`), Compose AST security validator, systemd sandboxing. |
|
||||
| **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0 with Pydantic v2 fail-closed models (`core_manifest.py`), two-axis status inspection, unified `appctl_engine.py`. |
|
||||
| **P4** | **Control Plane Daemon** | API & Dispatch | ✅ **Completed** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. |
|
||||
| **P4.5** | **Workloads Contract & Agent Readiness** | Monorepo & Grants | ✅ **Completed** *(in `nixos-core`)* | `~/Workloads/deployments.yaml` decoupling, read-only `agents` SSH user, `homelab.workloadGrants` (`ADR-0005`), `nixos/instance.example.nix`, and `:host` CI runner workflow. |
|
||||
| **P5** | **Identity & Secrets** | Auth & Providers | 🎯 **Current / Up Next** | LLDAP RBAC group mapping, Authelia ForwardAuth header integration, user-scoped token lifecycle, `SecretProvider` reference resolution. |
|
||||
| **P6** | **Homelab MCP Gateway** | Protocol Integration | ⏳ **Planned** | Standardized JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`), client-side human-in-the-loop approvals, deprecation of on-server AI proposal compilers. |
|
||||
| **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. |
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Detailed Milestones
|
||||
|
||||
### Milestone P0: Baseline Consolidation
|
||||
**Status**: ✅ **Completed**
|
||||
* Merged `refactor/appctl-rework` and `main` into a unified architectural baseline (commit `2297cd5`).
|
||||
* Modernized metadata engine with strongly-typed models (`SitesApp`, `CoreService`, `SourceConfig`) and Docker status inspection.
|
||||
* Formalized the control-plane ADR and consolidated roadmap; marked legacy roadmaps as superseded.
|
||||
* Verified test suite and NixOS flake sandbox evaluation.
|
||||
|
||||
---
|
||||
|
||||
### Milestone P1: Mail Topology Realignment & Zero-Data-Loss Migration
|
||||
**Status**: ✅ **Completed**
|
||||
* **Objective**: Segregate platform mail routing from user-facing webmail while preserving all user data and settings.
|
||||
* **Key Deliverables**:
|
||||
1. *State Freeze & Verified Snapshot*: Generate timestamped, SHA256-verified backup archive of `Core/config/snappymail/data`.
|
||||
2. *Workload Provisioning*: Scaffold `~/Sites/snappymail/` (Class B Image-Only workload) and provision persistent state root at `~/var/lib/homelab/snappymail/`.
|
||||
3. *Zero-Data-Loss State Replication*: Copy data using `cp -a` and prove byte parity (`diff -r`).
|
||||
4. *Stalwart Re-homing*: Updated Stalwart public endpoint in `Core/docker-compose.yml` to the configured `smtp.<domain>` subdomain; removed SnappyMail from Core stack.
|
||||
5. *Live Verification*: Verified webmail at the configured `mail.<domain>` endpoint, user logins, address books, IMAP/SMTP routing, and Diun SMTPS delivery on port 465.
|
||||
* **Exit Criteria**: 100% of user data survives cutover; mail flow and Diun alert delivery confirmed.
|
||||
|
||||
---
|
||||
|
||||
### Milestone P2: GitOps Privilege & Authority Hardening
|
||||
**Status**: ✅ **Completed**
|
||||
* **Objective**: Close remaining trust boundaries in the webhook continuous deployment engine.
|
||||
* **Key Deliverables**:
|
||||
1. *Authoritative Core Registry*: Establish `Core/config/deployments.yaml` as the sole authority for admitted deployment repositories.
|
||||
2. *Decouple Data Vault from Workload GitOps*: Evict vault special-casing (`BRAIN_DIR`) from GitOps engine; continuous deployment strictly manages Sites container workloads.
|
||||
3. *Compose AST Security Validator*: Pre-flight parser rejecting `privileged: true`, Docker socket bind mounts, host networking, and host mounts outside workload root or state root.
|
||||
4. *Systemd Sandboxing*: Apply `ProtectSystem=strict`, `ProtectHome=read-only`, `ReadWritePaths`, `NoNewPrivileges=true`, and private temporary directories to `homelab-gitops.service`.
|
||||
* **Exit Criteria**: Path traversal rejection tests pass; Compose AST security validator rejects prohibited capabilities.
|
||||
|
||||
---
|
||||
|
||||
### Milestone P3: Manifest Contract Convergence & Provenance Engine
|
||||
**Status**: ✅ **Completed**
|
||||
* **Objective**: Establish a single authoritative manifest schema and two-axis inspection engine across the platform.
|
||||
* **Key Deliverables**:
|
||||
1. *Schema v1.0 & Parser Library (`core_manifest.py`)*: Fail-closed Pydantic v2 manifest validation (`ConfigDict(extra="forbid")`), transport scheme validation (`https://`, `ssh://`, `git@`), and explicit ref semantics (moving branches vs. pinned tags vs. commit SHAs).
|
||||
2. *Two-Axis Inspection*: Local deployment checkout state (`✓ Synced`, `* Dirty`) evaluated independently of upstream software provenance (resolved via `git ls-remote` bounded by a 10s timeout during `--fetch`).
|
||||
3. *Engine Promotion & Cleanup*: Promoted unified engine to `scripts/appctl_engine.py`, retired `scripts/appctl_engine_v2.py` shim, and achieved zero Pyright static analysis warnings.
|
||||
* **Exit Criteria**: Manifest validation active in CI; all provenance resolution tests passing.
|
||||
|
||||
---
|
||||
|
||||
### Milestone P4: Appctl Control Plane Daemon & Command-Oriented API
|
||||
**Status**: ✅ **Completed**
|
||||
* **Objective**: Evolve `appctl` from a collection of local shell scripts into the authoritative platform daemon while enforcing authorization gates from day one.
|
||||
* **Key Deliverables**:
|
||||
1. *Daemon Service (`homelab-appctl.service`)*: Systemd daemon running as dedicated user `homelab-appctl` (`Group = "homelab-operators"`), exposing one logical HTTP/1.1 API across dual transports: Unix domain socket (`/run/homelab/appctl.sock`) on host and loopback HTTP listener (`127.0.0.1:9001`).
|
||||
2. *Mandatory Authorization Gate*: Enforce SOPS-projected SHA-256 Bearer tokens (`/run/secrets/appctl/tokens.json`) and 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`) for all mutations, sensitive reads (`workload.config`, `workload.logs`), and HTTP calls; restrict `SO_PEERCRED` on UDS to non-sensitive `homelab-viewer` inspection.
|
||||
3. *Command-Oriented Operational Router*: Single canonical command endpoint (`POST /v1/operations` + `GET /v1/health`) invoking `core_manifest.py`, `appctl_engine.py`, `validate_compose_security()`, and pure-Python `.env` assembly with per-target `flock` serialization and revision-consistent `workload.update` execution (unifying CLI and `gitops_dispatcher.py` worker execution).
|
||||
4. *Thin-Client CLI*: Re-implement `scripts/appctl` as a lightweight dispatch client communicating with the local daemon socket.
|
||||
5. *Append-Only Audit Log*: Record every mutating command, sensitive read, and denied request to `/var/log/homelab/appctl/audit.jsonl` with restricted `0600` permissions (`homelab-appctl`) and a fail-closed pre-execution disk guard. Telemetry captures `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, and `result`.
|
||||
* **Exit Criteria**: Hermetic API test suite passing; unauthenticated and unauthorized mutation attempts rejected across both transports; audit log capturing multi-dimensional telemetry under `homelab-appctl` isolation.
|
||||
|
||||
---
|
||||
|
||||
### Milestone P5: Identity, RBAC & SecretProvider Interface
|
||||
**Status**: ⏳ **Planned**
|
||||
* **Objective**: Expand the P4 authorization gate with directory-backed RBAC identity providers and dynamic secret projection.
|
||||
* **Key Deliverables**:
|
||||
1. *Identity Provider Integration*: Plug Traefik/Authelia trusted headers (`Remote-User`, `Remote-Groups`) for web requests, LLDAP user-scoped API token lifecycle for CLI requests, and HMAC-SHA256 verification for GitOps webhooks into the P4 authorization middleware.
|
||||
2. *Role-Based Authorization Engine*: Enforce LLDAP group-based access control (`homelab-admin`, `homelab-operator`, `homelab-viewer`).
|
||||
3. *SecretProvider Interface*: Control plane resolves secret references (`secretKeyRef`) at container runtime, eliminating Git history pollution for workload credentials.
|
||||
* **Exit Criteria**: RBAC permission matrix verified by automated tests; secret references correctly materialized into runtime environments.
|
||||
|
||||
---
|
||||
|
||||
### Milestone P6: Homelab MCP Gateway (Protocol Tool Integration)
|
||||
**Status**: ⏳ **Planned** *(Amended: Deprecated on-server `DeploymentProposal` compiler in favor of decoupled Model Context Protocol gateway)*
|
||||
* **Objective**: Expose `appctl` control plane capabilities over standardized JSON-RPC Model Context Protocol (MCP) tools for external AI assistants (Antigravity, Claude Code, Cursor) without running unverified autonomous agents on the appliance host.
|
||||
* **Key Deliverables**:
|
||||
1. *Protocol Tool Gateway*: Standardized MCP server wrapping deterministic `appctl` operations (`appctl_status`, `appctl_logs`, `appctl_deploy`, `appctl_audit`) over JSON-RPC.
|
||||
2. *Client-Side Human-in-the-Loop Confirmation*: Native IDE/client confirmation gating for all mutating tools before execution.
|
||||
3. *Deprecate On-Server AI Proposal Compiler*: Remove requirements for server-side `DeploymentProposal` $\to$ `DeploymentModel` pipelines; desired state remains standard Git-tracked declarative YAML (`app.yaml` + Compose).
|
||||
4. *Schema & Tool Security Guards*: Strict Pydantic parameter validation on incoming MCP tool calls matching `appctl_contracts.py`.
|
||||
* **Exit Criteria**: External AI clients successfully query status, inspect logs, and request deployments through MCP with strict confirmation gates; Core boundaries remain 100% deterministic with zero autonomous agent code on the host.
|
||||
|
||||
---
|
||||
|
||||
### Milestone P7: Operations UI & Dashboard Integration
|
||||
**Status**: ⏳ **Planned**
|
||||
* **Objective**: Deliver a unified web-based management experience without coupling the control plane to specific frontend engines.
|
||||
* **Key Deliverables**:
|
||||
1. *Operations UI Client*: Dedicated lightweight web client consuming the `appctl` API for workload inspection, deployment management, real-time log streaming, and API token management.
|
||||
2. *Homepage Status Integration*: Homepage consumes live status widgets from `appctl` live endpoints or compiled service maps.
|
||||
* **Exit Criteria**: End-to-end browser and CLI deployment verification; Homepage accurately reflecting live container health.
|
||||
|
||||
---
|
||||
|
||||
## 🔒 Verification & Quality Gates
|
||||
|
||||
Progress across milestones is governed by explicit verification criteria:
|
||||
* **Behavioral Invariant Coverage**: All defined domain, authorization, deployment, and security invariants must have automated regression tests.
|
||||
* **Pre-Merge Validation**: Every commit must pass `./scripts/run-tests` (Ruff linter + Pytest suite + Nix flake check).
|
||||
* **Zero Production Regressions**: Platform migrations must include verified pre-flight snapshots, state parity proofs, and documented rollback runbooks.
|
||||
+59
-41
@@ -1,53 +1,71 @@
|
||||
# Security Policy & Hardening Overview
|
||||
# 🛡️ Canopy NixOS Core — Security Controls & Hardening
|
||||
|
||||
This document outlines the security posture of the **Hardened Private Cloud Hub** and provides guidance on maintaining a secure environment.
|
||||
|
||||
## 🛡️ Implemented Hardening Measures
|
||||
|
||||
### 1. Docker Socket Isolation (Socket-Proxy)
|
||||
The most critical security feature. No container (including Traefik or Portainer) has direct access to the host's `/var/run/docker.sock`.
|
||||
- **Mechanism**: The `socket-proxy` container is the *only* one with access to the real socket.
|
||||
- **Filtering**: It uses HAProxy to filter API calls. Traefik can see containers and networks but cannot create/delete them. Management tools like Watchtower are granted specific POST/DELETE permissions only through this proxy.
|
||||
- **Benefit**: Even if an attacker compromises Traefik, they cannot use the Docker API to spin up a privileged container and take over the host (a common "container breakout" attack).
|
||||
|
||||
### 2. Identity & Access Management (Authelia)
|
||||
- **SSO**: All management tools (Traefik Dash, Dozzle, Portainer) and critical apps (Gitea) are behind Authelia.
|
||||
- **2FA Support**: Authelia supports TOTP (Google Authenticator, etc.) and FIDO2 (Yubikey).
|
||||
- **Forward Auth**: Traefik intercepts all requests and validates the session with Authelia before the request ever reaches the target app.
|
||||
|
||||
### 3. Network Segmentation
|
||||
- **`proxy-net`**: Shared network for Traefik to route traffic to apps.
|
||||
- **`socket-net`**: Highly restricted network for infrastructure-to-socket communication. Application containers are **not** members of this network.
|
||||
|
||||
### 4. Automated Maintenance
|
||||
- **Watchtower**: Automatically updates containers when new security patches are released for their images.
|
||||
This document outlines the security controls, container isolation rules, and operational boundaries implemented in **Canopy NixOS Core** (`canopy-homelab/nixos-core`).
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Potential Attack Vectors & Concerns
|
||||
## 1. Implemented Security Controls
|
||||
|
||||
Despite the hardening, you should remain vigilant about the following:
|
||||
### A. Docker Socket Isolation (`socket-proxy`)
|
||||
* Direct container mounts of `/var/run/docker.sock` are restricted.
|
||||
* Only the dedicated `socket-proxy` container mounts `/var/run/docker.sock:ro`.
|
||||
* State-modifying and execution API endpoints are disabled in HAProxy (`POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`, `COMMIT=0`, `CONFIGS=0`, `DISTRIBUTION=0`, `NODES=0`, `PLUGINS=0`, `SECRETS=0`, `SWARM=0`, `SYSTEM=0`).
|
||||
* Traefik and Dozzle query Docker metrics and metadata via `tcp://socket-proxy:2375` rather than direct socket mounts.
|
||||
|
||||
### 1. Host-Level Security (The Foundation)
|
||||
If an attacker gains SSH access to your Arch Linux host, they have total control.
|
||||
- **Action**: Use SSH Keys only (disable password login). Install `fail2ban`. Keep the host kernel updated (`pacman -Syu`).
|
||||
### B. Identity & Access Management (`lldap` & `authelia`)
|
||||
* **Directory Service**: User accounts and group memberships are stored in LLDAP (`users.${HOMELAB_DOMAIN}`).
|
||||
* **ForwardAuth**: Traefik intercepts incoming HTTP/HTTPS requests and validates sessions with Authelia (`auth.${HOMELAB_DOMAIN}`) before routing to protected backends.
|
||||
* **MFA Support**: Supports TOTP and FIDO2 authentication.
|
||||
|
||||
### 2. Application-Specific Vulnerabilities
|
||||
A zero-day exploit in Gitea or Ollama could allow an attacker to execute code *inside* that specific container.
|
||||
- **Mitigation**: Containers run as non-root users where possible. The `socket-proxy` ensures they cannot escape to the host easily.
|
||||
### C. Network Segmentation
|
||||
* **`proxy-net`**: Bridge network connecting Traefik to backend application containers.
|
||||
* **`socket-net`**: Restricted bridge network connecting infrastructure daemons to `socket-proxy`. Workload applications in `~/Sites` are not attached to `socket-net`.
|
||||
|
||||
### 3. Let's Encrypt / ACME Exposure
|
||||
The `acme.json` file contains your private keys.
|
||||
- **Action**: This file is restricted to `chmod 600`. Never share it or commit it to version control.
|
||||
### D. Webhook Admission Controls
|
||||
* **HMAC-SHA256 Signatures**: Webhook requests are verified using `hmac.compare_digest` against `/run/secrets/gitops/webhook_secret`.
|
||||
* **Trusted Name Resolution**: Webhook payloads specify logical repository names; filesystem path traversal (`..`, `/`) and symlink escapes are rejected.
|
||||
* **Non-Shell Execution**: Deployment commands execute as fixed argument lists without `shell=True`. Custom shell commands fail validation closed.
|
||||
* **Revision-Consistent Validation**: Manifest deployment policy is re-validated directly on the deployed commit immediately post-pull.
|
||||
|
||||
### 4. Denial of Service (DDoS)
|
||||
Home connections are vulnerable to bandwidth saturation.
|
||||
- **Mitigation**: Consider using a Cloudflare Tunnel or a VPS-based "Entry Node" if you expect high traffic or targeted attacks.
|
||||
### E. Declarative Secrets Encryption (`sops-nix`)
|
||||
* Secrets are stored encrypted in `nixos/secrets.yaml` using Age keys derived from the host SSH key (`/etc/ssh/ssh_host_ed25519_key`).
|
||||
* Decrypted secrets reside in RAM-backed ephemeral filesystems (`/run/secrets/`, `/run/credentials/`) and are not committed to unencrypted persistent files.
|
||||
|
||||
### F. Operational Control Plane Security (`homelab-appctl.service`)
|
||||
* **Transport Isolation**: Daemon listens on a restricted Unix Domain Socket (`/run/homelab/appctl.sock`, mode `0660`, group `homelab-operators`) and loopback HTTP (`127.0.0.1:9876`). It never binds to public interfaces.
|
||||
* **Authentication & RBAC**:
|
||||
- **UDS Peer Credential Identification**: Local connections inspect kernel peer credentials (`SO_PEERCRED`). Callers in `homelab-operators` or `wheel` receive read-only viewer privileges automatically without requiring secrets on disk.
|
||||
- **Cryptographic Bearer Tokens**: Mutating actions require Bearer tokens defined in SOPS (`/run/secrets/appctl/tokens.json`). Tokens are validated using `hmac.compare_digest` against SHA-256 digests.
|
||||
- **Three-Tier RBAC**: Granular role enforcement distinguishes read-only inspectors (`viewer`), workload managers (`operator`), and core platform administrators (`admin`).
|
||||
* **Per-Target Concurrency Control (`flock`)**: Non-blocking file locks (`/run/lock/homelab/<target>.lock`) serialize mutating actions per workload, returning HTTP 409 Conflict if an operation is already in flight.
|
||||
* **Fail-Closed Structured Audit Logging**: Every operational command is appended synchronously to a tamper-evident audit log (`/var/log/homelab/appctl/audit.jsonl`, mode `0600`). If disk writing fails, the daemon fails closed and rejects the request.
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Security Checklist for Production
|
||||
- [ ] Replace all placeholder secrets in `infra/authelia/.env`.
|
||||
- [ ] Hash your user passwords in `infra/authelia/config/users.yml` using `docker run --rm authelia/authelia authelia crypto hash generate pbkdf2 --password "your_password_here"`.
|
||||
- [ ] Disable Traefik/Authelia access from the public internet if only local use is needed (via Firewall/IP Whitelisting).
|
||||
- [ ] Ensure `acme.json` is backed up securely but kept private.
|
||||
## 2. Threat Model & Operational Considerations
|
||||
|
||||
### Host Access
|
||||
* SSH root login is disabled (`PermitRootLogin = "no"`). Access is authenticated via ED25519 public keys.
|
||||
* Unneeded services (such as printing, bluetooth, sleep/suspend targets) are disabled at the NixOS configuration level.
|
||||
|
||||
### ACME Certificates
|
||||
* Let's Encrypt keys in `config/letsencrypt/acme.json` are maintained with mode `0600`.
|
||||
|
||||
### Workload Containment
|
||||
* Applications run in dedicated containers attached to `proxy-net`.
|
||||
* Application manifests cannot request arbitrary host commands through the GitOps engine.
|
||||
|
||||
---
|
||||
|
||||
## 3. Verification Checklist
|
||||
|
||||
- [x] Secrets encrypted in `nixos/secrets.yaml` via Age / SOPS.
|
||||
- [x] User identities managed in LLDAP (`users.${HOMELAB_DOMAIN}`).
|
||||
- [x] `socket-proxy` configured with `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`.
|
||||
- [x] Webhook HMAC signature verification active on port 9000.
|
||||
- [x] Invariant test runner (`./scripts/run-tests`) passing on changes.
|
||||
- [x] `config/letsencrypt/acme.json` permissions set to `0600`.
|
||||
- [x] Host firewall ports restricted to declared services in `nixos/modules/homeserver.nix`.
|
||||
- [x] Control plane daemon (`homelab-appctl.service`) isolated to UDS (`0660`) and loopback HTTP.
|
||||
- [x] Operational audit log (`/var/log/homelab/appctl/audit.jsonl`) append-only with strict `0600` permissions.
|
||||
- [x] Control plane mutation endpoints enforce per-target `flock` and SHA-256 Bearer tokens.
|
||||
@@ -8,22 +8,39 @@ totp:
|
||||
issuer: authelia.com
|
||||
|
||||
authentication_backend:
|
||||
file:
|
||||
path: /config/users.yml
|
||||
ldap:
|
||||
implementation: custom
|
||||
address: 'ldap://lldap:3890'
|
||||
timeout: 5s
|
||||
start_tls: false
|
||||
base_dn: '{{ env "LLDAP_LDAP_BASE_DN" }}'
|
||||
additional_users_dn: 'ou=people'
|
||||
users_filter: '(&({username_attribute}={input})(objectClass=person))'
|
||||
additional_groups_dn: 'ou=groups'
|
||||
groups_filter: '(member={dn})'
|
||||
attributes:
|
||||
distinguished_name: 'dn'
|
||||
username: 'uid'
|
||||
display_name: 'displayName'
|
||||
mail: 'mail'
|
||||
group_name: 'cn'
|
||||
user: 'uid=admin,ou=people,{{ env "LLDAP_LDAP_BASE_DN" }}'
|
||||
|
||||
access_control:
|
||||
default_policy: deny
|
||||
rules:
|
||||
- domain: 'auth.{{ env "DOMAIN" }}'
|
||||
policy: bypass
|
||||
- domain: 'users.{{ env "DOMAIN" }}'
|
||||
policy: one_factor
|
||||
- domain: '*.{{ env "DOMAIN" }}'
|
||||
policy: one_factor
|
||||
|
||||
session:
|
||||
name: authelia_session
|
||||
secret: '{{ env "AUTHELIA_SESSION_SECRET" }}'
|
||||
expiration: 3600
|
||||
inactivity: 300
|
||||
expiration: 7d
|
||||
inactivity: 3d
|
||||
remember_me: 1M
|
||||
cookies:
|
||||
- domain: '{{ env "DOMAIN" }}'
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Example Repository Identity Registry Template
|
||||
# Live production deployments are configured in ~/Workloads/deployments.yaml
|
||||
# (or overridden via the HOMELAB_DEPLOYMENTS_FILE environment variable).
|
||||
#
|
||||
# Owns: repository identity, canonical filesystem path, and aliases.
|
||||
# Enforces: strict path containment within ~/Workloads (WORKLOADS_DIR).
|
||||
|
||||
schemaVersion: "1.0"
|
||||
repositories:
|
||||
example-app:
|
||||
path: "~/Workloads/example-app"
|
||||
aliases:
|
||||
- "example"
|
||||
- "homelab-example"
|
||||
example-docs:
|
||||
path: "~/Workloads/example-docs"
|
||||
aliases:
|
||||
- "docs"
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
# For configuration options and examples, please see:
|
||||
# https://gethomepage.dev/configs/bookmarks
|
||||
|
||||
- My Projects:
|
||||
- Github:
|
||||
- abbr: GH
|
||||
href: https://github.com
|
||||
|
||||
- Social Media:
|
||||
- Instagram:
|
||||
- abbr: IN
|
||||
href: https://www.instagram.com/tierraenmisbotas//
|
||||
|
||||
- Learning Content:
|
||||
- YouTube:
|
||||
- abbr: YT
|
||||
href: https://www.youtube.com/@scicreep8979
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
# For configuration options and examples, please see:
|
||||
# https://gethomepage.dev/configs/docker/
|
||||
|
||||
my-docker:
|
||||
host: socket-proxy
|
||||
port: 2375
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 412 449" fill="#ffffff"><path d="M54.4 370a373 373 0 0036.6 16.5c42.9 16.5 81 27 127 32.7 39 4.9 98 6.1 134-9.7l.2-28.7 10.9-4.2.1 7.6c.1 9.5 10.2 10 10.1 16.6l-.2 19.5a10.9 10.9 0 01-5.3 8.8 126 126 0 01-34.7 13.1c-27.4 5.9-54.8 7.6-83 6.1a502 502 0 01-114.8-19.3C98.3 418.3 63.3 404.2 30.4 384.4c-1.8-1.1-4.6-4.1-4.6-5.8l.5-25.2 11-8.4c1.5-34.5-.5-23-14.7-49.9C-4.9 243.1-6.6 188.6 13.7 132.1c9.6 20.2 21.2 38.3 37.4 52.9C37.7 162.7 27.2 140 22.1 114.6 58.6 40.2 137.3-5.7 220.2.6c51 3.8 94.2 25.6 130.4 62-12-3.2-22.2-5.6-33.7-6.8-41.1-31.1-89.5-44.9-140.7-36.2-20.9 3.5-34 7-50.7 16.9l14.1-2.5 15.9-2.8c8.5-1.5 24.6-1 33.8-.2 22.7 2.1 53.6 13.7 71.7 29-12.6 3.8-24.8 7-37.2 12.5-54.8 24.4-99.9 64.9-131 115.9-7.9-2.9-15.5-4.4-23.5-2.5 29.8 6 39 41.1 31.8 68-2.4 9-7.4 16.2-14.7 22.4a346.5 346.5 0 00147.3 97.2l12 21.2c1.8 3.3.4 10.1.3 14.5-54.7-3.5-108.5-14.2-157.9-37.6l-33.3-15.8a55.5 55.5 0 00-.3 14.3m15.8-103.6c8.8-2.1 12.7-9.2 15.7-16.5 4-13 2.4-27.4-5.3-38.7-5.4-7.8-14.8-12.2-23.8-9.3a20.8 20.8 0 00-13.4 12.7c8.4-7.9 19.2-8.3 27.1-.2 12.6 13.1 13.3 38-.3 52M56.2 335.7c19.3 9.7 37.1 17.6 57.6 25.6l.5-41c0-5.6-7.1-8.2-10.9-7.4-13.3 2.7-5.9 17.1-8 29.2l-39.8-19.4c-1 4.6-1.3 9.4.6 13m139.6 48.3c1.1-4.4 1.2-8.7-.8-11.5a513 513 0 01-66-18 16.3 16.3 0 00-.1 12.2c8.3 2.7 16.2 5.3 24.7 7.3z"/><path d="M326 373.5c-78.7 7.3-171.3-41.7-224.8-98.7 21-21.4 19.6-56.4 1.4-79.5 14.1-22 29.7-42 48.5-59.7C194 95.2 252.8 65.2 312.9 67.5c31.5 1.8 71.1 11.3 70.5 49.8a215.2 215.2 0 017.4 201.1c3.6 38.3-33.5 51.8-64.9 55.1m-156.6-69.6c44.6 29.3 106.3 54.1 159.9 46.5 8.5-1.2 16.5-3.9 24.6-6.3 5-1.5 7.1-5.2 9.6-9 48.2-74.2 42.9-170.7-13.8-238.4C301.1 78.6 245.2 94.2 203 121.5c-17 11-32.9 23.2-46.2 38.5-14.8 17-20.8 39.2-21.9 61.4-1.2 23.5 5.3 45.1 17.5 64.8a53.6 53.6 0 0017 17.8"/><path d="M298.5 409.1c-4.5.4-7.9-1.7-9.4-5.2a12.3 12.3 0 011.1-11c1.5-2.5 5.4-4.9 8.9-5.2l31.9-2.5a8.6 8.6 0 019.3 6.1c.9 3.4.5 9.3-3.5 10.6-12.4 4.1-24.7 6-38.3 7.2"/><rect width="15.3" height="16.2" x="258.6" y="409.9" rx="0" transform="rotate(-89.7 266.3 418)"/><path d="M370.4 283.3c-6.1 17.6-13.5 33.4-26.4 47.2 26-57.7 30.3-124.2 4.1-182.3-6.7-14.8-15-27.3-24.8-41 5.1.8 13 .9 17 4.2 7.8 6.5 12.5 15.5 17.4 24.5 24.5 45.2 29.8 98.2 12.7 147.5"/></svg>
|
||||
|
After Width: | Height: | Size: 2.2 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 412 449" fill="#ffffff"><path d="M54.4 370a373 373 0 0036.6 16.5c42.9 16.5 81 27 127 32.7 39 4.9 98 6.1 134-9.7l.2-28.7 10.9-4.2.1 7.6c.1 9.5 10.2 10 10.1 16.6l-.2 19.5a10.9 10.9 0 01-5.3 8.8 126 126 0 01-34.7 13.1c-27.4 5.9-54.8 7.6-83 6.1a502 502 0 01-114.8-19.3C98.3 418.3 63.3 404.2 30.4 384.4c-1.8-1.1-4.6-4.1-4.6-5.8l.5-25.2 11-8.4c1.5-34.5-.5-23-14.7-49.9C-4.9 243.1-6.6 188.6 13.7 132.1c9.6 20.2 21.2 38.3 37.4 52.9C37.7 162.7 27.2 140 22.1 114.6 58.6 40.2 137.3-5.7 220.2.6c51 3.8 94.2 25.6 130.4 62-12-3.2-22.2-5.6-33.7-6.8-41.1-31.1-89.5-44.9-140.7-36.2-20.9 3.5-34 7-50.7 16.9l14.1-2.5 15.9-2.8c8.5-1.5 24.6-1 33.8-.2 22.7 2.1 53.6 13.7 71.7 29-12.6 3.8-24.8 7-37.2 12.5-54.8 24.4-99.9 64.9-131 115.9-7.9-2.9-15.5-4.4-23.5-2.5 29.8 6 39 41.1 31.8 68-2.4 9-7.4 16.2-14.7 22.4a346.5 346.5 0 00147.3 97.2l12 21.2c1.8 3.3.4 10.1.3 14.5-54.7-3.5-108.5-14.2-157.9-37.6l-33.3-15.8a55.5 55.5 0 00-.3 14.3m15.8-103.6c8.8-2.1 12.7-9.2 15.7-16.5 4-13 2.4-27.4-5.3-38.7-5.4-7.8-14.8-12.2-23.8-9.3a20.8 20.8 0 00-13.4 12.7c8.4-7.9 19.2-8.3 27.1-.2 12.6 13.1 13.3 38-.3 52M56.2 335.7c19.3 9.7 37.1 17.6 57.6 25.6l.5-41c0-5.6-7.1-8.2-10.9-7.4-13.3 2.7-5.9 17.1-8 29.2l-39.8-19.4c-1 4.6-1.3 9.4.6 13m139.6 48.3c1.1-4.4 1.2-8.7-.8-11.5a513 513 0 01-66-18 16.3 16.3 0 00-.1 12.2c8.3 2.7 16.2 5.3 24.7 7.3z"/><path d="M326 373.5c-78.7 7.3-171.3-41.7-224.8-98.7 21-21.4 19.6-56.4 1.4-79.5 14.1-22 29.7-42 48.5-59.7C194 95.2 252.8 65.2 312.9 67.5c31.5 1.8 71.1 11.3 70.5 49.8a215.2 215.2 0 017.4 201.1c3.6 38.3-33.5 51.8-64.9 55.1m-156.6-69.6c44.6 29.3 106.3 54.1 159.9 46.5 8.5-1.2 16.5-3.9 24.6-6.3 5-1.5 7.1-5.2 9.6-9 48.2-74.2 42.9-170.7-13.8-238.4C301.1 78.6 245.2 94.2 203 121.5c-17 11-32.9 23.2-46.2 38.5-14.8 17-20.8 39.2-21.9 61.4-1.2 23.5 5.3 45.1 17.5 64.8a53.6 53.6 0 0017 17.8"/><path d="M298.5 409.1c-4.5.4-7.9-1.7-9.4-5.2a12.3 12.3 0 011.1-11c1.5-2.5 5.4-4.9 8.9-5.2l31.9-2.5a8.6 8.6 0 019.3 6.1c.9 3.4.5 9.3-3.5 10.6-12.4 4.1-24.7 6-38.3 7.2"/><rect width="15.3" height="16.2" x="258.6" y="409.9" rx="0" transform="rotate(-89.7 266.3 418)"/><path d="M370.4 283.3c-6.1 17.6-13.5 33.4-26.4 47.2 26-57.7 30.3-124.2 4.1-182.3-6.7-14.8-15-27.3-24.8-41 5.1.8 13 .9 17 4.2 7.8 6.5 12.5 15.5 17.4 24.5 24.5 45.2 29.8 98.2 12.7 147.5"/></svg>
|
||||
|
After Width: | Height: | Size: 2.2 KiB |
@@ -0,0 +1,2 @@
|
||||
---
|
||||
# sample kubernetes config
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
# pve:
|
||||
# url: https://proxmox.host.or.ip:8006
|
||||
# token: username@pam!Token ID
|
||||
# secret: secret
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
# Example Homepage services configuration
|
||||
# Note: In active homelab deployments, config/services.yaml is auto-generated by `appctl sync`.
|
||||
- Knowledge & Notes:
|
||||
- Docs-Viewer:
|
||||
icon: files.png
|
||||
href: https://docs.example.test
|
||||
description: Reactive Obsidian & Markdown Documentation Viewer
|
||||
server: my-docker
|
||||
container: docs
|
||||
- Excalidraw:
|
||||
icon: excalidraw.png
|
||||
href: https://excalidraw.example.test
|
||||
description: Collaborative Whiteboarding & Sketching Tool
|
||||
server: my-docker
|
||||
container: excalidraw
|
||||
|
||||
- Media & Productivity:
|
||||
- Jellyfin:
|
||||
icon: jellyfin.png
|
||||
href: https://jellyfin.example.test
|
||||
description: Media Server & Streaming Hub
|
||||
server: my-docker
|
||||
container: jellyfin
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
# For configuration options and examples, please see:
|
||||
# https://gethomepage.dev/configs/settings/
|
||||
|
||||
providers:
|
||||
openweathermap: openweathermapapikey
|
||||
weatherapi: weatherapiapikey
|
||||
@@ -0,0 +1,11 @@
|
||||
---
|
||||
# For configuration options and examples, please see:
|
||||
# https://gethomepage.dev/configs/info-widgets/
|
||||
|
||||
- resources:
|
||||
cpu: true
|
||||
memory: true
|
||||
|
||||
- search:
|
||||
provider: google
|
||||
target: _blank
|
||||
Whitespace-only changes.
Whitespace-only changes.
+131
-31
@@ -3,6 +3,8 @@ services:
|
||||
image: tecnativa/docker-socket-proxy
|
||||
container_name: socket-proxy
|
||||
restart: always
|
||||
ports:
|
||||
- "127.0.0.1:2375:2375"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
environment:
|
||||
@@ -42,7 +44,7 @@ services:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
environment:
|
||||
- DYNU_API_KEY=${DYNU_API_KEY}
|
||||
- CF_DNS_API_TOKEN=${CF_DNS_API_TOKEN}
|
||||
- DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40}
|
||||
command:
|
||||
- "--log.level=INFO"
|
||||
@@ -59,7 +61,7 @@ services:
|
||||
- "--entrypoints.websecure.http.tls.domains[0].sans=*.${DOMAIN}"
|
||||
# SSL Setup
|
||||
- "--certificatesresolvers.myresolver.acme.dnschallenge=true"
|
||||
- "--certificatesresolvers.myresolver.acme.dnschallenge.provider=dynu"
|
||||
- "--certificatesresolvers.myresolver.acme.dnschallenge.provider=cloudflare"
|
||||
- "--certificatesresolvers.myresolver.acme.email=${ACME_EMAIL}"
|
||||
- "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"
|
||||
volumes:
|
||||
@@ -79,6 +81,11 @@ services:
|
||||
- "traefik.http.middlewares.authelia-auth.forwardauth.trustForwardHeader=true"
|
||||
- "traefik.http.middlewares.authelia-auth.forwardauth.authResponseHeaders=Remote-User,Remote-Groups,Remote-Email,Remote-Name"
|
||||
|
||||
# Middleware: Public Rate Limit (mitigates scraper/crawler bursts on public routes)
|
||||
- "traefik.http.middlewares.public-ratelimit.ratelimit.average=20"
|
||||
- "traefik.http.middlewares.public-ratelimit.ratelimit.burst=40"
|
||||
- "traefik.http.middlewares.public-ratelimit.ratelimit.period=1s"
|
||||
|
||||
# Dashboard - Public (HTTPS)
|
||||
- "traefik.http.routers.traefik-dash.rule=Host(`traefik.${DOMAIN}`)"
|
||||
- "traefik.http.routers.traefik-dash.entrypoints=websecure"
|
||||
@@ -99,18 +106,54 @@ services:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
lldap:
|
||||
image: nitnelave/lldap:stable
|
||||
container_name: lldap
|
||||
restart: always
|
||||
environment:
|
||||
- TZ=America/Bogota
|
||||
- LLDAP_HTTP_URL=https://users.${DOMAIN}
|
||||
- LLDAP_LDAP_BASE_DN=${LLDAP_LDAP_BASE_DN:-dc=example,dc=test}
|
||||
- LLDAP_JWT_SECRET=${LLDAP_JWT_SECRET}
|
||||
- LLDAP_KEY_SEED=${LLDAP_KEY_SEED}
|
||||
- LLDAP_LDAP_USER_PASS=${LLDAP_LDAP_USER_PASS}
|
||||
- LLDAP_LDAP_USER_EMAIL=${LLDAP_ADMIN_EMAIL:-admin@${DOMAIN:-example.test}}
|
||||
- LLDAP_DATABASE_URL=sqlite:///data/users.db?mode=rwc
|
||||
volumes:
|
||||
- ./config/lldap/data:/data
|
||||
networks:
|
||||
- proxy-net
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
# Public (HTTPS)
|
||||
- "traefik.http.routers.lldap.rule=Host(`users.${DOMAIN}`)"
|
||||
- "traefik.http.routers.lldap.entrypoints=websecure"
|
||||
- "traefik.http.routers.lldap.tls=true"
|
||||
- "traefik.http.routers.lldap.tls.certresolver=myresolver"
|
||||
- "traefik.http.routers.lldap.service=lldap-svc"
|
||||
- "traefik.http.routers.lldap.middlewares=authelia-auth@docker"
|
||||
# Public (Redirect)
|
||||
- "traefik.http.routers.lldap-red.rule=Host(`users.${DOMAIN}`)"
|
||||
- "traefik.http.routers.lldap-red.entrypoints=web"
|
||||
- "traefik.http.routers.lldap-red.middlewares=https-redirect@docker"
|
||||
- "traefik.http.services.lldap-svc.loadbalancer.server.port=17170"
|
||||
|
||||
authelia:
|
||||
image: authelia/authelia:latest
|
||||
container_name: authelia
|
||||
restart: always
|
||||
user: "1000:100"
|
||||
depends_on:
|
||||
- lldap
|
||||
volumes:
|
||||
- ./config/authelia:/config
|
||||
- /run/secrets/rendered/users.yml:/config/users.yml:ro
|
||||
environment:
|
||||
- DOMAIN=${DOMAIN}
|
||||
- LLDAP_LDAP_BASE_DN=${LLDAP_LDAP_BASE_DN}
|
||||
- AUTHELIA_SESSION_SECRET=${AUTHELIA_SESSION_SECRET}
|
||||
- AUTHELIA_STORAGE_ENCRYPTION_KEY=${AUTHELIA_STORAGE_ENCRYPTION_KEY}
|
||||
- AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET=${AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET}
|
||||
- AUTHELIA_AUTHENTICATION_BACKEND_LDAP_PASSWORD=${AUTHELIA_LDAP_PASSWORD:-${LLDAP_LDAP_USER_PASS}}
|
||||
- X_AUTHELIA_CONFIG_FILTERS=template
|
||||
networks:
|
||||
- proxy-net
|
||||
@@ -126,31 +169,6 @@ services:
|
||||
- "traefik.http.routers.authelia-red.entrypoints=web"
|
||||
- "traefik.http.routers.authelia-red.middlewares=https-redirect@docker"
|
||||
|
||||
portainer:
|
||||
image: portainer/portainer-ce:latest
|
||||
container_name: portainer
|
||||
restart: always
|
||||
command: -H tcp://socket-proxy:2375
|
||||
volumes:
|
||||
- portainer_data:/data
|
||||
networks:
|
||||
- socket-net
|
||||
- proxy-net
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
# Public (HTTPS)
|
||||
- "traefik.http.routers.portainer.rule=Host(`portainer.${DOMAIN}`)"
|
||||
- "traefik.http.routers.portainer.entrypoints=websecure"
|
||||
- "traefik.http.routers.portainer.tls=true"
|
||||
- "traefik.http.routers.portainer.tls.certresolver=myresolver"
|
||||
- "traefik.http.routers.portainer.middlewares=authelia-auth@docker"
|
||||
- "traefik.http.routers.portainer.service=portainer-svc"
|
||||
# Public (Redirect)
|
||||
- "traefik.http.routers.portainer-red.rule=Host(`portainer.${DOMAIN}`)"
|
||||
- "traefik.http.routers.portainer-red.entrypoints=web"
|
||||
- "traefik.http.routers.portainer-red.middlewares=https-redirect@docker"
|
||||
- "traefik.http.services.portainer-svc.loadbalancer.server.port=9000"
|
||||
|
||||
dozzle:
|
||||
image: amir20/dozzle:latest
|
||||
container_name: dozzle
|
||||
@@ -158,6 +176,10 @@ services:
|
||||
environment:
|
||||
- DOCKER_HOST=tcp://socket-proxy:2375
|
||||
- DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40}
|
||||
- DOZZLE_AUTH_PROVIDER=forward-proxy
|
||||
- DOZZLE_AUTH_LOGOUT_URL=https://auth.${DOMAIN}/logout
|
||||
volumes:
|
||||
- dozzle_data:/data
|
||||
networks:
|
||||
- proxy-net
|
||||
- socket-net
|
||||
@@ -192,19 +214,96 @@ services:
|
||||
container_name: diun
|
||||
restart: always
|
||||
command: serve
|
||||
depends_on:
|
||||
- socket-proxy
|
||||
- stalwart
|
||||
environment:
|
||||
- TZ=UTC
|
||||
- LOG_LEVEL=info
|
||||
- LOG_JSON=false
|
||||
- DIUN_WATCH_WORKERS=20
|
||||
- DIUN_WATCH_WORKERS=6
|
||||
- DIUN_WATCH_JITTER=30s
|
||||
- DIUN_WATCH_SCHEDULE=0 */6 * * *
|
||||
- DIUN_PROVIDERS_DOCKER=true
|
||||
- DIUN_PROVIDERS_DOCKER_ENDPOINT=tcp://socket-proxy:2375
|
||||
- DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40}
|
||||
- DIUN_PROVIDERS_DOCKER_WATCHBYDEFAULT=true
|
||||
- DIUN_PROVIDERS_DOCKER_APIVERSION=${DOCKER_API_VERSION:-1.40}
|
||||
- DIUN_NOTIF_MAIL_HOST=stalwart
|
||||
- DIUN_NOTIF_MAIL_PORT=465
|
||||
- DIUN_NOTIF_MAIL_USERNAME=${DIUN_NOTIF_MAIL_USERNAME:-notifier@${DOMAIN:-example.test}}
|
||||
- DIUN_NOTIF_MAIL_PASSWORD=${DIUN_SMTP_PASSWORD}
|
||||
- DIUN_NOTIF_MAIL_SSL=true
|
||||
- DIUN_NOTIF_MAIL_INSECURESKIPVERIFY=true
|
||||
- DIUN_NOTIF_MAIL_FROM=${DIUN_NOTIF_MAIL_FROM:-notifier@${DOMAIN:-example.test}}
|
||||
- DIUN_NOTIF_MAIL_TO=${DIUN_NOTIF_MAIL_TO:-operator@${DOMAIN:-example.test}}
|
||||
volumes:
|
||||
- ./config/diun:/data
|
||||
networks:
|
||||
- socket-net
|
||||
- proxy-net
|
||||
|
||||
stalwart:
|
||||
image: stalwartlabs/stalwart:v0.16.22
|
||||
container_name: stalwart
|
||||
restart: always
|
||||
depends_on:
|
||||
- lldap
|
||||
ports:
|
||||
- "25:25" # Inbound SMTP (receiving mail)
|
||||
- "465:465" # SMTPS (Submission with implicit TLS)
|
||||
- "587:587" # SMTP Submission (STARTTLS for mail clients)
|
||||
- "993:993" # IMAPS (Encrypted IMAP for Thunderbird/mobile)
|
||||
- "4190:4190" # ManageSieve (Server-side mail rules)
|
||||
volumes:
|
||||
- ./config/stalwart/etc:/etc/stalwart
|
||||
- ./config/stalwart/data:/var/lib/stalwart
|
||||
environment:
|
||||
- DOMAIN=${DOMAIN}
|
||||
- STALWART_PUBLIC_URL=https://smtp.${DOMAIN}
|
||||
- STALWART_RECOVERY_ADMIN=admin:${LLDAP_LDAP_USER_PASS}
|
||||
networks:
|
||||
- proxy-net
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
# HTTPS WebAdmin & JMAP Router
|
||||
- "traefik.http.routers.stalwart.rule=Host(`smtp.${DOMAIN}`)"
|
||||
- "traefik.http.routers.stalwart.entrypoints=websecure"
|
||||
- "traefik.http.routers.stalwart.tls=true"
|
||||
- "traefik.http.routers.stalwart.tls.certresolver=myresolver"
|
||||
- "traefik.http.routers.stalwart.service=stalwart-svc"
|
||||
# HTTP -> HTTPS Redirect
|
||||
- "traefik.http.routers.stalwart-red.rule=Host(`smtp.${DOMAIN}`)"
|
||||
- "traefik.http.routers.stalwart-red.entrypoints=web"
|
||||
- "traefik.http.routers.stalwart-red.middlewares=https-redirect@docker"
|
||||
# Forward to Stalwart's internal HTTP/WebAdmin port
|
||||
- "traefik.http.services.stalwart-svc.loadbalancer.server.port=8080"
|
||||
|
||||
homepage:
|
||||
image: ghcr.io/gethomepage/homepage:latest
|
||||
container_name: homepage
|
||||
restart: always
|
||||
volumes:
|
||||
- ./config/homepage:/app/config
|
||||
- ./config/homepage/icons:/app/public/icons:ro
|
||||
environment:
|
||||
- HOMEPAGE_ALLOWED_HOSTS=${HOMEPAGE_DOMAIN:-dashboard.${DOMAIN}}
|
||||
networks:
|
||||
- socket-net
|
||||
- proxy-net
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
# Public (HTTPS)
|
||||
- "traefik.http.routers.homepage.rule=Host(`${HOMEPAGE_DOMAIN:-dashboard.${DOMAIN}}`)"
|
||||
- "traefik.http.routers.homepage.entrypoints=websecure"
|
||||
- "traefik.http.routers.homepage.tls=true"
|
||||
- "traefik.http.routers.homepage.tls.certresolver=myresolver"
|
||||
- "traefik.http.routers.homepage.service=homepage-svc"
|
||||
- "traefik.http.routers.homepage.middlewares=authelia-auth@docker"
|
||||
# Public (Redirect)
|
||||
- "traefik.http.routers.homepage-red.rule=Host(`${HOMEPAGE_DOMAIN:-dashboard.${DOMAIN}}`)"
|
||||
- "traefik.http.routers.homepage-red.entrypoints=web"
|
||||
- "traefik.http.routers.homepage-red.middlewares=https-redirect@docker"
|
||||
- "traefik.http.services.homepage-svc.loadbalancer.server.port=3000"
|
||||
|
||||
networks:
|
||||
proxy-net:
|
||||
@@ -213,4 +312,5 @@ networks:
|
||||
external: true
|
||||
|
||||
volumes:
|
||||
portainer_data:
|
||||
dozzle_data:
|
||||
|
||||
+332
@@ -0,0 +1,332 @@
|
||||
# 📦 Workload Orchestration & `app.yaml` Reference (`appctl`)
|
||||
|
||||
The `appctl` tool is the command-line orchestrator and metadata engine for the **Homelab Core** platform. It coordinates interactions between independent workload repositories in `~/Sites` and platform services in `~/Core`.
|
||||
|
||||
> [!NOTE]
|
||||
> **Implementation Reference**: This document serves as the **current implementation manual (Milestone P4)** for the `appctl` Operational Control Plane Daemon (`scripts/appctl_daemon.py`), Operational Router (`scripts/appctl_router.py`), Thin-Client CLI (`scripts/appctl`, `scripts/appctl_cli.py`), metadata/provenance engine (`scripts/appctl_engine.py`), and Pydantic v2 manifest parser (`scripts/core_manifest.py`).
|
||||
> For the platform's phased engineering roadmap, see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md).
|
||||
|
||||
---
|
||||
|
||||
## 1. How `appctl` Works
|
||||
|
||||
Under Milestone P4, `appctl` operates as a centralized operational control plane daemon (`homelab-appctl.service`, running as isolated user `homelab-appctl:homelab-operators`) backed by cooperating modules in `scripts/`:
|
||||
|
||||
1. **[`scripts/appctl`](../scripts/appctl) & [`scripts/appctl_cli.py`](../scripts/appctl_cli.py)** (Thin-Client CLI): Dispatches operational commands over the Unix domain socket (`/run/homelab/appctl.sock`) using HTTP/1.1 (`POST /v1/operations`), resolves operator Bearer tokens (`--token`, `APPCTL_TOKEN`, `~/.config/homelab/token`), renders human-readable tables, and fast-paths local shell autocompletions (`complete`, `completion`, `resolve`).
|
||||
2. **[`scripts/appctl_daemon.py`](../scripts/appctl_daemon.py) & [`scripts/appctl_contracts.py`](../scripts/appctl_contracts.py)** (Dual-Transport Control Plane Server & Contracts): Serves a single logical HTTP/1.1 API (`POST /v1/operations` + `GET /v1/health`) identically across `/run/homelab/appctl.sock` (mode `0660`) and loopback TCP (`127.0.0.1:9001`), enforcing 64 KiB request caps and strict Pydantic v2 contracts (`ConfigDict(extra="forbid", strict=True)`).
|
||||
3. **[`scripts/appctl_auth.py`](../scripts/appctl_auth.py) & [`scripts/appctl_audit.py`](../scripts/appctl_audit.py)** (Zero-Trust Auth, 3-Role RBAC & Fail-Closed Audit Guard): Verifies SHA-256 Bearer tokens against `/run/secrets/appctl/tokens.json` (mode `0400`) using `hmac.compare_digest`, maps tokenless local UDS `SO_PEERCRED` callers strictly to `homelab-viewer` (non-sensitive read-only inspection), enforces `homelab-admin` / `homelab-operator` / `homelab-viewer` RBAC, serializes mutations via per-target `fcntl.flock`, and writes append-only audit records to `/var/log/homelab/appctl/audit.jsonl` (mode `0600`) before any mutation executes.
|
||||
4. **[`scripts/appctl_router.py`](../scripts/appctl_router.py)** (Operational Router & Unified Execution Engine): Enforces pre-flight path containment, `core_manifest.parse_manifest()`, and `validate_compose_security()` AST checks; assembles the 6-layer execution environment in pure Python (zero shell `source` or `eval`); and runs bounded `git` and `docker compose` subprocesses (`shell=False`, 256 KiB output cap, hard timeouts).
|
||||
5. **[`scripts/appctl_engine.py`](../scripts/appctl_engine.py) & [`scripts/core_manifest.py`](../scripts/core_manifest.py)** (Discovery, Provenance & Schema v1.0 Validator): Scans `~/Sites/*`, evaluates **two-axis status** (local deployment checkout state vs. upstream software provenance), inspects live container health and TLS certificates, validates `app.yaml` manifests, and atomically compiles the Homepage dashboard configuration under `_homepage_sync.lock`.
|
||||
|
||||
```text
|
||||
┌──────────────────────────┐ ┌──────────────────────────┐
|
||||
│ appctl <cmd> (CLI) │ │ homelab-gitops.service │
|
||||
└────────────┬─────────────┘ └────────────┬─────────────┘
|
||||
│ UDS (/run/homelab/appctl.sock) │ Bearer Token (homelab-operator)
|
||||
└─────────────────┬─────────────────┘
|
||||
▼
|
||||
┌────────────────────────────────────────────────┐
|
||||
│ homelab-appctl.service (appctl_daemon.py) │
|
||||
│ • POST /v1/operations & GET /v1/health │
|
||||
│ • Auth: SHA-256 tokens.json + SO_PEERCRED │
|
||||
│ • RBAC: admin / operator / viewer │
|
||||
└────────────────────────┬───────────────────────┘
|
||||
▼
|
||||
┌────────────────────────────────────────────────┐
|
||||
│ OperationalRouter (appctl_router.py) │
|
||||
│ • Per-target flock + Fail-closed DISPATCHED │
|
||||
│ audit write (/var/log/homelab/appctl/...) │
|
||||
│ • Pre-flight: parse_manifest() + Compose AST │
|
||||
│ • Pure-Python 6-layer .env assembly │
|
||||
└────────────────────────┬───────────────────────┘
|
||||
▼
|
||||
┌────────────────────────────────────────────────┐
|
||||
│ 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
|
||||
|
||||
### Status & Inspection
|
||||
|
||||
#### `appctl list` / `appctl status`
|
||||
Lists applications discovered in `~/Sites` using **two-axis inspection**:
|
||||
- **`DEPLOYMENT` (Axis 1 — Local Checkout)**: Inspects the local `~/Sites/<app>` Git working tree (`✓ Synced`, `* Dirty`, `⬇ Behind`, `⚠️ Non-Git`).
|
||||
- **`PROVENANCE` (Axis 2 — Upstream Software)**: Evaluates upstream software provenance for Class A (Source-Backed) vs. Class B (`— Image-Only`) workloads.
|
||||
|
||||
**Options**:
|
||||
* `--fetch` (`-f`): Queries upstream Git remotes (`git ls-remote` with a 10s timeout) and fetches local deployment tracking branches before computing provenance badges.
|
||||
* `--core` (`-c` / `--all` / `-a`): Appends Core infrastructure services (`traefik`, `authelia`, `lldap`, `stalwart`, `homepage`, `dozzle`, `watchtower`) to the output.
|
||||
* `--ssl` (`-s`): Queries SSL/TLS certificates over port 443 for each public domain and appends a `CERT` column.
|
||||
|
||||
**Example Output**:
|
||||
```text
|
||||
SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN
|
||||
------- ---------- ---------- ------ ------
|
||||
docs ✓ Synced (main) ✓ Synced 🟢 Running (1) docs.example.com
|
||||
jellyfin ✓ Synced (main) — Image-Only 🟢 Running (1) jellyfin.example.com
|
||||
gitea ✓ Synced (main) ⬆ Update Available 🟢 Running (2) gitea.example.com
|
||||
mongodb * Dirty (1) (main) — Image-Only 🔴 Stopped mongodb.example.com
|
||||
```
|
||||
|
||||
#### `appctl ssl [service]`
|
||||
Inspects SSL/TLS certificates over port 443. If a service is specified, shows detailed issuer, subject, and expiration data; otherwise, inspects all non-internal homelab domains.
|
||||
|
||||
```bash
|
||||
# Check all domains
|
||||
appctl ssl
|
||||
|
||||
# Check a specific service
|
||||
appctl ssl jellyfin
|
||||
```
|
||||
|
||||
#### `appctl info <service> [--ssl]`
|
||||
Displays comprehensive two-axis diagnostics for a workload or Core service:
|
||||
* Canonical name, directory path, aliases, and workload class (`Class A (Source-Backed)` vs. `Class B (Image-Only)`).
|
||||
* Primary routed domain, networks, and Authelia guard status.
|
||||
* **Axis 1 (Local Deployment Checkout)**: Branch, commit hash, dirty file count, and sync status.
|
||||
* **Axis 2 (Upstream Software Provenance)**: Upstream Git URL, tracked ref (`branch`, `tag`, or `commit`), resolved remote commit, and running container OCI revision label.
|
||||
* Injected environment variable defaults and Homepage card metadata.
|
||||
* SSL certificate details (when `--ssl` is passed).
|
||||
|
||||
```bash
|
||||
appctl info docs --ssl
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Lifecycle Management
|
||||
|
||||
#### `appctl up <service|core> [--build] [--no-cache]`
|
||||
Starts the specified service stack in detached mode (`--remove-orphans`).
|
||||
* For a workload in `~/Sites`: starts containers and triggers `appctl sync`.
|
||||
* For `core`: starts the entire Core Compose stack using `/run/secrets/homeserver.env`.
|
||||
* For an individual Core service (e.g., `appctl up traefik`): starts that specific container.
|
||||
* When `--build` is passed: invokes `docker compose build --pull` prior to deployment. The `--pull` flag guarantees base images in Dockerfile `FROM` lines are refreshed from remote registries.
|
||||
* When `--no-cache` is passed: `--build` is implied (`build: True`) and `docker compose build --pull --no-cache` is executed, forcing a clean rebuild without cached layers.
|
||||
|
||||
#### `appctl down <service|core>`
|
||||
Stops and removes containers defined in the target's Compose file (or stops the targeted Core container).
|
||||
|
||||
#### `appctl restart <service|core>`
|
||||
Restarts the target stack or individual container:
|
||||
* `appctl restart docs`: Recreates the `docs` workload stack and syncs Homepage.
|
||||
* `appctl restart core`: Restarts all Core Compose services.
|
||||
* `appctl restart traefik`: Restarts only the Traefik container.
|
||||
|
||||
#### `appctl update <service> [--branch <branch>] [--build] [--no-cache]`
|
||||
Performs a sequential, revision-consistent update workflow for a Sites workload stack:
|
||||
1. Verifies that the local Git working tree is clean (aborts if uncommitted changes exist).
|
||||
2. Runs `git pull --ff-only [origin <expected_branch>]` to fast-forward the current branch.
|
||||
3. Re-validates `app.yaml`, expected branch declaration, and Compose security rules against the newly pulled working tree.
|
||||
4. Executes declared actions in `app.yaml` (`actions: [git_pull, compose_pull, compose_build, compose_up, compose_restart]`):
|
||||
* `compose_pull`: Runs `docker compose pull` to fetch updated container images.
|
||||
* `compose_build`: Runs `docker compose build --pull` (and `--no-cache` if requested).
|
||||
* `compose_up`: Runs `docker compose up -d --remove-orphans` to recreate containers.
|
||||
* When `--build` is passed via CLI, `compose_build` is automatically executed prior to `compose_up`, even if omitted from manifest actions.
|
||||
* When `--no-cache` is passed, build is implied and executes with `--no-cache`.
|
||||
5. Runs `appctl sync` to update the Homepage dashboard.
|
||||
|
||||
> [!NOTE]
|
||||
> **Source-Built Workload Policy**: For workloads built directly from local source Dockerfiles rather than pre-built registry images, declare `compose_build` in `app.yaml` `deployment.actions` (`actions: [git_pull, compose_build, compose_up]`). Both manual `appctl update` and automated GitOps dispatcher runs will execute `docker compose build --pull` before recreating containers, ensuring reproducible builds with current upstream base layers.
|
||||
|
||||
> [!NOTE]
|
||||
> Core platform updates are managed via version-controlled NixOS generations (`git pull` followed by `nixos-rebuild switch`), not through `appctl update core` (as Core is mounted read-only for `homelab-appctl.service`).
|
||||
|
||||
#### `appctl pull <service|core>`
|
||||
Pulls latest container images and recreates the target service.
|
||||
|
||||
#### `appctl logs <service|core> [--tail N]`
|
||||
Fetches a bounded snapshot of container logs (default: `--tail 100`). Supports passing a workload or targeted Core service container (e.g., `appctl logs traefik`).
|
||||
*(Note: As an HTTP/1.1 request-response API, log streaming `-f` is replaced by bounded snapshots).*
|
||||
|
||||
#### `appctl config <service|core>`
|
||||
Validates the manifest and renders the resolved Docker Compose configuration with all injected variables. Fails closed if `app.yaml` is missing or invalid.
|
||||
|
||||
#### `appctl sync`
|
||||
Scans all valid `~/Sites/*/app.yaml` manifests and compiles `config/homepage/services.yaml`.
|
||||
|
||||
#### `appctl completion [bash]`
|
||||
Outputs the bash autocompletion script.
|
||||
|
||||
---
|
||||
|
||||
## 3. `app.yaml` Schema v1.0 Contract
|
||||
|
||||
Workload manifests in `~/Sites/<app>/app.yaml` are validated by [`scripts/core_manifest.py`](../scripts/core_manifest.py) using strict Pydantic v2 models (`extra="forbid"`). Any unknown field, invalid transport URL, or prohibited deployment action causes validation to fail closed.
|
||||
|
||||
```yaml
|
||||
schema_version: "1.0" # Schema version (only "1.0" is supported)
|
||||
|
||||
# ── Identity & Routing ────────────────────────────────────────────────────────
|
||||
name: "jellyfin" # Canonical name: ^[a-zA-Z0-9][a-zA-Z0-9._-]*$
|
||||
aliases: # Optional CLI aliases
|
||||
- "media"
|
||||
- "movies"
|
||||
domain: "jellyfin.example.com" # Primary routed domain (defaults to <name>.${HOMELAB_DOMAIN})
|
||||
description: "Media Streaming Server"
|
||||
|
||||
# ── Platform Integration ──────────────────────────────────────────────────────
|
||||
visible: true # Display on Homepage dashboard (default: true)
|
||||
auth: false # Authelia ForwardAuth protection (default: false)
|
||||
networks: # Docker networks to join (default: [proxy-net])
|
||||
- proxy-net
|
||||
|
||||
# ── Upstream Software Provenance (Optional: Defines Class A vs. Class B) ─────
|
||||
# Omit 'source' for Class B (Image-Only third-party workloads).
|
||||
# Include 'source' for Class A (Source-Backed workloads):
|
||||
source:
|
||||
url: "https://github.com/example/jellyfin-app.git" # Strictly https://, ssh://, or git@host:path
|
||||
ref: "main" # Branch, v* tag, or 40-char commit SHA
|
||||
|
||||
# ── Injected Environment Defaults ─────────────────────────────────────────────
|
||||
# Keys must match ^[a-zA-Z_][a-zA-Z0-9_]*$ and cannot override reserved host keys
|
||||
# (PATH, LD_PRELOAD, IFS, SHELL, USER, HOME, CORE_DIR, SITES_DIR, etc.)
|
||||
env:
|
||||
MEDIA_PATH: "/media"
|
||||
JELLYFIN_TZ: "UTC"
|
||||
|
||||
# ── GitOps Deployment Policy ──────────────────────────────────────────────────
|
||||
# Evaluated by scripts/gitops_dispatcher.py upon webhook admission
|
||||
deployment:
|
||||
branch: "main" # Target branch that triggers deployment
|
||||
strategy: "compose" # Only 'compose' strategy is permitted
|
||||
actions: # Strictly allowlisted: git_pull, compose_pull,
|
||||
- git_pull # compose_up, compose_build, compose_restart
|
||||
- compose_up
|
||||
|
||||
# ── Homepage Dashboard Metadata ───────────────────────────────────────────────
|
||||
homepage:
|
||||
title: "Jellyfin" # Card title
|
||||
group: "Media & Productivity" # Dashboard group name
|
||||
icon: "jellyfin.png" # Icon name (matched against config/homepage/icons/)
|
||||
container: "jellyfin" # Container name for live status widget
|
||||
weight: 10 # Card sort weight (lower sorts first)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Environment Injection & Resolution Precedence
|
||||
|
||||
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. **Base System Path & Docker Config**: `PATH` and `DOCKER_CONFIG`.
|
||||
2. **Global Secrets & Templates**: Parsed inertly from `/run/secrets/rendered/homeserver.env` and `/run/secrets/rendered/traefik-deployments.env` (with `/run/secrets/*` fallbacks).
|
||||
3. **Canonical Root Domain Lock**: `HOMELAB_DOMAIN` is locked using precedence `HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN` (failing closed if unset).
|
||||
4. **Infrastructure Defaults & Application Identity**:
|
||||
- `PROXY_NETWORK` (defaults to `proxy-net`)
|
||||
- `CERT_RESOLVER` (defaults to `myresolver`)
|
||||
- `DOMAIN_SUFFIX` (`$HOMELAB_DOMAIN`)
|
||||
- `SERVICE_NAME` = `<canonical-name>`
|
||||
- `CONTAINER_NAME` = `<canonical-name>`
|
||||
- `SERVICE_DOMAIN` = `<canonical-name>.<HOMELAB_DOMAIN>`
|
||||
- `DOMAIN` = `<HOMELAB_DOMAIN>`
|
||||
5. **Manifest Variables**: Validated key-value pairs from the `env:` block in `app.yaml`.
|
||||
6. **Local Repository Files**: Parsed inertly from `$APP_DIR/.env` and `$APP_DIR/app.env` if present, rejecting any key violating `ENV_KEY_RE` or matching `RESERVED_ENV_KEYS`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Homepage Dashboard Compilation
|
||||
|
||||
When `appctl sync` runs:
|
||||
1. `appctl_engine.py` scans all `~/Sites/*/app.yaml` manifests (skipping any workload with a `manifest_error`).
|
||||
2. Core services (`traefik`, `authelia`, `lldap`, `stalwart`, `homepage`, `dozzle`, `watchtower`) are assigned to `Core Infrastructure`.
|
||||
3. Workload applications with `visible: true` are grouped by their `homepage.group` (ordered: `Core Infrastructure`, `Knowledge & Notes`, `Media & Productivity`, `Development & AI`, `Applications`) and sorted by `(weight, title)`.
|
||||
4. Custom icons matching files in `config/homepage/icons/` (`.svg` or `.png`) are mapped to `/icons/<name>`.
|
||||
5. The compiled configuration is written to `config/homepage/services.yaml`.
|
||||
@@ -0,0 +1,180 @@
|
||||
# 🏛️ Homelab Core — Architecture & System Design
|
||||
|
||||
This document details the architectural structure, component roles, networking models, and security controls of the **Homelab Core** platform.
|
||||
|
||||
> [!NOTE]
|
||||
> **Implementation Scope**: This document details the **current runtime architecture (Milestone P4)**, operational control plane daemon (`homelab-appctl.service`), edge routing, container topologies, and network isolation models of Homelab Core.
|
||||
> For phased engineering milestones (P5–P7), see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md).
|
||||
|
||||
---
|
||||
|
||||
## 1. System Structure: Ownership vs. Runtime Layers vs. Orchestration
|
||||
|
||||
To understand how the system is organized, three architectural dimensions are distinguished:
|
||||
|
||||
### A. Ownership Boundary
|
||||
* **Core (`~/Core`) owns**: NixOS host configuration, shared platform services, edge ingress, identity boundaries, secrets distribution, and deployment orchestration mechanics.
|
||||
* **Workload Plane (`~/Workloads`) owns**: Independent application deployments, workload-specific Docker Compose files, declarative `app.yaml` manifests, `~/Workloads/deployments.yaml`, and workload-scoped runtime state (`~/var/lib/homelab/<app>/`).
|
||||
|
||||
### B. Four Runtime Layers
|
||||
The runtime environment consists of four functional layers:
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ 1. EDGE GATEWAY & INGRESS │
|
||||
│ Traefik (v3.6) · Let's Encrypt Wildcard TLS · Dynu DNS-01 Provider │
|
||||
└───────────────────────────────────┬────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ 2. CONTROL & PLATFORM SERVICES (Core Compose Stack) │
|
||||
│ Authelia SSO · LLDAP Directory · Stalwart Mail Server │
|
||||
│ Homepage Dashboard · Dozzle · Watchtower · Diun │
|
||||
│ socket-proxy (Read-Only Docker API Barrier) │
|
||||
└───────────────────────────────────┬────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ 3. WORKLOAD PLANE (~/Workloads) │
|
||||
│ Autonomous Workload Repositories (SnappyMail, Docs, Gitea, etc.) │
|
||||
│ Declarative app.yaml Manifests & Compose Stacks │
|
||||
└───────────────────────────────────┬────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ 4. HOST FOUNDATION & CONTROL PLANE DAEMONS │
|
||||
│ NixOS Linux · sops-nix Secrets · Docker Engine · Systemd Units │
|
||||
│ homelab-appctl.service (Control Plane Daemon) · homelab-gitops │
|
||||
│ Smart Dynu DDNS Monitor · Host Firewall · /run Secret Projections │
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### C. Cross-Cutting Orchestration
|
||||
Orchestration coordinates operations across the runtime layers:
|
||||
* **`appctl` Operational Control Plane Daemon (`homelab-appctl.service`, `scripts/appctl_daemon.py`, `scripts/appctl_router.py`)**: Centralized control plane running under isolated service identity `homelab-appctl:homelab-operators`. Exposes `POST /v1/operations` and `GET /v1/health` over `/run/homelab/appctl.sock` (mode `0660`) and `127.0.0.1:9001`, enforcing SHA-256 Bearer token authentication, 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`), per-target `flock` serialization, fail-closed append-only audit logging (`/var/log/homelab/appctl/audit.jsonl`), Pydantic v2 `app.yaml` validation, Compose AST security checks (enforcing host-granted `homelab.workloadGrants` from `/etc/homelab/grants.json` via `scripts/workload_grants.py`), and pure-Python `.env` assembly.
|
||||
* **GitOps Webhook Dispatcher (`scripts/gitops_dispatcher.py`)**: Governed by the `homelab-gitops.service` systemd unit, it receives webhooks on port 9000, verifies HMAC-SHA256 signatures, enforces the `~/Workloads/deployments.yaml` allowlist (configured via `HOMELAB_DEPLOYMENTS_FILE`, with `config/deployments.yaml` as the example template), and delegates serialized `workload.update` execution to `homelab-appctl.service` over `/run/homelab/appctl.sock` using its `homelab-operator` Bearer token.
|
||||
|
||||
---
|
||||
|
||||
## 2. Component Roles & Operational Boundaries
|
||||
|
||||
### A. Edge Gateway (`traefik`)
|
||||
* **Role**: Ingress proxy for incoming HTTP (80) and HTTPS (443) traffic.
|
||||
* **TLS Management**: Employs Traefik's native ACME resolver using the Dynu DNS-01 challenge provider (`myresolver`) to obtain and renew wildcard certificates for `*.${HOMELAB_DOMAIN}` and `${HOMELAB_DOMAIN}` (e.g., `*.example.com`). Certificate data is stored at `config/letsencrypt/acme.json` (mode `0600`).
|
||||
* **Redirection**: Automatically upgrades HTTP traffic to HTTPS via the `https-redirect@docker` middleware.
|
||||
* **Dynamic Routing**: Discovers routers and services dynamically by reading Docker container labels via `socket-proxy` (`tcp://socket-proxy:2375`).
|
||||
|
||||
### B. Security Barrier (`socket-proxy`)
|
||||
* **Role**: Isolates the host Docker daemon socket from direct container access.
|
||||
* **Access Rules**:
|
||||
- Mounted read-only: `/var/run/docker.sock:/var/run/docker.sock:ro`.
|
||||
- State-modifying and execution endpoints disabled: `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`, `COMMIT=0`, `CONFIGS=0`, `DISTRIBUTION=0`, `NODES=0`, `PLUGINS=0`, `SECRETS=0`, `SWARM=0`, `SYSTEM=0`.
|
||||
- Read-only inspection endpoints enabled: `CONTAINERS=1`, `NETWORKS=1`, `SERVICES=1`, `TASKS=1`, `IMAGES=1`, `VOLUMES=1`, `INFO=1`, `EVENTS=1`, `PING=1`, `VERSION=1`.
|
||||
* **Network**: Attached exclusively to `socket-net`. Application containers in `~/Workloads` are never attached to `socket-net`.
|
||||
|
||||
### C. Identity & Directory Services (`lldap` & `authelia`)
|
||||
* **`lldap`**: Lightweight LDAP directory service storing user accounts, password hashes, and groups. Web UI exposed at `users.${HOMELAB_DOMAIN}` (protected by Authelia). SQLite database stored in `config/lldap/data/users.db`.
|
||||
* **`authelia`**: Authentication and SSO gateway (`auth.${HOMELAB_DOMAIN}`).
|
||||
- Configured with an LDAP authentication backend querying `ldap://lldap:3890`.
|
||||
- Exposes the ForwardAuth endpoint (`/api/verify?rd=https://auth.${HOMELAB_DOMAIN}/`), registered as the `authelia-auth@docker` Traefik middleware.
|
||||
- Passes user identity headers (`Remote-User`, `Remote-Groups`, `Remote-Email`, `Remote-Name`) upon successful session verification.
|
||||
|
||||
### D. Mail Subsystem (`stalwart`)
|
||||
* **`stalwart`**: Core mail transport and storage server handling inbound SMTP (25), SMTPS (465), SMTP Submission (587), IMAPS (993), and ManageSieve (4190).
|
||||
- WebAdmin & JMAP endpoint accessible at `smtp.${HOMELAB_DOMAIN}` via Traefik.
|
||||
- Authenticates users against the LLDAP directory.
|
||||
- Outbound mail relay configured to route through an external smart host (Brevo SMTP relay via SOPS secrets).
|
||||
- *(Note: User-facing webmail, such as SnappyMail, runs as an independent Class B workload in `~/Workloads/snappymail` with isolated state under `~/var/lib/homelab/snappymail/`.)*
|
||||
|
||||
### E. Portal & Observability (`homepage`, `dozzle`)
|
||||
* **`homepage`**: Service dashboard at `dashboard.${HOMELAB_DOMAIN}`. Synchronized from `app.yaml` manifests in `~/Workloads` by `appctl sync`.
|
||||
* **`dozzle`**: Real-time container log viewer at `logs.${HOMELAB_DOMAIN}`, connecting read-only through `socket-proxy`.
|
||||
|
||||
### F. Host Foundation & Daemons
|
||||
* **`homeserver-core.service`**: Systemd unit managing the Core Docker Compose stack (`~/Core/docker-compose.yml`) using secrets projected to `/run/secrets/homeserver.env`.
|
||||
* **`homelab-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`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Network Segmentation
|
||||
|
||||
Homelab Core configures two isolated Docker bridge networks:
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ HOST DOCKER ENGINE │
|
||||
├────────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────────────────────────────────────────────────────────┐ │
|
||||
│ │ proxy-net (Bridge) │ │
|
||||
│ │ │ │
|
||||
│ │ • traefik (router) • authelia (sso) │ │
|
||||
│ │ • lldap (directory) • stalwart (mail) │ │
|
||||
│ │ • homepage (dashboard) • dozzle (logs) │ │
|
||||
│ │ • All User Workloads (~/Workloads/*) │ │
|
||||
│ └──────────────────────────────┬───────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌──────────────────────────────┴───────────────────────────────┐ │
|
||||
│ │ socket-net (Bridge) │ │
|
||||
│ │ │ │
|
||||
│ │ • socket-proxy (HAProxy :2375) • traefik │ │
|
||||
│ │ • dozzle • watchtower │ │
|
||||
│ │ • diun • homepage │ │
|
||||
│ └──────────────────────────────┬───────────────────────────────┘ │
|
||||
│ │ (ro mount) │
|
||||
│ ▼ │
|
||||
│ /var/run/docker.sock │
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
1. **`proxy-net`**: Ingress routing network. Traefik directs traffic to backend service containers on this network. Workload containers in `~/Workloads` join `proxy-net`.
|
||||
2. **`socket-net`**: Isolated Docker socket proxy network. Only Core infrastructure components needing read-only container metadata join this network.
|
||||
|
||||
---
|
||||
|
||||
## 4. Host Firewall & Port Exposure
|
||||
|
||||
The host firewall is configured in `nixos/modules/homeserver.nix`:
|
||||
|
||||
| Port | Protocol | Service | Description | Exposure |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| **80** | TCP | Traefik | HTTP Ingress (Redirects to 443) | Public |
|
||||
| **443** | TCP | Traefik | HTTPS Ingress (TLS Termination) | Public |
|
||||
| **22** | TCP | OpenSSH | Host SSH Access (`PermitRootLogin = "no"`) | Host Access |
|
||||
| **2223** | TCP | Gitea SSH | Git over SSH for Workloads & Gitea | Public |
|
||||
| **9000** | TCP | GitOps Webhook | GitOps Webhook Receiver | Public / Gitea |
|
||||
| **25** | TCP | Stalwart | Inbound SMTP | Public |
|
||||
| **465** | TCP | Stalwart | SMTPS (Implicit TLS) | Public |
|
||||
| **587** | TCP | Stalwart | SMTP Submission (STARTTLS) | Public |
|
||||
| **993** | TCP | Stalwart | IMAPS (Secure IMAP) | Public |
|
||||
| **4190** | TCP | Stalwart | ManageSieve (Mail Filters) | Public |
|
||||
|
||||
Application containers in `~/Workloads` do not bind host ports directly; they receive traffic routed by Traefik over `proxy-net`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Workload Integration Model
|
||||
|
||||
Workloads in `~/Workloads/<app>` integrate with Core through three mechanisms:
|
||||
|
||||
1. **Manifest Metadata (`app.yaml`)**: Validated by `scripts/core_manifest.py` (Schema v1.0). Declares canonical identity, routed domain, upstream source provenance (`source.url`, `source.ref`), environment defaults, Homepage card layout, and allowlisted GitOps deployment policy.
|
||||
2. **Compose Configuration (`docker-compose.yml`)**:
|
||||
- Attaches to the external `proxy-net` network.
|
||||
- Declares Traefik routing labels:
|
||||
```yaml
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}.rule=Host(`${SERVICE_DOMAIN}`)"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}.entrypoints=websecure"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}.tls=true"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}.service=${CONTAINER_NAME}-svc"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}-red.rule=Host(`${SERVICE_DOMAIN}`)"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}-red.entrypoints=web"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}-red.middlewares=https-redirect@docker"
|
||||
- "traefik.http.services.${CONTAINER_NAME}-svc.loadbalancer.server.port=8080"
|
||||
# If auth is required:
|
||||
- "traefik.http.routers.${CONTAINER_NAME}.middlewares=authelia-auth@docker"
|
||||
```
|
||||
3. **Execution & State Isolation**: `appctl` and `gitops_dispatcher.py` validate the manifest and Compose AST (blocking privilege escalation and out-of-bounds mounts unless explicitly authorized per workload in `homelab.workloadGrants`, projected to `/etc/homelab/grants.json` and read via `HOMELAB_GRANTS_FILE` per ADR-0005) before supplying runtime environment variables (`SERVICE_DOMAIN`, `CONTAINER_NAME`, and projected secrets). Persistent mutable workload data resides strictly under `~/var/lib/homelab/<app>/`.
|
||||
@@ -0,0 +1,99 @@
|
||||
---
|
||||
type: decision
|
||||
status: accepted
|
||||
project: homelab-core
|
||||
date: 2026-09-28
|
||||
tags: [architecture, homelab, provenance, gitops, state, kiss]
|
||||
---
|
||||
|
||||
# ADR 0001: Homelab 3-Tier Architecture & Deployment Provenance Model
|
||||
|
||||
## Context and Problem Statement
|
||||
|
||||
Homelab Core operates as a dedicated NixOS appliance hosting self-hosted productivity services and independent backend engineering projects. In early platform iterations (v1 through v3), several structural tensions emerged:
|
||||
|
||||
1. **Application & Deployment Coupling**: Custom applications co-located application source trees with host-specific Traefik labels, Docker bridge networks, and host path mounts inside individual Git repositories in `~/Sites/<app>`.
|
||||
2. **Repository Inflation**: Third-party off-the-shelf applications (`jellyfin`, `stirling`, `snappymail`) required standalone Git repositories simply to store a minimal Compose file and manifest.
|
||||
3. **Ambiguous Freshness**: Local Git status checks in `~/Sites/<app>` could only report whether deployment descriptors had uncommitted edits, never whether running containers matched current upstream application source code.
|
||||
4. **Mutable State Entanglement**: Application databases, caches, and runtime state lived inside or adjacent to version-controlled Git working trees (`Core/config/` and `Sites/<app>/data`), risking dirty checkouts, accidental secret/state commits, or data loss during branch operations.
|
||||
5. **Orchestrator Sprawl Risk**: Scaling operational scripts threatened to introduce secondary distributed infrastructure (queues, databases, message brokers) around basic single-node container deployments.
|
||||
|
||||
The central architectural question is: **How should Homelab Core structure application source code, deployment configuration, runtime state, and platform orchestration to maintain strict separation of concerns, verifiable provenance, and linear KISS operations?**
|
||||
|
||||
## Decision Drivers
|
||||
|
||||
* **Clean Separation of Concerns**: Application software projects must be developable, testable, and publishable independently of Homelab Core infrastructure, domains, or bridge networks.
|
||||
* **Workload Simplicity**: Off-the-shelf third-party applications should not incur standalone source repository overhead.
|
||||
* **Verifiable Two-Axis Provenance**: Operators must be able to independently verify local deployment configuration freshness (`~/Sites/<app>`) versus upstream software code freshness (`source.url` vs. running container image).
|
||||
* **KISS Primitives & Minimal Control Paths**: Operational reconciliation must remain bounded, deterministic, and linear without distributed brokers, queues, or deployment databases.
|
||||
* **Filesystem State Hygiene**: Mutable runtime data must never reside inside version-controlled Git trees.
|
||||
|
||||
## Considered Options
|
||||
|
||||
* **Option 1: Monolithic / Single-Repo Deployment (Status Quo v1–v3)**: Co-locate application source code, Dockerfiles, Compose files, and mutable runtime state inside a single Git repository per application.
|
||||
* **Option 2: Miniature Cloud Platform**: Introduce message brokers (RabbitMQ/Redis), a deployment state database, multi-environment controllers, and asynchronous rollback daemons.
|
||||
* **Option 3: Bounded 3-Tier Platform with OCI Provenance Labels & Linear Control Path (Adopted)**: Decouple Software, Deployment, and Platform tiers; connect them via OCI image artifacts carrying source revision labels and content-addressed digests; enforce two-axis provenance inspection, linear reconciliation, and isolated host state roots.
|
||||
|
||||
## Decision Outcome
|
||||
|
||||
Chosen option: **Option 3: Bounded 3-Tier Platform with OCI Provenance Labels & Linear Control Path**, because it resolves source-deployment coupling and provenance ambiguity while retaining a strictly bounded, single-appliance operational footprint.
|
||||
|
||||
### Summary of Architectural Commitments
|
||||
|
||||
1. **3-Tier Separation of Concerns**:
|
||||
* **Tier 1 — Software Layer (Application Repositories)**: Standalone Git repositories owning application source code, tests, Dockerfiles, and CI workflows. Zero Homelab infrastructure coupling.
|
||||
* **Intermediate Provenance Artifacts**: OCI container images produced by CI act as immutable provenance objects identified by their OCI digest and carrying source commit metadata via the `org.opencontainers.image.revision` label.
|
||||
* **Tier 2 — Deployment Layer (`~/Sites` Workload Plane)**: Declarative catalog in `~/Sites/<app>` owning workload-specific `app.yaml` manifests and `docker-compose.yml` topologies.
|
||||
* **Tier 3 — Platform Layer (Homelab Core Appliance)**: Declarative NixOS host foundation (`~/Core`) owning edge ingress (`traefik`), SSO/directory (`authelia`, `lldap`), mail (`stalwart`), monitoring (`dozzle`, `diun`), and operational controllers (`appctl`, `gitops_dispatcher`).
|
||||
2. **Two Workload Deployment Classes**:
|
||||
* **Class A (Source-Backed)**: Declares an explicit upstream `source:` block (`source.url`, `source.ref`) in `app.yaml`; tracks upstream Git revisions against running container OCI labels.
|
||||
* **Class B (Image-Only)**: Standard third-party workloads omitting `source:`; deployment freshness relies on container registry image tags and content-addressed digests.
|
||||
3. **Two Operational Inspection Axes (`scripts/provenance.py`)**:
|
||||
* **Axis 1 (Local Deployment Checkout)**: Evaluates local `~/Sites/<app>` working-tree cleanliness (`✓ Synced`, `* Dirty`, `⬆ Ahead`, `⬇ Behind`).
|
||||
* **Axis 2 (Upstream Software Provenance)**: Independently resolves upstream remote revisions via bounded `git ls-remote` (10-second timeout during `--fetch`) against running container revision labels.
|
||||
4. **Minimal Linear Reconciliation Path**:
|
||||
* The deployment lifecycle remains strictly linear:
|
||||
$$\text{Source Push} \longrightarrow \text{CI Build} \longrightarrow \text{GitOps Ingress} \longrightarrow \text{appctl Reconcile} \longrightarrow \text{Compose Up}$$
|
||||
* Secondary message queues, brokers, and deployment databases are rejected.
|
||||
5. **Isolated Persistent State Root**:
|
||||
* Mutable application runtime state (databases, caches, uploads, dynamic configs) resides strictly under `~/var/lib/homelab/<app>/`, isolated from version-controlled Git repositories.
|
||||
|
||||
## Pros and Cons of the Options
|
||||
|
||||
### Option 1: Monolithic / Single-Repo Deployment
|
||||
* Good, because it requires only a single Git repository per custom application.
|
||||
* Bad, because host-specific routing labels and bridge networks leak into application source repositories, preventing clean open-sourcing or reuse.
|
||||
* Bad, because off-the-shelf tools require artificial wrapper repositories.
|
||||
* Bad, because a single commit SHA conflates software code revisions with deployment configuration edits.
|
||||
* Bad, because mutable state co-located in `Sites/<app>/data` creates dirty Git trees and risks accidental commits or data loss.
|
||||
|
||||
### Option 2: Miniature Cloud Platform
|
||||
* Good, because it mirrors enterprise Kubernetes / ArgoCD continuous deployment pipelines.
|
||||
* Bad, because running distributed brokers, queues, and state databases on a single appliance introduces disproportionate operational overhead and failure modes.
|
||||
* Bad, because it violates the KISS principle.
|
||||
|
||||
### Option 3: Bounded 3-Tier Platform with OCI Provenance Labels (Adopted)
|
||||
* Good, because custom software is completely decoupled from homelab infrastructure and remains portable and instance-agnostic.
|
||||
* Good, because off-the-shelf software incurs zero source repository overhead.
|
||||
* Good, because two-axis inspection resolves local configuration status and upstream code provenance unambiguously.
|
||||
* Good, because runtime state is cleanly isolated under `~/var/lib/homelab/<app>/`.
|
||||
* Bad, because custom applications manage source code and Sites deployment manifests as separate concerns.
|
||||
* Bad, because verifying remote revisions without local clones (`git ls-remote`) evaluates commit equality (`HEAD` match) rather than full commit ancestry distance.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Consequences
|
||||
* **Independent Software Lifecycle**: Custom applications can be developed, tested, and published without exposing homelab domains, secrets, or network topologies.
|
||||
* **Precise Diagnostic Truth**: Operators and `appctl` can distinguish between uncommitted local deployment edits (`* Dirty`) and upstream software updates (`git ls-remote`).
|
||||
* **Zero-Data-Loss State Isolation**: Proven during the Milestone P1 SnappyMail migration, moving persistent runtime data to `~/var/lib/homelab/<app>/` keeps Git trees pure and backups deterministic.
|
||||
* **Operational Restraint**: Preserves a linear, local reconciliation path without distributed state stores.
|
||||
|
||||
### Negative Consequences & Accepted Trade-offs
|
||||
* **Dual Repositories for Custom Workloads**: Deploying a custom application separates upstream source CI from the `~/Sites/<app>` deployment manifest.
|
||||
* **Commit Equality Without Ancestry Graph**: Remote `git ls-remote` queries confirm whether the deployed revision matches upstream `HEAD`, without computing commit ahead/behind counts on uncloned source repos.
|
||||
|
||||
## More Information
|
||||
|
||||
* **Architecture Specification**: [`docs/architecture.md`](../architecture.md)
|
||||
* **Secrets & State Contract**: [`docs/secrets-and-state.md`](../secrets-and-state.md)
|
||||
* **Governing Roadmap**: [`ROADMAP.md`](../../ROADMAP.md) (Milestones P1 & P3)
|
||||
@@ -0,0 +1,139 @@
|
||||
---
|
||||
type: decision
|
||||
status: accepted
|
||||
project: homelab-core
|
||||
date: 2026-10-07
|
||||
tags: [architecture, homelab, appctl, control-plane, security, rbac, audit, gitops]
|
||||
---
|
||||
|
||||
# ADR 0002: Homelab Operational Control Plane & Deployment Model Architecture
|
||||
|
||||
## Context and Problem Statement
|
||||
|
||||
Homelab Core historically relied on `appctl` as a procedural Bash CLI wrapper (`scripts/appctl`) coupled with a Python metadata helper (`scripts/appctl_engine.py`). Operational commands (`up`, `down`, `restart`, `update`, `logs`, `config`, `sync`) executed as local subprocesses in the operator's shell session, sourcing environment files directly from `/run/secrets/` and `$APP_DIR/.env`.
|
||||
|
||||
As the platform matured and AI coding agents began operating inside developer SSH sessions, this script-based model exposed five architectural and security liabilities:
|
||||
|
||||
1. **Conflated Host & Control Plane Authority**: Entering the server via SSH granted full operational mutation authority. Any unprivileged process or AI coding agent running under the operator's UID could invoke `appctl` to mutate containers, inspect secrets, or alter routing with zero authentication.
|
||||
2. **Duplicated Execution & Pre-Flight Drift**: The local CLI (`scripts/appctl`) and the GitOps webhook worker (`scripts/gitops_dispatcher.py`) maintained separate implementations of `git pull` and `docker compose`, with the CLI path bypassing Compose AST security validation and sourcing `.env` files via shell `source`.
|
||||
3. **Absence of Tamper-Evident Auditability**: Operational actions produced only ephemeral terminal output with no centralized, append-only audit log recording principal identity, transport, origin, target revision, and outcome.
|
||||
4. **Secret Lifecycle Coupling**: Workload secrets were broadly sourced into parent shell environments or coupled to static SOPS rebuilds rather than resolved via scoped references.
|
||||
5. **Manual Workload Authoring Friction**: Onboarding workloads required handwriting boilerplate descriptors without a structured boundary separating AI-generated proposals (`DeploymentProposal`) from human-approved declarative intent (`DeploymentModel`).
|
||||
|
||||
The central architectural question is: **How should Homelab Core transition `appctl` into an authoritative, fail-closed operational control plane with strict privilege isolation, unified execution, mandatory token authorization, and safe deployment authoring without introducing distributed cloud complexity?**
|
||||
|
||||
## Decision Drivers
|
||||
|
||||
* **Control Plane Centralization**: Exactly one authoritative execution pipeline for all workload and platform operations across CLI, GitOps, and future web clients.
|
||||
* **Host Access Does Not Confer Mutation Authority**: Entering the host via SSH must not bypass control-plane authentication. Every mutating action and sensitive read requires cryptographic token verification.
|
||||
* **OS Privilege Isolation**: The control plane daemon, token store, and audit log must be isolated under a dedicated system identity (`homelab-appctl`) inaccessible to unprivileged operator shell processes and AI sessions.
|
||||
* **Unified Pre-Flight & Inert Environment Assembly**: Eliminate shell `eval` and `source`; enforce Pydantic v2 schema validation ([ADR-0003](0003-pydantic-v2-runtime-validation.md)) and Compose AST security checks before every Compose invocation.
|
||||
* **Declarative Git Ground Truth & AI Boundary**: Git remains the sole authoritative source of deployment state; AI agents act strictly as upstream proposal generators (`DeploymentProposal`) with zero execution authority.
|
||||
* **KISS Primitives**: Preserve synchronous, linear execution using local `flock` serialization and HTTP/1.1 without external message brokers or databases.
|
||||
|
||||
## Considered Options
|
||||
|
||||
* **Option 1: Status Quo with Modernized Local CLI**: Modernize `appctl_engine.py` into a type-safe Python CLI while keeping execution in-process inside the caller's SSH session.
|
||||
* **Option 2: Cloud-Native Micro-Platform (Kubernetes / Nomad / ArgoCD)**: Replace `appctl` and Docker Compose with enterprise cluster orchestration and distributed control loops.
|
||||
* **Option 3: Authoritative `homelab-appctl.service` Daemon with Single Command Router & Stable Deployment Model (Adopted)**: Evolve `appctl` into an isolated systemd daemon exposing one logical HTTP/1.1 command API (`POST /v1/operations`) across Unix domain socket and TCP, backed by mandatory Bearer token auth, 3-role RBAC, fail-closed audit logging, and a 5-stage `DeploymentModel` lifecycle.
|
||||
|
||||
## Decision Outcome
|
||||
|
||||
Chosen option: **Option 3: Authoritative `homelab-appctl.service` Daemon with Single Command Router & Stable Deployment Model**, because it enforces an OS-level security boundary between operator sessions and platform execution, unifies CLI and GitOps codepaths behind a single fail-closed pipeline, and establishes a clean roadmap for directory-backed identity (P5) and human-gated AI deployment authoring (P6).
|
||||
|
||||
### Summary of Architectural Commitments (Reconciled with Pre-P4 Locked Decisions `DEC-01`–`DEC-05`)
|
||||
|
||||
```text
|
||||
Clients (CLI / GitOps Worker / Future Web UI)
|
||||
│
|
||||
POST /v1/operations + GET /v1/health
|
||||
(One Logical HTTP/1.1 Command Contract)
|
||||
│
|
||||
┌─────────────────────┴─────────────────────┐
|
||||
▼ ▼
|
||||
Unix Domain Socket (/run/homelab/appctl.sock) HTTP Listener (127.0.0.1:9001)
|
||||
mode 0660 (homelab-appctl:homelab-operators) (Loopback in P4)
|
||||
│ │
|
||||
└─────────────────────┬─────────────────────┘
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ Unified Fail-Closed Pipeline (homelab-appctl)│
|
||||
│ 1. Pydantic v2 Validator (extra="forbid", 64K)│
|
||||
│ 2. Auth & 3-Role RBAC Gate (Bearer / PeerCred)│
|
||||
│ 3. Per-Target flock (/var/lib/homelab/appctl) │
|
||||
│ 4. Pre-Exec Audit Disk Guard (DISPATCHED) │
|
||||
│ 5. Pre-Flight (Manifest + Compose AST + .env) │
|
||||
│ 6. Subprocess Execution (Fixed argv, 256K cap)│
|
||||
│ 7. Post-Exec Audit Record (COMPLETED / FAILED)│
|
||||
└───────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
#### 1. One Logical Command API Across Dual Transports (`DEC-01`)
|
||||
* `appctl` runs as a dedicated systemd daemon (`homelab-appctl.service`) speaking standard **HTTP/1.1** over both a local Unix Domain Socket (`/run/homelab/appctl.sock`) and a TCP listener (`127.0.0.1:9001` in P4).
|
||||
* All 13 canonical domain operations (`workload.list`, `workload.get`, `workload.resolve`, `platform.ssl`, `platform.health`, `workload.config`, `workload.logs`, `workload.deploy`, `workload.stop`, `workload.restart`, `workload.pull`, `workload.update`, `platform.sync_homepage`) dispatch through a **single canonical endpoint**: `POST /v1/operations` (plus `GET /v1/health` for liveness). Multi-route REST aliases are rejected.
|
||||
* `scripts/appctl` acts as a thin HTTP/1.1 UDS client with zero local Docker or Git execution logic.
|
||||
|
||||
#### 2. Host Access Does Not Confer Mutation Authority & 3-Role RBAC (`DEC-02`)
|
||||
* Entering via SSH confers zero control-plane mutation authority. Every mutating operation, every sensitive read (`workload.config`, `workload.logs`), and every HTTP request requires an explicit Bearer token validated via constant-time SHA-256 comparison (`hmac.compare_digest`) against `/run/secrets/appctl/tokens.json` (`0400`).
|
||||
* **UDS `SO_PEERCRED` Viewer Fallback**: Unauthenticated local Unix socket calls extract kernel peer credentials (`SO_PEERCRED`) and fall back strictly to `homelab-viewer` privileges for non-sensitive reads (`list`, `get`, `resolve`, `ssl`, `health`), preserving zero-friction CLI inspection and shell tab-completion while blocking all mutations and secret dumps (`401`/`403`).
|
||||
* **3-Role Authorization Hierarchy**:
|
||||
* `homelab-admin`: Full access across `core`, `core_service`, and all valid `~/Sites/<app>` workloads.
|
||||
* `homelab-operator`: Mutations and sensitive reads strictly restricted to workloads admitted in `Core/config/deployments.yaml` (used by `gitops-dispatcher`). Denied (`403`) on `core`, `core_service`, and unregistered Sites directories.
|
||||
* `homelab-viewer`: Non-sensitive read-only operations only.
|
||||
* *(Milestone P5 expands this gate with LLDAP directory group mapping and authenticated Traefik/Authelia ForwardAuth proxy headers).*
|
||||
|
||||
#### 3. Dedicated Service Identity, OS Isolation & Fail-Closed Audit Guard (`DEC-03`)
|
||||
* The daemon executes as system user `homelab-appctl` (`Group = "homelab-operators"`, `SupplementaryGroups = [ "docker" ]`), with declarative recursive POSIX ACLs (`systemd.tmpfiles.rules`) granting shared read/write access on `~/Sites`, `~/var/lib/homelab`, and `~/Core/config/homepage`.
|
||||
* **Append-Only Audit Telemetry (`/var/log/homelab/appctl/audit.jsonl`, mode `0600`)**: Records `DISPATCHED`, `COMPLETED`, `FAILED`, and `DENIED` lifecycle events with `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, `commit_sha`, and secret-redacted `parameters`/`result`.
|
||||
* **Fail-Closed Disk Guard**: Mutating operations must write and flush a `DISPATCHED` audit record **before** invoking any Docker or Git subprocess. If the audit write fails (`OSError`), the mutation aborts immediately with `500 ERR_EXECUTION_FAILED`.
|
||||
|
||||
#### 4. GitOps Execution Unification (`DEC-04`)
|
||||
* `scripts/gitops_dispatcher.py` retains webhook HTTP ingress (port 9000), HMAC-SHA256 verification, `config/deployments.yaml` admission, and the commit-superseding `.pending.json` queue.
|
||||
* The background worker delegates deployment execution to the daemon's `workload.update` operation over `/run/homelab/appctl.sock` using its `homelab-operator` Bearer token, eliminating duplicated `git pull` and `docker compose` execution codepaths.
|
||||
|
||||
#### 5. Unified Pre-Flight & Pure-Python Environment Assembly (`DEC-05`)
|
||||
* Shell `eval` and `source` are completely eliminated. Subprocess environments are assembled in memory via an inert pure-Python `KEY=VALUE` reader enforcing `ENV_KEY_RE`, `RESERVED_ENV_KEYS`, and canonical domain precedence (`HOMELAB_DOMAIN` $\to$ `DOMAIN_SUFFIX` $\to$ `DOMAIN`).
|
||||
* Every workload mutation and `workload.config` call enforces path containment, `core_manifest.parse_manifest()`, and `validate_compose_security()` pre-flight inspection before invoking Docker Compose.
|
||||
|
||||
#### 6. Declarative Git Truth, Model Context Protocol (MCP) Gateway & AI Boundary (P5–P7 Trajectory)
|
||||
* **Git is Authoritative**: Approved deployment definitions are versioned in Git; `appctl` reconciles desired Git state into running containers.
|
||||
* **Architecture Amendment (2026-10-23 — MCP Tool Gateway Supersedes On-Server Authoring)**:
|
||||
The 5-stage on-server AI deployment authoring compiler (`ApplicationProfile` $\to$ `DeploymentProposal` $\to$ `DeploymentModel`) originally planned for Milestone P6 is **deprecated and superseded by a decoupled Model Context Protocol (MCP) Tool Gateway**. Rather than building bespoke AI authoring engines or autonomous agents into the appliance host, platform management operations (`appctl_status`, `appctl_deploy`, `appctl_logs`, `appctl_audit`) will be exposed via standardized JSON-RPC MCP tools consumed by external developer clients (Antigravity, Claude Code, Cursor) with native human-in-the-loop confirmation. The deterministic boundary of `appctl` is preserved, with zero autonomous AI agent code executing inside the appliance host.
|
||||
* **Secret Reference Invariant (P5)**: Manifests reference secrets by key (`secretKeyRef`) resolved at runtime via `SecretProvider`, never storing plaintext credentials in Git.
|
||||
* **Client Decoupling (P7)**: Homepage remains a read-only status portal; interactive web management belongs to a dedicated Operations UI client consuming `POST /v1/operations`.
|
||||
|
||||
## Pros and Cons of the Options
|
||||
|
||||
### Option 1: Status Quo with Local CLI Modernization
|
||||
* Good, because it requires no background daemon or socket listener.
|
||||
* Bad, because every process running under the operator's SSH UID retains full unauthenticated mutation authority over containers and secrets.
|
||||
* Bad, because CLI and GitOps execution remain split across separate processes without unified lock management or tamper-evident auditing.
|
||||
|
||||
### Option 2: Cloud-Native Micro-Platform
|
||||
* Good, because Kubernetes/ArgoCD provide built-in API servers and RBAC.
|
||||
* Bad, because cluster control planes impose heavy resource and operational complexity disproportionate to a single-node NixOS appliance.
|
||||
|
||||
### Option 3: Authoritative `homelab-appctl.service` Daemon (Adopted)
|
||||
* Good, because it isolates operational authority, secrets (`/run/secrets/appctl/tokens.json`), and audit logs (`/var/log/homelab/appctl/audit.jsonl`) under `homelab-appctl`.
|
||||
* Good, because `POST /v1/operations` guarantees 100% contract parity across UDS and HTTP transports.
|
||||
* Good, because `SO_PEERCRED` viewer fallback preserves ergonomic local read commands (`appctl list`, `appctl info`) while requiring tokens for mutations and secret reads.
|
||||
* Bad, because it introduces a core systemd daemon and requires provisioning SOPS-managed API tokens for mutating CLI and GitOps operations.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Consequences
|
||||
* **Defense-in-Depth Against Session Compromise**: Unprivileged scripts or AI coding agents in the operator's shell cannot mutate infrastructure, read `tokens.json`, or alter `audit.jsonl`.
|
||||
* **Single Execution Truth**: Interactive CLI commands and automated GitOps webhooks execute through the exact same pre-flight validator, lock manager, and environment builder.
|
||||
* **Deterministic Concurrency**: Per-target non-blocking `flock` locks (`/var/lib/homelab/appctl/locks/<target>.lock`) prevent overlapping mutations (`409 ERR_CONCURRENT_MUTATION`).
|
||||
|
||||
### Negative Consequences & Accepted Trade-offs
|
||||
* **Daemon Dependency**: Normal operational commands depend on `homelab-appctl.service` availability (emergency host recovery remains possible for human administrators via `sudo`).
|
||||
* **Token Provisioning**: Mutating CLI invocations require `APPCTL_TOKEN` / token configuration rather than relying on ambient SSH user identity.
|
||||
|
||||
## More Information
|
||||
|
||||
* **P4 Readiness & Boundary Specification**: [`docs/plans/p4-readiness-plan.md`](../plans/p4-readiness-plan.md)
|
||||
* **Companion ADRs**:
|
||||
* [ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model](0001-3tier-architecture-and-provenance.md)
|
||||
* [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md)
|
||||
* **Governing Roadmap**: [`ROADMAP.md`](../../ROADMAP.md) (Milestones P4–P7)
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
type: decision
|
||||
status: accepted
|
||||
project: homelab-core
|
||||
date: 2026-10-15
|
||||
tags: [architecture, appctl, validation, pydantic, security, api]
|
||||
---
|
||||
|
||||
# ADR 0003: Centralized Runtime Validation & Serialization via Pydantic v2
|
||||
|
||||
## Context and Problem Statement
|
||||
|
||||
As Homelab Core transitions from decoupled CLI scripts into an authoritative operational control plane (`homelab-appctl.service`, Milestone P4), the system must process untrusted inputs across two distinct ingestion boundaries:
|
||||
1. Declarative workload manifests (`app.yaml`) authored in `~/Sites` by independent workloads or external repository webhooks.
|
||||
2. Command-oriented API requests sent across dual transports (host Unix Domain Socket `/run/homelab/appctl.sock` and network HTTP listener).
|
||||
|
||||
Previously, manifest parsing relied on Python standard library dataclasses combined with manual regex checking and dictionary traversals in `scripts/core_manifest.py`. While functional for basic validation, manual ad-hoc validation created subtle security and maintainability risks:
|
||||
- Input parsing logic was duplicated across `core_manifest.py`, `appctl_engine.py`, and `gitops_dispatcher.py`.
|
||||
- Validation errors varied in structure and could inadvertently reflect unvalidated raw payloads (potentially leaking secrets or host paths).
|
||||
- Future daemon API endpoints would require writing independent request/response serialization, type-checking, and error-handling routines for every operation.
|
||||
|
||||
The central architectural question is: **How should the control plane enforce strict, fail-closed type safety and consistent serialization across workload manifests and daemon API endpoints without duplicating validation logic or leaking secrets?**
|
||||
|
||||
## Decision Drivers
|
||||
|
||||
* **Fail-Closed Type Safety**: Unrecognized fields, unexpected types, or invalid operations must be rejected immediately at the transport boundary before reaching the operational router.
|
||||
* **Unified Contract Enforcement**: Workload manifests (`app.yaml`) and control plane API payloads must share a common, declarative schema definition rather than separate parser implementations.
|
||||
* **Prevention of Information Disclosure**: Error payloads returned to clients or logged to audit streams must describe schema violations without echoing raw input values, environment variables, or credentials.
|
||||
* **Dual-Transport Parity**: The same validated contract must govern both local Unix Domain Socket calls (CLI) and remote HTTP calls (GitOps dispatcher, Web UI).
|
||||
* **Maintainability & Performance**: Minimizing bespoke parsing code while maintaining fast validation overhead suitable for daemon and CLI operations.
|
||||
|
||||
## Considered Options
|
||||
|
||||
* **Option 1: Standard Library Dataclasses with Custom Manual Validators**: Continue relying solely on Python `dataclasses` and manual validation functions (`isinstance`, regexes).
|
||||
* **Option 2: JSON Schema (`jsonschema`) with Manual Object Deserialization**: Use JSON Schema definitions to validate raw dicts, then manually map validated dicts to dataclasses.
|
||||
* **Option 3: Pydantic v2 with Strict Mode & Fail-Closed Configuration (Adopted)**: Introduce Pydantic v2 as the authoritative validation and serialization engine across manifests and API models.
|
||||
|
||||
## Decision Outcome
|
||||
|
||||
Chosen option: **Option 3: Pydantic v2 with Strict Mode & Fail-Closed Configuration**, because:
|
||||
|
||||
> *"We opted for centralizing runtime validation and serialization across workload manifest and daemon API around Pydantic models to enforce fail-closed type safety, strict schema-based contract boundaries and consistent serialization and error handling without leaking secrets."*
|
||||
|
||||
### Summary of Architectural Commitments
|
||||
|
||||
1. **Single Schema & Validation Layer**:
|
||||
All domain entities—including workload manifest configurations (`SourceConfig`, `DeploymentConfig`, `HomepageConfig`, `Manifest`) and control plane API command payloads (requests, responses, errors)—are defined exclusively as Pydantic v2 models inheriting from `pydantic.BaseModel`.
|
||||
2. **Fail-Closed Schema Boundaries (`extra="forbid"`)**:
|
||||
Every model enforces `ConfigDict(extra="forbid")`. Any payload containing unexpected, undocumented, or extraneous fields is rejected at the transport boundary with zero execution.
|
||||
3. **Strict Typing Policy (`strict=True`)**:
|
||||
To prevent unexpected coercion bugs (e.g. string `"false"` coercing to boolean `True`, or floats coercing to ints), API operations, target identifiers, flags (`recreate`, `remove_orphans`, `visible`, `auth`), and tokens enforce strict types. Explicit field validators handle string trimming/normalization where intentional.
|
||||
4. **Information Disclosure Prevention**:
|
||||
Transport adapters intercept `pydantic.ValidationError` and map it into structured `ERR_VALIDATION_FAILED` (HTTP 400) responses. Error messages report violating field names and failure rules, but strictly sanitize and redact raw input values to prevent leaking secrets, credentials, or filesystem paths.
|
||||
5. **Dual-Transport Parity**:
|
||||
The identical Pydantic request and response models govern both Unix domain socket messages and HTTP API endpoints. Neither transport performs custom validation outside the shared Pydantic models.
|
||||
6. **Host Runtime Alignment**:
|
||||
Pydantic is packaged into the NixOS system environment (`nixos/configuration.nix`), systemd unit paths (`nixos/modules/homeserver.nix`), Nix flake development shells, and repository test dependencies (`pyproject.toml`) constrained to major version range `>=2.0,<3.0`.
|
||||
|
||||
## Pros and Cons of the Options
|
||||
|
||||
### Option 1: Standard Library Dataclasses with Custom Manual Validators
|
||||
* Good, because it requires zero external dependencies and uses Python standard library modules.
|
||||
* Bad, because validation code must be manually implemented for every field, nested structure, and API payload.
|
||||
* Bad, because it is error-prone and historically led to parser duplication across `core_manifest.py`, `appctl_engine.py`, and `gitops_dispatcher.py`.
|
||||
* Bad, because serialization and deserialization (e.g. JSON to model and back) require bespoke helper methods.
|
||||
|
||||
### Option 2: JSON Schema (`jsonschema`) with Manual Object Deserialization
|
||||
* Good, because JSON Schema is a standardized language-agnostic specification.
|
||||
* Bad, because it requires maintaining two separate artifacts for every entity: a JSON Schema document and a corresponding Python dataclass or class.
|
||||
* Bad, because mapping validated JSON Schema dicts to Python typed objects adds runtime boilerplate and cognitive overhead.
|
||||
* Bad, because error messages from `jsonschema` can be difficult to sanitize and format into uniform domain error structures.
|
||||
|
||||
### Option 3: Pydantic v2 with Strict Mode & Fail-Closed Configuration (Adopted)
|
||||
* Good, because it provides declarative, unified model definitions that handle validation, type-checking, and JSON serialization in a single class.
|
||||
* Good, because Pydantic v2's Rust core (`pydantic-core`) delivers high-performance validation with minimal latency impact on the daemon.
|
||||
* Good, because built-in `ValidationError` metadata makes structured error mapping straightforward and consistent.
|
||||
* Good, because `model_dump(mode="json")` and `model_validate_json()` provide deterministic, standardized serialization across dual transports.
|
||||
* Bad, because it introduces a third-party dependency into the Core platform that must be maintained across NixOS packages, development shells, and CI pipelines (mitigated by locking `>=2.0,<3.0` in `pyproject.toml` and Nix flake checks).
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Consequences
|
||||
* Eliminates fragmented parsing code: all callers (`appctl_engine.py`, `gitops_dispatcher.py`, `homelab-appctl.service`) validate against the same authoritative schemas in `core_manifest.py`.
|
||||
* Pre-P4 security posture is substantially hardened: unvalidated fields and type confusion attacks are blocked at ingestion.
|
||||
* Clean separation of concerns: transport adapters focus on wire protocol handling while Pydantic guarantees valid domain objects for the operational router.
|
||||
* Client error payloads are structured, actionable, and safe from secret leakage.
|
||||
|
||||
### Negative Consequences & Accepted Trade-offs
|
||||
* Core depends on `pydantic` in host NixOS environment; all host Python environments executing `appctl` or `homelab-gitops` must have `python3Packages.pydantic` available.
|
||||
* Schema evolution requires strict versioning: since `extra="forbid"` is enforced, extending manifests or API payloads with new fields requires coordinated model updates.
|
||||
|
||||
## More Information
|
||||
|
||||
* **Governing Readiness Plan**: [`docs/plans/p4-readiness-plan.md`](../plans/p4-readiness-plan.md) (Section 2.B)
|
||||
* **Governing Roadmap**: [`ROADMAP.md`](../../ROADMAP.md) (Milestone P4)
|
||||
* **Platform Security Invariants**: [`AGENTS.md`](../../AGENTS.md) (Invariants #1, #2, #3)
|
||||
@@ -0,0 +1,91 @@
|
||||
---
|
||||
type: decision
|
||||
status: accepted
|
||||
project: homelab-core
|
||||
date: 2026-11-16
|
||||
tags: [architecture, workloads, monorepo, gitops, state, nixos]
|
||||
amends: 0001-3tier-architecture-and-provenance.md
|
||||
---
|
||||
|
||||
# ADR 0004: Unified ~/Workloads Monorepo & State Isolation
|
||||
|
||||
## Context and Problem Statement
|
||||
|
||||
Under [ADR-0001](0001-3tier-architecture-and-provenance.md), Tier 2 deployment descriptors (`app.yaml` and `docker-compose.yml`) were hosted in `~/Sites/<app>` as one standalone Git repository per application. In practice, operating a fleet of 9+ Tier 2 workloads (including both Class A source-backed services and Class B off-the-shelf image-only tools) revealed structural friction:
|
||||
|
||||
1. **Per-App Repository Sprawl**: Every third-party tool (`jellyfin`, `snappymail`, `excalidraw`, `mermaid`) required its own Gitea repository, webhook configuration, and clone lifecycle just to version 2–3 declarative files.
|
||||
2. **Naming Coupling (`~/Sites`)**: The directory name `~/Sites` implied web-only sites rather than general self-hosted workloads (mail, media, diagrams, internal tools).
|
||||
3. **Cross-Workload Drift & Webhook Overhead**: Coordinating shared network, label, or manifest conventions across N separate deployment repositories required N separate commits and N separate Gitea webhook registrations.
|
||||
4. **State Co-location Risk**: Moving to a unified monorepo increases the blast radius if any workload stores mutable runtime state inside its deployment directory instead of the isolated host state root (`~/var/lib/homelab/<app>/`).
|
||||
|
||||
The central architectural question is: **How should Canopy NixOS Core organize Tier 2 deployment descriptors to eliminate per-app repository sprawl while preserving independent per-workload deployment, backward-compatible migration, and strict runtime state isolation?**
|
||||
|
||||
## Decision Drivers
|
||||
|
||||
* **Eliminate Tier 2 Repository Sprawl**: Consolidate Tier 2 deployment descriptors (`<app>/app.yaml`, `<app>/docker-compose.yml`) into a single unified `canopy-workloads` monorepo at `~/Workloads`.
|
||||
* **Preserve Per-Workload Independence**: Pushing to `canopy-workloads` must selectively deploy only the workload subdirectories modified in that push, without restarting unaffected services.
|
||||
* **Zero-Downtime Migration Compatibility**: Support `WORKLOADS_DIR` as the canonical configuration variable with a clean `SITES_DIR` fallback, and support hybrid per-app `.git` checkouts alongside monorepo subdirectories during transition.
|
||||
* **Strict State Isolation**: Enforce `~/var/lib/homelab/<app>/` as the sole persistent runtime state root so the `~/Workloads` Git working tree remains 100% declarative and clean.
|
||||
* **Preserve 3-Tier & Security Boundaries**: Keep Tier 1 application source repositories independent, keep Core platform services in `~/Core`, and maintain `deployments.yaml` allowlisting and Compose AST security validation.
|
||||
|
||||
## Considered Options
|
||||
|
||||
* **Option 1: Keep Per-App Tier 2 Repositories in `~/Sites/<app>` (Status Quo)**: Maintain one Git repository per workload under `~/Sites`.
|
||||
* **Option 2: Merge Tier 2 Workloads into `~/Core`**: Place all workload `app.yaml` and `docker-compose.yml` files directly inside `canopy-homelab/nixos-core`.
|
||||
* **Option 3: Unified `~/Workloads` Monorepo (`canopy-workloads`) with Isolated Host State (Adopted)**: Amend ADR-0001 to rename Tier 2 from `~/Sites` to `~/Workloads`, consolidate Tier 2 manifests into `canopy-workloads`, and enforce `~/var/lib/homelab/<app>/` state isolation.
|
||||
|
||||
## Decision Outcome
|
||||
|
||||
Chosen option: **Option 3: Unified `~/Workloads` Monorepo (`canopy-workloads`) with Isolated Host State**, because it eliminates Tier 2 repository and webhook sprawl while preserving the 3-tier boundary between Tier 1 application source, Tier 2 deployment intent, and Tier 3 NixOS Core platform infrastructure.
|
||||
|
||||
### Summary of Architectural Commitments
|
||||
|
||||
This ADR formally amends [ADR-0001](0001-3tier-architecture-and-provenance.md) with the following commitments:
|
||||
|
||||
1. **Tier 2 Rename (`~/Sites` $\rightarrow$ `~/Workloads`)**:
|
||||
* The canonical Tier 2 deployment root is `~/Workloads` (configured via `homelab.workloadsDir` / `homelab.sitesDir` in NixOS and `WORKLOADS_DIR` in Core services).
|
||||
* Core Python modules (`appctl_engine.py`, `appctl_daemon.py`, `appctl_router.py`, `gitops_dispatcher.py`) default to `~/Workloads`, honoring `WORKLOADS_DIR` first and falling back to `SITES_DIR` for backward compatibility.
|
||||
2. **Unified `canopy-workloads` Monorepo**:
|
||||
* Tier 2 workloads reside as subdirectories `~/Workloads/<app>/` inside the `canopy-workloads` monorepo, each owning its own `app.yaml` and `docker-compose.yml`.
|
||||
* During migration, `~/Workloads/<app>` may operate either as a monorepo subdirectory (sharing `~/Workloads/.git`) or as a standalone checkout (`~/Workloads/<app>/.git`).
|
||||
3. **Mandatory State Isolation (`~/var/lib/homelab/<app>/`)**:
|
||||
* All mutable application data (databases, caches, uploads, dynamic configs) must reside under `~/var/lib/homelab/<app>/` (or named Docker volumes) and never inside `~/Workloads/<app>/`.
|
||||
* NixOS `systemd.tmpfiles.rules` provisions `~/Workloads` and `~/var/lib/homelab` with recursive `A+` POSIX ACLs for `homelab-appctl`.
|
||||
4. **Core Registry & Safe Directory Containment**:
|
||||
* `config/deployments.yaml` maps admitted workload identities to canonical `~/Workloads/<app>` paths, enforced by strict containment inside `WORKLOADS_DIR`.
|
||||
* Host Git `safe.directory` configuration includes `~/Workloads` and `~/Workloads/*` (alongside `~/Core`).
|
||||
|
||||
## Pros and Cons of the Options
|
||||
|
||||
### Option 1: Keep Per-App Tier 2 Repositories in `~/Sites/<app>`
|
||||
* Good, because each workload has an isolated Git history and independent webhook.
|
||||
* Bad, because adding or updating a simple third-party service requires creating and maintaining a full Git repository.
|
||||
* Bad, because fleet-wide manifest or Compose conventions require N separate PRs and commits.
|
||||
|
||||
### Option 2: Merge Tier 2 Workloads into `~/Core`
|
||||
* Good, because only one repository exists for Core and Workloads.
|
||||
* Bad, because it violates the 3-tier boundary (ADR-0001), mixing NixOS host/platform configuration with application deployment topologies.
|
||||
* Bad, because `~/Core` changes would trigger NixOS evaluation/rebuild concerns alongside routine app updates.
|
||||
|
||||
### Option 3: Unified `~/Workloads` Monorepo (`canopy-workloads`) with Isolated Host State (Adopted)
|
||||
* Good, because Tier 2 deployment descriptors are managed in one repository with atomic cross-workload changes and a single GitOps webhook.
|
||||
* Good, because Tier 1 software repositories and Tier 3 NixOS Core remain strictly decoupled.
|
||||
* Good, because `WORKLOADS_DIR` $\rightarrow$ `SITES_DIR` fallback allows incremental host cutover without breaking existing environments.
|
||||
* Bad, because GitOps webhook dispatch and provenance inspection must distinguish monorepo-root `.git` from per-app `.git` checkouts (addressed in follow-up slices).
|
||||
* Bad, because monorepo commits touching multiple subdirectories require changed-path filtering to avoid redeploying unaffected workloads.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Consequences
|
||||
* **Single Tier 2 Control Surface**: One `canopy-workloads` repository versions all workload manifests and Compose topologies.
|
||||
* **Clean Git Working Tree**: Enforcing `~/var/lib/homelab/<app>/` ensures runtime state never dirties the monorepo checkout.
|
||||
* **Smooth Cutover**: Dual `WORKLOADS_DIR` / `SITES_DIR` environment support and `homelab.sitesDir` NixOS option compatibility prevent abrupt breakage.
|
||||
|
||||
### Negative Consequences & Accepted Trade-offs
|
||||
* **Hybrid Provenance & Subpath Dispatch Complexity**: Core tooling (`provenance.py`, `gitops_dispatcher.py`) must handle both monorepo-level `.git` and legacy per-app `.git` directories, as well as selective changed-directory deployment on monorepo pushes.
|
||||
|
||||
## More Information
|
||||
|
||||
* **Amended Decision**: [`0001-3tier-architecture-and-provenance.md`](0001-3tier-architecture-and-provenance.md)
|
||||
* **Architecture Specification**: [`docs/architecture.md`](../architecture.md)
|
||||
* **Secrets & State Contract**: [`docs/secrets-and-state.md`](../secrets-and-state.md)
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
type: decision
|
||||
status: accepted
|
||||
project: homelab-core
|
||||
date: 2026-11-20
|
||||
tags: [architecture, security, nixos, workloads, appctl, gitops]
|
||||
amends: 0002-appctl-control-plane-architecture.md
|
||||
---
|
||||
|
||||
# ADR 0005: Host-Granted Workload Capabilities ("Compose Requests, Nix Grants")
|
||||
|
||||
## Context and Problem Statement
|
||||
|
||||
Under [ADR-0001](0001-3tier-architecture-and-provenance.md), [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`), and [ADR-0004](0004-unified-workloads-monorepo.md), `validate_compose_security()` (shared pre-flight validator invoked authoritatively by `homelab-appctl.service` in `scripts/appctl_router.py` across CLI and GitOps paths) enforces a uniform deny-all policy on Tier 2 workload `docker-compose.yml` files:
|
||||
|
||||
* `devices:` mounts are blocked.
|
||||
* Host bind mounts outside `~/Workloads/<app>` and `~/var/lib/homelab/<app>` are blocked.
|
||||
* Host namespace sharing (`network_mode: host`, etc.) is blocked.
|
||||
|
||||
While this prevents a Tier 2 `git push` from escalating privileges on the host, it blocks required single-operator capability classes:
|
||||
|
||||
1. **Hardware-Accelerated & External-Storage Workloads**: Media transcoding or compute workloads requiring an integrated GPU (`/dev/dri/renderD128`) must mount host device nodes, pass a supplementary device group (such as `render` / GID `303`), and read an external read-only storage partition (`/media:ro`). Currently, `devices:` and external bind mounts are blocked, while `group_add:` and `user:` primary GIDs are unconstrained (risking arbitrary host GID elevation to groups such as `docker` or `wheel` unless constrained).
|
||||
2. **LAN Broadcast / Peer-Discovery Services (Out of Scope for Host Networking)**: Workloads that send Wake-on-LAN magic packets or discover LAN peers cannot traverse Docker bridge L2 isolation, prompting requests for `network_mode: host`. Because blanket host networking collapses network namespace isolation—exposing loopback control services such as `homelab-appctl.service` on `127.0.0.1:9001`—host networking remains out of scope for workload grants and must be handled via isolated L2 Docker networks (`macvlan`/`ipvlan`) or host-side intermediaries.
|
||||
3. **Host-Agnostic Core Boundary**: Hardcoding `/dev/dri`, `/media`, or specific workload names inside `nixos-core` violates platform portability and couples Core to one machine's hardware and app catalog.
|
||||
|
||||
The central architectural question is: **How should Canopy NixOS Core permit hardware devices, supplementary/primary GIDs, and external read-only storage paths for specific workloads without hardcoding personal infrastructure into `nixos-core` or weakening the Tier 2 -> Tier 3 trust boundary?**
|
||||
|
||||
## Decision Drivers
|
||||
|
||||
* **Preserve the Trust Split**: A push to Tier 2 (`canopy-workloads`) must never grant itself root-equivalent host access; capability grants must originate from root-level Tier 3 NixOS host configuration (`nixos-rebuild switch`).
|
||||
* **Keep `nixos-core` Generic**: Core defines the capability schema and enforcement logic only, with zero hardcoded personal app names, device nodes, or media paths.
|
||||
* **Keep `app.yaml` Free of Host Paths**: Workload manifests remain declarative routing/provenance metadata; `docker-compose.yml` already declares requested `devices`, `volumes`, `group_add`, and `user`.
|
||||
* **Documented Instance Schema**: Provide a tracked `nixos/instance.example.nix` template so new hosts can configure `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants` in `/etc/nixos/homelab-instance.nix` (or gitignored `nixos/instance.nix`).
|
||||
* **Fail-Closed Validation**: An absent grants file defaults to zero grants (current baseline); a present but unreadable, tampered, or malformed grants file fails closed across all workloads. `privileged: true`, `/var/run/docker.sock`, `cap_add`, `device_cgroup_rules:`, and host/container namespace sharing remain permanently prohibited.
|
||||
|
||||
## Considered Options
|
||||
|
||||
* **Option 1: Relax `validate_compose_security()` Globally**: Allow `/dev/dri` and arbitrary `:ro` paths for all workloads.
|
||||
* **Option 2: Store Grants in `~/Workloads/grants.yaml`**: Allow `canopy-workloads` to declare its own exceptions alongside `deployments.yaml`.
|
||||
* **Option 3: "Compose Requests, Nix Grants" via `homelab.workloadGrants` (Adopted)**: Define a typed `homelab.workloadGrants` option in `nixos-core` rendered to root-owned `/etc/homelab/grants.json`, validated with Pydantic v2 (`extra="forbid"`), and enforced by `validate_compose_security()`.
|
||||
|
||||
## Decision Outcome
|
||||
|
||||
Chosen option: **Option 3: "Compose Requests, Nix Grants" via `homelab.workloadGrants`**, because it keeps `nixos-core` hardware- and workload-agnostic while preserving the security boundary between Tier 2 Git pushes and Tier 3 `sudo nixos-rebuild switch`.
|
||||
|
||||
### Summary of Architectural Commitments
|
||||
|
||||
This ADR formally amends [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`) with the following commitments:
|
||||
|
||||
1. **Typed Host Grant Schema (`homelab.workloadGrants`)**:
|
||||
* `nixos/modules/homeserver.nix` defines `homelab.workloadGrants` as an attribute set keyed by workload name, supporting three explicit grant fields:
|
||||
* `devices` (list of exact device paths; prefer specific nodes such as `"/dev/dri/renderD128"` over whole directories unless display control is required).
|
||||
* `groups` (list of supplementary/primary group names or GIDs permitted in `group_add` and `user:`, such as `"render"` or `"303"`; privileged host groups `0`/`root`, `wheel`, and `docker` are permanently rejected).
|
||||
* `readOnlyPaths` (list of host directories permitted for read-only bind mounts only).
|
||||
* `privileged: true`, `/var/run/docker.sock`, `cap_add`, `device_cgroup_rules:`, and namespace sharing (`network_mode: host`, `network_mode: container:*`, `network_mode: service:*`, `pid`, `ipc`, `uts`, `userns_mode: host`) remain permanently prohibited and are not grantable.
|
||||
|
||||
2. **Immutable Host Projection (`/etc/homelab/grants.json`)**:
|
||||
* NixOS generates `/etc/homelab/grants.json` (`root`-owned, group-owned by `homelab-operators` with mode `0640`, granting read access to both `homelab-appctl` and `operator` without POSIX ACLs; overridable via `HOMELAB_GRANTS_FILE`, which is reserved in `RESERVED_ENV_KEYS` so workload `.env` / `app.yaml` cannot override it).
|
||||
* In production, the loader verifies regular-file (non-symlink), root-owned, non-world/group-writable permissions before parsing.
|
||||
* If `/etc/homelab/grants.json` is **absent**, `validate_compose_security()` defaults to zero grants. If it is **present** but unreadable, fails permission checks, or fails Pydantic v2 (`extra="forbid"`) validation, pre-flight fails closed for all workloads.
|
||||
|
||||
3. **Exact-Match Pre-Flight Enforcement**:
|
||||
* `validate_compose_security()` evaluates resolved values (post-6-layer env assembly, or rejects uninterpolated `${...}` in `devices`, `volumes`, `group_add`, and `user`). When `app_name` is `None` or unknown, zero grants apply.
|
||||
* Every capability requested in `<app>/docker-compose.yml` must match an explicit grant for `<app>`:
|
||||
* `devices` entries support `host:container[:perms]`, forbid `m` (`mknod`) in permissions, and require the host path to exist and resolve canonically within the granted device node or directory, disallowing `..` traversal or symlink escapes.
|
||||
* `group_add` transitions from unconstrained to **default-deny** when no `groups` grant exists; `groups` entries canonicalize bidirectionally between group names and integer GIDs via the host group database. `user:` primary GIDs must either fall within granted `groups` or be unprivileged numeric IDs that do not map to privileged or host-sensitive groups.
|
||||
* `readOnlyPaths` validates both short (`host:container:ro[,opts]`) and long (`type: bind`, `read_only: true`) volume syntax, rejects unsafe bind propagation, and requires the host path to exist and resolve canonically within the granted directory.
|
||||
|
||||
4. **Tracked Instance Template (`nixos/instance.example.nix`)**:
|
||||
* `nixos-core` tracks `nixos/instance.example.nix` documenting `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants`.
|
||||
* Live hosts keep concrete values in `/etc/nixos/homelab-instance.nix` (loaded via `--impure` flake evaluation, taking precedence over gitignored `nixos/instance.nix` if both exist). Both paths remain optional so pure `nix flake check` CI passes with defaults.
|
||||
|
||||
## Pros and Cons of the Options
|
||||
|
||||
### Option 1: Relax `validate_compose_security()` Globally
|
||||
* Good, because it requires minimal code.
|
||||
* Bad, because it hardcodes host hardware assumptions into `nixos-core` and weakens tenant isolation for all workloads.
|
||||
|
||||
### Option 2: Store Grants in `~/Workloads/grants.yaml`
|
||||
* Good, because grants live next to `deployments.yaml`.
|
||||
* Bad, because Tier 2 would self-authorize Tier 3 host privileges on a single `git push`.
|
||||
|
||||
### Option 3: "Compose Requests, Nix Grants" via `homelab.workloadGrants` (Adopted)
|
||||
* Good, because `nixos-core` stays generic, `canopy-workloads` remains free of host-privilege grants, and privilege elevation requires explicit host-level `nixos-rebuild switch`.
|
||||
* Bad, because adding a new privileged capability requires editing `/etc/nixos/homelab-instance.nix` and rebuilding NixOS before `appctl up`.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Consequences
|
||||
* **Hardware & Media Operability**: Workloads can use GPU acceleration and external `:ro` storage cleanly via standard `docker-compose.yml` syntax once authorized by the host.
|
||||
* **Closed GID & Namespace Loopholes**: Transitions `group_add:`, `user:` primary GIDs, `device_cgroup_rules:`, and `network_mode: container:*` to fail-closed enforcement.
|
||||
* **CI Compatibility**: Pure `nix flake check` evaluates cleanly with empty default grants.
|
||||
|
||||
### Negative Consequences & Accepted Trade-offs
|
||||
* **Tier 2 / Tier 3 Deployment Ordering**: Pushing a Compose file requesting a new capability before running `nixos-rebuild switch` fails closed at pre-flight (surfaced clearly via a distinct capability-denial error/audit signal such as `ERR_CAPABILITY_NOT_GRANTED`).
|
||||
* **Host Path Coupling**: Workload Compose files declare physical host paths matching host grants; logical capability aliasing via environment-variable injection remains an optional future refinement.
|
||||
|
||||
## More Information
|
||||
|
||||
* Amends [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`).
|
||||
* Related specifications: [docs/architecture.md](../architecture.md), [docs/appctl.md](../appctl.md), [docs/secrets-and-state.md](../secrets-and-state.md).
|
||||
@@ -0,0 +1,89 @@
|
||||
# 🏛️ Homelab Core & Appctl Architecture Decision Index
|
||||
|
||||
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 (`NNNN-slug.md`).
|
||||
|
||||
---
|
||||
|
||||
## 📋 Active Architectural Decisions
|
||||
|
||||
| Decision Record | Status | Date | Scope & One-Line Purpose |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| [**ADR-0005: Host-Granted Workload Capabilities**](0005-workload-capability-grants.md) | `accepted` | 2026-11-20 | Amends ADR-0002 to introduce `homelab.workloadGrants` (`/etc/homelab/grants.json`) and `nixos/instance.example.nix` so NixOS hosts explicitly authorize `devices`, `groups`, and `readOnlyPaths` per workload while keeping host/container networking prohibited. |
|
||||
| [**ADR-0004: Unified ~/Workloads Monorepo & State Isolation**](0004-unified-workloads-monorepo.md) | `accepted` | 2026-11-16 | Amends ADR-0001 to adopt the unified `~/Workloads` Tier 2 monorepo (`canopy-workloads`), rename `~/Sites` to `~/Workloads` with `WORKLOADS_DIR` fallback, and enforce `~/var/lib/homelab/<app>/` state isolation. |
|
||||
| [**ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. |
|
||||
| [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and deterministic Git-backed declarative deployment state. |
|
||||
| [**ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model**](0001-3tier-architecture-and-provenance.md) | `accepted` | 2026-09-28 | Establishes 3-tier separation (Software, OCI Artifact, Sites Deployment, Core Platform), two workload classes (Source-Backed vs. Image-Only), isolated state root (`~/var/lib/homelab/<app>/`), and two operational inspection axes. |
|
||||
|
||||
---
|
||||
|
||||
## 🧭 Summaries of Governing Decisions
|
||||
|
||||
### [ADR-0005: Host-Granted Workload Capabilities ("Compose Requests, Nix Grants")](0005-workload-capability-grants.md)
|
||||
* **Canonical Document**: [`0005-workload-capability-grants.md`](0005-workload-capability-grants.md)
|
||||
* **Status**: `accepted` (Active — Amends ADR-0002)
|
||||
* **Core Commitments**:
|
||||
1. **Typed Host Grant Schema (`homelab.workloadGrants`)**: NixOS exposes per-workload `devices`, `groups`, and `readOnlyPaths` grants while keeping `privileged: true`, `docker.sock`, `cap_add`, `device_cgroup_rules`, and host/container namespace sharing permanently forbidden.
|
||||
2. **Immutable Host Projection (`/etc/homelab/grants.json`)**: Projected root-owned at rebuild time; absent file defaults to zero grants, malformed file fails closed.
|
||||
3. **Exact-Match Pre-Flight Enforcement**: `validate_compose_security()` allows requested capabilities only when canonically matched against the workload's Nix grant (and `:ro` for `readOnlyPaths`).
|
||||
4. **Tracked Instance Template (`nixos/instance.example.nix`)**: Documents `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants` for `/etc/nixos/homelab-instance.nix`.
|
||||
|
||||
### [ADR-0004: Unified ~/Workloads Monorepo & State Isolation](0004-unified-workloads-monorepo.md)
|
||||
* **Canonical Document**: [`0004-unified-workloads-monorepo.md`](0004-unified-workloads-monorepo.md)
|
||||
* **Status**: `accepted` (Active — Amends ADR-0001)
|
||||
* **Core Commitments**:
|
||||
1. **Tier 2 Rename (`~/Sites` -> `~/Workloads`)**: Canonical Tier 2 deployment root is `~/Workloads`, with `WORKLOADS_DIR` -> `SITES_DIR` environment fallback.
|
||||
2. **Unified `canopy-workloads` Monorepo**: Tier 2 workload manifests (`app.yaml`, `docker-compose.yml`) consolidate under `~/Workloads/<app>/`, supporting hybrid per-app `.git` checkouts during migration.
|
||||
3. **Mandatory State Isolation**: All mutable application data resides strictly under `~/var/lib/homelab/<app>/` (or named Docker volumes), never inside `~/Workloads`.
|
||||
4. **Workloads Registry & Safe Directory Containment**: `~/Workloads/deployments.yaml` (templated by `config/deployments.yaml`) resolves admitted workloads within `WORKLOADS_DIR`; NixOS `safe.directory` includes `~/Workloads` and `~/Workloads/*`.
|
||||
|
||||
### [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md)
|
||||
* **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md)
|
||||
* **Status**: `accepted` (Active)
|
||||
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Milestone P4)
|
||||
* **Core Commitments**:
|
||||
1. **Single Schema & Validation Layer**: Workload manifests (`core_manifest.py`) and API command models inherit from `pydantic.BaseModel`.
|
||||
2. **Fail-Closed Extra Fields (`extra="forbid"`)**: Immediate rejection of unexpected or undocumented payload properties.
|
||||
3. **Strict Typing Policy (`strict=True`)**: Coercion forbidden on operations, targets, identifiers, and flags.
|
||||
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.
|
||||
|
||||
### [ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture](0002-appctl-control-plane-architecture.md)
|
||||
* **Canonical Document**: [`0002-appctl-control-plane-architecture.md`](0002-appctl-control-plane-architecture.md)
|
||||
* **Status**: `accepted` (Active — Reconciled with Pre-P4 Locked Decisions `DEC-01`–`DEC-05`)
|
||||
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v6)
|
||||
* **Core Commitments**:
|
||||
1. **One Logical Command API Across Dual Transports (`DEC-01`)**: `homelab-appctl.service` exposes `POST /v1/operations` (13 canonical domain operations) and `GET /v1/health` over HTTP/1.1 on `/run/homelab/appctl.sock` and `127.0.0.1:9001`.
|
||||
2. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**: Every mutating operation and sensitive read (`workload.config`, `workload.logs`) requires an authenticated SHA-256 Bearer token (`/run/secrets/appctl/tokens.json`); tokenless UDS calls fall back via `SO_PEERCRED` strictly to `homelab-viewer` read-only inspection.
|
||||
3. **Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)**: Daemon executes as `homelab-appctl:homelab-operators` with mode `0600` append-only `/var/log/homelab/appctl/audit.jsonl` and a pre-execution `DISPATCHED` disk guard.
|
||||
4. **GitOps Worker Unification & Pure-Python Pre-Flight (`DEC-04`, `DEC-05`)**: `gitops_dispatcher.py` worker delegates `workload.update` to the daemon; shell `source`/`eval` are replaced with pure-Python `.env` parsing and mandatory `validate_compose_security()` pre-flight checks.
|
||||
5. **Git Truth, Model Context Protocol (MCP) Gateway & AI Boundary (P5–P7)**: Git remains authoritative deployment state; on-server AI proposal compilers deprecated in favor of a decoupled Model Context Protocol (MCP) tool gateway with human confirmation gating; resolves workload secrets via `SecretProvider` (`secretKeyRef`).
|
||||
|
||||
### [ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model](0001-3tier-architecture-and-provenance.md)
|
||||
* **Canonical Document**: [`0001-3tier-architecture-and-provenance.md`](0001-3tier-architecture-and-provenance.md)
|
||||
* **Status**: `accepted` (Active)
|
||||
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v6)
|
||||
* **Core Commitments**:
|
||||
1. **3-Tier Separation of Concerns**:
|
||||
* *Tier 1 (Software Layer)*: Upstream application repositories owning code, tests, and CI. Zero Homelab infrastructure coupling.
|
||||
* *Intermediate Provenance Artifact*: OCI container images produced by CI carrying commit provenance in metadata labels and content-addressed digests.
|
||||
* *Tier 2 (Sites Deployment Layer)*: Declarative manifests (`app.yaml`) and Compose specs in `~/Sites`.
|
||||
* *Tier 3 (Platform Core Appliance)*: NixOS host foundation, edge routing, SSO, and operational controllers.
|
||||
2. **Two Workload Deployment Classes**:
|
||||
* *Class A (Source-Backed)*: Declares upstream Git source and ref (`source.url`, `source.ref`); tracks upstream Git revisions against container labels.
|
||||
* *Class B (Image-Only)*: Standard third-party tools; tracks container registry image tags and digests.
|
||||
3. **Isolated Persistent State Root**: Mutable data lives strictly under `~/var/lib/homelab/<app>/`, isolated from Git repositories.
|
||||
4. **Two Operational Inspection Axes**: Local deployment checkout state evaluated independently of upstream software provenance (resolved via `git ls-remote`).
|
||||
|
||||
---
|
||||
|
||||
## 📜 Superseded Historical Decisions & Lineage
|
||||
|
||||
The following historical plans and design iterations have been formally superseded by the active ADRs and Roadmap v6:
|
||||
|
||||
* **Roadmap v5 (`architecture-consolidation-roadmap-v5.md`)**: Superseded by Roadmap v6 (`DEC-01`–`DEC-05` pre-P4 boundary lock).
|
||||
* **Roadmap v4, v3, v2 & v1** (`architecture-consolidation-roadmap-v4.md`): Superseded by Roadmap v5/v6.
|
||||
* **appctl-v2 Modernization Plan** (`appctl-engine-v2-refactoring.md`): Scaffolded and absorbed into Roadmap Phases P0 and P3.
|
||||
* **Smart Selective Deployment Pipeline Plan** (`smart-deployment-pipeline.md`): Absorbed into Phase P4 control-plane reconciliation.
|
||||
* **Architecture Implementation Guide v3 & v2** (`architecture-consolidation-implementation-guide-v3.md`): Superseded by unified Roadmap v4–v6.
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
# ⚡ Homelab Core — GitOps Continuous Deployment Engine
|
||||
|
||||
Homelab Core includes an automated GitOps deployment engine implemented in [`scripts/gitops_dispatcher.py`](../scripts/gitops_dispatcher.py). It processes Git push webhooks from Gitea (or external Git forges) and executes declared deployment actions strictly for admitted application workloads in `~/Sites`.
|
||||
|
||||
---
|
||||
|
||||
## 1. Architectural Model
|
||||
|
||||
The GitOps engine is invoked via the `homelab-gitops.service` systemd unit running on internal/firewall port 9000:
|
||||
|
||||
```
|
||||
Webhook Request (:9000)
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 1. Cryptographic HMAC-SHA256 Verification │
|
||||
│ Constant-time comparison with SOPS secret │
|
||||
└───────────────────────┬───────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 2. Event & Ref Format Admission │
|
||||
│ Admits 'push' to 'refs/heads/*' │
|
||||
│ Rejects PRs, issues, releases, and tags │
|
||||
└───────────────────────┬───────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 3. Authoritative Registry Resolution │
|
||||
│ Maps names via ~/Workloads/deployments.yaml│
|
||||
│ Fails closed; zero dynamic discovery on host│
|
||||
└───────────────────────┬───────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 4. Pre-Pull Manifest & Branch Policy Check │
|
||||
│ Validates app.yaml & matches target branch │
|
||||
└───────────────────────┬───────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 5. Atomic Enqueue & Immediate HTTP 200 │
|
||||
│ Writes pending state & spawns async worker │
|
||||
└───────────────────────┬───────────────────────┘
|
||||
│
|
||||
▼ (Detached Worker Process)
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 6. Serialized Worker & Lock Acquisition │
|
||||
│ Non-blocking flock; supersedes stale queue │
|
||||
└───────────────────────┬───────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 7. Revision-Consistent Validation & Execution │
|
||||
│ git pull -> re-validate manifest on-tree │
|
||||
│ Compose AST security validator (containment│
|
||||
│ & privilege checks) -> compose up -> status│
|
||||
└───────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Admission & Execution Gates
|
||||
|
||||
### A. Non-Shell Subprocess Execution
|
||||
* The deployment engine contains no `shell=True` subprocess invocations.
|
||||
* Commands are executed as fixed argument lists (e.g. `["docker", "compose", "-f", ..., "up", "-d"]`).
|
||||
* Arbitrary `custom:` shell actions fail validation closed.
|
||||
|
||||
### B. Cryptographic HMAC-SHA256 Authentication
|
||||
* Incoming webhook payloads must provide a signature via `X-Gitea-Signature` or `X-Hub-Signature-256`.
|
||||
* Signatures are verified using HMAC-SHA256 with `hmac.compare_digest` against the shared secret stored in `nixos/secrets.yaml` (projected to `/run/secrets/gitops/webhook_secret`).
|
||||
* Missing, empty, or mismatched signatures are rejected.
|
||||
|
||||
### C. Authoritative Repository Registry (`deployments.yaml`)
|
||||
* Webhook payloads identify targets strictly by logical name (e.g. `docs`, `homelab-docs`), never by raw filesystem path.
|
||||
* `~/Workloads/deployments.yaml` (configured via `HOMELAB_DEPLOYMENTS_FILE`, with `Core/config/deployments.yaml` serving as the example template) is the **sole admission authority** for GitOps workloads.
|
||||
* **No Dynamic Discovery**: Scanning `~/Sites` dynamically is strictly prohibited. An unapproved directory created on disk cannot receive webhook deployment rights merely by providing an `app.yaml`.
|
||||
* **Fail-Closed Guarantee**: If `deployments.yaml` is missing, unreadable, or malformed, the dispatcher fails closed and admits zero repositories.
|
||||
* **Input Validation**: Names must match `^[a-zA-Z0-9][a-zA-Z0-9._-]*$`. Slashes, backslashes, and path traversal sequences (`..`) are rejected.
|
||||
* **Containment Check**: Declared repository paths must resolve strictly within `~/Sites`. Paths escaping `~/Sites` are rejected during registry loading.
|
||||
|
||||
### D. Revision-Consistent Manifest Validation
|
||||
* When a webhook is admitted, an initial policy check verifies that the pushed branch matches the declared `deployment.branch`.
|
||||
* After `git pull --ff-only` runs, the working tree reflects the newly pulled commit.
|
||||
* The engine **re-reads and re-validates `app.yaml` from the newly pulled working tree** before running subsequent container actions (`compose_up`, `compose_build`, etc.).
|
||||
* If the pulled commit introduces an invalid action, unsupported strategy, or changes the target branch away from the pushed branch, deployment is aborted.
|
||||
|
||||
### E. Compose AST Security Validation
|
||||
Before executing `docker compose up -d`, `validate_compose_security()` parses the application's Compose file and enforces platform security invariants:
|
||||
* **File Integrity**: `docker-compose.yml` and `app.yaml` must be regular files, not symlinks escaping the workload root.
|
||||
* **Privilege Containment**: Rejects `privileged: true`, `cap_add` capabilities, `devices` mounts, and `security_opt: ["apparmor:unconfined"]`.
|
||||
* **Namespace Isolation**: Rejects host namespaces (`network_mode: host`, `pid: host`, `ipc: host`, `uts: host`, `userns_mode: host`).
|
||||
* **Docker Socket Ban**: Rejects direct bind mounts of `/var/run/docker.sock` (reserved exclusively for Core `socket-proxy:ro`).
|
||||
* **Top-Level Directives**: Rejects top-level `include:` directives to prevent out-of-tree file inclusions.
|
||||
* **Bind-Mount & State Isolation**:
|
||||
- Resolves all bind mounts (both relative and absolute) against the authorized workload directory.
|
||||
- Bind mounts are strictly restricted to **either** the workload root (`~/Sites/<app>/`) **or** the dedicated per-workload persistent state root (`~/var/lib/homelab/<app>/`).
|
||||
- Cross-tenant mounts (mounting another application's directory under `~/var/lib/homelab/`) are rejected fail-closed.
|
||||
|
||||
---
|
||||
|
||||
|
||||
## 3. Asynchronous Queueing, Serialization & Superseding
|
||||
|
||||
To avoid blocking HTTP connections and handle overlapping pushes:
|
||||
|
||||
1. **Immediate HTTP 200 Return**: Upon passing admission, the dispatcher writes a pending file (`~/.local/state/homelab/gitops/<target>.pending.json`), spawns a detached worker (`--worker <target>`), and returns HTTP 200.
|
||||
2. **Per-Target `flock` Serialization & Daemon Delegation**: The worker acquires an exclusive non-blocking `fcntl.flock` on `~/.local/state/homelab/gitops/<target>.lock`. When `/run/homelab/appctl.sock` is available, the worker delegates `workload.update` to `homelab-appctl.service` over UDS authenticating with `/run/secrets/gitops/appctl_token` (`homelab-operator` role), which executes `git pull --ff-only`, re-validates `app.yaml` and Compose security, runs the declared actions, logs to `/var/log/homelab/appctl/audit.jsonl`, and syncs Homepage.
|
||||
3. **Commit Superseding**:
|
||||
- Commit A begins deploying.
|
||||
- Commit B arrives and is written to the pending file.
|
||||
- Commit C arrives while A is still deploying; C overwrites B in the pending file.
|
||||
- Commit A completes; the worker processes C, skipping intermediate commit B.
|
||||
|
||||
---
|
||||
|
||||
## 4. Manifest Deployment Configuration (`app.yaml`)
|
||||
|
||||
Workload repositories declare their deployment policy under the `deployment` block in `app.yaml`:
|
||||
|
||||
```yaml
|
||||
deployment:
|
||||
branch: "main" # Target branch that triggers deployment
|
||||
strategy: "compose" # Deployment strategy (only 'compose' is permitted)
|
||||
actions: # Strictly allowlisted actions
|
||||
- git_pull # Pulls latest branch revision (--ff-only)
|
||||
- compose_up # Runs docker compose up -d --remove-orphans
|
||||
```
|
||||
|
||||
### Allowlisted Deployment Actions
|
||||
* **`git_pull`**: Executes `git -C <target> pull --ff-only origin <branch>`.
|
||||
* **`compose_up`**: Executes `docker compose -f <compose_file> up -d --remove-orphans`.
|
||||
* **`compose_build`**: Executes `docker compose -f <compose_file> build` followed by `compose_up`.
|
||||
* **`compose_restart`**: Executes `docker compose -f <compose_file> restart`.
|
||||
|
||||
Any action outside this list causes manifest validation to fail closed.
|
||||
|
||||
---
|
||||
|
||||
## 5. Execution State & Monitoring
|
||||
|
||||
Each deployment records its result to a status file:
|
||||
|
||||
**Path**: `~/.local/state/homelab/gitops/<target>.status.json`
|
||||
|
||||
**Example Content**:
|
||||
```json
|
||||
{
|
||||
"target": "homelab-docs",
|
||||
"branch": "main",
|
||||
"commit_sha": "d4f8a1e2c3b5a7",
|
||||
"success": true,
|
||||
"timestamp": "2026-09-16T12:00:00+00:00"
|
||||
}
|
||||
```
|
||||
|
||||
### Diagnostics & Manual Invocations
|
||||
```bash
|
||||
# View live webhook dispatcher logs
|
||||
journalctl -u homelab-gitops -f
|
||||
|
||||
# Inspect deployment status for a service
|
||||
cat ~/.local/state/homelab/gitops/homelab-docs.status.json
|
||||
|
||||
# Trigger a local manual deployment run
|
||||
python3 ~/Core/scripts/gitops_dispatcher.py --repo docs --branch main
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Pre-Merge CI Gating vs. Post-Merge CD Dispatcher
|
||||
|
||||
The continuous deployment engine operates strictly **downstream** of CI verification:
|
||||
|
||||
```
|
||||
[Developer / PR] ──► [Gitea Actions CI] ──► [Merge to main] ──► [Gitea Webhook] ──► [homelab-gitops] ──► [Deploy]
|
||||
(:host act_runner) (Host Daemon)
|
||||
```
|
||||
|
||||
1. **Pre-Merge CI Invariant (`.gitea/workflows/ci.yaml`)**:
|
||||
- Executes directly on `:host` `act_runner` instances (`ubuntu-latest:host` / `nix:host`) with a **pre-baked host toolchain** (`nix`, `node`, `git`, `coreutils`), without spawning nested `container:` jobs.
|
||||
- Runs hermetic validation (`nix flake check`, `pytest`, `ruff`) with Git safe directory enforcement.
|
||||
- Prevents broken code, misconfigured flakes, or regression bugs from entering `main`.
|
||||
2. **Post-Merge CD Execution (`homelab-gitops.service`)**:
|
||||
- Triggers only after commits are admitted into `main`.
|
||||
- Executes non-shell allowlisted actions (`git_pull`, `compose_up`) on the server host.
|
||||
- Operates fully decoupled from the CI runner runtime.
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
# ADR 001: Removal of Localhost Routers for Development Freedom
|
||||
|
||||
* **Status**: Accepted & Implemented
|
||||
* **Date**: 2026-05-17
|
||||
* **Decider**: User & Gemini CLI
|
||||
|
||||
## Context
|
||||
Initially, we implemented `*.localhost` routers in Traefik to allow local access to services (e.g., `jellyfin.localhost`) without traversing the public internet. The goal was to provide a "fast lane" for local management.
|
||||
|
||||
However, two major technical hurdles were encountered:
|
||||
1. **SSL/TLS Restrictions**: Public Certificate Authorities (like Let's Encrypt) cannot issue certificates for the `.localhost` TLD. This resulted in "Insecure" warnings in browsers and the need to manage a local CA (like `mkcert`) or accept self-signed certificates.
|
||||
2. **SSO (Cookie) Limitations**: Browsers enforce strict domain matching for cookies. Our Authelia instance is configured for `arch-services.mywire.org`. Browsers refuse to send these session cookies to `*.localhost` domains. This caused an infinite redirect loop or authentication errors when accessing services locally.
|
||||
3. **Namespace Pollution**: Using `*.localhost` in Traefik intercepts traffic that might be needed for other developer workflows (e.g., running undeployed apps, Vite dev servers, or testing environments that default to `localhost`).
|
||||
|
||||
## Decision
|
||||
We decided to **deprecate and remove all `*.localhost` routers** from the Traefik configuration across all services.
|
||||
|
||||
Instead of dedicated local hostnames, we will use the **Public Domain + Local IP** strategy for local access.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive
|
||||
* **Seamless SSO**: Authelia SSO works perfectly because the browser sees the public domain (`*.arch-services.mywire.org`) and sends the correct cookies.
|
||||
* **Valid SSL**: Traefik serves the real Let's Encrypt wildcard certificate, providing "Green Lock" security in browsers without manual certificate management.
|
||||
* **Clean Namespace**: The `.localhost` TLD is now entirely free for other developer-specific tools and testing.
|
||||
* **Local Speed**: When configured correctly via `/etc/hosts`, traffic never leaves the local machine, maintaining the speed benefits of the previous implementation.
|
||||
|
||||
### Negative / Required Actions
|
||||
* **Manual Configuration**: Users must manually update their machine's `/etc/hosts` file to point the public subdomains to `127.0.0.1`.
|
||||
* **SSO Requirement**: Local access now requires the same Authelia authentication as public access (unless explicitly bypassed in the public router, which is not recommended for security).
|
||||
|
||||
## Implementation Detail
|
||||
To access services locally with this architecture, add the following to your `/etc/hosts`:
|
||||
```text
|
||||
127.0.0.1 traefik.arch-services.mywire.org auth.arch-services.mywire.org jellyfin.arch-services.mywire.org gitea.arch-services.mywire.org excalidraw.arch-services.mywire.org homepage.arch-services.mywire.org mermaid.arch-services.mywire.org ollama.arch-services.mywire.org learning.arch-services.mywire.org logs.arch-services.mywire.org portainer.arch-services.mywire.org
|
||||
```
|
||||
@@ -1,32 +0,0 @@
|
||||
# ADR 002: Migrate Dynu DDNS IP Discovery to Host NixOS Configuration
|
||||
|
||||
* **Status**: Accepted & Implemented
|
||||
* **Date**: 2026-06-24
|
||||
* **Decider**: User & Antigravity
|
||||
|
||||
## Context
|
||||
Previously, we managed dynamic DNS IP synchronization using custom bash scripts (`ip-monitor.sh`) and systemd unit configurations in the `homeserver` scripts directory. The service checked the WAN IP and pushed updates to Dynu every 5 minutes.
|
||||
|
||||
However, this design introduced several structural problems:
|
||||
1. **Imperative Secrets Leakage**: Credentials were stored in a cleartext out-of-band environment file (`/etc/conf.d/dynu-environment`). This required manual setup on target hosts and broke the declarative reproducibility goal.
|
||||
2. **Redundant Logic**: The desktop machine (`desktop`) and server machine shared the same router (external public IP), but operated separate, duplicated cron/timer implementations.
|
||||
3. **Inefficient Polling**: Checking the external IP and calling the Dynu APIs every 5 minutes from multiple endpoints generated unnecessary network traffic and risked API bans.
|
||||
|
||||
## Decision
|
||||
We decided to **deprecate and remove all native Dynu IP updater scripts and systemd definitions** from the `homeserver` codebase.
|
||||
|
||||
Instead, the Dynu IP monitoring and DDNS update lifecycle is now managed directly by the host operating system's configuration repository ([nixos-config](https://github.com/kiskaadee/nixos-config)).
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive
|
||||
* **Single Source of Truth**: All WAN IP discovery, validation, and update logic is handled declaratively in the [nixos-config](https://github.com/kiskaadee/nixos-config) repository.
|
||||
* **Cryptographic Secrets**: Credentials are encrypted inside Git using `sops-nix` and `age`, allowing safe storage in public dotfiles repositories.
|
||||
* **Smart Change Detection**: A lightweight background Python script (`monitor.py`) checks the public IP every 30 minutes, keeping a local historical log (`ip_history.jsonl`) and triggering updates via `ddclient` *only* when a WAN IP rotation actually occurs.
|
||||
* **Clean Repository**: Removed bloat and deprecated files from this service-level repo.
|
||||
|
||||
### Negative / Required Actions
|
||||
* None. The deployment process is simplified as secrets and services are now handled automatically during the system-wide NixOS activation phase.
|
||||
|
||||
## References
|
||||
* This decision was implemented in the [nixos-config commits](https://github.com/kiskaadee/nixos-config/commits/main/) under hash `c7acc2b0a3bb262dfd5577989d8d7f0218f2721e` (and subsequent hardening adjustments).
|
||||
@@ -1,106 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Server Architecture | Hardened Hub</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<main>
|
||||
<header>
|
||||
<h1>🏗️ Server Architecture</h1>
|
||||
<p><strong>Model:</strong> Hardened Hub v2.0</p>
|
||||
</header>
|
||||
|
||||
<nav>
|
||||
<h4>Contents</h4>
|
||||
<ul>
|
||||
<li><a href="#physical">Host Layer</a></li>
|
||||
<li><a href="#infra">Infrastructure</a></li>
|
||||
<li><a href="#apps">Applications</a></li>
|
||||
<li><a href="#network">Networking</a></li>
|
||||
<li><a href="#security">Security</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<p>The homeserver follows a <strong>Layered Architecture</strong> designed for security, observability, and modularity. It is split into two logical tiers: the <strong>Control Plane</strong> (Infrastructure) and the <strong>Data Plane</strong> (Applications).</p>
|
||||
|
||||
<section id="physical">
|
||||
<h2>1. Physical & Host Layer</h2>
|
||||
<p>The foundation of the system running directly on the host hardware or virtualized OS.</p>
|
||||
<div class="layer-box">
|
||||
<ul>
|
||||
<li><strong>OS:</strong> Linux (Generic).</li>
|
||||
<li><strong>IP Sync:</strong> <span style="color: #cc0000; font-weight: bold;">[DEPRECATED/MOVED]</span> Dynu DDNS updates are now handled declaratively by the host's NixOS configuration repository (<a href="https://github.com/kiskaadee/nixos-config">nixos-config</a>).</li>
|
||||
<li><strong>Docker Engine:</strong> Orchestrates all containerized services.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="infra">
|
||||
<h2>2. Infrastructure Layer (Control Plane)</h2>
|
||||
<p>The management tier that handles routing, identity, and system maintenance.</p>
|
||||
|
||||
<div class="grid">
|
||||
<article class="card">
|
||||
<h4>🌐 Edge Gateway</h4>
|
||||
<p><strong>Traefik v3:</strong> Reverse Proxy & SSL (DNS-01 Challenges). Routes subdomains for all core and user-deployed services.</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h4>🔐 Identity</h4>
|
||||
<p><strong>Authelia:</strong> SSO & 2FA provider. Forward Auth integration with Traefik.</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h4>🛡️ Socket Proxy</h4>
|
||||
<p>Protects the Docker socket from container-escape vulnerabilities.</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h4>🛠️ Maintenance</h4>
|
||||
<p>Portainer (Management), Watchtower (Updates), and Diun (Notifications).</p>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="apps">
|
||||
<h2>3. Application Layer (Data Plane)</h2>
|
||||
<p>Consumer-facing services isolated from the core infrastructure.</p>
|
||||
<div class="layer-box">
|
||||
<ul>
|
||||
<li><strong>Service Discovery:</strong> <em>Homepage</em> dashboard serves as a unified entry portal.</li>
|
||||
<li><strong>SSO Protection:</strong> Critical administration pages and external services utilize Authelia Forward Auth.</li>
|
||||
<li><strong>Decoupled Lifecycles:</strong> User applications run in separate containers outside this repository, keeping the core system clean and stable.</li>
|
||||
<li><strong>Isolation:</strong> Services have no direct host access and communicate strictly over dynamic internal networks.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
<section id="network">
|
||||
<h2>4. Networking Model</h2>
|
||||
<p>Traffic flow is segmented to minimize the blast radius of a potential breach.</p>
|
||||
<ul>
|
||||
<li><code>proxy-net</code>: Shared internal network for Traefik and all exposed applications.</li>
|
||||
<li><code>socket-net</code>: Isolated network for Docker management tools.</li>
|
||||
<li><strong>External:</strong> Only ports 80 and 443 are exposed.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section id="security">
|
||||
<h2>🛡️ Security Posture</h2>
|
||||
<p>Current hardening measures enforced across the Hub:</p>
|
||||
<ul>
|
||||
<li><span class="badge badge-success">HARDENED</span> <strong>No Root Docker:</strong> Standardized PUID/PGID usage.</li>
|
||||
<li><span class="badge badge-success">PRIVATE</span> <strong>Wildcard SSL:</strong> Prevents subdomain enumeration via certificate transparency logs.</li>
|
||||
<li><span class="badge badge-success">ISO</span> <strong>Network Segmentation:</strong> Strict isolation of management traffic.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
<p>(c) 2026 | <a href="https://roadtotech.me">Kiskaadee</a></p>
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,63 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Dynu IP Protocol | Hardened Hub</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<main>
|
||||
<header style="background: #ffe6e6; border: 1px solid #ff9999; padding: 15px; border-radius: 5px; margin-bottom: 25px; color: #cc0000;">
|
||||
<strong>⚠️ DEPRECATED</strong>
|
||||
<p>This script-based DDNS implementation has been deprecated and removed from the homeserver repository. The Dynamic DNS update service and IP monitor are now handled declaratively by the host's NixOS configuration repository. See the nixos-config repository commit <a href="https://github.com/kiskaadee/nixos-config/commit/c7acc2b0a3bb262dfd5577989d8d7f0218f2721e" target="_blank">c7acc2b0a3b</a> for implementation details.</p>
|
||||
</header>
|
||||
|
||||
<header>
|
||||
<h1>📡 Dynu IP Monitor & Updater</h1>
|
||||
<p>Design and architecture of the DDNS synchronization mechanism.</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h2>Problem Definition</h2>
|
||||
<p>Maintain accurate DNS A records despite dynamic public IPs and unreliable providers.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Core Design Decisions</h2>
|
||||
<div class="grid">
|
||||
<article class="card">
|
||||
<h4>1. Probe Model</h4>
|
||||
<p>Runs periodically via systemd instead of a long-lived daemon.</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h4>2. Dual-Source</h4>
|
||||
<p>Uses DNS (primary) and HTTP (fallback) for IP discovery.</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h4>3. Validation</h4>
|
||||
<p>Strict pipeline ensures no RFC1918 or private IPs are ever synced.</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h4>4. Atomicity</h4>
|
||||
<p>State updates use atomic file moves to prevent corruption.</p>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Failure Model</h2>
|
||||
<ul>
|
||||
<li><strong>Degraded:</strong> Fallback used, system remains functional.</li>
|
||||
<li><strong>Error:</strong> No valid IP found, abort mutation.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
<p>(c) 2026 | <a href="https://roadtotech.me">Kiskaadee</a></p>
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,49 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Documentation | Hardened Hub</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<main>
|
||||
<header>
|
||||
<h1>📚 Documentation Hub</h1>
|
||||
<p>Hardened Private Cloud Architecture & Operations</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h2>Guides & Architecture</h2>
|
||||
<div class="grid">
|
||||
<article class="card">
|
||||
<h4>🏗️ <a href="architecture.html">Server Architecture</a></h4>
|
||||
<p>Deep dive into the layered model, networking, and security posture.</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h4>🛠️ <a href="usability.html">Usability & Operations</a></h4>
|
||||
<p>How to use the hub, add new apps, and manage updates.</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h4>🩺 <a href="troubleshooting.html">Troubleshooting</a></h4>
|
||||
<p>Solutions for common connectivity, SSL, and authentication issues.</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h4>🗺️ <a href="roadmap.html">Project Roadmap</a></h4>
|
||||
<p>Current status and future planned features.</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h4>📡 <a href="dynu-ip-update-protocol.html">Dynu IP Protocol</a></h4>
|
||||
<p>Technical details on the DDNS synchronization mechanism.</p>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
<p>(c) 2026 | <a href="https://roadtotech.me">Kiskaadee</a></p>
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,74 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Project Roadmap | Hardened Hub</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<main>
|
||||
<header>
|
||||
<h1>🗺️ Project Roadmap</h1>
|
||||
<p>Current system maturity and future priorities for the core infrastructure.</p>
|
||||
</header>
|
||||
|
||||
<nav>
|
||||
<h4>Phases</h4>
|
||||
<ul>
|
||||
<li><a href="#phase1">Phase 1: Core</a></li>
|
||||
<li><a href="#phase2">Phase 2: Observability</a></li>
|
||||
<li><a href="#phase3">Phase 3: Automation</a></li>
|
||||
<li><a href="#phase4">Phase 4: Optimization</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<section id="phase1">
|
||||
<h2>✅ Phase 1: Core Gateway & Infrastructure</h2>
|
||||
<p><span class="badge badge-success">COMPLETE</span> Stable external access, identity management, and core security.</p>
|
||||
<ul class="status-list">
|
||||
<li class="status-item"><span>[x]</span> <strong>Dynamic DNS:</strong> IP synchronization migrated to host NixOS configuration (<a href="https://github.com/kiskaadee/nixos-config">nixos-config</a>).</li>
|
||||
<li class="status-item"><span>[x]</span> <strong>Edge Routing:</strong> Traefik v3 with Let's Encrypt (DNS-01) automation.</li>
|
||||
<li class="status-item"><span>[x]</span> <strong>Layered Architecture:</strong> Separation of control plane and decoupled data plane folders.</li>
|
||||
<li class="status-item"><span>[x]</span> <strong>Identity & SSO:</strong> Authelia integration with 2FA/OIDC support.</li>
|
||||
<li class="status-item"><span>[x]</span> <strong>Security Hardening:</strong> Docker socket proxy and internal network segmentation.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section id="phase2">
|
||||
<h2>🏗️ Phase 2: Observability & Portal Layer</h2>
|
||||
<p><span class="badge badge-warning">IN PROGRESS</span> Expand utility and improve system monitoring.</p>
|
||||
<ul class="status-list">
|
||||
<li class="status-item"><span>[x]</span> <strong>Service Discovery:</strong> 'Homepage' dashboard integration.</li>
|
||||
<li class="status-item"><span>[ ]</span> <strong>Unified Health:</strong> Integrate Traefik/Docker health checks into Homepage via socket-proxy.</li>
|
||||
<li class="status-item"><span>[ ]</span> <strong>Resource Monitoring:</strong> Add lightweight system metrics (Glances/Netdata) to the portal.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section id="phase3">
|
||||
<h2>🚀 Phase 3: Automation & Resilience</h2>
|
||||
<ul class="status-list">
|
||||
<li class="status-item"><span>[x]</span> <strong>Automated Updates:</strong> Watchtower and Diun for image lifecycle.</li>
|
||||
<li class="status-item"><span>[ ]</span> <strong>Backup Strategy:</strong> Automated, encrypted off-site backups for persistent core volumes.</li>
|
||||
<li class="status-item"><span>[ ]</span> <strong>Infrastructure as Code:</strong> NixOS declarative system module mapping.</li>
|
||||
<li class="status-item"><span>[ ]</span> <strong>Alerting:</strong> Push notifications (Gotify/Ntfy) for core system failures.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section id="phase4">
|
||||
<h2>🌐 Phase 4: Network Optimization</h2>
|
||||
<ul class="status-list">
|
||||
<li class="status-item"><span>[ ]</span> <strong>Local DNS:</strong> Ad-blocking DNS (Pi-hole/AdGuard Home) for LAN.</li>
|
||||
<li class="status-item"><span>[ ]</span> <strong>Hairpin NAT:</strong> Validation and optimization for internal LAN routing.</li>
|
||||
<li class="status-item"><span>[ ]</span> <strong>VPN Integration:</strong> WireGuard-based secure remote access.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
<p>(c) 2026 | <a href="https://roadtotech.me">Kiskaadee</a></p>
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,103 +0,0 @@
|
||||
:root {
|
||||
--primary: #2563eb;
|
||||
--secondary: #475569;
|
||||
--bg: #f8fafc;
|
||||
--text: #1e293b;
|
||||
--border: #e2e8f0;
|
||||
--accent: #f1f5f9;
|
||||
--success: #166534;
|
||||
--success-bg: #dcfce7;
|
||||
--warning: #9a3412;
|
||||
--warning-bg: #ffedd5;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
margin: 0;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
main {
|
||||
max-width: 900px;
|
||||
margin: 0 auto;
|
||||
background: white;
|
||||
padding: 3rem;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
|
||||
}
|
||||
|
||||
header {
|
||||
border-bottom: 2px solid var(--border);
|
||||
margin-bottom: 2rem;
|
||||
padding-bottom: 1rem;
|
||||
}
|
||||
|
||||
h1 { font-size: 2.5rem; color: var(--primary); margin: 0; }
|
||||
h2 { font-size: 1.75rem; color: var(--secondary); margin-top: 2.5rem; border-left: 4px solid var(--primary); padding-left: 1rem; }
|
||||
h3 { font-size: 1.25rem; color: var(--text); margin-top: 1.5rem; }
|
||||
|
||||
code {
|
||||
background: var(--accent);
|
||||
padding: 0.2rem 0.4rem;
|
||||
border-radius: 4px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
pre {
|
||||
background: #1e293b;
|
||||
color: #f8fafc;
|
||||
padding: 1.5rem;
|
||||
border-radius: 6px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
pre code {
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.layer-box {
|
||||
background: var(--accent);
|
||||
padding: 1.5rem;
|
||||
border-radius: 6px;
|
||||
margin: 1rem 0;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
nav {
|
||||
background: var(--accent);
|
||||
padding: 1rem;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
nav h4 { margin: 0 0 0.5rem 0; font-size: 0.9rem; text-transform: uppercase; color: var(--secondary); }
|
||||
nav ul { list-style: none; padding: 0; margin: 0; display: flex; flex-wrap: wrap; gap: 1rem; font-size: 0.9rem; }
|
||||
nav a { color: var(--primary); text-decoration: none; }
|
||||
nav a:hover { text-decoration: underline; }
|
||||
|
||||
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
|
||||
.card { border: 1px solid var(--border); padding: 1rem; border-radius: 4px; background: white; }
|
||||
.card h4 { margin: 0 0 0.5rem 0; color: var(--primary); }
|
||||
|
||||
.badge {
|
||||
padding: 0.2rem 0.6rem;
|
||||
border-radius: 9999px;
|
||||
font-size: 0.8rem;
|
||||
font-weight: bold;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.badge-success { background: var(--success-bg); color: var(--success); }
|
||||
.badge-warning { background: var(--warning-bg); color: var(--warning); }
|
||||
|
||||
.status-list { list-style: none; padding: 0; }
|
||||
.status-item { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem; }
|
||||
|
||||
footer { margin-top: 4rem; font-size: 0.8rem; color: var(--secondary); text-align: center; border-top: 1px solid var(--border); padding-top: 2rem; }
|
||||
footer a { color: var(--primary); text-decoration: none; }
|
||||
@@ -1,83 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Troubleshooting | Hardened Hub</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<main>
|
||||
<header>
|
||||
<h1>🩺 Troubleshooting Guide</h1>
|
||||
<p>Common issues and resolutions for the Hardened Hub.</p>
|
||||
</header>
|
||||
|
||||
<nav>
|
||||
<h4>Issues</h4>
|
||||
<ul>
|
||||
<li><a href="#connectivity">Connectivity</a></li>
|
||||
<li><a href="#ssl">SSL & Certificates</a></li>
|
||||
<li><a href="#auth">Authentication</a></li>
|
||||
<li><a href="#docker">Docker & Perf</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<section id="connectivity">
|
||||
<h2>🌐 Connectivity Issues</h2>
|
||||
<div class="card">
|
||||
<h4>Site is unreachable</h4>
|
||||
<ul>
|
||||
<li><strong>Check External IP:</strong> Verify your public IP matches Dynu.</li>
|
||||
<li><strong>Check Traefik:</strong> <code>docker compose -f infra/core/docker-compose.yml ps</code></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h4>Bad Gateway (502/503)</h4>
|
||||
<p>The application is down or not on <code>proxy-net</code>.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="ssl">
|
||||
<h2>🔒 SSL & Certificate Issues</h2>
|
||||
<p>If you see "Connection not private", Traefik may be failing the ACME challenge.</p>
|
||||
|
||||
<div class="card">
|
||||
<h4>Dynu Quota Deadlock (Record Hoarding)</h4>
|
||||
<p>On the Dynu free tier (4-record limit), failed challenges can leave stale <code>TXT</code> records that block new attempts with a <code>503: Quota Exception</code>.</p>
|
||||
<p><strong>Fix:</strong> Run the automated purge script to clear stale records and restart the challenge:</p>
|
||||
<pre><code>./scripts/purge-dynu.sh</code></pre>
|
||||
</div>
|
||||
|
||||
<div class="layer-box">
|
||||
<h4>Manual Inspection</h4>
|
||||
<pre><code># Check Traefik ACME logs
|
||||
docker compose -f infra/core/docker-compose.yml logs -f traefik
|
||||
|
||||
# Run automated SSL diagnostic
|
||||
./scripts/check-ssl.sh</code></pre>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="auth">
|
||||
<h2>🔐 Authentication (Authelia)</h2>
|
||||
<div class="layer-box">
|
||||
<h4>Stuck in Login Loop?</h4>
|
||||
<p>Sync server time: <code>sudo ntpdate pool.ntp.org</code> and clear cookies.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="docker">
|
||||
<h2>🐳 Docker & Performance</h2>
|
||||
<p>If disk is full, run cleanup:</p>
|
||||
<pre><code>docker system prune -a --volumes</code></pre>
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
<p>(c) 2026 | <a href="https://roadtotech.me">Kiskaadee</a></p>
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,163 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Usability & Operations | Hardened Hub</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<main>
|
||||
<header>
|
||||
<h1>🖱️ Usability & Operational Notes</h1>
|
||||
<p>A guide for interacting with the Hardened Hub and exposing external services.</p>
|
||||
</header>
|
||||
|
||||
<nav>
|
||||
<h4>Topics</h4>
|
||||
<ul>
|
||||
<li><a href="#auth">Authentication</a></li>
|
||||
<li><a href="#nav">Navigation</a></li>
|
||||
<li><a href="#mgmt">Management</a></li>
|
||||
<li><a href="#add">Exposing New Services</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<section id="auth">
|
||||
<h2>🔑 Authentication (SSO)</h2>
|
||||
<p>Critical core services and protected user applications are shielded by <strong>Authelia</strong>.</p>
|
||||
<ol>
|
||||
<li>Access a protected URL (e.g., <code>https://portainer.arch-services.mywire.org</code>).</li>
|
||||
<li>You will be redirected to the Auth Portal (<code>https://auth.arch-services.mywire.org</code>).</li>
|
||||
<li>Log in with your credentials.</li>
|
||||
<li>Once authenticated, you obtain global session access to all SSO-protected services.</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
<section id="nav">
|
||||
<h2>🧭 Navigating the Hub</h2>
|
||||
<p>The <strong>Homepage</strong> dashboard is your central entry point:</p>
|
||||
<ul>
|
||||
<li><strong>Access URL:</strong> <a href="https://arch-services.mywire.org">https://arch-services.mywire.org</a></li>
|
||||
<li><strong>Widgets:</strong> View real-time Docker container statuses, system resources, and service links.</li>
|
||||
</ul>
|
||||
<div class="layer-box">
|
||||
<h4>Local Access (Fast Lane)</h4>
|
||||
<p>To bypass traversing the public internet when you are on the same local network as the server, we use a **Public Domain + Local IP** mapping strategy (see <a href="adr-001-remove-localhost-routers.md">ADR 001</a>).</p>
|
||||
<p>Add the following mapping to your client machine's <code>/etc/hosts</code> file (using your server's local IP, e.g., <code>192.168.1.100</code> or <code>127.0.0.1</code> if testing locally):</p>
|
||||
<pre><code>127.0.0.1 arch-services.mywire.org traefik.arch-services.mywire.org auth.arch-services.mywire.org logs.arch-services.mywire.org portainer.arch-services.mywire.org [your-app-subdomain].arch-services.mywire.org</code></pre>
|
||||
<p><em>Note: This guarantees valid SSL handshakes and working SSO cookies for local LAN sessions.</em></p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="mgmt">
|
||||
<h2>🛠️ Core Infrastructure Management</h2>
|
||||
<p>Deploy the control plane stacks and homepage directly using the host scripts:</p>
|
||||
<pre><code># Start the Control Plane + Homepage Portal
|
||||
./up.sh
|
||||
|
||||
# Stop all Core services
|
||||
./down.sh</code></pre>
|
||||
</section>
|
||||
|
||||
<section id="add">
|
||||
<h2>➕ Exposing a New Service (Decoupled Model)</h2>
|
||||
<p>User applications are fully decoupled from the core repository and managed in their own directories (e.g., <code>/home/kiskaadee/deployments/my-app</code>). We use Traefik labels to expose them under the <code>*.arch-services.mywire.org</code> wildcard domain.</p>
|
||||
|
||||
<p>Depending on your security and access needs, you can configure your stack for one of two scenarios:</p>
|
||||
|
||||
<div class="grid">
|
||||
<article class="card">
|
||||
<h4>🔓 Scenario A: Public / Direct Access</h4>
|
||||
<p>Use this for applications that have their own built-in authentication (e.g., Jellyfin, Gitea) or public-facing projects (e.g., public web demos, portfolios).</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h4>🔒 Scenario B: SSO-Protected</h4>
|
||||
<p>Use this for administrative tools, private databases, or custom internal apps that do not have native authentication and need to be secured behind Authelia.</p>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<br>
|
||||
|
||||
<h3>Scenario A: Public / Direct Access (Bypassing Authelia)</h3>
|
||||
<p>This configuration exposes your service directly to the internet. Authelia is bypassed, allowing anyone (or the app's own login manager) to handle access.</p>
|
||||
|
||||
<pre><code class="language-yaml">services:
|
||||
my-public-app:
|
||||
image: my-app-image:latest
|
||||
container_name: my-public-app
|
||||
networks:
|
||||
- proxy-net
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
|
||||
# 1. Main HTTPS Route Rule
|
||||
- "traefik.http.routers.public-app.rule=Host(`demo.arch-services.mywire.org`)"
|
||||
- "traefik.http.routers.public-app.entrypoints=websecure"
|
||||
- "traefik.http.routers.public-app.tls=true"
|
||||
- "traefik.http.routers.public-app.service=public-app-svc"
|
||||
|
||||
# 2. HTTP to HTTPS Redirection Route
|
||||
- "traefik.http.routers.public-app-red.rule=Host(`demo.arch-services.mywire.org`)"
|
||||
- "traefik.http.routers.public-app-red.entrypoints=web"
|
||||
- "traefik.http.routers.public-app-red.middlewares=https-redirect@docker"
|
||||
|
||||
# 3. Port Mapping (Target port inside the container)
|
||||
- "traefik.http.services.public-app-svc.loadbalancer.server.port=8080"
|
||||
|
||||
networks:
|
||||
proxy-net:
|
||||
external: true</code></pre>
|
||||
|
||||
<h3>Scenario B: SSO-Protected (Secured by Authelia)</h3>
|
||||
<p>This configuration intercepts all incoming requests and redirects unauthenticated users to the Authelia portal first. Once logged in, users are returned to the service.</p>
|
||||
|
||||
<pre><code class="language-yaml">services:
|
||||
my-secure-app:
|
||||
image: my-app-image:latest
|
||||
container_name: my-secure-app
|
||||
networks:
|
||||
- proxy-net
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
|
||||
# 1. Main HTTPS Route Rule
|
||||
- "traefik.http.routers.secure-app.rule=Host(`admin.arch-services.mywire.org`)"
|
||||
- "traefik.http.routers.secure-app.entrypoints=websecure"
|
||||
- "traefik.http.routers.secure-app.tls=true"
|
||||
- "traefik.http.routers.secure-app.service=secure-app-svc"
|
||||
|
||||
# 2. SSO Authentication Middleware (Crucial Line)
|
||||
- "traefik.http.routers.secure-app.middlewares=authelia-auth@docker"
|
||||
|
||||
# 3. HTTP to HTTPS Redirection Route
|
||||
- "traefik.http.routers.secure-app-red.rule=Host(`admin.arch-services.mywire.org`)"
|
||||
- "traefik.http.routers.secure-app-red.entrypoints=web"
|
||||
- "traefik.http.routers.secure-app-red.middlewares=https-redirect@docker"
|
||||
|
||||
# 4. Port Mapping (Target port inside the container)
|
||||
- "traefik.http.services.secure-app-svc.loadbalancer.server.port=3000"
|
||||
|
||||
networks:
|
||||
proxy-net:
|
||||
external: true</code></pre>
|
||||
|
||||
<h3>3. Register in Homepage Dashboard</h3>
|
||||
<p>To list your new service on the central dashboard, update <code>homepage/config/services.yaml</code> inside the core repository:</p>
|
||||
<pre><code class="language-yaml">- User Applications:
|
||||
- My Application:
|
||||
icon: custom-app-icon
|
||||
href: https://my-app.arch-services.mywire.org
|
||||
description: Custom exposed app description
|
||||
server: my-docker
|
||||
container: my-app # Must match container_name exactly</code></pre>
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
<p>(c) 2026 | <a href="https://roadtotech.me">Kiskaadee</a></p>
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,637 @@
|
||||
# 🛠️ Homelab Core — Operator Runbook & Procedures
|
||||
|
||||
This document contains operational procedures, system maintenance workflows, diagnostic commands, and recovery runbooks for administering **Homelab Core**.
|
||||
|
||||
---
|
||||
|
||||
## 1. System Lifecycle & NixOS Administration
|
||||
|
||||
The host system runs NixOS configured declaratively via the flake in `~/Core`.
|
||||
|
||||
### Rebuilding the System Configuration
|
||||
After modifying any file in `nixos/` (including `configuration.nix`, `hardware-configuration.nix`, or any `nixos/modules/*.nix`), apply changes to the running host:
|
||||
|
||||
```bash
|
||||
# Using the built-in shell alias:
|
||||
nix-switch
|
||||
|
||||
# Or using the explicit command:
|
||||
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> **Flake Fetcher Scheme for Untracked Files**:
|
||||
> When importing the gitignored `nixos/instance.nix`, Nix's default Git fetcher filters it out unless the `path:` scheme is used (`path:/home/operator/Core#server` or `path:~/Core#server`). The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index.
|
||||
> If using `/etc/nixos/homelab-instance.nix`, a standard `--flake ~/Core#server --impure` works directly since `/etc/nixos` is outside the repository.
|
||||
|
||||
|
||||
### Dry Build Validation & Rollback
|
||||
```bash
|
||||
# Validate build without activating (catches evaluation and syntax errors)
|
||||
nix flake check
|
||||
nix build .#nixosConfigurations.server.config.system.build.toplevel --no-link
|
||||
|
||||
# Roll back to the previous generation if needed
|
||||
sudo nixos-rebuild switch --rollback
|
||||
```
|
||||
|
||||
### System Maintenance & Disk Space Management
|
||||
```bash
|
||||
# Check disk usage across partitions
|
||||
df -h
|
||||
|
||||
# Delete older system generations (older than 7 days)
|
||||
sudo nix-env --delete-generations +7d --profile /nix/var/nix/profiles/system
|
||||
|
||||
# Prune unreachable Nix store paths
|
||||
sudo nix-collect-garbage -d
|
||||
|
||||
# Prune old Docker resources (only containers stopped for >7 days)
|
||||
docker system prune -a --volumes --filter "until=168h"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Managing Core Systemd Services
|
||||
|
||||
Homelab Core runs several platform services managed by systemd:
|
||||
|
||||
### `homeserver-core.service` (Core Compose Stack)
|
||||
Manages the lifecycle of Traefik, Authelia, LLDAP, Stalwart, Homepage, Dozzle, Watchtower, and Diun.
|
||||
|
||||
```bash
|
||||
# Check service status
|
||||
systemctl status homeserver-core
|
||||
|
||||
# View startup and runtime logs
|
||||
journalctl -u homeserver-core -f
|
||||
|
||||
# Restart the entire Core stack
|
||||
sudo systemctl restart homeserver-core
|
||||
|
||||
# Stop or Start the Core stack
|
||||
sudo systemctl stop homeserver-core
|
||||
sudo systemctl start homeserver-core
|
||||
```
|
||||
|
||||
### `homelab-gitops.service` (Dynamic GitOps Webhook)
|
||||
Listens on port 9000 for Gitea webhook requests and dispatches automated deployments.
|
||||
|
||||
```bash
|
||||
# Check status and port binding
|
||||
systemctl status homelab-gitops
|
||||
|
||||
# Stream webhook reception and deployment worker logs
|
||||
journalctl -u homelab-gitops -f -n 50
|
||||
|
||||
# Restart the webhook dispatcher daemon
|
||||
sudo systemctl restart homelab-gitops
|
||||
```
|
||||
|
||||
### `dynu-monitor.service` & `dynu-monitor.timer` (Smart DDNS)
|
||||
Runs every 30 minutes to detect WAN IP address changes and trigger `ddclient`.
|
||||
|
||||
```bash
|
||||
# Check next scheduled timer execution
|
||||
systemctl list-timers dynu-monitor.timer
|
||||
|
||||
# Check last monitor run status and output
|
||||
systemctl status dynu-monitor.service
|
||||
|
||||
# Manually trigger an immediate IP check
|
||||
sudo systemctl start dynu-monitor.service
|
||||
|
||||
# View historical WAN IP transitions log
|
||||
tail -n 20 /var/lib/dynu/ip_history.jsonl
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Workload Lifecycle Operations (`appctl`)
|
||||
|
||||
Applications in `~/Workloads` are managed with the `appctl` CLI.
|
||||
|
||||
### Inspection & Status
|
||||
```bash
|
||||
# Check status of all applications and their Git tracking state
|
||||
appctl list
|
||||
|
||||
# Fetch remote changes from Git remotes before rendering status
|
||||
appctl list --fetch
|
||||
|
||||
# Check applications and Core infrastructure services together
|
||||
appctl list --core
|
||||
|
||||
# Check SSL/TLS certificate validity across all domains
|
||||
appctl list --ssl --core
|
||||
|
||||
# Inspect diagnostic details for a specific service
|
||||
appctl info docs
|
||||
appctl info jellyfin --ssl
|
||||
```
|
||||
|
||||
### Deployment & Lifecycle Actions
|
||||
```bash
|
||||
# Start a service stack
|
||||
appctl up docs
|
||||
|
||||
# Gracefully stop a service stack
|
||||
appctl down docs
|
||||
|
||||
# Restart a service stack (re-injects environment)
|
||||
appctl restart docs
|
||||
|
||||
# Restart an individual Core component without restarting the whole host
|
||||
appctl restart traefik
|
||||
appctl restart authelia
|
||||
|
||||
# Sequential stack update for independent Workloads (clean tree check -> git pull -> compose pull -> up -> sync)
|
||||
appctl update docs
|
||||
|
||||
# Stream live container logs
|
||||
appctl logs docs
|
||||
appctl logs -f stalwart
|
||||
|
||||
# View resolved Docker Compose configuration
|
||||
appctl config docs
|
||||
```
|
||||
|
||||
### Workload vs. Core Update Policy
|
||||
|
||||
Homelab enforces a strict architectural boundary between independent application workloads (`~/Workloads/<app>`) and Homelab Core (`~/Core`):
|
||||
|
||||
#### 1. Independent Workloads (`~/Workloads/<app>`)
|
||||
- **Automated Lifecycle**: Workloads declare their lifecycle via `app.yaml` manifests and Compose definitions.
|
||||
- **Update Command**: `appctl update <workload>` performs pre-flight verification, branch matching, `git pull --ff-only`, container image pull, stack reload, and dashboard synchronization.
|
||||
- **GitOps Webhook Dispatch**: Workloads registered in `~/Workloads/deployments.yaml` (with `config/deployments.yaml` as the example template) can be triggered automatically via authenticated GitOps webhooks on Gitea push events.
|
||||
- **Daemon Permissions**: `homelab-appctl.service` holds read-write permissions over `~/Workloads` to manage files, compose configurations, and workload state.
|
||||
|
||||
#### 2. Homelab Core Platform Stack (`~/Core`)
|
||||
- **Host Foundation & Invariant Boundary**: Core defines NixOS host definitions, platform secrets, edge ingress, and security sandboxes.
|
||||
- **No Untrusted Webhooks**: Core does **not** register for webhook dispatch in `~/Workloads/deployments.yaml`. External push events can never trigger an automated deployment or rebuild of Core.
|
||||
- **Read-Only Sandbox**: Under NixOS systemd sandboxing (`ProtectHome = "read-only"`), `homelab-appctl.service` has strictly read-only access to `/home/operator/Core`. The daemon cannot mutate the Core Git repository or run `git pull` on Core.
|
||||
- **Operator-Driven Update Workflow**: Core updates must be executed explicitly by the operator:
|
||||
1. Review and pull repository changes:
|
||||
```bash
|
||||
cd ~/Core && git pull --ff-only
|
||||
```
|
||||
2. If NixOS modules or secrets changed, evaluate and activate the new system generation:
|
||||
```bash
|
||||
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
|
||||
```
|
||||
3. If Compose definitions changed, restart the platform stack:
|
||||
```bash
|
||||
docker compose up -d --remove-orphans
|
||||
# or via systemd:
|
||||
sudo systemctl restart homeserver-core
|
||||
```
|
||||
4. Individual platform services can be restarted via appctl using an authenticated admin token (`appctl restart traefik`, `appctl restart authelia`).
|
||||
|
||||
---
|
||||
|
||||
## 4. User Identity & Access Management (LLDAP & Authelia)
|
||||
|
||||
User accounts and group memberships are managed dynamically in **LLDAP** rather than static configuration files.
|
||||
|
||||
### Accessing the Directory
|
||||
1. Open `https://users.${HOMELAB_DOMAIN}` (e.g., `https://users.example.com`) in your browser.
|
||||
2. Authenticate using your admin credentials (`admin` / password configured in `nixos/secrets.yaml`).
|
||||
3. From the LLDAP UI, you can:
|
||||
- Create and delete user accounts.
|
||||
- Reset user passwords.
|
||||
- Manage user email addresses.
|
||||
- Assign users to groups (e.g. `admin`, `users`, `media`).
|
||||
|
||||
### Authelia Session & Authentication
|
||||
* **URL**: `https://auth.${HOMELAB_DOMAIN}` (e.g., `https://auth.example.com`)
|
||||
* **Session Lifetime**: 7 days maximum session, 3 days inactivity timeout.
|
||||
* **ForwardAuth Guard**: Applications requiring authentication attach the `authelia-auth@docker` middleware.
|
||||
|
||||
---
|
||||
|
||||
## 5. Troubleshooting Common Failure Modes
|
||||
|
||||
### A. SSL/TLS Certificate Failures (Let's Encrypt / Dynu)
|
||||
* **Symptom**: Browser reports `NET::ERR_CERT_AUTHORITY_INVALID` or self-signed Traefik default certificate.
|
||||
* **Diagnosis**:
|
||||
1. Verify certificate status: `appctl ssl <service>` or `appctl list --ssl`.
|
||||
2. Inspect Traefik logs: `appctl logs traefik | grep -i acme`.
|
||||
3. Verify Dynu API key is valid and not rate-limited.
|
||||
4. Check `config/letsencrypt/acme.json` permissions (must be `0600`).
|
||||
* **Recovery**:
|
||||
```bash
|
||||
# Check acme.json permissions
|
||||
ls -la ~/Core/config/letsencrypt/acme.json
|
||||
chmod 600 ~/Core/config/letsencrypt/acme.json
|
||||
|
||||
# Restart Traefik to trigger challenge retry
|
||||
appctl restart traefik
|
||||
```
|
||||
|
||||
### B. Dynamic DNS (WAN IP) Drift
|
||||
* **Symptom**: External domain (`${HOMELAB_DOMAIN}`) does not resolve to the current ISP WAN address.
|
||||
* **Diagnosis**:
|
||||
```bash
|
||||
# Check current public IP vs resolved DNS IP
|
||||
curl -s https://api.ipify.org
|
||||
dig +short example.com @1.1.1.1
|
||||
|
||||
# Check dynu-monitor logs
|
||||
systemctl status dynu-monitor
|
||||
journalctl -u dynu-monitor -n 30
|
||||
```
|
||||
* **Recovery**:
|
||||
```bash
|
||||
# Trigger manual IP update run
|
||||
sudo systemctl start dynu-monitor
|
||||
```
|
||||
|
||||
### C. Docker Socket Communication Errors
|
||||
* **Symptom**: Traefik fails to discover routers, or Dozzle shows "Cannot connect to Docker daemon".
|
||||
* **Diagnosis**:
|
||||
```bash
|
||||
# Verify socket-proxy is running and healthy
|
||||
docker ps -f name=socket-proxy
|
||||
|
||||
# Verify socket-proxy logs
|
||||
appctl logs socket-proxy
|
||||
|
||||
# Test internal socket-proxy connectivity from another container
|
||||
docker exec -it traefik wget -qO- http://socket-proxy:2375/version
|
||||
```
|
||||
* **Recovery**:
|
||||
```bash
|
||||
appctl restart socket-proxy
|
||||
appctl restart traefik
|
||||
```
|
||||
|
||||
### D. GitOps Deployment Stuck or Failed
|
||||
* **Symptom**: Pushed commit to Gitea did not deploy or container is in an inconsistent state.
|
||||
* **Diagnosis**:
|
||||
```bash
|
||||
# Check webhook daemon logs
|
||||
journalctl -u homelab-gitops -f -n 50
|
||||
|
||||
# Check execution status file for the target service
|
||||
cat ~/.local/state/homelab/gitops/<service>.status.json
|
||||
|
||||
# Check if a lock file is held
|
||||
ls -la ~/.local/state/homelab/gitops/
|
||||
```
|
||||
* **Recovery**:
|
||||
```bash
|
||||
# Manually run deployment via appctl
|
||||
appctl update <service>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Backup & Disaster Recovery
|
||||
|
||||
### Critical Persistent State Locations
|
||||
To back up the homelab, create secure snapshots of the following state directories:
|
||||
|
||||
| Component | Host Path | Description |
|
||||
| :--- | :--- | :--- |
|
||||
| **Secrets Key** | `/etc/ssh/ssh_host_ed25519_key` | Host SSH key used by sops-nix to decrypt secrets |
|
||||
| **Encrypted Secrets** | `~/Core/nixos/secrets.yaml` | Encrypted secrets source |
|
||||
| **SSL Certificates** | `~/Core/config/letsencrypt/acme.json` | Active Let's Encrypt certificates |
|
||||
| **User Directory** | `~/Core/config/lldap/data/` | LLDAP SQLite database (`users.db`) |
|
||||
| **Auth Database** | `~/Core/config/authelia/db.sqlite3` | Authelia session database |
|
||||
| **Mail Storage** | `~/Core/config/stalwart/` | Stalwart database, mailboxes, and DKIM keys |
|
||||
| **Workload State** | `~/var/lib/homelab/<app>/` | Per-workload persistent runtime state (e.g., `snappymail`) |
|
||||
| **Dashboard State** | `~/Core/config/homepage/` | Homepage configuration and custom icons |
|
||||
|
||||
### Host Recovery Requirements
|
||||
To bring up a replacement host from version control:
|
||||
1. Boot the target system with a NixOS installation medium and configure partitions according to `nixos/hardware-configuration.nix`.
|
||||
2. **Restore the host SSH private key** to `/etc/ssh/ssh_host_ed25519_key` (mode `0600`) before running `nixos-install`, as `sops-nix` requires this key during system evaluation and activation.
|
||||
3. Install NixOS targeting the server flake:
|
||||
```bash
|
||||
nixos-install --flake /mnt/home/<operator>/Core#server
|
||||
reboot
|
||||
```
|
||||
4. Restore persistent data directories (`config/` and `~/var/lib/homelab/` backups) and start the Core stack:
|
||||
```bash
|
||||
sudo systemctl start homeserver-core
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Operator Account Migration Runbook (Decision D2: Staged Coexistence Cutover)
|
||||
|
||||
> [!CAUTION]
|
||||
> **MAINTENANCE WINDOW REQUIRED — EXECUTION ON LIVE HOST CURRENTLY BLOCKED**
|
||||
> Live execution of this runbook against production hosts is strictly blocked until an authorized platform maintenance window is scheduled. This runbook is codified for procedural readiness and dry-run verification only.
|
||||
|
||||
This runbook defines the 4-stage staged coexistence cutover procedure to migrate host operation from a legacy personal operator account (`<legacy-operator>`) to the platform standard `operator` user (`uid = 1000`, `extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]`), fulfilling Decision D2 and eliminating personal identity coupling.
|
||||
|
||||
### Stage 1: Pre-Flight Checks & Session Preservation
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Maintain Active Legacy Shell Session**:
|
||||
> Do not terminate your active SSH or terminal session as `<legacy-operator>`. Keep at least one authenticated shell open throughout the entire cutover process to prevent lockout in case of SSH key, user profile, or PAM misconfiguration.
|
||||
|
||||
1. **Verify or provision `operator` account**:
|
||||
Check if the `operator` user exists in the running environment:
|
||||
```bash
|
||||
id operator
|
||||
```
|
||||
If `operator` does not exist yet (as `homelab.operatorUser` has not been switched in the active NixOS generation), provision the initial coexistence user before proceeding:
|
||||
```bash
|
||||
sudo useradd -m -s /run/current-system/sw/bin/bash -G wheel,docker,homelab-operators operator
|
||||
```
|
||||
|
||||
2. **Verify SSH key provisioning & permissions**:
|
||||
Ensure the operator's authorized keys are installed with strict permissions (copying from `<legacy-operator>` if needed):
|
||||
```bash
|
||||
sudo mkdir -p /home/operator/.ssh
|
||||
if [ ! -f /home/operator/.ssh/authorized_keys ] && [ -f /home/<legacy-operator>/.ssh/authorized_keys ]; then
|
||||
sudo cp /home/<legacy-operator>/.ssh/authorized_keys /home/operator/.ssh/authorized_keys
|
||||
fi
|
||||
sudo chmod 700 /home/operator/.ssh
|
||||
sudo chmod 600 /home/operator/.ssh/authorized_keys
|
||||
sudo chown -R operator:users /home/operator/.ssh
|
||||
```
|
||||
|
||||
3. **Verify administrative (`sudo`) access**:
|
||||
Test that `operator` can authenticate and execute privileged commands without failure:
|
||||
```bash
|
||||
sudo -u operator sudo -n true || echo "Passwordless or password sudo required for operator"
|
||||
```
|
||||
|
||||
4. **Prepare persistent directories**:
|
||||
Ensure `/home/operator/Sites`, `/home/operator/Core`, `/home/operator/var/lib/homelab`, and state parent paths are ready:
|
||||
```bash
|
||||
sudo mkdir -p /home/operator/{Core,Sites,.config/homelab,var/lib/homelab,.local/state/homelab}
|
||||
sudo chown -R operator:homelab-operators /home/operator/{Core,Sites,.config,var,.local}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Stage 2: State and Repository Synchronization
|
||||
Synchronize repository checkouts, workload persistent data, and runtime state from the legacy user account to `/home/operator/` using non-destructive archive flags (`-aHAX` preserves hard links, attributes, and extended ACLs):
|
||||
|
||||
1. **Initial background synchronization**:
|
||||
Seed the file trees for Core, Sites, workload databases, and configurations while services continue running:
|
||||
```bash
|
||||
sudo rsync -aHAX --info=progress2 \
|
||||
--exclude=".venv" \
|
||||
--exclude=".pytest_cache" \
|
||||
/home/<legacy-operator>/Core/ /home/operator/Core/
|
||||
|
||||
sudo rsync -aHAX --info=progress2 \
|
||||
/home/<legacy-operator>/Sites/ /home/operator/Sites/
|
||||
|
||||
if [ -d "/home/<legacy-operator>/var/lib/homelab" ]; then
|
||||
sudo rsync -aHAX --info=progress2 \
|
||||
/home/<legacy-operator>/var/lib/homelab/ /home/operator/var/lib/homelab/
|
||||
fi
|
||||
|
||||
if [ -d "/home/<legacy-operator>/.local/state/homelab" ]; then
|
||||
sudo rsync -aHAX --info=progress2 \
|
||||
/home/<legacy-operator>/.local/state/homelab/ /home/operator/.local/state/homelab/
|
||||
fi
|
||||
|
||||
if [ -d "/home/<legacy-operator>/.config/homelab" ]; then
|
||||
sudo rsync -aHAX --info=progress2 \
|
||||
/home/<legacy-operator>/.config/homelab/ /home/operator/.config/homelab/
|
||||
fi
|
||||
```
|
||||
|
||||
2. **Quiesce active database writers**:
|
||||
Stop running workload containers and the Core platform stack to guarantee point-in-time consistency across SQLite databases (e.g. LLDAP `users.db`, Authelia `db.sqlite3`, Stalwart storage, and workload app volumes in `~/var/lib/homelab/`) before the final sync:
|
||||
```bash
|
||||
# Stop running workload containers
|
||||
appctl down --all 2>/dev/null || docker stop $(docker ps -q) 2>/dev/null || true
|
||||
|
||||
# Stop platform core services
|
||||
sudo systemctl stop homeserver-core
|
||||
sudo systemctl stop homelab-appctl
|
||||
sudo systemctl stop homelab-gitops
|
||||
```
|
||||
|
||||
3. **Final delta synchronization (`--delete`)**:
|
||||
Perform a rapid final delta synchronization with `--delete` to capture the quiesced database state and prune removed files:
|
||||
```bash
|
||||
sudo rsync -aHAX --delete --info=progress2 \
|
||||
--exclude=".venv" \
|
||||
--exclude=".pytest_cache" \
|
||||
/home/<legacy-operator>/Core/ /home/operator/Core/
|
||||
|
||||
sudo rsync -aHAX --delete --info=progress2 \
|
||||
/home/<legacy-operator>/Sites/ /home/operator/Sites/
|
||||
|
||||
if [ -d "/home/<legacy-operator>/var/lib/homelab" ]; then
|
||||
sudo rsync -aHAX --delete --info=progress2 \
|
||||
/home/<legacy-operator>/var/lib/homelab/ /home/operator/var/lib/homelab/
|
||||
fi
|
||||
|
||||
if [ -d "/home/<legacy-operator>/.local/state/homelab" ]; then
|
||||
sudo rsync -aHAX --delete --info=progress2 \
|
||||
/home/<legacy-operator>/.local/state/homelab/ /home/operator/.local/state/homelab/
|
||||
fi
|
||||
```
|
||||
|
||||
4. **Fix ownership and permissions**:
|
||||
Set primary ownership to `operator` and group to `homelab-operators` across all migrated trees:
|
||||
```bash
|
||||
sudo chown -R operator:homelab-operators \
|
||||
/home/operator/Core \
|
||||
/home/operator/Sites \
|
||||
/home/operator/.config \
|
||||
/home/operator/.local \
|
||||
/home/operator/var
|
||||
sudo chmod -R u+rwX,g+rX /home/operator/Core /home/operator/Sites /home/operator/var
|
||||
|
||||
# ACME certificate security invariant: Traefik strictly requires 0600 on acme.json;
|
||||
# recursive group read permissions will cause Traefik to refuse to start.
|
||||
if [ -f /home/operator/Core/config/letsencrypt/acme.json ]; then
|
||||
sudo chmod 600 /home/operator/Core/config/letsencrypt/acme.json
|
||||
fi
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Stage 3: Service Rebuild & Environment Cutover
|
||||
Activate the declarative configuration under the `operator` profile:
|
||||
|
||||
1. **Configure instance domain injection (Decision D1)**:
|
||||
Ensure `nixos/instance.nix` (or `/etc/nixos/homelab-instance.nix`) is in place with the host's production domain:
|
||||
```bash
|
||||
cat << 'EOF' | sudo -u operator tee /home/operator/Core/nixos/instance.nix > /dev/null
|
||||
{
|
||||
homelab.domain = "example.com";
|
||||
}
|
||||
EOF
|
||||
chmod 600 /home/operator/Core/nixos/instance.nix
|
||||
```
|
||||
|
||||
2. **Bootstrap appctl control plane tokens (CR-SO-08)**:
|
||||
The `homelab-appctl.service` control plane daemon enforces 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`) authenticated via SHA-256 Bearer tokens stored in `/run/secrets/appctl/tokens.json`.
|
||||
|
||||
Generate the operator administrator token and local CLI credentials:
|
||||
```bash
|
||||
sudo -u operator python3 /home/operator/Core/scripts/bootstrap_token.py
|
||||
```
|
||||
This command:
|
||||
- Creates `~/.config/homelab/token` (mode `0600`) owned by `operator:homelab-operators` containing the raw Bearer token used automatically by the `appctl` CLI.
|
||||
- Outputs the JSON token descriptor containing the SHA-256 digest:
|
||||
```json
|
||||
{
|
||||
"token_id": "operator-admin",
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"sha256": "<64-character-sha256-digest>"
|
||||
}
|
||||
```
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Unprovisioned Token Behavior & RBAC Fallback**:
|
||||
> If tokens are not provisioned in `/run/secrets/appctl/tokens.json`, local UDS connections (`/run/homelab/appctl.sock`) fall back to Linux `SO_PEERCRED` socket credentials, granting callers in `homelab-operators` the read-only `homelab-viewer` role.
|
||||
> Under `homelab-viewer`, safe queries succeed (`appctl list`, `appctl status`, `appctl health`).
|
||||
> However, **all mutating and privileged operations** (`appctl up`, `appctl down`, `appctl restart`, `appctl update`, `appctl deploy`, `appctl config`, `appctl info`) **strictly require** a valid Bearer token with `homelab-operator` or `homelab-admin` role. If tokens are not enrolled in SOPS, attempting mutating actions fails with HTTP 403 `ERR_PERMISSION_DENIED`.
|
||||
|
||||
Enroll the token descriptor into SOPS secrets:
|
||||
```bash
|
||||
sops /home/operator/Core/nixos/secrets.yaml
|
||||
```
|
||||
Under `appctl.tokens_json`, insert the descriptor into the JSON array:
|
||||
```yaml
|
||||
appctl:
|
||||
tokens_json: |
|
||||
[
|
||||
{
|
||||
"token_id": "operator-admin",
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"sha256": "<paste-sha256-digest-here>"
|
||||
}
|
||||
]
|
||||
```
|
||||
*(Optional: If GitOps webhook dispatch is enabled, generate and enroll a `gitops-webhook` token with `homelab-operator` role using `python3 scripts/bootstrap_token.py --identity gitops --role homelab-operator --token-id gitops-webhook --print-json`).*
|
||||
|
||||
3. **Rebuild NixOS host configuration**:
|
||||
Execute the rebuild from the new canonical Core path using `--impure` and the `path:` scheme to import the untracked instance profile:
|
||||
```bash
|
||||
cd /home/operator/Core
|
||||
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index, ensuring untracked/gitignored `nixos/instance.nix` is evaluated. (If using `/etc/nixos/homelab-instance.nix`, bare `--flake .#server --impure` works directly). Rebuilding also decrypts and projects `/run/secrets/appctl/tokens.json` via `sops-nix`.
|
||||
|
||||
4. **Restart platform services**:
|
||||
Restart the Core Compose stack and control plane services to consume updated paths and secrets:
|
||||
```bash
|
||||
sudo systemctl restart homeserver-core
|
||||
sudo systemctl restart homelab-appctl
|
||||
sudo systemctl restart homelab-gitops
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Stage 4: Post-Flight Verification
|
||||
Validate system health and operational readiness under the `operator` identity:
|
||||
|
||||
1. **Verify Git safe directory**:
|
||||
Ensure Git does not complain about dubious ownership when invoked by `operator` or `homelab-appctl`:
|
||||
```bash
|
||||
sudo -u operator git -C /home/operator/Core status
|
||||
sudo -u operator git -C /home/operator/Sites/<any-workload> status
|
||||
```
|
||||
|
||||
2. **Verify SOPS secrets and tokens projection**:
|
||||
Ensure `/run/secrets/appctl/tokens.json` is readable by `homelab-appctl` (mode `0400`, owned by `homelab-appctl:homelab-operators`) and contains valid descriptors:
|
||||
```bash
|
||||
sudo ls -l /run/secrets/appctl/tokens.json
|
||||
```
|
||||
|
||||
3. **Verify appctl control plane status & RBAC authentication**:
|
||||
Execute CLI inspection using both UDS peercred authentication (read-only viewer fallback) and authenticated admin token operations:
|
||||
```bash
|
||||
# 1. Peercred UDS inspection (demonstrates viewer fallback for read-only actions)
|
||||
sudo -u operator appctl list --core
|
||||
sudo -u operator appctl status
|
||||
sudo -u operator appctl health
|
||||
|
||||
# 2. Authenticated operator admin verification (requires homelab-admin Bearer token)
|
||||
sudo -u operator appctl info docs
|
||||
sudo -u operator appctl config docs
|
||||
```
|
||||
Confirm that `info` and `config` return resolved configuration without `ERR_PERMISSION_DENIED`, verifying that `~/.config/homelab/token` matches the provisioned SHA-256 digest in `/run/secrets/appctl/tokens.json`.
|
||||
|
||||
4. **Verify container reachability & proxy routing**:
|
||||
Check that external endpoints and internal reverse proxies resolve:
|
||||
```bash
|
||||
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
|
||||
curl -s -k https://127.0.0.1 -H "Host: dashboard.example.com" | head -n 5
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Rollback Procedure
|
||||
If unexpected service degradation occurs during the cutover:
|
||||
|
||||
1. **Revert NixOS system generation**:
|
||||
```bash
|
||||
sudo nixos-rebuild switch --rollback
|
||||
```
|
||||
|
||||
2. **Restart legacy Core services**:
|
||||
```bash
|
||||
sudo systemctl restart homeserver-core
|
||||
sudo systemctl restart homelab-appctl
|
||||
sudo systemctl restart homelab-gitops
|
||||
```
|
||||
|
||||
3. **Log rollback reason**:
|
||||
Record the diagnostic failure logs in `journalctl -xe` and investigate before attempting another cutover window.
|
||||
|
||||
---
|
||||
|
||||
## 8. Read-Only Agent Inspection (`agents` SSH Identity)
|
||||
|
||||
For automated troubleshooting and agentic workflows, use the dedicated `agents` SSH user instead of the `operator` account.
|
||||
|
||||
### Workstation Setup
|
||||
1. Generate a dedicated Ed25519 keypair on the workstation (if not already provisioned during setup):
|
||||
```bash
|
||||
ssh-keygen -t ed25519 -f ~/.ssh/canopy_agents -C "canopy-agents"
|
||||
```
|
||||
2. Register the `.pub` key in `users.users.agents.openssh.authorizedKeys.keys` (`nixos/configuration.nix`) and rebuild NixOS.
|
||||
3. Add a host entry to `~/.ssh/config` (using your server hostname or `server.example.test`):
|
||||
```sshconfig
|
||||
Host server-agents
|
||||
HostName <server-host>
|
||||
User agents
|
||||
IdentityFile ~/.ssh/canopy_agents
|
||||
IdentitiesOnly yes
|
||||
```
|
||||
|
||||
### Safe Read-Only Usage Examples
|
||||
Commands are passed non-interactively over SSH and validated by the `ForceCommand` wrapper:
|
||||
```bash
|
||||
# Container status and logs (via read-only socket-proxy)
|
||||
ssh server-agents "docker ps"
|
||||
ssh server-agents "docker logs --tail 50 <container>"
|
||||
ssh server-agents "docker inspect <container>"
|
||||
|
||||
# Platform & workload status
|
||||
ssh server-agents "appctl list --core"
|
||||
ssh server-agents "appctl status"
|
||||
ssh server-agents "appctl info <app>"
|
||||
|
||||
# Systemd service logs
|
||||
ssh server-agents "journalctl -u homelab-appctl -n 5"
|
||||
```
|
||||
|
||||
### Security Boundaries & Allowlist
|
||||
The `agents` account is constrained at both the OS and OpenSSH layers (`nixos/configuration.nix` and `nixos/scripts/agents-force-command.sh`):
|
||||
- **Allowlisted commands only (`Match User agents` `ForceCommand`)**:
|
||||
- `docker`: `ps`, `logs`, `inspect` only (routed to `DOCKER_HOST=tcp://127.0.0.1:2375`; `-H`, `--host`, `--context`, `-c`, and `--config` overrides are rejected).
|
||||
- `appctl`: `list`, `status`, `info`, `logs`, `ssl`, `health`, `resolve` only.
|
||||
- `journalctl`: read-only queries only (mutating flags such as `--flush`, `--rotate`, `--vacuum-*`, `--relinquish-var`, `--sync`, `--setup-keys`, and `--update-catalog` are rejected).
|
||||
- Empty commands, control characters, and shell metacharacters (`;`, `&`, `|`, `` ` ``, `$`, `(`, `)`, `<`, `>`, `\`, `'`, `"`) are rejected.
|
||||
- **No privilege escalation or interactive shell**: `agents` is not in `wheel` or `docker`, has no `sudo` access, and OpenSSH enforces `PermitTTY no`, `PasswordAuthentication no`, `AllowTcpForwarding no`, `X11Forwarding no`, and `AllowAgentForwarding no`.
|
||||
- **No host state write access**: `agents` has no write permissions to `~/Core`, `~/Workloads`, or `~/var/lib/homelab/*`.
|
||||
@@ -0,0 +1,394 @@
|
||||
# 📋 Control Plane Milestone P4: Readiness Plan & Boundary Specifications
|
||||
|
||||
**Status**: ✅ **Approved & Locked (Pre-P4 Security Gate Complete; Ready for Daemon Implementation)**
|
||||
**Target Milestone**: [Milestone P4: Appctl Control Plane Daemon & API](../../ROADMAP.md#milestone-p4-appctl-control-plane-daemon--command-oriented-api)
|
||||
**Governing ADR**: [`0002-appctl-control-plane-architecture.md`](../decisions/0002-appctl-control-plane-architecture.md)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Purpose & Scope
|
||||
|
||||
Before initiating code implementation for `homelab-appctl.service`, this readiness plan formalizes the operational contracts, execution boundaries, and security invariants that P4 depends upon.
|
||||
|
||||
Milestones P0–P3 and the Pre-P4 Security Gate established the core foundation:
|
||||
- **P0**: Baseline consolidation & Pytest/Nix test harness.
|
||||
- **P1**: Zero-data-loss mail realignment & state isolation (`~/var/lib/homelab/snappymail`).
|
||||
- **P2**: GitOps repository registry (`deployments.yaml`), AST security validation, and Systemd sandboxing.
|
||||
- **P3**: Manifest Schema v1.0 ([`core_manifest.py`](../../scripts/core_manifest.py)), two-axis inspection ([`provenance.py`](../../scripts/provenance.py)), and authoritative engine ([`appctl_engine.py`](../../scripts/appctl_engine.py)).
|
||||
- **Pre-P4 Security Gate (Completed)**:
|
||||
- Eliminated shell `eval` and unvalidated environment injection in `scripts/appctl`.
|
||||
- Enforced `Core/config/deployments.yaml` as sole GitOps registry authority, removing dynamic host discovery.
|
||||
- Hardened Compose AST validator against relative traversal, cross-tenant mounts, and host capability escapes.
|
||||
- Unified manifest parsing on `core_manifest.py` and enforced fail-closed `cmd_resolve` behavior.
|
||||
|
||||
This plan resolves the six architectural prerequisites necessary to implement P4 as a secure, fail-closed operational control plane rather than discovering boundaries ad-hoc during coding.
|
||||
|
||||
---
|
||||
|
||||
## 📑 Sequence of Deliverables
|
||||
|
||||
| Deliverable | Phase | Focus | Status |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **1. Implementation Inventory** | P0 Verification | Baseline truth, callers, dependencies, and migration state | ✅ **Completed** |
|
||||
| **2. Command & Error Contract** | P4 Prerequisite (Blocker) | Canonical domain operations, typed schemas, and error taxonomy | ✅ **Locked & Approved** |
|
||||
| **3. Authorization Design** | Security Gate (Blocker) | Token lifecycle, RBAC matrix, and fail-closed evaluation | ✅ **Locked & Approved** |
|
||||
| **4. Execution & Privilege Boundaries** | P4 Prerequisite | Subprocess allowlist, Docker API capabilities, and filesystem roots | ✅ **Locked & Approved** |
|
||||
| **5. Audit Telemetry Semantics** | P4 Prerequisite | RFC JSONL audit schema, persistent ownership, and lifecycle | ✅ **Locked & Approved** |
|
||||
| **6. P4 Acceptance Test Suite** | Verification | Concrete DoD, black-box transport parity, and security regression gates | ✅ **Locked & Approved** |
|
||||
|
||||
---
|
||||
|
||||
## 1. Reconcile the Implementation Inventory
|
||||
|
||||
### A. Current File & Module Roles
|
||||
|
||||
| File / Component | Language | Authority Status | Functional Responsibilities |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| [`scripts/appctl`](../../scripts/appctl) | Bash | **Active CLI Client** | CLI entry point; secret environment sourcing (`homeserver.env`, `traefik-deployments.env`); resolves metadata via engine; directly runs `docker compose` and `git pull` subprocesses. |
|
||||
| [`scripts/appctl_engine.py`](../../scripts/appctl_engine.py) | Python 3 | **Authoritative Engine** | Domain models (`SitesApp`, `CoreService`); schema v1.0 parsing (`core_manifest.py`); two-axis inspection (`provenance.py`); SSL cert inspection; Homepage compilation; metadata serialization (`resolve`). |
|
||||
| [`scripts/core_manifest.py`](../../scripts/core_manifest.py) | Python 3 | **Schema Library** | Authoritative Pydantic v2 models (`ConfigDict(extra="forbid")`); transport validation (`https://`, `ssh://`, `git@`); ref semantics classification (`branch`, `tag`, `commit`). |
|
||||
| [`scripts/provenance.py`](../../scripts/provenance.py) | Python 3 | **Provenance Library** | Two-axis status engine; local checkout inspection (`git status`, commit SHA); bounded upstream query (`git ls-remote` with 10s timeout). |
|
||||
| [`scripts/gitops_dispatcher.py`](../../scripts/gitops_dispatcher.py) | Python 3 | **Webhook Ingress & Queue** | Webhook listener (port 9000); HMAC validation; `deployments.yaml` admission; `.pending.json` commit-superseding queue; Compose AST validator (`validate_compose_security`). |
|
||||
|
||||
### B. Command Inventory & Implementation Division
|
||||
|
||||
| Command | CLI Syntax | Handled By | Operation Type | Current Behavior |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| `list` / `status` | `appctl list [--fetch] [--core] [--ssl]` | `appctl_engine.py` | Read-Only | Scans `~/Sites`, evaluates two-axis checkout and upstream provenance, queries container status, prints formatted table. |
|
||||
| `info` | `appctl info <service> [--ssl]` | `appctl_engine.py` | Read-Only | Prints detailed metadata, two-axis local checkout vs. upstream provenance, network memberships, and TLS certificate info. |
|
||||
| `ssl` | `appctl ssl [service]` | `appctl_engine.py` | Read-Only | Connects over TLS socket (port 443), extracts peer X.509 certificate, calculates days until expiration. |
|
||||
| `resolve` | `appctl resolve <query>` | `appctl_engine.py` | Read-Only | Resolves canonical name / alias; emits JSON string consumed by Bash `setup_app_env`. |
|
||||
| `complete` | `appctl complete` | `appctl_engine.py` | Read-Only | Emits space-separated list of known workload names, aliases, and core services for Bash shell autocompletion. |
|
||||
| `sync` | `appctl sync [--homepage-dir=PATH]` | `appctl_engine.py` | Mutating (Filesystem) | Reads all `app.yaml` manifests, groups and sorts cards by weight, writes `config/homepage/services.yaml`. |
|
||||
| `up` | `appctl up <service\|core>` | `scripts/appctl` (Bash) | Mutating (Containers) | Sourced environment variables $\to$ `docker compose up -d --remove-orphans` $\to$ triggers `appctl sync`. |
|
||||
| `down` | `appctl down <service\|core>` | `scripts/appctl` (Bash) | Mutating (Containers) | `docker compose down` (or `stop` for Core services) $\to$ triggers `appctl sync`. |
|
||||
| `restart` | `appctl restart <service\|core>` | `scripts/appctl` (Bash) | Mutating (Containers) | Sourced environment variables $\to$ `docker compose restart` (or down/up) $\to$ triggers `appctl sync`. |
|
||||
| `update` | `appctl update <service\|core>` | `scripts/appctl` (Bash) | Mutating (Git + Containers) | Verifies clean git working tree $\to$ `git pull --ff-only` $\to$ `docker compose pull` $\to$ `docker compose up -d` $\to$ triggers `appctl sync`. |
|
||||
| `pull` | `appctl pull <service\|core>` | `scripts/appctl` (Bash) | Mutating (Images) | `docker compose pull` $\to$ `docker compose up -d --remove-orphans`. |
|
||||
| `logs` | `appctl logs <service\|core>` | `scripts/appctl` (Bash) | Read-Only (Sensitive) | Dispatches `docker compose logs`. (Bounded tail output in P4; live streaming deferred to P7.) |
|
||||
| `config` | `appctl config <service\|core>` | `scripts/appctl` (Bash) | Read-Only (Sensitive) | Injects environment $\to$ executes `docker compose config` to view fully evaluated compose AST. |
|
||||
|
||||
### C. Active Call Sites Across the Repository
|
||||
|
||||
1. **System Path Integration**:
|
||||
- [`nixos/configuration.nix`](../../nixos/configuration.nix#L119-L122): Installs host wrapper `/run/current-system/sw/bin/appctl` calling `${CORE_DIR:-$HOME/Core}/scripts/appctl "$@"`.
|
||||
2. **Internal Script Invocation**:
|
||||
- `scripts/appctl` calls `python3 "$ENGINE" resolve "$query"` to set up the Compose environment.
|
||||
- `scripts/appctl` calls `python3 "$ENGINE" sync` after mutating actions (`up`, `down`, `restart`, `update`).
|
||||
3. **Automated Test Coverage (124 Passing Tests)**:
|
||||
- [`tests/unit/test_core_manifest.py`](../../tests/unit/test_core_manifest.py): 24 unit tests covering Pydantic v2 schema validation, extra-field rejection, and ref classification.
|
||||
- [`tests/unit/test_appctl_engine.py`](../../tests/unit/test_appctl_engine.py): 20 unit tests exercising `resolve_app`, `get_docker_status`, `check_ssl_cert`, and `cmd_sync_homepage`.
|
||||
- [`tests/unit/test_provenance.py`](../../tests/unit/test_provenance.py): 10 unit tests covering two-axis status inspection and timeout handling.
|
||||
- [`tests/security/test_gitops_security.py`](../../tests/security/test_gitops_security.py): 60 security tests covering HMAC verification, `deployments.yaml` containment, Compose AST validation, and worker serialization.
|
||||
- [`tests/security/test_security_invariants.py`](../../tests/security/test_security_invariants.py): 7 security invariant tests covering `socket-proxy`, `eval` absence, CLI env injection resilience, and platform genericism.
|
||||
- [`tests/structural/test_repository_structure.py`](../../tests/structural/test_repository_structure.py): 3 structural tests asserting required paths and license preservation.
|
||||
|
||||
### D. Architectural Findings & Migration Deductions
|
||||
|
||||
1. **V1 Engine is Fully Superseded & V2 Shim Retired**: `scripts/appctl_engine.py` is the single authoritative metadata engine, and `scripts/core_manifest.py` is migrated to Pydantic v2 (`ADR-0003`).
|
||||
2. **Duplicated Operational Execution in GitOps (`DEC-04`)**: `scripts/gitops_dispatcher.py` and `scripts/appctl` maintain separate implementations of `git pull` and `docker compose up`, and `gitops_dispatcher.py` currently omits workload environment injection (`SERVICE_DOMAIN`, `CONTAINER_NAME`, `app.yaml` `env:`, `traefik-deployments.env`). In P4, `gitops_dispatcher.py` retains webhook HMAC verification, `deployments.yaml` admission, and the asynchronous `.pending.json` commit-superseding queue, while its worker delegates deployment execution to the daemon's `workload.update` operation over `/run/homelab/appctl.sock` and uses `core_manifest.parse_manifest()`.
|
||||
3. **Shell `.env` Sourcing & Missing Compose AST Pre-Flight on CLI Path (`DEC-05`)**: While `eval` was removed from `scripts/appctl`, the Bash CLI still runs `source "$APP_DIR/.env"` and `source "$APP_DIR/app.env"` and does not invoke `validate_compose_security()`. The P4 daemon replaces Bash `source` with an inert pure-Python key-value parser (enforcing `ENV_KEY_RE` and `RESERVED_ENV_KEYS`) and runs `validate_compose_security()` before every workload Compose operation.
|
||||
|
||||
---
|
||||
|
||||
## 2. Command and Error Contract (P4 Prerequisite — Locked via `DEC-01` & `DEC-04`)
|
||||
|
||||
### A. Wire Protocol, Endpoint Surface & Canonical Domain Operations (`DEC-01`)
|
||||
|
||||
1. **HTTP/1.1 Over Both Transports**: Both the local Unix Domain Socket (`/run/homelab/appctl.sock`) and the loopback TCP listener (`127.0.0.1:9001`) speak standard **HTTP/1.1** and traverse a single shared request pipeline (Body Size Limit $\to$ JSON Parse $\to$ Pydantic v2 Validate $\to$ Auth/RBAC Gate $\to$ Target Resolution & Lock $\to$ Pre-Execution Audit $\to$ Execution $\to$ Post-Execution Audit).
|
||||
2. **Single Canonical Operation Endpoint**:
|
||||
- `POST /v1/operations`: Dispatches all 13 canonical domain operations (both read-only and mutating).
|
||||
- `GET /v1/health`: Convenience liveness probe that internally dispatches `platform.health`.
|
||||
- No multi-route REST aliases (`GET /workloads`, `POST /operations/deploy`, etc.) are exposed in P4, eliminating URL-vs-body ambiguity.
|
||||
3. **Bounded Non-Streaming Logs**: `workload.logs` is strictly non-streaming in P4 (`tail: StrictInt` bounded `1..1000`, default `100`). Live streaming (`--follow` / SSE) is deferred to Milestone P7.
|
||||
4. **Payload & Output Bounds**: Maximum HTTP request body size is `64 KiB` (larger bodies are rejected with `400 ERR_VALIDATION_FAILED`). Maximum captured subprocess `stdout`/`stderr` is `256 KiB` per invocation.
|
||||
|
||||
```text
|
||||
┌─────────────────────────┐
|
||||
│ Client Request │
|
||||
│ POST /v1/operations │
|
||||
└────────────┬────────────┘
|
||||
▼
|
||||
┌───────────────────────────────────────────┐
|
||||
│ Operation Dispatch Router │
|
||||
└─────────────────────┬─────────────────────┘
|
||||
│
|
||||
┌───────────────────────────────┴───────────────────────────────┐
|
||||
▼ ▼
|
||||
[ Read-Only Operations ] [ Mutating Operations ]
|
||||
• workload.list (viewer) • workload.deploy (operator / admin*)
|
||||
• workload.get (viewer) • workload.stop (operator / admin*)
|
||||
• workload.resolve (viewer) • workload.restart (operator / admin*)
|
||||
• platform.ssl (viewer) • workload.update (operator / admin*)
|
||||
• platform.health (viewer) • workload.pull (operator / admin*)
|
||||
• workload.config (operator / admin* — sensitive read) • platform.sync_homepage (operator / admin)
|
||||
• workload.logs (operator / admin* — sensitive read)
|
||||
(* targeting 'core' or a 'core_service' strictly requires 'homelab-admin')
|
||||
```
|
||||
|
||||
### B. Typed Request and Response Models (Pydantic v2 Pipeline)
|
||||
|
||||
All control plane API requests, responses, and error payloads are defined and validated through **Pydantic v2** (`pydantic.BaseModel`, `pydantic.Field`, `ConfigDict(extra="forbid", strict=True)`), joining the existing Pydantic v2 manifest schema in [`scripts/core_manifest.py`](../../scripts/core_manifest.py):
|
||||
|
||||
- **Runtime Validation Boundary**: Incoming JSON payloads over both Unix Domain Socket and HTTP endpoints are validated at the transport boundary before reaching the operational router.
|
||||
- **Fail-Closed Extra Fields (`extra="forbid"`)**: Rejects any undeclared or unknown fields immediately.
|
||||
- **Strict Typing vs. Coercion Rules (`strict=True`)**:
|
||||
- *Strict Validation*: Operations (`operation`), target identifiers (`target`), integer bounds (`tail`), boolean flags (`recreate`, `remove_orphans`, `build`, `fetch`, `core`, `ssl`), and optional strings (`expected_branch`) enforce strict types (`StrictStr`, `StrictBool`, `StrictInt`). Implicit coercion (e.g., `"true"` or `1` to `True`, or floats to ints) is forbidden.
|
||||
- *Permitted Normalization*: Only explicitly defined string whitespace trimming via field validators is permitted.
|
||||
- **Operation-Specific Parameters (`DEC-04`)**:
|
||||
- `workload.deploy`: `recreate: StrictBool = True`, `remove_orphans: StrictBool = True`, `build: StrictBool = False`.
|
||||
- `workload.update`: `expected_branch: StrictStr | None = None`, `build: StrictBool = False`. Enforces revision-consistent post-pull validation of `app.yaml` (`deployment.branch` and `deployment.actions`, supporting `git_pull`, `compose_pull`, `compose_build`, `compose_up`, `compose_restart`).
|
||||
- `workload.logs`: `tail: StrictInt = Field(default=100, ge=1, le=1000)`.
|
||||
- `workload.list`: `fetch: StrictBool = False`, `core: StrictBool = False`, `ssl: StrictBool = False`.
|
||||
- `workload.get`: `ssl: StrictBool = False`.
|
||||
- **Information Disclosure Prevention**: Transport handlers intercept `pydantic.ValidationError`, strip raw input values (`e.errors(include_input=False, include_url=False)`), and map violations to `ERR_VALIDATION_FAILED` (`400 Bad Request`).
|
||||
|
||||
All requests and responses use strict JSON payloads with explicit schema versioning (`version: "1.0"`):
|
||||
|
||||
```json
|
||||
// Example: POST /v1/operations
|
||||
// Request:
|
||||
{
|
||||
"version": "1.0",
|
||||
"operation": "workload.deploy",
|
||||
"target": "jellyfin",
|
||||
"parameters": {
|
||||
"recreate": true,
|
||||
"remove_orphans": true,
|
||||
"build": false
|
||||
}
|
||||
}
|
||||
|
||||
// Response (Success):
|
||||
{
|
||||
"version": "1.0",
|
||||
"status": "success",
|
||||
"operation_id": "op_01JAX71BC98E4",
|
||||
"target": "jellyfin",
|
||||
"timestamp": "2026-10-16T12:00:00Z",
|
||||
"duration_ms": 1420,
|
||||
"result": {
|
||||
"action": "deployed",
|
||||
"target_type": "app",
|
||||
"health": "🟢 Running (1)"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### C. Standardized Error Taxonomy
|
||||
|
||||
Failures are strongly typed and distinguished across six canonical error codes:
|
||||
|
||||
| Error Classification | HTTP Code | Error Code | Description / Fail-Closed Action |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Validation Error** | `400 Bad Request` | `ERR_VALIDATION_FAILED` | Request schema violation, body $>64\text{ KiB}$, invalid target format, malformed `app.yaml`, dirty git working tree on update, post-pull branch mismatch, or Compose AST security violation. |
|
||||
| **Authentication Error** | `401 Unauthorized` | `ERR_AUTH_REQUIRED` | Missing, unknown, or malformed Bearer token (or unauthenticated UDS caller attempting a token-gated operation). |
|
||||
| **Authorization Error** | `403 Forbidden` | `ERR_PERMISSION_DENIED` | Authenticated principal lacks required role (e.g., `homelab-viewer` attempting mutation or `config`/`logs`; `homelab-operator` targeting `core`/`core_service` or a workload not in `deployments.yaml`). |
|
||||
| **Target Not Found** | `404 Not Found` | `ERR_TARGET_NOT_FOUND` | Workload target does not exist under `~/Sites` or Core services registry. |
|
||||
| **State Conflict** | `409 Conflict` | `ERR_CONCURRENT_MUTATION` | Another mutating operation on the target workload is currently holding the per-target operation lock. |
|
||||
| **Execution Error** | `500 Internal Error`| `ERR_EXECUTION_FAILED` | Audit log write failure, Docker/Git subprocess non-zero exit, or subprocess timeout expiration. |
|
||||
|
||||
---
|
||||
|
||||
## 3. Authorization Design (Security Gate — Locked via `DEC-02` & `DEC-05`)
|
||||
|
||||
### A. The Core Principle: Host Access Does Not Confer Mutation Authority
|
||||
|
||||
Entering the host via SSH establishes Unix access, but **zero operational control plane mutation or secret-inspection privileges**. Every mutating request—and every sensitive read (`workload.config`, `workload.logs`)—to `homelab-appctl.service` must present an authenticated Bearer token.
|
||||
|
||||
### B. Principal Identity, Role Mapping & Target Scope (`DEC-02`, `DEC-05`)
|
||||
|
||||
The platform enforces three hierarchical authorization tiers:
|
||||
|
||||
| Role | Permitted Operations & Target Scope | Typical Principals |
|
||||
| :--- | :--- | :--- |
|
||||
| `homelab-admin` | All operations across **all targets**: `core` stack, individual `core_service` containers (`traefik`, `authelia`, `stalwart`, etc.), and any valid `~/Sites/<app>` directory contained within `SITES_DIR`. | Interactive human operator token (`operator`). |
|
||||
| `homelab-operator` | Workload mutations (`deploy`, `stop`, `restart`, `update`, `pull`, `sync_homepage`) and sensitive reads (`config`, `logs`) **strictly restricted to workloads registered in [`config/deployments.yaml`](../../config/deployments.yaml)**. Cannot target `core`, `core_service`, or unregistered `~/Sites` directories (`403 ERR_PERMISSION_DENIED`). | GitOps webhook worker token (`gitops-dispatcher`), scoped automation scripts. |
|
||||
| `homelab-viewer` | Non-sensitive read-only operations (`workload.list`, `workload.get`, `workload.resolve`, `platform.ssl`, `platform.health`). Zero mutations permitted; `workload.config` and `workload.logs` are denied (`403 ERR_PERMISSION_DENIED`). | Local UDS `SO_PEERCRED` operator session fallback, read-only status monitors. |
|
||||
|
||||
### C. Transport Authentication Rules (P4 vs. P5 Boundary)
|
||||
|
||||
1. **SOPS-Projected Hashed Token Store (`/run/secrets/appctl/tokens.json`)**:
|
||||
- Owned by `homelab-appctl` (mode `0400`).
|
||||
- Stores an array of token descriptors (`token_id`, `identity`, `role`, and 64-char hex `sha256` digest of the bearer secret).
|
||||
- Incoming `Authorization: Bearer <secret>` headers are hashed with SHA-256 and compared via `hmac.compare_digest`.
|
||||
- Required for **all mutations**, **all `workload.config` / `workload.logs` calls**, and **all HTTP listener requests**.
|
||||
2. **Unix Domain Socket (`/run/homelab/appctl.sock`) & `SO_PEERCRED`**:
|
||||
- Socket ownership: `homelab-appctl:homelab-operators`, file mode `0660`.
|
||||
- The UDS listener extracts kernel peer credentials (`SO_PEERCRED`: `uid`, `gid`, `pid`) on every connection and records `origin = f"peer_uid_{uid}"`.
|
||||
- If no `Authorization` header is supplied over UDS and `uid` belongs to an authorized local operator, the request is authenticated as `Principal(identity=f"unix_uid_{uid}", role="homelab-viewer", token_id=None, auth_method="unix_peercred")`. This enables zero-friction local inspection (`appctl list`, `appctl info`, `appctl ssl`) and shell tab-completion (`appctl complete`) while blocking all mutations and secret dumps (`401`/`403`).
|
||||
3. **HTTP Network Listener (`127.0.0.1:9001`)**:
|
||||
- Bound strictly to loopback (`127.0.0.1`) in P4 (`APPCTL_HTTP_HOST=127.0.0.1`, `APPCTL_HTTP_PORT=9001`).
|
||||
- Every `POST /v1/operations` call over HTTP requires a valid Bearer token (`401 ERR_AUTH_REQUIRED` if missing).
|
||||
- **ForwardAuth Headers Deferred to P5**: Proxy headers (`Remote-User`, `Remote-Groups`) are **ignored and never trusted** in P4. (In P5, ForwardAuth will be introduced with dedicated proxy authentication so workload containers on `proxy-net` cannot spoof headers.)
|
||||
4. **GitOps Ingress (`homelab-gitops.service` $\to$ Daemon UDS)**:
|
||||
- `gitops_dispatcher.py` verifies the Gitea webhook HMAC-SHA256 signature against `/run/secrets/gitops/webhook_secret`, admits the push against `config/deployments.yaml`, and enqueues `<target>.pending.json`.
|
||||
- The serialized background worker invokes `POST /v1/operations` (`operation: "workload.update"`, `parameters: {"expected_branch": branch}`) over `/run/homelab/appctl.sock` authenticating with its `homelab-operator` Bearer token.
|
||||
|
||||
---
|
||||
|
||||
## 4. Execution & Privilege Boundaries (P4 Prerequisite — Locked via `DEC-03` & `DEC-05`)
|
||||
|
||||
### A. Operational Capability Matrix & Timeouts
|
||||
|
||||
Each canonical operation is bound to minimal execution permissions, fixed argument lists (`shell=False`), hard timeouts, and role checks:
|
||||
|
||||
| Domain Operation | Subprocess / Tool | Allowed Arguments / API | Timeout | Required Role (`Sites` / `Core`) |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| `workload.list` | In-process (`appctl_engine.py`, `provenance.py`) | Scan `~/Sites/`, `git status` (`5s`), optional `git ls-remote` (`10s`), `docker compose ps` (`15s`) | `15s` / cmd | `homelab-viewer` |
|
||||
| `workload.get` | In-process (`appctl_engine.py`, `core_manifest.py`) | Parse `app.yaml`, inspect git status (`5s`), `git ls-remote` (`10s`), `docker inspect` (`15s`) | `15s` / cmd | `homelab-viewer` |
|
||||
| `workload.resolve` | In-process (`appctl_engine.py`) | Canonical target resolution & metadata dictionary | In-process | `homelab-viewer` |
|
||||
| `platform.ssl` | In-process (`appctl_engine.py`) | TLS peer certificate check on port 443 | `3s` / host | `homelab-viewer` |
|
||||
| `platform.health` | In-process | Daemon liveness, socket/lock/audit readiness check | In-process | `homelab-viewer` |
|
||||
| `workload.config` | `docker` | `compose -f <compose_file> config` (with secret redaction for non-admin) | `15s` | `homelab-operator` / `homelab-admin` |
|
||||
| `workload.logs` | `docker` | `compose -f <compose_file> logs --no-color --tail <1..1000>` | `15s` | `homelab-operator` / `homelab-admin` |
|
||||
| `workload.deploy` | `docker` | Optional `compose -f <compose_file> build` (`if build=True`) $\to$ `compose -f <compose_file> up -d [--remove-orphans]` $\to$ Homepage sync | `300s` | `homelab-operator` / `homelab-admin` |
|
||||
| `workload.stop` | `docker` | `compose -f <compose_file> down` (or `stop <container>` for `core_service`) $\to$ Homepage sync | `300s` | `homelab-operator` / `homelab-admin` |
|
||||
| `workload.restart`| `docker` | `compose -f <compose_file> restart [<container>]` $\to$ Homepage sync | `300s` | `homelab-operator` / `homelab-admin` |
|
||||
| `workload.pull` | `docker` | `compose -f <compose_file> pull [<container>]` $\to$ `compose -f <compose_file> up -d --remove-orphans` | `300s` | `homelab-operator` / `homelab-admin` |
|
||||
| `workload.update` | `git`, `docker` | 1. Clean tree check (`git status --porcelain`, `5s`)<br>2. `git -C <dir> pull --ff-only [origin <expected_branch>]` (`60s`)<br>3. Re-validate `app.yaml` & `expected_branch` + `validate_compose_security()`<br>4. Execute declared actions (`compose_pull`, `compose_build`, `compose_up`, `compose_restart`, `300s` each) $\to$ Homepage sync | `60s` (git)<br>`300s` (docker) | `homelab-operator` / `homelab-admin` |
|
||||
| `platform.sync_homepage` | In-process (`appctl_engine.py`) | Atomic compile of `Core/config/homepage/services.yaml` under `_homepage_sync.lock` | In-process | `homelab-operator` / `homelab-admin` |
|
||||
|
||||
### B. Unified Pre-Flight, Environment Assembly & Secret Boundary (`DEC-05`)
|
||||
|
||||
1. **Pre-Flight Validation Gate**: Every workload mutation and `workload.config` call executes in strict order:
|
||||
- **Path Containment**: Target directory must resolve strictly inside `SITES_DIR.resolve()` (or equal `CORE_DIR.resolve()` for `homelab-admin`).
|
||||
- **Registry Admission**: If `principal.role == "homelab-operator"`, target must be present in `config/deployments.yaml`.
|
||||
- **Manifest Validation**: `core_manifest.parse_manifest(app_dir / "app.yaml")` must succeed with zero errors.
|
||||
- **Compose AST Security Validation**: `validate_compose_security(compose_file, app_dir, app_name=manifest.name)` must pass (blocking `privileged: true`, `cap_add`, `devices`, `security_opt: unconfined`, host namespaces, `/var/run/docker.sock`, top-level `include`, escaping `env_file`, undeclared volumes, and cross-tenant bind mounts).
|
||||
2. **Inert Pure-Python Environment Assembly (No Shell `source`)**:
|
||||
- The daemon constructs the subprocess environment dictionary in memory:
|
||||
1. Base system `PATH` and `DOCKER_CONFIG`.
|
||||
2. Global secret files (`/run/secrets/rendered/homeserver.env`, `/run/secrets/rendered/traefik-deployments.env` with `/run/secrets/*` fallback) parsed via a pure-Python `KEY=VALUE` reader (no shell expansion).
|
||||
3. Canonical domain lock (`HOMELAB_DOMAIN` resolved via `HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN`).
|
||||
4. Infrastructure defaults (`PROXY_NETWORK=proxy-net`, `CERT_RESOLVER=myresolver`, `DOMAIN_SUFFIX=$HOMELAB_DOMAIN`) and workload identity (`SERVICE_NAME`, `CONTAINER_NAME`, `SERVICE_DOMAIN`, `DOMAIN`).
|
||||
5. Validated `manifest.env` dictionary from `app.yaml`.
|
||||
6. Optional `$APP_DIR/.env` and `$APP_DIR/app.env` parsed via pure-Python `KEY=VALUE` reader with every key validated against `ENV_KEY_RE` and `RESERVED_ENV_KEYS`.
|
||||
3. **Secret Isolation & Redaction**:
|
||||
- The daemon never accesses SOPS master keys (`/etc/ssh/ssh_host_ed25519_key`).
|
||||
- Any key matching `*_KEY`, `*_SECRET`, `*_PASSWORD`, `*_TOKEN`, `*_PASS`, or `*_HASH` (and any known secret value from `/run/secrets/`) is replaced with `"[REDACTED]"` in audit logs, error responses, and diagnostic messages.
|
||||
|
||||
### C. Systemd Unit Sandboxing & Service Identity (`homelab-appctl.service` — `DEC-03`)
|
||||
|
||||
- **Dedicated Service Identity**:
|
||||
- `User = "homelab-appctl"`
|
||||
- `Group = "homelab-operators"`
|
||||
- `SupplementaryGroups = [ "docker" ]`
|
||||
- **Managed Runtime, State & Log Directories**:
|
||||
- `RuntimeDirectory = "homelab"` (`RuntimeDirectoryMode = "0750"`): Hosts `/run/homelab/appctl.sock` (mode `0660`, `homelab-appctl:homelab-operators`).
|
||||
- `StateDirectory = "homelab/appctl"` (`StateDirectoryMode = "0700"`): Hosts `/var/lib/homelab/appctl/locks/<target>.lock` and `_homepage_sync.lock`.
|
||||
- `LogsDirectory = "homelab/appctl"` (`LogsDirectoryMode = "0700"`): Hosts `/var/log/homelab/appctl/audit.jsonl` (mode `0600`, `homelab-appctl:homelab-operators`).
|
||||
- **Declarative Filesystem Access (`systemd.tmpfiles.rules` POSIX ACLs)**:
|
||||
- Grants `homelab-appctl` traverse (`x`) on `/home/<operator>` and `/home/<operator>/Core`.
|
||||
- Applies recursive default POSIX ACLs (`A+`) granting `d:u:homelab-appctl:rwx,u:homelab-appctl:rwx` on `/home/<operator>/Sites`, `/home/<operator>/var/lib/homelab`, and `/home/<operator>/Core/config/homepage` so both `<operator>` and `homelab-appctl` can update Git checkouts and write `services.yaml` without permission conflicts.
|
||||
- **Systemd Hardening**:
|
||||
- `ProtectSystem = "strict"`, `ProtectHome = "read-only"`, `PrivateTmp = true`, `NoNewPrivileges = true`, `ProtectKernelTunables = true`, `ProtectControlGroups = true`.
|
||||
- `ReadWritePaths`: `/home/<operator>/Sites`, `/home/<operator>/var/lib/homelab`, `/home/<operator>/Core/config/homepage`, `/var/log/homelab/appctl`, `/var/lib/homelab/appctl`, `/run/homelab`.
|
||||
|
||||
### D. Platform Genericism & Domain Decoupling
|
||||
Per `AGENTS.md` §3, all control-plane modules, NixOS definitions, Compose stacks, and tests must remain instance-agnostic:
|
||||
- Canonical domain precedence: `HOMELAB_DOMAIN` $\to$ `DOMAIN_SUFFIX` $\to$ `DOMAIN` (fails closed if unset).
|
||||
- Test fixtures and documentation examples use RFC 2606 domains (`example.com`, `example.org`, `example.test`).
|
||||
|
||||
---
|
||||
|
||||
## 5. Audit Telemetry & Operational State Semantics (`DEC-03`)
|
||||
|
||||
### A. Distinction Between Operation Result, Audit Event & Deployment State
|
||||
|
||||
1. **Operation Result (`OperationResponse`)**: Synchronous HTTP/1.1 response payload returned immediately to the caller.
|
||||
2. **Audit Event (`/var/log/homelab/appctl/audit.jsonl`)**: Authoritative append-only control-plane security and mutation log. Captures pre-execution (`DISPATCHED`), post-execution (`COMPLETED` / `FAILED`), and admission rejection (`DENIED`) records correlated by `operation_id`, including pre/post `commit_sha` on `workload.update` and `workload.deploy`.
|
||||
3. **GitOps Status Snapshot (`~/.local/state/homelab/gitops/<target>.status.json`)**: Lightweight latest-run status file written by `gitops_dispatcher.py` worker upon completion for backward-compatible webhook status inspection. (No separate rollback database or `appctl history` command is introduced in P4 v1.)
|
||||
|
||||
### B. Field Schema (RFC-Compliant JSONL)
|
||||
|
||||
Every audited lifecycle event is appended as a single line to `/var/log/homelab/appctl/audit.jsonl` (mode `0600`, overridable via `APPCTL_AUDIT_LOG` in hermetic tests):
|
||||
|
||||
```json
|
||||
{
|
||||
"audit_version": "1.0",
|
||||
"event_id": "evt_01JAX73AB190",
|
||||
"operation_id": "op_01JAX71BC98E4",
|
||||
"timestamp": "2026-10-16T12:00:03.112Z",
|
||||
"phase": "COMPLETED",
|
||||
"principal": {
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"token_id": "tok_admin_01",
|
||||
"auth_method": "bearer_token"
|
||||
},
|
||||
"action": "workload.update",
|
||||
"target": "docs",
|
||||
"transport": "unix_socket",
|
||||
"origin": "peer_uid_1000",
|
||||
"client": "appctl-cli/2.0",
|
||||
"parameters": {
|
||||
"expected_branch": null,
|
||||
"build": false
|
||||
},
|
||||
"result": {
|
||||
"status": "SUCCESS",
|
||||
"exit_code": 0,
|
||||
"duration_ms": 3210,
|
||||
"commit_sha": "d4f8a1e",
|
||||
"error_code": null,
|
||||
"message": "Workload updated and reconciled successfully"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### C. Event Lifecycle States & Audited Scope
|
||||
|
||||
| Phase | Trigger & Scope |
|
||||
| :--- | :--- |
|
||||
| `DISPATCHED` | Written and flushed **before** any subprocess or file mutation executes for all mutating operations (`deploy`, `stop`, `restart`, `pull`, `update`, `sync_homepage`). |
|
||||
| `COMPLETED` | Written when a mutating operation or sensitive read (`workload.config`, `workload.logs`) terminates cleanly (`exit_code == 0`). |
|
||||
| `FAILED` | Written when a mutating operation or sensitive read fails during pre-flight validation (`400`) or execution (`500`). |
|
||||
| `DENIED` | Written when authentication (`401`), RBAC authorization (`403`), or concurrency lock acquisition (`409`) rejects a request. |
|
||||
|
||||
*(Note: High-frequency non-sensitive viewer reads—`list`, `get`, `resolve`, `ssl`, `health`—do not emit `COMPLETED` audit records, preventing log bloat during CLI status checks and shell tab-completion.)*
|
||||
|
||||
### D. Failure Handling & Explicit Audit Threat Model
|
||||
|
||||
1. **Fail-Closed Pre-Execution Disk Guard**: If writing or flushing the `DISPATCHED` record to `audit.jsonl` fails (`OSError`), the daemon **immediately aborts the mutation and returns `500 ERR_EXECUTION_FAILED`** with zero Docker or Git invocations.
|
||||
2. **Post-Execution Persistence Failure**: If writing the `COMPLETED`/`FAILED` record fails after subprocess execution, the daemon logs a critical alert to `stderr` (`journald`) and returns `500 ERR_EXECUTION_FAILED`.
|
||||
3. **Explicit Threat Model**:
|
||||
- **Protected Boundary**: Running the daemon as `homelab-appctl` with `/var/log/homelab/appctl/audit.jsonl` (`0600`) and `/run/secrets/appctl/tokens.json` (`0400`) enforces an OS user boundary against unprivileged processes and AI coding agents running inside the human operator's SSH session (`<operator>` UID). Session processes cannot read `tokens.json`, forge/truncate `audit.jsonl`, or signal the daemon without `sudo`.
|
||||
- **Out-of-Scope Boundary**: Protection against an actor who possesses host `root` / `sudo` / `docker`-group escalation privileges is out of scope for single-node P4 (as `root` can modify any local file on the host).
|
||||
|
||||
---
|
||||
|
||||
## 6. P4 Implementation Slices (Dependency-Ordered)
|
||||
|
||||
1. **Slice 1 — Pydantic v2 API Contracts & Error Sanitizer (`scripts/appctl_contracts.py`)**:
|
||||
- Strict request/response/error/audit models (`ConfigDict(extra="forbid", strict=True)`), operation parameter schemas, and `ValidationError` $\to$ `400 ERR_VALIDATION_FAILED` sanitizer (`include_input=False`).
|
||||
- Add `"compose_pull"` to `ALLOWED_ACTIONS` in `scripts/core_manifest.py`.
|
||||
2. **Slice 2 — Append-Only Audit Logger & Per-Target Lock Manager**:
|
||||
- `AuditLogger` (`DISPATCHED`, `COMPLETED`, `FAILED`, `DENIED`, `0600` enforcement, secret redaction, fail-closed disk guard) and non-blocking `fcntl.flock` manager (`/var/lib/homelab/appctl/locks/<target>.lock` + `_homepage_sync.lock`).
|
||||
3. **Slice 3 — Authentication & 3-Role RBAC Gate**:
|
||||
- SOPS `tokens.json` SHA-256 authenticator (`hmac.compare_digest`), UDS `SO_PEERCRED` extractor (`unix_peercred` viewer fallback for non-sensitive reads), and role-scoped authorization policy (`homelab-admin` vs `homelab-operator` `deployments.yaml` restriction vs `homelab-viewer`).
|
||||
4. **Slice 4 — Operational Router & Unified Execution Engine**:
|
||||
- Pure-Python `.env` parser (no shell `source`), mandatory `parse_manifest()` + `validate_compose_security()` pre-flight, revision-consistent `workload.update` (`expected_branch`, dynamic action adoption, `build`), bounded `workload.logs` (`tail`), and atomic Homepage sync.
|
||||
5. **Slice 5 — Dual-Transport HTTP/1.1 Daemon (`scripts/appctl_daemon.py`) & GitOps Cutover**:
|
||||
- HTTP/1.1 server over UDS (`/run/homelab/appctl.sock`) and TCP (`127.0.0.1:9001`), graceful `SIGTERM`/`SIGINT` cleanup, and rewiring `scripts/gitops_dispatcher.py` to parse manifests via `core_manifest.parse_manifest()` and execute worker deployments through the daemon.
|
||||
6. **Slice 6 — Thin-Client CLI (`scripts/appctl`), NixOS Service & Platform Genericism Cleanup**:
|
||||
- Re-implement `scripts/appctl` as a thin UDS HTTP client, declare `homelab-appctl.service` (`homelab-appctl:homelab-operators` + POSIX ACLs) in `nixos/modules/homeserver.nix`, scrub remaining hardcoded domain/username literals across `nixos/`, `config/deployments.yaml`, and `docker-compose.yml`, and add `pyright` to `flake.nix` checks and `.githooks/pre-commit`.
|
||||
|
||||
---
|
||||
|
||||
## 7. P4 Definition of Done & Acceptance Test Matrix
|
||||
|
||||
Before marking Milestone P4 complete, the following automated regression suite must pass:
|
||||
|
||||
| Test Suite / Area | Assertion / Invariant Verified | Failure Action |
|
||||
| :--- | :--- | :--- |
|
||||
| **Transport Parity** | `test_transport_dual_equivalence`: Compare responses of `POST /v1/operations` (`workload.list`, `workload.get`, errors) over Unix socket vs HTTP `127.0.0.1`. Assert 100% schema and status parity. | Reject PR |
|
||||
| **Unauthenticated Rejection** | `test_auth_missing_token_fails_closed`: Mutating operations and `workload.config`/`workload.logs` without `Authorization: Bearer` return `401 ERR_AUTH_REQUIRED` on both UDS and HTTP and execute zero subprocesses. | Block Release |
|
||||
| **UDS Peercred Viewer Scope** | `test_uds_peercred_viewer_boundary`: Tokenless UDS call from operator UID succeeds for `workload.list` (`auth_method: "unix_peercred"`), but fails with `401`/`403` on any mutation or `workload.config`. | Block Release |
|
||||
| **RBAC & Role-Scoped Resolution**| `test_rbac_role_matrix`: `homelab-viewer` denied (`403`) on all mutations; `homelab-operator` allowed on `deployments.yaml` workloads but denied (`403`) on `core`, `core_service`, and unregistered `~/Sites` dirs; `homelab-admin` allowed on all valid targets. | Block Release |
|
||||
| **Pre-Flight & `.env` Safety** | `test_daemon_preflight_and_dotenv_safety`: Workload with malicious `.env` (`$(touch ...)`) or prohibited Compose directive (`privileged: true`, `/var/run/docker.sock`) is blocked / parsed inertly with zero shell execution. | Block Release |
|
||||
| **Concurrency Lock (`409`)** | `test_concurrent_mutation_conflict`: Second concurrent mutation on the same target immediately returns `409 ERR_CONCURRENT_MUTATION` and logs `DENIED`. | Block Release |
|
||||
| **Truthful Error Reporting** | `test_execution_failure_audit`: Failing or timing-out Docker/Git subprocess returns `500 ERR_EXECUTION_FAILED` and records `phase: FAILED` in `audit.jsonl`. | Reject PR |
|
||||
| **Audit Persistence Gate** | `test_audit_failure_blocks_mutation`: Unwritable `audit.jsonl` aborts mutating command with `500 ERR_EXECUTION_FAILED` and zero Docker/Git invocations. | Block Release |
|
||||
| **Daemon Crash Recovery** | `test_daemon_restart_preserves_state`: Clean stop and restart of daemon unlinks/rebinds socket cleanly and leaves running workloads and Git state undisturbed. | Reject PR |
|
||||
| **Existing Invariant Regression** | Run `./scripts/run-tests`: All 124 existing unit, security, structural, Ruff, Pyright, and Nix flake sandbox checks pass with 0 regressions. | Block Merge |
|
||||
@@ -0,0 +1,106 @@
|
||||
# 📋 Implementation Plan: Control Plane Hardening, Instance Decoupling & MCP Alignment
|
||||
|
||||
**Document Version**: 1.0
|
||||
**Status**: 🚀 Approved for Implementation
|
||||
**Date**: 2026-10-23
|
||||
**Target Milestone**: P4 Hardening & P6 Deprecation
|
||||
**Branch**: `refactor/appctl-rework`
|
||||
|
||||
---
|
||||
|
||||
## 1. Executive Summary & Context
|
||||
|
||||
During the pre-merge readiness investigation of the `refactor/appctl-rework` branch, four deployment blockers and several architectural divergences were identified:
|
||||
1. **Unconfigured Root Domain**: `options.homelab.domain` defaulted to `"example.test"`, which would overwrite live routing templates (`homeserver.env`, `traefik-deployments.env`) upon `nixos-rebuild switch`.
|
||||
2. **Authelia/LLDAP Base DN Desynchronization**: Compose defaulted `LLDAP_LDAP_BASE_DN` to `dc=example,dc=test`, conflicting with the existing on-host LLDAP database (`dc=<domain-prefix>,dc=<tld>`).
|
||||
3. **Operator Identity Coupling**: Core configurations referenced legacy operator username literals rather than a generic system operator (`operator`).
|
||||
4. **POSIX ACL & Git Dubious Ownership**: `tmpfiles.rules` used lowercase `a+` (non-recursive), leaving existing checkouts in `~/Sites` unwriteable to `homelab-appctl`. Furthermore, Git 2.35.2+ lacked `safe.directory` declarations for `homelab-appctl`.
|
||||
5. **AI Authoring Boundary Evolution**: Earlier architectural planning explored an on-server 5-stage deployment authoring pipeline (`ApplicationProfile` $\to$ `DeploymentProposal` $\to$ `DeploymentModel` compiler). This requirement is formally deprecated in favor of a decoupled Model Context Protocol (MCP) tool gateway.
|
||||
|
||||
This plan establishes the concrete implementation work packages to resolve these findings and ensure 100% deployment safety.
|
||||
|
||||
---
|
||||
|
||||
## 2. Architectural Decisions & Scope
|
||||
|
||||
### A. Operator Identity Decoupling (Legacy Operator $\to$ `operator`)
|
||||
- Standardize the primary platform operator as `operator` with home directory `/home/operator`.
|
||||
- `config.homelab.operatorUser` defaults to `"operator"`.
|
||||
- NixOS declares user `operator` (`uid = 1000` or standard user, `extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]`).
|
||||
- Eliminates hardcoded personal usernames from the Core platform foundation.
|
||||
|
||||
### B. Platform Genericism & Instance Profile (Decision D1)
|
||||
- Core modules in `nixos/modules/` remain strictly generic, defaulting to RFC 2606 placeholders (`example.test` and `operator`).
|
||||
- **Decision D1: Dual-Path Instance Domain Injection**: Rather than committing host-specific production domains to tracked Git files, `nixos/configuration.nix` implements an optional dual-path import mechanism:
|
||||
```nix
|
||||
imports = [
|
||||
./hardware-configuration.nix
|
||||
./modules/homeserver.nix
|
||||
./modules/traefik-deployments.nix
|
||||
./modules/dynu.nix
|
||||
./modules/shell.nix
|
||||
] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix
|
||||
++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix;
|
||||
```
|
||||
- `nixos/instance.nix` is git-ignored, allowing host-specific overrides (like `homelab.domain = "example.com";`) without dirtying version control. Alternatively, `/etc/nixos/homelab-instance.nix` provides a persistent host-level configuration path outside the repository checkout.
|
||||
- `LLDAP_LDAP_BASE_DN` is computed dynamically in Nix from `config.homelab.domain` (`domain: example.test` $\implies$ `dc=example,dc=test`), eliminating hardcoded domain strings across templates and Compose files.
|
||||
|
||||
### C. Control Plane Security & POSIX Permissions
|
||||
- **Recursive ACLs**: Change `a+` to uppercase `A+` for `${config.homelab.sitesDir}` and `${config.homelab.coreDir}/config/homepage` in `systemd.tmpfiles.rules`.
|
||||
- **Git Safe Directory**: Configure `programs.git.config.safe.directory = [ "/home/operator/Sites/*" ]` for the host.
|
||||
- **Fail-Closed CLI**: If `/run/homelab/appctl.sock` is unavailable, `scripts/appctl` fails closed with an informative error rather than silently falling back to unauthenticated Bash execution.
|
||||
- **CLI Status Restoration**: Restore live container inspection (`get_docker_status()`) in `workload.list` and format the `STATUS` column in `scripts/appctl_cli.py`.
|
||||
|
||||
### D. Deprecation of On-Server AI Authoring Pipeline (MCP Gateway Adoption)
|
||||
- As documented in `~/Brain/02-discussions/homelab/mcp-gateway-and-platform-evolution.md`, on-server AI deployment agents (`DeploymentProposal` compilers) are deprecated.
|
||||
- Milestone P6 is redefined as the **Homelab MCP Gateway**:
|
||||
- Exposes deterministic `appctl` operations over JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`, `appctl_audit`).
|
||||
- Gated by native client-side human confirmation (Antigravity, Claude Code, Cursor).
|
||||
- Keeps Core 100% deterministic with zero autonomous agent loops executing on the appliance host.
|
||||
|
||||
---
|
||||
|
||||
## 3. Work Breakdown Structure (WBS)
|
||||
|
||||
### Phase 1: Host Configuration & Identity Migration
|
||||
- [x] **Task 1.1**: Update `nixos/configuration.nix` to declare user `operator` and configure `homelab.operatorUser = "operator"` and `homelab.domain` with the configured production domain.
|
||||
- [x] **Task 1.2**: Declare `programs.git.config.safe.directory = [ "/home/operator/Sites/*" ]` in `nixos/configuration.nix`.
|
||||
- [x] **Task 1.3**: Derive `LLDAP_LDAP_BASE_DN` dynamically from `config.homelab.domain` in `nixos/modules/homeserver.nix` and pass it to `sops.templates."homeserver.env"`.
|
||||
- [x] **Task 1.4**: Update `docker-compose.yml` to consume `LLDAP_LDAP_BASE_DN` from `homeserver.env`.
|
||||
- [x] **Task 1.5**: Update `systemd.tmpfiles.rules` in `nixos/modules/homeserver.nix` from `a+` to recursive `A+` on `sitesDir`.
|
||||
|
||||
### Phase 2: CLI Hardening & Status Parity
|
||||
- [x] **Task 2.1**: Update `scripts/appctl` to fail closed when `[ ! -S "$SOCKET_PATH" ]`, removing the silent fallback to legacy Bash.
|
||||
- [x] **Task 2.2**: Update `_op_workload_list` in `scripts/appctl_router.py` to query live container health (`get_docker_status()`).
|
||||
- [x] **Task 2.3**: Update `_format_workload_table` in `scripts/appctl_cli.py` to render the `STATUS` column (`🟢 Running (1)` / `🔴 Stopped`).
|
||||
- [x] **Task 2.4**: Bootstrap operator admin token documentation and setup instructions in `docs/appctl.md` and `docs/secrets-and-state.md`.
|
||||
- [x] **Task 2.5**: Wire `--build` and `--no-cache` in `scripts/appctl_cli.py`, pass `--pull` during `compose_build` in `scripts/appctl_router.py`, and document source-built action policy in `docs/appctl.md`.
|
||||
|
||||
### Phase 3: Architectural Records & Roadmap Synchronization
|
||||
- [x] **Task 3.1**: Update `ROADMAP.md` (P6 redefined as Homelab MCP Gateway; on-server AI compiler deprecated).
|
||||
- [x] **Task 3.2**: Add architectural amendment note to `docs/decisions/0002-appctl-control-plane-architecture.md`.
|
||||
- [x] **Task 3.3**: Update `docs/decisions/README.md`.
|
||||
- [x] **Task 3.4**: Update `docs/appctl.md` (clarifying bounded log snapshots and Core update workflow).
|
||||
- [x] **Task 3.5**: Synchronize `todo.txt` with active implementation tasks.
|
||||
|
||||
### Phase 4: Work Package 6 (WP6: Instance Decoupling & Operator Cutover Runbook)
|
||||
- [x] **Task 4.1**: Update `nixos/configuration.nix` with optional dual-path imports for `./instance.nix` and `/etc/nixos/homelab-instance.nix` (Decision D1).
|
||||
- [x] **Task 4.2**: Add `nixos/instance.nix` to `.gitignore` to preserve 100% repository genericism.
|
||||
- [x] **Task 4.3**: Implement automated invariant tests in `tests/security/test_security_invariants.py` (default domain evaluation, dynamic LDAP base DN, instance override, platform genericism).
|
||||
- [x] **Task 4.4**: Document instance domain injection procedure in `docs/setup_guide.md`.
|
||||
- [x] **Task 4.5**: Codify the 4-stage Staged Coexistence Cutover Runbook (Decision D2) in `docs/operations.md` with explicit notice blocking live host execution pending maintenance window.
|
||||
|
||||
---
|
||||
|
||||
## 4. Verification & Quality Gates
|
||||
|
||||
The implementation must pass:
|
||||
1. **Static Analysis & Linting**: `ruff check .` and `pyright` (0 errors, 0 warnings).
|
||||
2. **Full Regression Suite**: All 283 existing unit, security, and invariant tests passing.
|
||||
3. **New Test Coverage**:
|
||||
- Assert dynamic LDAP base DN computation from domain.
|
||||
- Assert `scripts/appctl` fails closed when socket is absent.
|
||||
- Assert `appctl list` output formatting includes container status.
|
||||
- Assert platform genericism invariants across updated Nix modules.
|
||||
4. **Hermetic Flake Check**: `nix flake check` builds cleanly.
|
||||
5. **NixOS Evaluation**: `nix eval .#nixosConfigurations.server.config.system.build.toplevel.drvPath` evaluates without warnings.
|
||||
@@ -0,0 +1,137 @@
|
||||
# 🔒 Homelab Core — Secrets Management & Persistent State
|
||||
|
||||
This document explains the secrets distribution architecture, runtime projection mechanisms, user directory model, and persistent state boundaries for **Homelab Core**.
|
||||
|
||||
---
|
||||
|
||||
## 1. Secrets Management Policy
|
||||
|
||||
* **No Plaintext Secrets in Git**: All sensitive credentials, API keys, tokens, and private keys are encrypted at rest using **Mozilla SOPS** with **Age keys** derived from the server's SSH host key.
|
||||
* **In-Memory Projections**: Secret files are decrypted at boot by **`sops-nix`** into an ephemeral in-memory filesystem (`/run/secrets/` and `/run/credentials/`) and are not committed to unencrypted persistent storage.
|
||||
|
||||
---
|
||||
|
||||
## 2. Secrets Lifecycle & Projection Architecture
|
||||
|
||||
```text
|
||||
[nixos/secrets.yaml] (Encrypted with Age / SOPS)
|
||||
│
|
||||
▼ (Decrypted at boot by sops-nix using /etc/ssh/ssh_host_ed25519_key)
|
||||
┌──────┴─────────────────────────────────────────────────────────────────┐
|
||||
│ In-Memory Projections (/run/secrets/ & /run/credentials/) │
|
||||
├────────────────────────────────────────────────────────────────────────┤
|
||||
│ 1. /run/secrets/homeserver.env │
|
||||
│ -> Consumed by homeserver-core.service & Core docker-compose.yml │
|
||||
│ │
|
||||
│ 2. /run/secrets/traefik-deployments.env │
|
||||
│ -> Consumed by appctl to inject secrets into Sites workloads │
|
||||
│ │
|
||||
│ 3. /run/secrets/gitops/webhook_secret │
|
||||
│ -> Consumed by homelab-gitops.service for HMAC verification │
|
||||
│ │
|
||||
│ 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 │
|
||||
│ │
|
||||
│ 7. /run/secrets/pdf_decrypt_password │
|
||||
│ -> Consumed by shell pdf_dc utility │
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Projected Secret Templates & Token Store
|
||||
|
||||
### A. Core Platform Environment (`/run/secrets/homeserver.env`)
|
||||
Generated by `nixos/modules/homeserver.nix`. Supplies credentials to the Core Compose stack:
|
||||
* `DOMAIN`: Apex domain (e.g., `example.com`).
|
||||
* `DYNU_API_KEY`: API key for Dynu DNS-01 ACME Let's Encrypt validation.
|
||||
* `ACME_EMAIL`: Account email for Let's Encrypt certificates.
|
||||
* `AUTHELIA_SESSION_SECRET`: Authelia cookie encryption secret.
|
||||
* `AUTHELIA_STORAGE_ENCRYPTION_KEY`: Database encryption key for Authelia SQLite storage.
|
||||
* `AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET`: Reset password token secret.
|
||||
* `LLDAP_JWT_SECRET` & `LLDAP_KEY_SEED`: Cryptographic tokens for LLDAP.
|
||||
* `LLDAP_LDAP_USER_PASS`: Admin password for LLDAP and Authelia LDAP binding.
|
||||
* `SMTP_SERVER`, `SMTP_PORT`, `SMTP_LOGIN`, `SMTP_KEY`: Outbound relay credentials (Brevo) for Stalwart mail transport.
|
||||
|
||||
### B. Workload Deployments Environment (`/run/secrets/traefik-deployments.env`)
|
||||
Generated by `nixos/modules/traefik-deployments.nix`. Projects shared infrastructure secrets and workload credentials that `appctl` 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.
|
||||
|
||||
---
|
||||
|
||||
## 4. Secret Modification and Rotation Workflow
|
||||
|
||||
To edit or rotate secrets:
|
||||
|
||||
### 1. Open the Encrypted Secrets File
|
||||
```bash
|
||||
cd ~/Core
|
||||
sops nixos/secrets.yaml
|
||||
```
|
||||
SOPS decrypts the file using your host SSH private key and opens it in your editor.
|
||||
|
||||
### 2. Modify Secret Keys
|
||||
```yaml
|
||||
dynu:
|
||||
api_key: "..."
|
||||
authelia:
|
||||
session_secret: "..."
|
||||
jwt_secret: "..."
|
||||
lldap:
|
||||
admin_password: "..."
|
||||
gitops:
|
||||
webhook_secret: "..."
|
||||
appctl_token: "..."
|
||||
appctl:
|
||||
tokens_json: "[...]"
|
||||
brevo:
|
||||
smtp_login: "..."
|
||||
smtp_key: "..."
|
||||
```
|
||||
|
||||
### 3. Save and Apply Changes
|
||||
Saving the file in your editor automatically re-encrypts it with Age. Apply the updated templates to running services:
|
||||
```bash
|
||||
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. User Directory vs. Static Secrets
|
||||
|
||||
Homelab Core separates **user identity** from **static platform secrets**:
|
||||
|
||||
* **Static Secrets**: Stored in `nixos/secrets.yaml` (system API keys, JWT secrets, database passwords, control-plane token hashes).
|
||||
* **Dynamic User Directory**: User accounts, credentials, and group memberships are managed live in **LLDAP** (`https://users.${HOMELAB_DOMAIN}`). User account updates do not require editing `secrets.yaml` or rebuilding NixOS.
|
||||
* **Authelia Integration**: Authelia queries LLDAP over LDAP (`ldap://lldap:3890`) at runtime using credentials projected from `/run/secrets/homeserver.env`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Persistent State Map
|
||||
|
||||
| Category | Storage Location | Stored in Git? | Description |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Declarative Config** | `~/Core/nixos/*.nix`, `docker-compose.yml` | ✅ Yes | System and container definitions |
|
||||
| **Encrypted Secrets** | `~/Core/nixos/secrets.yaml` | ✅ Yes (Encrypted) | SOPS Age-encrypted secret source |
|
||||
| **Runtime Secrets** | `/run/secrets/*` | ❌ No (RAM tmpfs) | Ephemeral decrypted environment & token files |
|
||||
| **Control Plane Audit** | `/var/log/homelab/appctl/audit.jsonl` | ❌ No | Append-only JSONL security & mutation log (`0600`) |
|
||||
| **Control Plane Locks** | `/var/lib/homelab/appctl/locks/` | ❌ No | Per-target `flock` files & `_homepage_sync.lock` |
|
||||
| **SSL Certificates** | `~/Core/config/letsencrypt/acme.json` | ❌ No | Active Let's Encrypt certificates (mode 0600) |
|
||||
| **User Directory** | `~/Core/config/lldap/data/` | ❌ No | LLDAP SQLite database (`users.db`) |
|
||||
| **Auth Database** | `~/Core/config/authelia/db.sqlite3` | ❌ No | Authelia session database |
|
||||
| **Mail Data & Keys** | `~/Core/config/stalwart/` | ❌ No | Stalwart mail storage, DKIM keys, mailboxes |
|
||||
| **Workload State Root** | `~/var/lib/homelab/<app>/` | ❌ No | Per-workload persistent runtime state (e.g., `snappymail`) |
|
||||
| **Container Volumes** | Docker volume `dozzle_data` | ❌ No | Dozzle UI preferences and state |
|
||||
| **DDNS History** | `/var/lib/dynu/ip_history.jsonl` | ❌ No | Historical WAN IP transitions log |
|
||||
| **GitOps State** | `~/.local/state/homelab/gitops/` | ❌ No | Deployment locks, pending JSONs, status logs |
|
||||
+221
-85
@@ -1,107 +1,243 @@
|
||||
# Setup & Secrets Management Guide (Traefik Homelab)
|
||||
# 🚀 Homelab Core — Setup & Provisioning Guide
|
||||
|
||||
This document provides an exhaustive operational guide for configuring, deploying, securing, and maintaining the **Traefik Homelab Core Control Plane** on NixOS.
|
||||
This document describes procedures for provisioning a host machine, bootstrapping **Homelab Core**, and onboarding new application workloads into `~/Sites`.
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ Architectural Overview
|
||||
## 1. Host Provisioning & Bootstrapping
|
||||
|
||||
The core infrastructure runs as a consolidated Docker Compose stack in [`/home/kiskaadee/Core`](file:///home/kiskaadee/Core):
|
||||
### A. Fresh Machine Provisioning via NixOS Install
|
||||
When provisioning bare-metal hardware or a virtual machine from a NixOS Minimal ISO:
|
||||
|
||||
* **[`docker-compose.yml`](file:///home/kiskaadee/Core/docker-compose.yml)**: Root compose specification defining all control plane services (`traefik`, `authelia`, `portainer`, `dozzle`, `watchtower`, `diun`, `socket-proxy`).
|
||||
* **[`config/`](file:///home/kiskaadee/Core/config/)**: Persistent state directories:
|
||||
* `config/letsencrypt/`: Contains SSL certificate storage (`acme.json`).
|
||||
* `config/authelia/`: Contains configuration (`configuration.yml`, `users.yml`) and authentication database (`db.sqlite3`).
|
||||
* `config/diun/`: Diun container update tracking database (`diun.db`).
|
||||
|
||||
---
|
||||
|
||||
## 🔒 Secrets Architecture & SOPS Flow
|
||||
|
||||
All sensitive tokens, encryption keys, and credentials are encrypted using **`sops-nix`** (Mozilla SOPS with age keys derived from the host SSH key). No plaintext secrets exist in any git repository.
|
||||
|
||||
### Secrets Lifecycle:
|
||||
|
||||
```
|
||||
[~/Config/hosts/desktop/secrets.yaml] (Encrypted with Age)
|
||||
│
|
||||
▼ (Decrypted at boot by sops-nix daemon)
|
||||
1. [/run/secrets/rendered/homeserver.env] --> Fed to Core Compose Stack
|
||||
2. [/run/secrets/rendered/traefik-deployments.env] --> Fed to appctl & App Stacks
|
||||
│
|
||||
▼
|
||||
[Active Docker Containers]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔑 Modifying and Adding Secrets
|
||||
|
||||
To update credentials (e.g. changing your Dynu API key or updating Authelia user passwords):
|
||||
|
||||
1. Navigate to your NixOS configuration repository:
|
||||
1. Partition and format disks according to `nixos/hardware-configuration.nix` (e.g. boot EFI partition and root filesystem).
|
||||
2. Mount partitions under `/mnt`.
|
||||
3. **Restore Host Secrets Key**: Copy the host SSH private key to `/mnt/etc/ssh/ssh_host_ed25519_key` (mode `0600`). This is required because `sops-nix` decrypts `nixos/secrets.yaml` during system activation.
|
||||
4. Clone the Core repository to `/mnt/home/<operator>/Core`.
|
||||
5. Run the NixOS installer:
|
||||
```bash
|
||||
cd ~/Config
|
||||
nixos-install --flake /mnt/home/<operator>/Core#server
|
||||
reboot
|
||||
```
|
||||
2. Decrypt and open the secrets file in your editor:
|
||||
```bash
|
||||
nix-shell -p sops --run "sops hosts/desktop/secrets.yaml"
|
||||
```
|
||||
3. Update or append keys under the root block:
|
||||
```yaml
|
||||
dynu_api_key: "your_dynu_api_key"
|
||||
acme_email: "your_email@domain.com"
|
||||
authelia_session_secret: "secure_64_char_secret"
|
||||
authelia_storage_encryption_key: "secure_64_char_key"
|
||||
authelia_identity_validation_reset_password_jwt_secret: "secure_64_char_jwt_secret"
|
||||
authelia_user_kiskaadee_password_hash: "$argon2id$v=19$m=65536..."
|
||||
```
|
||||
*To generate an Argon2 password hash securely, run:*
|
||||
```bash
|
||||
docker run --rm -it authelia/authelia:latest authelia crypto hash generate argon2
|
||||
```
|
||||
4. Save and close. SOPS will automatically encrypt the modified file before saving.
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Declarative NixOS Modules
|
||||
## 2. Platform Bootstrap on a Running Host
|
||||
|
||||
The Core stack and deployment environments are defined declaratively in `~/Config`:
|
||||
When initializing the platform on an installed system:
|
||||
|
||||
### 1. Control Plane Module ([`hosts/desktop/homeserver.nix`](file:///home/kiskaadee/Config/hosts/desktop/homeserver.nix))
|
||||
Generates `/run/secrets/rendered/homeserver.env` and manages the `homeserver-core.service` systemd daemon:
|
||||
### Step 1: Verify Host Secrets Key
|
||||
Ensure the host SSH key exists with strict permissions:
|
||||
```bash
|
||||
sudo ls -l /etc/ssh/ssh_host_ed25519_key
|
||||
sudo chmod 600 /etc/ssh/ssh_host_ed25519_key
|
||||
```
|
||||
|
||||
### 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
|
||||
sops.templates."homeserver.env" = {
|
||||
owner = "kiskaadee";
|
||||
content = lib.generators.toKeyValue {} {
|
||||
DOMAIN = "roadtotech.me";
|
||||
DOCKER_API_VERSION = "1.40";
|
||||
DYNU_API_KEY = config.sops.placeholder.dynu_api_key;
|
||||
ACME_EMAIL = config.sops.placeholder.acme_email;
|
||||
AUTHELIA_SESSION_SECRET = config.sops.placeholder.authelia_session_secret;
|
||||
AUTHELIA_STORAGE_ENCRYPTION_KEY = config.sops.placeholder.authelia_storage_encryption_key;
|
||||
AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET = config.sops.placeholder.authelia_identity_validation_reset_password_jwt_secret;
|
||||
};
|
||||
};
|
||||
{
|
||||
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.
|
||||
|
||||
### 2. Applications Secret Module ([`hosts/desktop/traefik-deployments.nix`](file:///home/kiskaadee/Config/hosts/desktop/traefik-deployments.nix))
|
||||
Generates `/run/secrets/rendered/traefik-deployments.env` consumed by `appctl`.
|
||||
> [!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.
|
||||
|
||||
## 🚀 Running and Managing the Stack
|
||||
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.
|
||||
|
||||
### Standard Systemd Operations:
|
||||
* **Start:** `sudo systemctl start homeserver-core`
|
||||
* **Stop:** `sudo systemctl stop homeserver-core`
|
||||
* **Restart:** `sudo systemctl restart homeserver-core`
|
||||
* **Status:** `systemctl status homeserver-core`
|
||||
* **Live Logs:** `journalctl -u homeserver-core -f`
|
||||
|
||||
### Dynamic Tweaks without Rebuilding NixOS:
|
||||
When making configuration adjustments to `docker-compose.yml` (e.g. tuning Traefik middlewares):
|
||||
### Step 3: Apply Declarative NixOS Configuration
|
||||
```bash
|
||||
cd ~/Core
|
||||
docker compose --env-file /run/secrets/rendered/homeserver.env up -d --remove-orphans
|
||||
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
|
||||
```
|
||||
This configures:
|
||||
* Docker daemon, host firewall rules, and system packages.
|
||||
* Decrypted secret files in `/run/secrets/homeserver.env` and `/run/secrets/traefik-deployments.env`.
|
||||
* Systemd service units (`homeserver-core`, `homelab-appctl`, `homelab-gitops`, `dynu-monitor`).
|
||||
|
||||
### Step 4: Create External Docker Networks
|
||||
The Core Compose stack and workloads require the `proxy-net` and `socket-net` bridge networks:
|
||||
```bash
|
||||
docker network create proxy-net 2>/dev/null || true
|
||||
docker network create socket-net 2>/dev/null || true
|
||||
```
|
||||
|
||||
### Step 5: Start Platform Services
|
||||
```bash
|
||||
sudo systemctl start homeserver-core
|
||||
```
|
||||
Check running containers:
|
||||
```bash
|
||||
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
|
||||
```
|
||||
|
||||
### Step 6: Verify DNS & Certificates
|
||||
1. Trigger an immediate DDNS update:
|
||||
```bash
|
||||
sudo systemctl start dynu-monitor
|
||||
```
|
||||
2. Verify Let's Encrypt wildcard certificate generation:
|
||||
```bash
|
||||
appctl ssl traefik
|
||||
```
|
||||
|
||||
### Step 7: Initialize LLDAP Directory
|
||||
1. Navigate to `https://users.${HOMELAB_DOMAIN}` (e.g., `https://users.example.com`).
|
||||
2. Authenticate using `admin` and the password configured in `nixos/secrets.yaml` (`lldap/admin_password`).
|
||||
3. Create standard user accounts and assign them to required groups.
|
||||
|
||||
### Step 8: Provision Read-Only Agent SSH Access (`agents`)
|
||||
The `agents` user provides a restricted, read-only SSH identity for automated or agentic diagnostics without granting `sudo`, `docker` group membership, or write access to host state.
|
||||
|
||||
1. **Generate a dedicated Ed25519 SSH keypair** on your workstation:
|
||||
```bash
|
||||
ssh-keygen -t ed25519 -f ~/.ssh/canopy_agents -C "canopy-agents"
|
||||
```
|
||||
2. **Wire the public key into NixOS**:
|
||||
Add the contents of `~/.ssh/canopy_agents.pub` to `users.users.agents.openssh.authorizedKeys.keys` in `nixos/configuration.nix` and apply the configuration on the server:
|
||||
```bash
|
||||
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
|
||||
```
|
||||
`nixos/configuration.nix` assigns `agents` only to `homelab-operators` (for read-only `appctl` socket queries) and `systemd-journal` (for `journalctl`), and enforces `Match User agents` with `ForceCommand` (`nixos/scripts/agents-force-command.sh`), `PermitTTY no`, `PasswordAuthentication no`, and forwarding disabled.
|
||||
3. **Configure workstation `~/.ssh/config`** (replace `<server-host>` with your host or `server.example.test`):
|
||||
```sshconfig
|
||||
Host server-agents
|
||||
HostName <server-host>
|
||||
User agents
|
||||
IdentityFile ~/.ssh/canopy_agents
|
||||
IdentitiesOnly yes
|
||||
```
|
||||
4. **Verify read-only inspection** from the workstation:
|
||||
```bash
|
||||
ssh server-agents "docker ps"
|
||||
ssh server-agents "appctl list --core"
|
||||
ssh server-agents "journalctl -u homelab-appctl -n 5"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Onboarding a New Application Workload
|
||||
|
||||
Applications live in isolated repositories under `~/Sites/`. To deploy a new service:
|
||||
|
||||
### Step 1: Create Repository Directory
|
||||
```bash
|
||||
mkdir -p ~/Sites/homelab-myapp
|
||||
cd ~/Sites/homelab-myapp
|
||||
git init
|
||||
```
|
||||
|
||||
### Step 2: Create `app.yaml` Manifest
|
||||
Create `~/Sites/homelab-myapp/app.yaml`:
|
||||
```yaml
|
||||
schema_version: "1.0"
|
||||
name: "myapp"
|
||||
aliases:
|
||||
- "app"
|
||||
domain: "myapp.example.com"
|
||||
description: "My New Application Service"
|
||||
visible: true
|
||||
auth: false
|
||||
networks:
|
||||
- proxy-net
|
||||
|
||||
env:
|
||||
APP_PORT: "8080"
|
||||
|
||||
deployment:
|
||||
branch: "main"
|
||||
strategy: "compose"
|
||||
actions:
|
||||
- git_pull
|
||||
- compose_up
|
||||
|
||||
homepage:
|
||||
title: "My App"
|
||||
group: "Applications"
|
||||
icon: "default.png"
|
||||
container: "myapp"
|
||||
weight: 50
|
||||
```
|
||||
|
||||
### Step 3: Create `docker-compose.yml`
|
||||
Create `~/Sites/homelab-myapp/docker-compose.yml`:
|
||||
```yaml
|
||||
services:
|
||||
myapp:
|
||||
image: myapp/image:latest
|
||||
container_name: ${CONTAINER_NAME:-myapp}
|
||||
restart: always
|
||||
environment:
|
||||
- PORT=${APP_PORT:-8080}
|
||||
networks:
|
||||
- proxy-net
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
# HTTPS Router
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.rule=Host(`${SERVICE_DOMAIN}`)"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.entrypoints=websecure"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.tls=true"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.service=${CONTAINER_NAME:-myapp}-svc"
|
||||
# HTTP -> HTTPS Redirect
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}-red.rule=Host(`${SERVICE_DOMAIN}`)"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}-red.entrypoints=web"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}-red.middlewares=https-redirect@docker"
|
||||
# Target Port
|
||||
- "traefik.http.services.${CONTAINER_NAME:-myapp}-svc.loadbalancer.server.port=${APP_PORT:-8080}"
|
||||
|
||||
networks:
|
||||
proxy-net:
|
||||
name: ${PROXY_NETWORK:-proxy-net}
|
||||
external: true
|
||||
```
|
||||
|
||||
### Step 4: Launch and Sync
|
||||
```bash
|
||||
# Launch application stack via appctl
|
||||
appctl up myapp
|
||||
|
||||
# Inspect application diagnostics
|
||||
appctl info myapp
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Verification
|
||||
|
||||
Before committing changes to Homelab Core, run the repository test runner:
|
||||
|
||||
```bash
|
||||
cd ~/Core
|
||||
./scripts/run-tests
|
||||
```
|
||||
This runs:
|
||||
* Code formatting and lint checks (`ruff`).
|
||||
* Security and structural invariant tests (`pytest tests/`).
|
||||
* Nix flake check (`nix flake check`).
|
||||
Generated
+45
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"nodes": {
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1795234589,
|
||||
"narHash": "sha256-pAEASBc6wof0S58XcSEdZoQ2iFQDkCnZwH+wFLrkd1Q=",
|
||||
"rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f",
|
||||
"type": "tarball",
|
||||
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1125864.2786a2a72088/nixexprs.tar.zst"
|
||||
},
|
||||
"original": {
|
||||
"type": "tarball",
|
||||
"url": "https://channels.nixos.org/nixos-unstable/nixexprs.tar.zst"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"nixpkgs": "nixpkgs",
|
||||
"sops-nix": "sops-nix"
|
||||
}
|
||||
},
|
||||
"sops-nix": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1794866654,
|
||||
"narHash": "sha256-Y28AMB8lyKjASdJ0BVsR2AqR1cUsVuo8RVVpzHoECho=",
|
||||
"owner": "Mic92",
|
||||
"repo": "sops-nix",
|
||||
"rev": "7c637afdccdf9bcf35c4a2d67b58a77c1fd843a4",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "Mic92",
|
||||
"repo": "sops-nix",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
description = "Homelab Core — Turnkey Declarative NixOS Appliance";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "https://channels.nixos.org/nixos-unstable/nixexprs.tar.zst";
|
||||
|
||||
sops-nix = {
|
||||
url = "github:Mic92/sops-nix";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs, sops-nix, ... }@inputs:
|
||||
let
|
||||
system = "x86_64-linux";
|
||||
pkgs = nixpkgs.legacyPackages.${system};
|
||||
pythonEnv = pkgs.python3.withPackages (ps: with ps; [
|
||||
pyyaml
|
||||
types-pyyaml
|
||||
pytest
|
||||
pydantic
|
||||
]);
|
||||
in
|
||||
{
|
||||
nixosConfigurations.server = nixpkgs.lib.nixosSystem {
|
||||
inherit system;
|
||||
specialArgs = { inherit inputs; };
|
||||
modules = [
|
||||
./nixos/configuration.nix
|
||||
sops-nix.nixosModules.sops
|
||||
];
|
||||
};
|
||||
|
||||
devShells.${system}.default = pkgs.mkShell {
|
||||
buildInputs = with pkgs; [
|
||||
pythonEnv
|
||||
pyright
|
||||
ruff
|
||||
];
|
||||
shellHook = ''
|
||||
git config core.hooksPath .githooks 2>/dev/null || true
|
||||
if [ -d .venv ] && [ ! -L .venv ]; then
|
||||
rm -rf .venv
|
||||
fi
|
||||
ln -sfn ${pythonEnv} .venv
|
||||
'';
|
||||
};
|
||||
|
||||
checks.${system} = {
|
||||
test-suite = pkgs.runCommand "core-tests" {
|
||||
nativeBuildInputs = with pkgs; [
|
||||
git
|
||||
pythonEnv
|
||||
ruff
|
||||
pyright
|
||||
];
|
||||
} ''
|
||||
mkdir -p $out
|
||||
cp -r ${self} source
|
||||
chmod -R u+w source
|
||||
cd source
|
||||
HOME=/tmp ruff check --no-cache .
|
||||
HOME=/tmp pyright
|
||||
HOME=/tmp pytest -o cache_dir=/tmp/.pytest_cache tests/
|
||||
'';
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
# 🌐 Server NixOS Configuration — Turnkey Headless Homelab Appliance
|
||||
# Standalone declarative configuration for the homelab server.
|
||||
# No Home Manager. No shared desktop modules.
|
||||
# Goal: wipe & restore from any NixOS installation via `nixos-install --flake ~/Core#server`
|
||||
|
||||
{ config, lib, pkgs, inputs, ... }:
|
||||
|
||||
{
|
||||
imports = [
|
||||
./hardware-configuration.nix # Server-specific disk and CPU configuration
|
||||
./modules/homeserver.nix # Core services: systemd units, Authelia, SOPS secrets
|
||||
./modules/traefik-deployments.nix # Traefik deployment secrets and env templates
|
||||
./modules/dynu.nix # Dynu DDNS smart IP monitor service
|
||||
./modules/shell.nix # Declarative bash environment for the server
|
||||
] ++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix
|
||||
++ lib.optional (!(builtins.pathExists /etc/nixos/homelab-instance.nix) && builtins.pathExists ./instance.nix) ./instance.nix;
|
||||
|
||||
# ── Homelab platform settings ────────────────────────────────────────────────
|
||||
homelab.operatorUser = "operator";
|
||||
|
||||
# ── Host Git Safe Directory ──────────────────────────────────────────────────
|
||||
programs.git = {
|
||||
enable = true;
|
||||
config.safe.directory = [
|
||||
"/home/${config.homelab.operatorUser}/Core"
|
||||
"/home/${config.homelab.operatorUser}/Workloads"
|
||||
"/home/${config.homelab.operatorUser}/Workloads/*"
|
||||
"/home/${config.homelab.operatorUser}/Sites/*"
|
||||
];
|
||||
};
|
||||
|
||||
# ── SOPS secrets configuration ──────────────────────────────────────────────
|
||||
# Set once here to avoid duplicate-option conflicts across submodules
|
||||
sops.defaultSopsFile = ./secrets.yaml;
|
||||
sops.defaultSopsFormat = "yaml";
|
||||
|
||||
# ── Nix settings & maintenance ───────────────────────────────────────────────
|
||||
nix.settings.experimental-features = [ "nix-command" "flakes" ];
|
||||
|
||||
# Pin nixpkgs registry to the flake input (avoids GitHub API calls from the CLI)
|
||||
nix.registry.nixpkgs.flake = inputs.nixpkgs;
|
||||
|
||||
# Automated garbage collection and store hardlink deduplication
|
||||
nix.gc = {
|
||||
automatic = true;
|
||||
dates = "weekly";
|
||||
options = "--delete-older-than 14d";
|
||||
};
|
||||
nix.optimise.automatic = true;
|
||||
|
||||
nixpkgs.config.allowUnfree = true;
|
||||
|
||||
# ── Regional & locale settings ───────────────────────────────────────────────
|
||||
time.timeZone = "America/Bogota";
|
||||
i18n.defaultLocale = "en_US.UTF-8";
|
||||
|
||||
# ── Console ──────────────────────────────────────────────────────────────────
|
||||
console = {
|
||||
font = "Lat2-Terminus16";
|
||||
keyMap = "us";
|
||||
};
|
||||
|
||||
# ── Bootloader ───────────────────────────────────────────────────────────────
|
||||
boot.loader.systemd-boot.enable = true;
|
||||
boot.loader.efi.canTouchEfiVariables = true;
|
||||
|
||||
# ── Network ──────────────────────────────────────────────────────────────────
|
||||
networking.hostName = "server";
|
||||
networking.networkmanager.enable = true;
|
||||
|
||||
# ── User accounts ────────────────────────────────────────────────────────────
|
||||
users.users.${config.homelab.operatorUser} = {
|
||||
isNormalUser = true;
|
||||
description = "Primary server administrator";
|
||||
openssh.authorizedKeys.keys = [
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICAVPPMk+WApUd/fo78+lsRGnLKSlY4GDZiNGKwBAifD"
|
||||
];
|
||||
extraGroups = [
|
||||
"wheel" # sudo access
|
||||
"docker" # run docker without sudo
|
||||
"homelab-operators" # access /run/homelab/appctl.sock
|
||||
"networkmanager" # modify network settings
|
||||
];
|
||||
};
|
||||
|
||||
users.users.agents = {
|
||||
isNormalUser = true;
|
||||
description = "Read-only agent inspection user";
|
||||
openssh.authorizedKeys.keys = [
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIE1pxTdygG5696q0jT7clfJZWtx48ugfUjpzvkHzovVd canopy-agents"
|
||||
];
|
||||
extraGroups = [
|
||||
"homelab-operators" # read-only access via /run/homelab/appctl.sock
|
||||
"systemd-journal" # read-only access to journalctl
|
||||
];
|
||||
};
|
||||
|
||||
# ── SSH ──────────────────────────────────────────────────────────────────────
|
||||
services.openssh = let
|
||||
agentsForceCommand = pkgs.writeShellScriptBin "agents-force-command" ''
|
||||
export CORE_DIR="''${CORE_DIR:-/home/${config.homelab.operatorUser}/Core}"
|
||||
export WORKLOADS_DIR="''${WORKLOADS_DIR:-/home/${config.homelab.operatorUser}/Workloads}"
|
||||
export DOCKER_HOST="''${DOCKER_HOST:-tcp://127.0.0.1:2375}"
|
||||
exec ${pkgs.bash}/bin/bash ${./scripts/agents-force-command.sh} "$@"
|
||||
'';
|
||||
in {
|
||||
enable = true;
|
||||
ports = [ 22 ];
|
||||
settings.PermitRootLogin = "no";
|
||||
extraConfig = ''
|
||||
Match User agents
|
||||
ForceCommand ${agentsForceCommand}/bin/agents-force-command
|
||||
AllowTcpForwarding no
|
||||
X11Forwarding no
|
||||
AllowAgentForwarding no
|
||||
PermitTTY no
|
||||
PasswordAuthentication no
|
||||
'';
|
||||
};
|
||||
|
||||
# ── Virtualisation ───────────────────────────────────────────────────────────
|
||||
virtualisation.docker = {
|
||||
enable = true;
|
||||
daemon.settings = {
|
||||
dns = [ "1.1.1.1" "1.0.0.1" ];
|
||||
};
|
||||
};
|
||||
|
||||
# ── Dynamic binary support ───────────────────────────────────────────────────
|
||||
programs.nix-ld = {
|
||||
enable = true;
|
||||
libraries = with pkgs; [
|
||||
stdenv.cc.cc.lib
|
||||
zlib
|
||||
glib
|
||||
];
|
||||
};
|
||||
|
||||
# ── Headless optimizations ───────────────────────────────────────────────────
|
||||
# Disable peripheral hardware & desktop services not needed on a headless server
|
||||
services.pipewire.enable = false;
|
||||
services.printing.enable = false;
|
||||
hardware.bluetooth.enable = false;
|
||||
|
||||
# Disable power-saving sleep/suspend to keep the homelab always active
|
||||
systemd.targets.sleep.enable = false;
|
||||
systemd.targets.suspend.enable = false;
|
||||
systemd.targets.hibernate.enable = false;
|
||||
systemd.targets.hybrid-sleep.enable = false;
|
||||
|
||||
# Kernel-level power management tuning
|
||||
powerManagement.powertop.enable = true;
|
||||
|
||||
# ── CLI tools ────────────────────────────────────────────────────────────────
|
||||
# Minimal server-appropriate tooling (no desktop apps or user dotfiles)
|
||||
programs.tmux.enable = true;
|
||||
programs.neovim = {
|
||||
enable = true;
|
||||
defaultEditor = true;
|
||||
};
|
||||
|
||||
environment.systemPackages = with pkgs; [
|
||||
# Core orchestrator wrapper (available system-wide including non-interactive SSH)
|
||||
(writeShellScriptBin "appctl" ''
|
||||
exec "''${CORE_DIR:-$HOME/Core}/scripts/appctl" "$@"
|
||||
'')
|
||||
# Monitoring & diagnostics
|
||||
htop
|
||||
iotop
|
||||
iftop
|
||||
ncdu
|
||||
# Secrets tooling (required for sops-nix secret decryption and manual re-encryption)
|
||||
sops
|
||||
age
|
||||
# Python runtime (hard requirement for appctl, core_manifest, and gitops_dispatcher.py)
|
||||
(python3.withPackages (ps: with ps; [
|
||||
pyyaml
|
||||
pydantic
|
||||
]))
|
||||
# Modern shell utilities
|
||||
eza # ls replacement
|
||||
ripgrep # rg — fast grep
|
||||
fd # fast find
|
||||
tree # directory tree viewer
|
||||
# Network & transfer
|
||||
git
|
||||
curl
|
||||
wget
|
||||
rclone
|
||||
jq
|
||||
];
|
||||
|
||||
# ── State version ─────────────────────────────────────────────────────────────
|
||||
# Do not modify this value after the first install.
|
||||
system.stateVersion = "26.05";
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
# Do not modify this file! It was generated by ‘nixos-generate-config’
|
||||
# and may be overwritten by future invocations. Please make changes
|
||||
# to /etc/nixos/configuration.nix instead.
|
||||
{ config, lib, pkgs, modulesPath, ... }:
|
||||
|
||||
{
|
||||
imports =
|
||||
[ (modulesPath + "/installer/scan/not-detected.nix")
|
||||
];
|
||||
|
||||
boot.initrd.availableKernelModules = [ "nvme" "xhci_pci" "thunderbolt" "usbhid" ];
|
||||
boot.initrd.kernelModules = [ "dm-snapshot" ];
|
||||
boot.kernelModules = [ "kvm-amd" ];
|
||||
boot.extraModulePackages = [ ];
|
||||
|
||||
fileSystems."/" =
|
||||
{ device = "/dev/mapper/nixos_vg-root";
|
||||
fsType = "ext4";
|
||||
};
|
||||
|
||||
fileSystems."/boot" =
|
||||
{ device = "/dev/disk/by-uuid/66E6-7442";
|
||||
fsType = "vfat";
|
||||
options = [ "fmask=0022" "dmask=0022" ];
|
||||
};
|
||||
|
||||
fileSystems."/media" =
|
||||
{ device = "/dev/mapper/nixos_vg-media";
|
||||
fsType = "ext4";
|
||||
};
|
||||
|
||||
fileSystems."/home" =
|
||||
{ device = "/dev/mapper/nixos_vg-home";
|
||||
fsType = "ext4";
|
||||
};
|
||||
|
||||
swapDevices = [ ];
|
||||
|
||||
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
|
||||
hardware.cpu.amd.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
# Example host-local instance configuration for Canopy NixOS Core.
|
||||
# Copy to /etc/nixos/homelab-instance.nix (recommended, loaded with --impure)
|
||||
# or gitignored nixos/instance.nix, and customize for your host.
|
||||
{ ... }:
|
||||
|
||||
{
|
||||
homelab.domain = "example.com";
|
||||
homelab.operatorUser = "operator";
|
||||
|
||||
# Host-granted workload capabilities ("Compose Requests, Nix Grants" — ADR-0005).
|
||||
# Keyed by workload name matching ~/Workloads/<app>.
|
||||
homelab.workloadGrants = {
|
||||
# Example hardware-accelerated media workload:
|
||||
# media-server = {
|
||||
# devices = [ "/dev/dri/renderD128" ];
|
||||
# groups = [ "render" ];
|
||||
# readOnlyPaths = [ "/mnt/media" ];
|
||||
# };
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
# 🌐 Dynu DDNS IP Monitor & Updater Service
|
||||
# This NixOS module configures a smart, local-first IP change detector.
|
||||
# It queries public IP providers, maintains a history log of WAN IP rotations,
|
||||
# and triggers ddclient only when an actual change is detected to prevent API rate limits.
|
||||
|
||||
{ config, lib, pkgs, ... }:
|
||||
|
||||
let
|
||||
# Declaratively read the external Python script into the Nix store at evaluation time
|
||||
ipMonitorScript = pkgs.writers.writePython3Bin "dynu-ip-monitor" {
|
||||
flakeIgnore = [ "E501" ];
|
||||
} (builtins.readFile ../scripts/monitor.py);
|
||||
in
|
||||
{
|
||||
# Define the keys to decrypt
|
||||
sops.secrets."dynu/user" = { };
|
||||
sops.secrets."dynu/domain" = { };
|
||||
sops.secrets."dynu/password" = { };
|
||||
sops.secrets."system/pdf_decrypt_password" = {
|
||||
owner = config.homelab.operatorUser;
|
||||
};
|
||||
|
||||
# Assemble the ddclient config file securely at boot time in /run/secrets/
|
||||
# Defaults to owner root:root (which avoids dynamic user evaluation issues)
|
||||
sops.templates."ddclient.conf" = {
|
||||
content = builtins.replaceStrings
|
||||
[ "@dynu_user@" "@dynu_password@" "@dynu_domain@" ]
|
||||
[
|
||||
config.sops.placeholder."dynu/user"
|
||||
config.sops.placeholder."dynu/password"
|
||||
config.sops.placeholder."dynu/domain"
|
||||
]
|
||||
(builtins.readFile ../scripts/ddclient.conf);
|
||||
};
|
||||
|
||||
# Enable ddclient and feed it the decrypted configuration template via systemd credentials
|
||||
services.ddclient = {
|
||||
enable = true;
|
||||
configFile = "/run/credentials/ddclient.service/ddclient.conf";
|
||||
};
|
||||
|
||||
systemd.services.ddclient = {
|
||||
serviceConfig = {
|
||||
# Securely load the root-owned secret file into the dynamic ddclient service
|
||||
LoadCredential = [ "ddclient.conf:${config.sops.templates."ddclient.conf".path}" ];
|
||||
};
|
||||
};
|
||||
|
||||
# Disable ddclient's automatic timer.
|
||||
# This stops ddclient from polling every 10 minutes on its own.
|
||||
systemd.timers.ddclient.enable = false;
|
||||
|
||||
# Define the smart IP change detector service
|
||||
systemd.services.dynu-monitor = {
|
||||
description = "Dynu DDNS Smart IP Change Monitor";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
path = with pkgs; [
|
||||
systemd # Required for systemctl
|
||||
];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
User = "root";
|
||||
Group = "root";
|
||||
StateDirectory = "dynu";
|
||||
Environment = "HISTORY_FILE=/var/lib/dynu/ip_history.jsonl";
|
||||
ExecStart = "${ipMonitorScript}/bin/dynu-ip-monitor";
|
||||
TimeoutSec = 30;
|
||||
|
||||
# Hardening
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
ReadWritePaths = "/var/lib/dynu";
|
||||
};
|
||||
};
|
||||
|
||||
# Run the smart IP change monitor periodically (every 30 minutes)
|
||||
systemd.timers.dynu-monitor = {
|
||||
description = "Run Dynu IP monitor periodically";
|
||||
timerConfig = {
|
||||
OnBootSec = "5min";
|
||||
OnUnitActiveSec = "30min";
|
||||
AccuracySec = "1min";
|
||||
Persistent = true;
|
||||
};
|
||||
wantedBy = [ "timers.target" ];
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
# 🌐 Homeserver Core Environment Secrets & Systemd service configuration
|
||||
# This NixOS module manages secrets and the systemd lifecycle for the core homeserver stack.
|
||||
|
||||
{ config, lib, pkgs, ... }:
|
||||
|
||||
{
|
||||
# Declarative configuration options for Homelab Core
|
||||
options.homelab = {
|
||||
domain = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "example.test";
|
||||
description = "Canonical domain for homelab services";
|
||||
};
|
||||
operatorUser = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "operator";
|
||||
description = "Primary operator user identity";
|
||||
};
|
||||
coreDir = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "/home/${config.homelab.operatorUser}/Core";
|
||||
description = "Path to Homelab Core repository";
|
||||
};
|
||||
sitesDir = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "/home/${config.homelab.operatorUser}/Workloads";
|
||||
description = "Path to Workloads directory (legacy option name: sitesDir)";
|
||||
};
|
||||
workloadGrants = lib.mkOption {
|
||||
type = lib.types.attrsOf (lib.types.submodule {
|
||||
options = {
|
||||
devices = lib.mkOption {
|
||||
type = lib.types.listOf lib.types.str;
|
||||
default = [];
|
||||
description = "Host device paths permitted for this workload (prefer specific nodes such as /dev/dri/renderD128).";
|
||||
};
|
||||
groups = lib.mkOption {
|
||||
type = lib.types.listOf lib.types.str;
|
||||
default = [];
|
||||
description = "Host group names or numeric GIDs permitted in group_add and user: primary GID.";
|
||||
};
|
||||
readOnlyPaths = lib.mkOption {
|
||||
type = lib.types.listOf lib.types.str;
|
||||
default = [];
|
||||
description = "Host directories permitted for read-only (:ro) bind mounts.";
|
||||
};
|
||||
};
|
||||
});
|
||||
default = {};
|
||||
description = "Host-granted hardware devices, groups, and read-only storage paths keyed by workload name.";
|
||||
};
|
||||
};
|
||||
|
||||
config = let
|
||||
domainParts = lib.splitString "." config.homelab.domain;
|
||||
ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts);
|
||||
in {
|
||||
# ── Workload Capability Grant Invariants (ADR-0005) ─────────────────────────
|
||||
assertions = let
|
||||
grantsList = lib.mapAttrsToList (app: grant: { inherit app grant; }) config.homelab.workloadGrants;
|
||||
privilegedGroups = [ "0" "root" "wheel" "docker" ];
|
||||
hasInvalidPath = p:
|
||||
!(lib.hasPrefix "/" p)
|
||||
|| (lib.hasInfix "/../" p)
|
||||
|| (lib.hasSuffix "/.." p)
|
||||
|| (p == "..");
|
||||
in
|
||||
(map ({ app, grant }: {
|
||||
assertion = lib.all (g: !(lib.elem (lib.toLower (lib.strings.trim g)) privilegedGroups)) grant.groups;
|
||||
message = "homelab.workloadGrants.${app}.groups must not contain privileged groups (0, root, wheel, docker).";
|
||||
}) grantsList)
|
||||
++ (map ({ app, grant }: {
|
||||
assertion = lib.all (p: !(hasInvalidPath p)) grant.devices;
|
||||
message = "homelab.workloadGrants.${app}.devices must contain absolute paths without '..' traversal.";
|
||||
}) grantsList)
|
||||
++ (map ({ app, grant }: {
|
||||
assertion = lib.all (p: !(hasInvalidPath p)) grant.readOnlyPaths;
|
||||
message = "homelab.workloadGrants.${app}.readOnlyPaths must contain absolute paths without '..' traversal.";
|
||||
}) grantsList);
|
||||
|
||||
# ── Host Capability Grants Projection (/etc/homelab/grants.json) ─────────────
|
||||
environment.etc."homelab/grants.json" = {
|
||||
user = "root";
|
||||
group = "homelab-operators";
|
||||
mode = "0640";
|
||||
text = builtins.toJSON {
|
||||
schemaVersion = "1.0";
|
||||
workloads = config.homelab.workloadGrants;
|
||||
};
|
||||
};
|
||||
|
||||
# ── Host Activation Guard ────────────────────────────────────────────────────
|
||||
# Prevents activating on a live host if homelab.domain defaulted to example.test (e.g. forgot --impure)
|
||||
system.activationScripts.checkHomelabDomain = {
|
||||
text = ''
|
||||
if [ "${config.homelab.domain}" = "example.test" ]; then
|
||||
echo "❌ [homelab] FATAL: homelab.domain is defaulting to 'example.test'!" >&2
|
||||
echo "❌ [homelab] Did you run 'nixos-rebuild switch' without the '--impure' flag?" >&2
|
||||
echo "❌ [homelab] To activate properly: sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure" >&2
|
||||
exit 1
|
||||
fi
|
||||
'';
|
||||
};
|
||||
|
||||
# Re-apply home-dir traverse ACL after `users` activation (chmod 0700 resets POSIX ACL mask::---)
|
||||
system.activationScripts.homelabHomeAcl = lib.stringAfter [ "users" ] ''
|
||||
if [ -d "/home/${config.homelab.operatorUser}" ]; then
|
||||
${pkgs.acl}/bin/setfacl -m u:homelab-appctl:x,g:homelab-operators:x,m::rx "/home/${config.homelab.operatorUser}"
|
||||
fi
|
||||
'';
|
||||
# Define the keys to decrypt from secrets.yaml
|
||||
sops.secrets = (lib.genAttrs [
|
||||
"cloudflare/dns_api_token"
|
||||
"traefik/acme_email"
|
||||
"authelia/session_secret"
|
||||
"authelia/storage_encryption_key"
|
||||
"authelia/jwt_secret"
|
||||
"lldap/jwt_secret"
|
||||
"lldap/key_seed"
|
||||
"lldap/admin_password"
|
||||
"gitops/webhook_secret"
|
||||
"brevo/smtp_login"
|
||||
"brevo/smtp_key"
|
||||
"diun/smtp_password"
|
||||
] (name: { owner = config.homelab.operatorUser; })) // {
|
||||
"appctl/tokens_json" = {
|
||||
owner = "homelab-appctl";
|
||||
group = "homelab-operators";
|
||||
mode = "0400";
|
||||
path = "/run/secrets/appctl/tokens.json";
|
||||
};
|
||||
"gitops/appctl_token" = {
|
||||
owner = config.homelab.operatorUser;
|
||||
group = "homelab-operators";
|
||||
mode = "0400";
|
||||
};
|
||||
};
|
||||
|
||||
# Generate the unified environment file at runtime in /run/secrets/homeserver.env
|
||||
sops.templates."homeserver.env" = {
|
||||
owner = config.homelab.operatorUser;
|
||||
group = "homelab-operators";
|
||||
mode = "0440";
|
||||
content = lib.generators.toKeyValue {} {
|
||||
DOMAIN = config.homelab.domain;
|
||||
LLDAP_LDAP_BASE_DN = ldapBaseDn;
|
||||
DOCKER_API_VERSION = "1.40";
|
||||
CF_DNS_API_TOKEN = config.sops.placeholder."cloudflare/dns_api_token";
|
||||
ACME_EMAIL = config.sops.placeholder."traefik/acme_email";
|
||||
AUTHELIA_SESSION_SECRET = config.sops.placeholder."authelia/session_secret";
|
||||
AUTHELIA_STORAGE_ENCRYPTION_KEY = config.sops.placeholder."authelia/storage_encryption_key";
|
||||
AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET = config.sops.placeholder."authelia/jwt_secret";
|
||||
LLDAP_JWT_SECRET = config.sops.placeholder."lldap/jwt_secret";
|
||||
LLDAP_KEY_SEED = config.sops.placeholder."lldap/key_seed";
|
||||
LLDAP_LDAP_USER_PASS = config.sops.placeholder."lldap/admin_password";
|
||||
AUTHELIA_LDAP_PASSWORD = config.sops.placeholder."lldap/admin_password";
|
||||
SMTP_SERVER = "smtp-relay.brevo.com";
|
||||
SMTP_PORT = "587";
|
||||
SMTP_LOGIN = config.sops.placeholder."brevo/smtp_login";
|
||||
SMTP_KEY = config.sops.placeholder."brevo/smtp_key";
|
||||
DIUN_SMTP_PASSWORD = config.sops.placeholder."diun/smtp_password";
|
||||
};
|
||||
};
|
||||
|
||||
# Define the declarative systemd service to manage the homeserver container stack
|
||||
systemd.services.homeserver-core = {
|
||||
description = "Homeserver Core Stack (Traefik, Authelia, Homepage, etc.)";
|
||||
after = [ "network-online.target" "docker.service" ];
|
||||
wants = [ "network-online.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
WorkingDirectory = config.homelab.coreDir;
|
||||
ExecStart = "${pkgs.docker-compose}/bin/docker-compose --env-file ${config.sops.templates."homeserver.env".path} up -d --remove-orphans";
|
||||
ExecStop = "${pkgs.docker-compose}/bin/docker-compose down";
|
||||
};
|
||||
};
|
||||
|
||||
# Declarative Dynamic GitOps Webhook Service (Internal Port 9000)
|
||||
systemd.services.homelab-gitops = {
|
||||
description = "Dynamic Homelab GitOps Webhook Dispatcher";
|
||||
after = [ "network-online.target" "docker.service" "homelab-appctl.service" ];
|
||||
wants = [ "network-online.target" "homelab-appctl.service" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
|
||||
path = with pkgs; [
|
||||
git
|
||||
docker
|
||||
docker-compose
|
||||
(python3.withPackages (ps: with ps; [ pyyaml pydantic ]))
|
||||
coreutils
|
||||
bash
|
||||
openssh
|
||||
];
|
||||
|
||||
environment = {
|
||||
GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path;
|
||||
GITOPS_APPCTL_TOKEN_FILE = config.sops.secrets."gitops/appctl_token".path;
|
||||
DOCKER_CONFIG = "/home/${config.homelab.operatorUser}/.local/state/homelab/docker";
|
||||
HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab";
|
||||
WORKLOADS_DIR = config.homelab.sitesDir;
|
||||
SITES_DIR = config.homelab.sitesDir;
|
||||
HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.sitesDir}/deployments.yaml";
|
||||
HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";
|
||||
};
|
||||
|
||||
serviceConfig = {
|
||||
Type = "simple";
|
||||
User = config.homelab.operatorUser;
|
||||
SupplementaryGroups = [ "docker" "homelab-operators" ];
|
||||
WorkingDirectory = config.homelab.coreDir;
|
||||
ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [
|
||||
{
|
||||
id = "deploy";
|
||||
execute-command = "${config.homelab.coreDir}/scripts/gitops_dispatcher.py";
|
||||
pass-arguments-to-command = [
|
||||
{ source = "raw-request-body"; }
|
||||
{ source = "header"; name = "X-Gitea-Signature"; }
|
||||
{ source = "header"; name = "X-Gitea-Event"; }
|
||||
];
|
||||
command-working-directory = config.homelab.coreDir;
|
||||
response-message = "Deployment payload dispatched successfully.";
|
||||
}
|
||||
])} -port 9000 -verbose";
|
||||
Restart = "on-failure";
|
||||
RestartSec = "5s";
|
||||
|
||||
# Privilege separation & Systemd sandboxing
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = "read-only";
|
||||
ProtectKernelTunables = true;
|
||||
ProtectControlGroups = true;
|
||||
ReadWritePaths = [
|
||||
config.homelab.sitesDir
|
||||
"/home/${config.homelab.operatorUser}/.local/state/homelab"
|
||||
"-/run/homelab"
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
# Declarative Users and Groups for Control Plane Service Identity
|
||||
users.groups.homelab-operators.members = [ config.homelab.operatorUser ];
|
||||
users.users.homelab-appctl = {
|
||||
isSystemUser = true;
|
||||
group = "homelab-operators";
|
||||
extraGroups = [ "docker" ];
|
||||
description = "Homelab appctl control plane daemon service user";
|
||||
};
|
||||
|
||||
# Declarative appctl Control Plane Daemon (Internal HTTP 9001 + UDS /run/homelab/appctl.sock)
|
||||
systemd.services.homelab-appctl = {
|
||||
description = "Homelab appctl Control Plane Daemon";
|
||||
after = [ "network-online.target" "docker.service" ];
|
||||
wants = [ "network-online.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
|
||||
path = with pkgs; [
|
||||
git
|
||||
docker
|
||||
docker-compose
|
||||
(python3.withPackages (ps: with ps; [ pyyaml pydantic ]))
|
||||
coreutils
|
||||
bash
|
||||
openssh
|
||||
];
|
||||
|
||||
environment = {
|
||||
HOME = "/var/lib/homelab/appctl";
|
||||
DOCKER_CONFIG = "/var/lib/homelab/appctl/.docker";
|
||||
HOMELAB_DOMAIN = config.homelab.domain;
|
||||
APPCTL_SOCKET_PATH = "/run/homelab/appctl.sock";
|
||||
APPCTL_HTTP_HOST = "127.0.0.1";
|
||||
APPCTL_HTTP_PORT = "9001";
|
||||
APPCTL_AUDIT_LOG = "/var/log/homelab/appctl/audit.jsonl";
|
||||
APPCTL_LOCK_DIR = "/var/lib/homelab/appctl/locks";
|
||||
APPCTL_TOKENS_FILE = config.sops.secrets."appctl/tokens_json".path;
|
||||
WORKLOADS_DIR = config.homelab.sitesDir;
|
||||
SITES_DIR = config.homelab.sitesDir;
|
||||
CORE_DIR = config.homelab.coreDir;
|
||||
HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab";
|
||||
HOMELAB_CONFIG_DIR = "/home/${config.homelab.operatorUser}/.config/homelab";
|
||||
HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.sitesDir}/deployments.yaml";
|
||||
HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";
|
||||
};
|
||||
|
||||
serviceConfig = {
|
||||
Type = "simple";
|
||||
User = "homelab-appctl";
|
||||
Group = "homelab-operators";
|
||||
SupplementaryGroups = [ "docker" ];
|
||||
WorkingDirectory = config.homelab.coreDir;
|
||||
ExecStart = "${(pkgs.python3.withPackages (ps: with ps; [ pyyaml pydantic ]))}/bin/python3 ${config.homelab.coreDir}/scripts/appctl_daemon.py";
|
||||
Restart = "always";
|
||||
RestartSec = "5s";
|
||||
|
||||
RuntimeDirectory = "homelab";
|
||||
RuntimeDirectoryMode = "0750";
|
||||
StateDirectory = "homelab/appctl";
|
||||
StateDirectoryMode = "0700";
|
||||
LogsDirectory = "homelab/appctl";
|
||||
LogsDirectoryMode = "0700";
|
||||
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = "read-only";
|
||||
ProtectKernelTunables = true;
|
||||
ProtectControlGroups = true;
|
||||
ReadWritePaths = [
|
||||
config.homelab.sitesDir
|
||||
"-/home/${config.homelab.operatorUser}/var/lib/homelab"
|
||||
"-${config.homelab.coreDir}/config/homepage"
|
||||
"/var/log/homelab/appctl"
|
||||
"-/var/lib/homelab/appctl"
|
||||
"-/run/homelab"
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
# Ensure persistent directories have proper permissions for container runtimes
|
||||
systemd.tmpfiles.rules = [
|
||||
"d ${config.homelab.coreDir}/config/stalwart/data 0777 ${config.homelab.operatorUser} users -"
|
||||
"d ${config.homelab.coreDir}/config/stalwart/etc 0777 ${config.homelab.operatorUser} users -"
|
||||
"d ${config.homelab.sitesDir} 0755 ${config.homelab.operatorUser} users -"
|
||||
"a+ ${config.homelab.coreDir}/config/authelia - - - - d:u:1000:rwX,u:1000:rwx,m::rwx"
|
||||
"a+ ${config.homelab.coreDir}/config/authelia/db.sqlite3 - - - - u:1000:rw,m::rw"
|
||||
"a+ ${config.homelab.coreDir}/config/authelia/emails.txt - - - - u:1000:rw,m::rw"
|
||||
"d /home/${config.homelab.operatorUser}/.local/state/homelab/gitops 0755 ${config.homelab.operatorUser} users -"
|
||||
"d /home/${config.homelab.operatorUser}/.local/state/homelab/docker 0755 ${config.homelab.operatorUser} users -"
|
||||
"d /home/${config.homelab.operatorUser}/var/lib/homelab 0755 ${config.homelab.operatorUser} users -"
|
||||
# POSIX ACLs granting homelab-appctl and homelab-operators traverse & access (explicit mask m:: required on 0700 home dirs)
|
||||
"a+ /home/${config.homelab.operatorUser} - - - - u:homelab-appctl:x,g:homelab-operators:x,m::rx"
|
||||
"a+ ${config.homelab.coreDir} - - - - u:homelab-appctl:x,g:homelab-operators:x,m::rx"
|
||||
"A+ ${config.homelab.sitesDir} - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
|
||||
"A+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
|
||||
"A+ ${config.homelab.coreDir}/config/homepage - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
|
||||
];
|
||||
|
||||
# Open ports in the firewall for Traefik, Gitea SSH, GitOps Webhook Receiver, and Mail (SMTP, Submission, SMTPS, IMAPS, ManageSieve)
|
||||
networking.firewall.allowedTCPPorts = [ 80 443 2223 9000 25 465 587 993 4190 ];
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
# 🐚 Server Shell Configuration
|
||||
# Declarative bash environment tailored for the headless homelab server.
|
||||
# This replaces the laptop-inherited ~/.bashrc with a clean, server-appropriate profile.
|
||||
# Delivered via /etc/bashrc — no Home Manager required.
|
||||
|
||||
{ pkgs, ... }:
|
||||
|
||||
{
|
||||
# ── Shell-integrated programs ─────────────────────────────────────────────────
|
||||
# These handle both installation and bash hook injection automatically
|
||||
programs.zoxide.enable = true; # smart cd with bash init wired into /etc/bashrc
|
||||
programs.starship.enable = true; # cross-shell prompt
|
||||
programs.direnv.enable = true; # per-project env vars via .envrc files
|
||||
|
||||
# ── Additional shell packages ─────────────────────────────────────────────────
|
||||
environment.systemPackages = with pkgs; [
|
||||
fastfetch # system info dashboard on shell entry
|
||||
fzf # fuzzy finder (keybindings handled in interactiveShellInit)
|
||||
bat # syntax-highlighted cat
|
||||
qpdf # PDF decryption (used by pdf_dc function)
|
||||
];
|
||||
|
||||
# ── Environment & PATH ────────────────────────────────────────────────────────
|
||||
# Export Core scripts and user bin to /etc/set-environment so all subshells inherit them
|
||||
environment.extraInit = ''
|
||||
export PATH="$HOME/Core/scripts:$HOME/.local/bin:$HOME/.cargo/bin:$PATH"
|
||||
'';
|
||||
|
||||
# ── Bash configuration ────────────────────────────────────────────────────────
|
||||
programs.bash = {
|
||||
shellAliases = {
|
||||
# Traversal
|
||||
".." = "cd ..";
|
||||
"..." = "cd ../..";
|
||||
"...." = "cd ../../..";
|
||||
"....." = "cd ../../../..";
|
||||
|
||||
# eza-based directory listing
|
||||
ls = "eza --group-directories-first --header --icons";
|
||||
la = "eza -a";
|
||||
ll = "eza -l";
|
||||
lla = "eza -la";
|
||||
lt = "eza --tree";
|
||||
# zoxide interactive jump with eza preview
|
||||
zi = "zoxide query -i --preview 'eza --tree --level 2 --color=always {}'";
|
||||
|
||||
# Git shortcuts
|
||||
ga = "git add";
|
||||
gc = "git commit -m";
|
||||
gp = "git push";
|
||||
gpl = "git pull";
|
||||
gs = "git status";
|
||||
gst = "git stash";
|
||||
gsp = "git stash && git pull";
|
||||
gfo = "git fetch origin";
|
||||
gcheck = "git checkout";
|
||||
gadc = "git add -A && git diff --staged";
|
||||
|
||||
# Editor & system
|
||||
v = "nvim";
|
||||
ff = "fastfetch --logo none";
|
||||
reload = "exec bash";
|
||||
pgoog = "ping google.com -c 3";
|
||||
wifi = "nmtui";
|
||||
# NixOS rebuild targeting this flake (path scheme + impure required for instance.nix)
|
||||
nix-switch = "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure";
|
||||
};
|
||||
|
||||
interactiveShellInit = ''
|
||||
# ── User PATH ────────────────────────────────────────────────────────────
|
||||
export PATH="$HOME/Core/scripts:$HOME/.local/bin:$HOME/.cargo/bin:$PATH"
|
||||
|
||||
# ── History ───────────────────────────────────────────────────────────────
|
||||
HISTFILESIZE=100000
|
||||
HISTSIZE=10000
|
||||
shopt -s histappend
|
||||
shopt -s extglob
|
||||
shopt -s globstar
|
||||
shopt -s checkjobs
|
||||
|
||||
# ── Readline keybindings ─────────────────────────────────────────────────
|
||||
if [[ -n "$BASH_VERSION" ]]; then
|
||||
bind '"\C-w": "\eb\ed"' 2>/dev/null # Ctrl+W: delete word backward
|
||||
bind '"\e[3;5~": kill-word' 2>/dev/null # Ctrl+Delete: delete word forward
|
||||
bind '"\e\x7f": backward-kill-word' 2>/dev/null
|
||||
bind '"\e\b": backward-kill-word' 2>/dev/null
|
||||
fi
|
||||
|
||||
# ── fzf shell integration ─────────────────────────────────────────────────
|
||||
if command -v fzf &>/dev/null; then
|
||||
eval "$(fzf --bash)"
|
||||
fi
|
||||
|
||||
# ── Shell entry dashboard ─────────────────────────────────────────────────
|
||||
fastfetch --logo none
|
||||
|
||||
# ── Git workflow functions ────────────────────────────────────────────────
|
||||
|
||||
# gacp: Stage all, commit with message, and push to current branch
|
||||
gacp() {
|
||||
if [ -z "$1" ]; then
|
||||
echo "Usage: gacp <commit-message>"
|
||||
return 1
|
||||
fi
|
||||
git add -A
|
||||
git commit -m "$1"
|
||||
local branch_name
|
||||
branch_name=$(git branch --show-current)
|
||||
git push origin "$branch_name"
|
||||
echo "Pushed to origin/$branch_name"
|
||||
}
|
||||
|
||||
# gitignore: Append pattern(s) to .gitignore and auto-commit
|
||||
gitignore() {
|
||||
if [ $# -eq 0 ]; then
|
||||
echo "Usage: gitignore <pattern> [pattern...]"
|
||||
return 1
|
||||
fi
|
||||
local GIT_ROOT
|
||||
GIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)
|
||||
if [ -z "$GIT_ROOT" ]; then
|
||||
echo "Error: Not a Git repository."
|
||||
return 1
|
||||
fi
|
||||
local GIT_IGNORE_FILE="$GIT_ROOT/.gitignore"
|
||||
[ -f "$GIT_IGNORE_FILE" ] || touch "$GIT_IGNORE_FILE"
|
||||
if [ -s "$GIT_IGNORE_FILE" ] && [ "$(tail -c1 "$GIT_IGNORE_FILE" | wc -l)" -eq 0 ]; then
|
||||
echo "" >> "$GIT_IGNORE_FILE"
|
||||
fi
|
||||
local added_count=0 commit_msg_list=""
|
||||
for pattern in "$@"; do
|
||||
if rg -Fxq "$pattern" "$GIT_IGNORE_FILE" 2>/dev/null; then
|
||||
echo "Skipping '$pattern' (already in .gitignore)"
|
||||
else
|
||||
echo "$pattern" >> "$GIT_IGNORE_FILE"
|
||||
echo "Added '$pattern'"
|
||||
(( added_count++ ))
|
||||
commit_msg_list+="$pattern, "
|
||||
fi
|
||||
done
|
||||
if [ "$added_count" -gt 0 ]; then
|
||||
commit_msg_list="''${commit_msg_list%, }"
|
||||
git add "$GIT_IGNORE_FILE"
|
||||
git commit -m "Add to .gitignore: $commit_msg_list"
|
||||
git push
|
||||
else
|
||||
echo "No new patterns were added."
|
||||
fi
|
||||
}
|
||||
|
||||
# ── PDF utilities ─────────────────────────────────────────────────────────
|
||||
|
||||
# pdf_dc: Decrypt a password-protected PDF
|
||||
# Reads password from /run/secrets/pdf_decrypt_password if not supplied
|
||||
pdf_dc() {
|
||||
local secret_file="/run/secrets/pdf_decrypt_password"
|
||||
local input_file="$1"
|
||||
local password="$2"
|
||||
if [[ -z "$password" ]] && [[ -f "$secret_file" ]]; then
|
||||
password=$(cat "$secret_file")
|
||||
fi
|
||||
if [[ -z "$password" ]]; then
|
||||
echo "Error: No password provided and default secret not found" >&2
|
||||
return 1
|
||||
fi
|
||||
if [[ ! -f "$input_file" ]]; then
|
||||
echo "Error: Input file '$input_file' not found" >&2
|
||||
return 1
|
||||
fi
|
||||
local output_file="''${input_file%.pdf}_decrypted.pdf"
|
||||
if [[ -f "$output_file" ]]; then
|
||||
read -rp "Output '$output_file' exists. Overwrite? (y/n): " overwrite
|
||||
[[ "$overwrite" != "y" ]] && { echo "Operation cancelled."; return 1; }
|
||||
fi
|
||||
echo "Decrypting $input_file..."
|
||||
if qpdf --password="$password" --decrypt "$input_file" "$output_file"; then
|
||||
echo "✅ Decryption successful: $output_file"
|
||||
else
|
||||
local exit_code=$?
|
||||
echo "❌ Decryption failed (qpdf exit code: $exit_code)"
|
||||
return "$exit_code"
|
||||
fi
|
||||
}
|
||||
|
||||
# ── Fuzzy directory navigation ────────────────────────────────────────────
|
||||
|
||||
# Internal: fuzzy-select a subdirectory with eza preview
|
||||
_fuzzy_select_dir() {
|
||||
local base="$1" query="$2" max_depth="''${3:-2}"
|
||||
[[ -d "$base" ]] || return 1
|
||||
(echo "$base"; fd . "$base" --type d --mindepth 1 --max-depth "$max_depth" 2>/dev/null) |
|
||||
fzf --query="$query" --select-1 --exit-0 \
|
||||
--preview 'eza --tree --level 2 --icons=always --color=always {}' \
|
||||
--preview-window="right:50%:rounded"
|
||||
}
|
||||
|
||||
# Internal: cd into a directory
|
||||
_jump_to() {
|
||||
local dir="$1"
|
||||
[[ -d "$dir" ]] || return 1
|
||||
cd "$dir" || return 1
|
||||
}
|
||||
|
||||
# jump: Fuzzy-select and enter a subdirectory under a base path
|
||||
jump() {
|
||||
local dir
|
||||
dir=$(_fuzzy_select_dir "$1" "$2" "''${3:-2}") || return
|
||||
_jump_to "$dir"
|
||||
}
|
||||
|
||||
# Shorthand jump targets
|
||||
prj() { jump "$HOME/Projects" "$1"; } # workspace projects
|
||||
dep() { jump "$HOME/Deployments" "$1"; } # deployment directories
|
||||
med() { jump "/media" "$1"; } # mounted media storage
|
||||
core() { jump "$HOME/Core" "$1"; } # homelab-core subdirectories
|
||||
'';
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
# 🌐 Traefik Deployments Environment Secrets configuration
|
||||
# This NixOS module manages secrets and environment variables for the unified apps in /traefik-deployments
|
||||
|
||||
{ config, lib, pkgs, ... }:
|
||||
|
||||
{
|
||||
# Define the keys to decrypt from secrets.yaml (avoiding repeating the owner boilerplate)
|
||||
sops.secrets = lib.genAttrs [
|
||||
"learning/turso_db_url"
|
||||
"learning/turso_auth_token"
|
||||
"mongo/root_username"
|
||||
"mongo/root_password"
|
||||
"ollama/api_key"
|
||||
"postgres/user"
|
||||
"postgres/password"
|
||||
"postgres/db"
|
||||
"gitea/runner_token"
|
||||
] (name: { owner = config.homelab.operatorUser; });
|
||||
|
||||
# Generate the unified environment file at runtime in /run/secrets/traefik-deployments.env
|
||||
sops.templates."traefik-deployments.env" = {
|
||||
owner = config.homelab.operatorUser;
|
||||
group = "homelab-operators";
|
||||
mode = "0440";
|
||||
content = lib.generators.toKeyValue {} {
|
||||
# --- Core / Infrastructure Settings ---
|
||||
PROXY_NETWORK = "proxy-net";
|
||||
CERT_RESOLVER = "myresolver";
|
||||
DOMAIN_SUFFIX = config.homelab.domain;
|
||||
|
||||
# --- Dashboard & Landing ---
|
||||
DASHBOARD_DOMAIN = "dashboard.${config.homelab.domain}";
|
||||
LANDING_DOMAIN = config.homelab.domain;
|
||||
|
||||
# --- Docs ---
|
||||
DOCS_DOMAIN = "docs.${config.homelab.domain}";
|
||||
DOCS_PROJECT_PATH = "/home/${config.homelab.operatorUser}/Brain";
|
||||
|
||||
# --- Excalidraw ---
|
||||
EXCALIDRAW_DOMAIN = "excalidraw.${config.homelab.domain}";
|
||||
|
||||
# --- Gitea ---
|
||||
GITEA_DOMAIN = "gitea.${config.homelab.domain}";
|
||||
GITEA_SSH_DOMAIN = "gitea.${config.homelab.domain}";
|
||||
GITEA_SSH_PORT = "2223";
|
||||
GITEA_AUTH_MIDDLEWARE = "https-redirect@docker";
|
||||
GITEA_RUNNER_TOKEN = config.sops.placeholder."gitea/runner_token";
|
||||
|
||||
# --- Jellyfin ---
|
||||
JELLYFIN_SERVICE_NAME = "jellyfin";
|
||||
JELLYFIN_CONTAINER_NAME = "jellyfin";
|
||||
JELLYFIN_IMAGE_TAG = "latest";
|
||||
JELLYFIN_DOMAIN = "jellyfin.${config.homelab.domain}";
|
||||
JELLYFIN_TZ = "UTC";
|
||||
JELLYFIN_PUID = "1000";
|
||||
JELLYFIN_PGID = "1000";
|
||||
JELLYFIN_MEDIA_PATH = "/media";
|
||||
JELLYFIN_HTTP_ENTRYPOINT = "web";
|
||||
JELLYFIN_HTTPS_ENTRYPOINT = "websecure";
|
||||
JELLYFIN_RATE_LIMIT_AVG = "100";
|
||||
JELLYFIN_RATE_LIMIT_BURST = "50";
|
||||
|
||||
# --- Learning Dashboard ---
|
||||
LEARNING_SERVICE_NAME = "learning-hub";
|
||||
LEARNING_DOMAIN = "learning.${config.homelab.domain}";
|
||||
LEARNING_APP_PORT = "8000";
|
||||
LEARNING_SOCKET_PROXY_NETWORK = "socket-net";
|
||||
LEARNING_DOCKER_HOST = "tcp://socket-proxy:2375";
|
||||
TURSO_DATABASE_URL = config.sops.placeholder."learning/turso_db_url";
|
||||
TURSO_AUTH_TOKEN = config.sops.placeholder."learning/turso_auth_token";
|
||||
|
||||
# --- Mermaid ---
|
||||
MERMAID_DOMAIN = "mermaid.${config.homelab.domain}";
|
||||
MERMAID_SERVICE_NAME = "mermaid";
|
||||
|
||||
# --- Minecraft ---
|
||||
MINECRAFT_DOMAIN = "minecraft.${config.homelab.domain}";
|
||||
|
||||
# --- MongoDB ---
|
||||
MONGO_ROOT_USERNAME = config.sops.placeholder."mongo/root_username";
|
||||
MONGO_ROOT_PASSWORD = config.sops.placeholder."mongo/root_password";
|
||||
MONGO_DOMAIN = "mongodb.${config.homelab.domain}";
|
||||
|
||||
# --- PostgreSQL ---
|
||||
POSTGRES_USER = config.sops.placeholder."postgres/user";
|
||||
POSTGRES_PASSWORD = config.sops.placeholder."postgres/password";
|
||||
POSTGRES_DB = config.sops.placeholder."postgres/db";
|
||||
POSTGRES_DOMAIN = "pgsql.${config.homelab.domain}";
|
||||
|
||||
# --- Ollama ---
|
||||
OLLAMA_DOMAIN = "ollama.${config.homelab.domain}";
|
||||
OLLAMA_API_KEY = config.sops.placeholder."ollama/api_key";
|
||||
OLLAMA_REPLICAS = "1";
|
||||
OLLAMA_DATA_VOLUME = "ollama_data";
|
||||
};
|
||||
};
|
||||
}
|
||||
Executable
+92
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env bash
|
||||
# Read-only ForceCommand allowlist wrapper for the `agents` SSH user.
|
||||
set -euo pipefail
|
||||
|
||||
export CORE_DIR="${CORE_DIR:-/home/operator/Core}"
|
||||
export WORKLOADS_DIR="${WORKLOADS_DIR:-/home/operator/Workloads}"
|
||||
export DOCKER_HOST="${DOCKER_HOST:-tcp://127.0.0.1:2375}"
|
||||
|
||||
raw_cmd="${SSH_ORIGINAL_COMMAND:-}"
|
||||
|
||||
if [[ -z "${raw_cmd// }" ]]; then
|
||||
echo "Error: empty SSH_ORIGINAL_COMMAND is not permitted" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "$raw_cmd" == *$'\n'* || "$raw_cmd" == *$'\r'* ]]; then
|
||||
echo "Error: control characters are not permitted" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "$raw_cmd" == *[';&|`$()<>\\'\''"']* ]]; then
|
||||
echo "Error: shell metacharacters are not permitted" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Word-split without globbing or shell evaluation
|
||||
set -f
|
||||
read -r -a args <<< "$raw_cmd"
|
||||
set +f
|
||||
|
||||
if [[ ${#args[@]} -eq 0 ]]; then
|
||||
echo "Error: empty SSH_ORIGINAL_COMMAND is not permitted" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cmd="${args[0]}"
|
||||
|
||||
case "$cmd" in
|
||||
docker)
|
||||
if [[ ${#args[@]} -lt 2 ]]; then
|
||||
echo "Error: docker subcommand is required" >&2
|
||||
exit 1
|
||||
fi
|
||||
subcmd="${args[1]}"
|
||||
case "$subcmd" in
|
||||
ps|logs|inspect) ;;
|
||||
*)
|
||||
echo "Error: docker subcommand '$subcmd' is not permitted" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
for arg in "${args[@]:2}"; do
|
||||
case "$arg" in
|
||||
-H|-H=*|--host|--host=*|--context|--context=*|-c|-c=*|--config|--config=*)
|
||||
echo "Error: docker connection override flag '$arg' is not permitted" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
exec docker "${args[@]:1}"
|
||||
;;
|
||||
journalctl)
|
||||
for arg in "${args[@]:1}"; do
|
||||
case "$arg" in
|
||||
--flush|--rotate|--vacuum-*|--relinquish-var|--sync|--setup-keys|--update-catalog)
|
||||
echo "Error: mutating journalctl flag '$arg' is not permitted" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
exec journalctl "${args[@]:1}"
|
||||
;;
|
||||
appctl)
|
||||
if [[ ${#args[@]} -lt 2 ]]; then
|
||||
echo "Error: appctl subcommand is required" >&2
|
||||
exit 1
|
||||
fi
|
||||
subcmd="${args[1]}"
|
||||
case "$subcmd" in
|
||||
list|status|info|logs|ssl|health|resolve) ;;
|
||||
*)
|
||||
echo "Error: appctl subcommand '$subcmd' is not permitted" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
exec appctl "${args[@]:1}"
|
||||
;;
|
||||
*)
|
||||
echo "Error: command '$cmd' is not permitted" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,12 @@
|
||||
# General configuration
|
||||
syslog=no
|
||||
pid=/run/ddclient/ddclient.pid
|
||||
cache=/var/lib/ddclient/ddclient.cache
|
||||
usev4=webv4
|
||||
|
||||
# Provider definition using credentials decrypted at runtime
|
||||
protocol=dyndns2
|
||||
server=api.dynu.com
|
||||
login=@dynu_user@
|
||||
password=@dynu_password@
|
||||
@dynu_domain@
|
||||
@@ -0,0 +1,201 @@
|
||||
"""
|
||||
Dynu DDNS Smart IP Change Monitor and Updater.
|
||||
|
||||
This script determines the current public IPv4 address by querying multiple
|
||||
external resolvers sequentially. It compares the discovered IP against the last
|
||||
recorded successful IP in a local history log. If a change is detected, it
|
||||
triggers the `ddclient.service` on-demand to perform the DNS record update.
|
||||
|
||||
This local-first state verification prevents making redundant API requests to
|
||||
the DNS provider, avoiding rate-limiting, IP bans, or API abuse flags.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import UTC, datetime
|
||||
|
||||
# History file location storing the transition log of public IP states.
|
||||
# Defaults to a state directory managed securely by the systemd service unit.
|
||||
HISTORY_FILE = os.environ.get("HISTORY_FILE", "/var/lib/dynu/ip_history.jsonl")
|
||||
|
||||
# Fallback sequence of external services to discover the public WAN IP.
|
||||
PROVIDERS = [
|
||||
"https://api.ipify.org",
|
||||
"https://ifconfig.me/ip",
|
||||
"https://icanhazip.com",
|
||||
"https://wtfismyip.com/text",
|
||||
]
|
||||
|
||||
|
||||
def is_valid_public_ipv4(ip):
|
||||
"""
|
||||
Validates that a string is a properly formatted public IPv4 address.
|
||||
|
||||
This function excludes standard private, loopback, link-local, and CGNAT
|
||||
blocks to avoid recording temporary, local, or invalid network states.
|
||||
"""
|
||||
match = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
|
||||
if not match:
|
||||
return False
|
||||
octets = [int(x) for x in match.groups()]
|
||||
if any(x > 255 for x in octets):
|
||||
return False
|
||||
a, b, _c, _d = octets
|
||||
|
||||
# RFC 1918 Private ranges: 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12
|
||||
if a == 10:
|
||||
return False
|
||||
if a == 192 and b == 168:
|
||||
return False
|
||||
if a == 172 and 16 <= b <= 31:
|
||||
return False
|
||||
|
||||
# Carrier-Grade NAT (CGNAT) RFC 6598: 100.64.0.0/10
|
||||
if a == 100 and 64 <= b <= 127:
|
||||
return False
|
||||
|
||||
# Loopback address range: 127.0.0.0/8
|
||||
if a == 127:
|
||||
return False
|
||||
|
||||
# Link-local addresses: 169.254.0.0/16
|
||||
return not (a == 169 and b == 254)
|
||||
|
||||
|
||||
def get_public_ip():
|
||||
"""
|
||||
Queries public IP providers until a valid public IPv4 is returned.
|
||||
|
||||
Returns:
|
||||
str: The validated public IP string, or None if all providers fail.
|
||||
"""
|
||||
errors = []
|
||||
for provider in PROVIDERS:
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
provider,
|
||||
headers={"User-Agent": "Mozilla/5.0 (NixOS WAN Monitor)"},
|
||||
)
|
||||
# Fetch with 5s timeout to avoid hanging the systemd service
|
||||
with urllib.request.urlopen(req, timeout=5) as response:
|
||||
ip = response.read().decode("utf-8").strip()
|
||||
if is_valid_public_ipv4(ip):
|
||||
return ip
|
||||
else:
|
||||
errors.append(f"{provider}: invalid public IPv4 '{ip}'")
|
||||
except (urllib.error.URLError, OSError, ValueError) as e:
|
||||
errors.append(f"{provider}: {e!s}")
|
||||
|
||||
print(
|
||||
f"Error: All IP discovery providers failed. Details: {errors}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def get_last_recorded_ip():
|
||||
"""
|
||||
Reads the history log to locate the last successful IP address.
|
||||
|
||||
Returns:
|
||||
str: The last successfully updated IP, or None if no log exists yet.
|
||||
"""
|
||||
if not os.path.exists(HISTORY_FILE):
|
||||
return None
|
||||
try:
|
||||
with open(HISTORY_FILE, "r") as f:
|
||||
lines = f.readlines()
|
||||
if not lines:
|
||||
return None
|
||||
# Search backwards to find the most recent successful transition
|
||||
for line in reversed(lines):
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
if entry.get("status") == "success":
|
||||
return entry.get("ip")
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
except OSError as e:
|
||||
print(f"Warning: Failed to read history file: {e}", file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def record_ip(ip, status, details=None):
|
||||
"""
|
||||
Appends a new event entry into the JSONLines history registry.
|
||||
"""
|
||||
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
|
||||
entry = {
|
||||
"timestamp": datetime.now(tz=UTC).isoformat(),
|
||||
"ip": ip,
|
||||
"status": status,
|
||||
}
|
||||
if details:
|
||||
entry["details"] = details
|
||||
try:
|
||||
with open(HISTORY_FILE, "a") as f:
|
||||
f.write(json.dumps(entry) + "\n")
|
||||
except OSError as e:
|
||||
print(f"Error: Failed to write to history file: {e}", file=sys.stderr)
|
||||
|
||||
|
||||
def trigger_ddclient():
|
||||
"""
|
||||
Invokes the systemd service unit for `ddclient` on-demand.
|
||||
|
||||
Returns:
|
||||
tuple: (bool, str) representing (success_boolean, error_details_string)
|
||||
"""
|
||||
try:
|
||||
# Run ddclient as a one-shot activation via systemd to perform API call
|
||||
res = subprocess.run(
|
||||
["systemctl", "start", "ddclient.service"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if res.returncode == 0:
|
||||
return True, None
|
||||
else:
|
||||
err_msg = (
|
||||
f"systemctl exited with {res.returncode}: {res.stderr.strip()}"
|
||||
)
|
||||
return False, err_msg
|
||||
except (OSError, subprocess.SubprocessError) as e:
|
||||
return False, str(e)
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
Orchestrator logic for DDNS state management.
|
||||
"""
|
||||
current_ip = get_public_ip()
|
||||
if not current_ip:
|
||||
sys.exit(1)
|
||||
|
||||
last_ip = get_last_recorded_ip()
|
||||
if current_ip == last_ip:
|
||||
# IP matches last recorded working IP; do nothing to conserve quota
|
||||
sys.exit(0)
|
||||
|
||||
print(f"IP rotation detected! Old: {last_ip}, New: {current_ip}")
|
||||
|
||||
# Trigger ddclient to perform the DNS record update
|
||||
success, error_msg = trigger_ddclient()
|
||||
if success:
|
||||
print("Dynu DDNS update via ddclient triggered successfully.")
|
||||
record_ip(current_ip, "success")
|
||||
else:
|
||||
err_msg = f"Error: Failed to trigger ddclient update: {error_msg}"
|
||||
print(err_msg, file=sys.stderr)
|
||||
record_ip(current_ip, "failed_update", details=error_msg)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,71 @@
|
||||
authelia:
|
||||
session_secret: ENC[AES256_GCM,data:TmujJ9I51cQrzRMcvFkhFnG1CICebOM332NUTwXSj33niFdrV3xfHWR3h83/WcNk+M/i0AjcFtZ7fRYNW5VV2766p2BAfsaihSN8yQPrsQRNPyQKvSgij2xWL/B5I1a7NQGRh7xX6yiQYqaPzrwKnlcv8kmKp8aFPlkdmWYOCPc=,iv:Pcj6yu1MvZBJ0VPfuEO4RiTiE5SOULI/jGAz8dy/X4g=,tag:firz8cjG9HP8HEgKM4c53Q==,type:str]
|
||||
storage_encryption_key: ENC[AES256_GCM,data:ycsfhh9cAsIbSEVaPvCH8ky0t+zayLtI6NVLcb+v2HIJMYSqD8eXu7JCvp5E0u1PkGTyaAoatXtcdChb2ABEiUNeqlOPXciF4ED+4yFAXftfMKy/M4AAYgp9jBA1v8JsE5mfBEOfmnBWV5SwGSaHBcQgUoJubKqcODPfHOmkKwg=,iv:1bgvgcClI+2VG6wXa5el5jfOrkCx+bj33VYiFdA1gas=,tag:0n7nJaZomtllFzSH2+Z8yw==,type:str]
|
||||
jwt_secret: ENC[AES256_GCM,data:C1FnoRi49PSaIZNp+SAS6Q5+odYwai75OR4UfvGx1Jk8wb4nVDUASpaOgm7ZFJysTX4WjuQi99PYyG5GshlHoJ5dVbLSFpEq7MSSiY8tZA2PqnHmIODNYARfFw6lB7udPjz8ANyU2UcrnwRKXnDD+T2Pa1uL9joW5rg7vWZlRks=,iv:IDZ2/wbmCPoR14b1imZrTJR5LuQp6V91tcZ/Z5Znl0w=,tag:d0UQ49QcEqgD+PCIBoOJ7Q==,type:str]
|
||||
diun:
|
||||
smtp_password: ENC[AES256_GCM,data:ED3NoQWxpuucfpGAiw==,iv:fWmHEnNr9r1OpgteTJwT8Z2iKn1WKPf8WudWWvBnvjA=,tag:MjVAN7IITEm+Og+3k/SGVg==,type:str]
|
||||
traefik:
|
||||
acme_email: ENC[AES256_GCM,data:U2IPYioGlfgSpfZy5E+2+VM0iXQ=,iv:zQ5Txq9H7mF7GcaZfyPPjSQFKa0736/DI7Y4XARMFqM=,tag:7Q4YN9OPA1rRVpXuapewQQ==,type:str]
|
||||
dynu:
|
||||
api_key: ENC[AES256_GCM,data:f4dAZjCplklE08kll1yGuYYYDKKTVEwvSL0d6fM9K+g=,iv:xjR/5lNfRXxTPWJ+WM+/qzZGWTMf7iNua/FoGwTYXTg=,tag:PuZZWUJ+WoZVcWDVKwxM9g==,type:str]
|
||||
user: ENC[AES256_GCM,data:RdKa9JmnllYQ,iv:2xW8vvzWvKp1rEV8G9fp+Jae38Wr3+lHAQ15htP3Sjs=,tag:tts/zHJqoBoK6vVnt7ho3A==,type:str]
|
||||
domain: ENC[AES256_GCM,data:Towv0BFeoXhIaP/pzA==,iv:yzMv6t/Z3NEiE7t5u9lVA5siy5APsWHpdPvqYI8EmQU=,tag:8YTWCtA/sshOOLaHOMH+nw==,type:str]
|
||||
password: ENC[AES256_GCM,data:oF8O3S5n2fuSFpgu8RVa0SwS4U4yYl/I7EMRTt640SQ=,iv:x0npliyj1cZocDce3hofvJYuQbXGOu+EU04GwR48cD4=,tag:ddNmxWp1uL2POW5mXdqfVQ==,type:str]
|
||||
postgres:
|
||||
user: ENC[AES256_GCM,data:ifJ3KSf6E6EQ,iv:Ryu/fce3mMRItSoRmwC6/HFWBebT3UXAwccfKMM+B1s=,tag:53ct7ZiF6UmklvPw0oeajw==,type:str]
|
||||
password: ENC[AES256_GCM,data:wbLdF/1RZwL6fY/IXJdT,iv:5Xk0B0qtDh0hoAKDtwpzwKdhQHhsLvlsnHiwMJP9VeE=,tag:BGlHuEHp0YucoJopg1rzBQ==,type:str]
|
||||
db: ENC[AES256_GCM,data:zBgGgioMBlVhUw==,iv:4X86eXVILuf98st1po5ipvEUDE2UG9jEPOso7CGR48k=,tag:ZXng+qF6/PUjP6D+Y/AC6w==,type:str]
|
||||
mongo:
|
||||
root_username: ENC[AES256_GCM,data:ImHe4j6Botsc,iv:dEXIA746kuh9//SLQO+RfDxIpObMMPZ2wfjgiwouS9Q=,tag:sD2uZKtwgbOgnKffv7DD4g==,type:str]
|
||||
root_password: ENC[AES256_GCM,data:hETEsUQ+EMnV2rN+ZoOd,iv:8Zt1RLAOm6CCt8W/ie1IC+3PXs2qGzcLCTGTjNxWkI0=,tag:Q9iowfgg5JjaMekRCdUizA==,type:str]
|
||||
ollama:
|
||||
api_key: ENC[AES256_GCM,data:D2KSzK6WP9Xstx2l5A3I,iv:DbEnYwhrcVMWPipwfGQ1cvUOhZuB4Q64vCDcutb24Nw=,tag:V4KIOKM7in1i8rTNDLIzZA==,type:str]
|
||||
gitea:
|
||||
runner_token: ENC[AES256_GCM,data:aFk3l8rah+lj5iNVDT2RXF2Ie5aqwcBUi9UPjsWv0aRM+i97kYtybA==,iv:pkJpmgt5goEHotx3sCbw6jBy8detOwhaE77yO+NTQ5g=,tag:nLVNSwH1bfAq+gduwgRJuQ==,type:str]
|
||||
learning:
|
||||
turso_db_url: ENC[AES256_GCM,data:DveoFqwgimUHJv48Sozh2XqT7Ha9DeX3VAslT7SrqSVHab5RPlEujF+eIHyvAUiE81A=,iv:PgWZMty5hBUsmRJW85xilcvIMO/j54WY249Jsw6LfiM=,tag:osYPQc/Q9734L0FUo9hOCQ==,type:str]
|
||||
turso_auth_token: ENC[AES256_GCM,data:lRdFDrsKWv90QSvNvYjqp07jU7DcWfrNlpg0bVljbOizixgstnFF70jjafN/QK4kId0nSJTx1DFlsTy7vG8+M00+UYl8SWDW7uTq/Ll1UGkaYinkhKFLNKUHXg5SUTfH3UA+nPBlZSNoZe6kdBgrt35TuV78lI/eUkxpVOI3D/70B6BP2DR4zmb70GztcxUY3e7xkGtVkCbyJd+BY8YOep/MgYvYg512LjESFwL/rJtJBYnh8XtQMcIDVDxRO5hGiy66xpXE4IC3wTPr4+/ZWS00H6VQccUcL0QVEVBkq+c9iytUlcTzTa7FkcYyiBnnlp1XGsk7OaE0E/VESaSaiUpQ6YQY7AllPTmhHs0uo+3KMbttjFLr,iv:OoPEVzYsmbdS2Po8C/lxo53UWxzA3gbPkrP3HZLB6Jo=,tag:1YKmvjWf5o3XZo40BZ6IWw==,type:str]
|
||||
system:
|
||||
gh_repo_token: ENC[AES256_GCM,data:QAsmG5iQQJ4TUhtrIbkq3wlw4JWbj2tFX6u2BbdB4werXfWyak8sdw==,iv:orGtlDW71QHDRSTED1xNfdOggF61hHsbGztWOUSdY+Y=,tag:4xe1I+hNjxWLc16BW4yTLA==,type:str]
|
||||
pdf_decrypt_password: ENC[AES256_GCM,data:n3XTANd+PbejUw==,iv:y2VIabyv/DfTgztbjS6M/xIfRNKOL+U+r3eXsal32OQ=,tag:oFpXg2E9dDM5dwkjSZkLgw==,type:str]
|
||||
gitops:
|
||||
webhook_secret: ENC[AES256_GCM,data:Kj3d0Repa3OOvjCkW6+kakQEfsCdpdVJQd71Am6zQHBt7QkLtxlnovUmmS+zJ+jChQBbCc9/7LunFvFT2pL36w==,iv:qh1pEIVtvB/fxbMv+a9pworhbXsIpfF5gKWS22Zn0GU=,tag:D4RNXkWhg9l3BJFp7MMloA==,type:str]
|
||||
appctl_token: ENC[AES256_GCM,data:+2BK6LejtvIj68+88zrjzgod8tXXVSRH+WpmIIHCbGU7aKbdTK20JlIIKb2u+2w/fHVrTwxUkX+dp5/AHsU+ZvVWh7tUsEo=,iv:tX5+bTfFFil46o7ZXa3dLIQH5+ET2e+75qRvjSJrhwU=,tag:mVGkDADx8RqaSi3AnDyPEw==,type:str]
|
||||
lldap:
|
||||
jwt_secret: ENC[AES256_GCM,data:RHtVgZJzNK7PFFvYO4jSsv+3928PYG2RdajG3ETEfN5eh0FwAmqcC98X2scT8H2JAeDV+bRI6QMZ3FoNRNcOHw==,iv:YGYImZJQzf1ONkc9lq2bEV/eWKIPfTyH+2hKzObaY08=,tag:jcUYKHrYSPYvHjQ86hLl0g==,type:str]
|
||||
key_seed: ENC[AES256_GCM,data:8Jf/xyMMXQFYxSO9RezTQRcS+Amm9hYOf97K03H/8cI=,iv:D5BJ4I12cMp2HAdCJC8MD/LnrBskbX7X/a6TnyisuMk=,tag:fhxge0iBSPllyrGQfCkw7w==,type:str]
|
||||
admin_password: ENC[AES256_GCM,data:587zjsdot9zj4Ez76TP0Zf7six54GDEl1BTm,iv:n3qxj3aIdyEXFrPYO5SIH7boeXvrMsYtS5NWvrJQkz0=,tag:PDuUjSDfnHaAnxx0U43hNA==,type:str]
|
||||
brevo:
|
||||
smtp_login: ENC[AES256_GCM,data:zfqKsAtoAOWCrSqx38sknwcJZT2m8W2J,iv:tMwTNDf+2CE3/8rKqWTWLl5Zp4LUVNSFV90QN94VXxo=,tag:XYXz9w3oIa0qkcfjCcgcYg==,type:str]
|
||||
smtp_key: ENC[AES256_GCM,data:YulXyaVF/sLWE9x12yxdBAj9KMbfP/CK/7FS3XkYO8sCj3GWgPbNoSaUT/9quLWHPtCsBxxdLeLoDNa1jE2WRyHP1W+Ioyyx5sAzdzevzHIBmfP+fdw0rKhe,iv:QT0HfzNPsTqXlN3IC/+bBzJfUzN9YkXYiv/3uqkXHBw=,tag:vBetkZPDYoh0Yy3BpMT9BQ==,type:str]
|
||||
cloudflare:
|
||||
account_name: ENC[AES256_GCM,data:fIuzvJbLoz/w,iv:tT3rCldA9hqHzKjJa4gENTk/XprzS5X6Wm/rqkb6jow=,tag:p0aEezfUFlJn25PdW/DAOA==,type:str]
|
||||
global_api_key: ENC[AES256_GCM,data:IDFHetxM2LE1/cytHo2Jn16piLeIvM27ui3Qld4Z5hwWauDRaY05nZH6+V6ic9dYFfagvA==,iv:9q3cosnJ+eC1BLmQ1Hx1y3Dksyc5k4UMQPZ6Or9vWFE=,tag:k/RilX02EJzMWZcfzBtu4A==,type:str]
|
||||
account_id: ENC[AES256_GCM,data:/IyUXySFGQSGs16Kv6yZajMiGTxwOuxILvcFZ/6YROo=,iv:TdMwtzs/LMnbhpsEbqunj4n+P+JxcscYGKaM42fYQ20=,tag:HHmIq03Jc4g8fBvuaWevAA==,type:str]
|
||||
dns_api_token: ENC[AES256_GCM,data:lTByYg0BM+mloaHDb2WkN7LY9twnVzKn6NO8W1rTH5FXyWaNlEovLxCPT2sG+JuRfqGJ52w=,iv:nBX3rUSdf1wFSTz0sY/ApNKVaYkCPJAJPhmMu+abzhE=,tag:LK8qyYap/T1HZb+jWnHyuA==,type:str]
|
||||
appctl:
|
||||
tokens_json: ENC[AES256_GCM,data:O2vsiMMcZjsduFSRen1MnnckdRYK45aPH40EhX42h1WUwf62Nm58PV5BQJOgJ97AH3hOH97mzg1tjL0C1oV/epXMaypRWY9AGLS00CfzD2sgdM5Wx7VKbfGggFnGqgd7veaCA+pxUC0uTk/Dq2Cz/uhXhLX1wVjafX0OAqS6fxO+L9Oza3+RBtKgx2xX0AKW+KSZQUM1nvNW8R/Eyvnqvw2OSb2FdKN1CKhlVWhCZiaxTe8617BqGhJDL9pu4lfn0m+tdIwvluI3h8cmKuT6dzd01Jxr0EHBY/+mZZ/WQoNhIy4QulFpKiMudiT+WGzUm+UT4mYBoGwzQCVV8MD7W1r84mkbCkLc/HpWG08TqK4tpAdtLgYK3Zslr1+lmboWyJ6WcinmxkhUexhj+gTyfXYmVSB3fF8PIeyQINGB3rLvmpZ7DDMzYa1ICgFbJ6zmYa54TXRDLGzLD09koeDp9FhXNKPvuwz2x4uwWDDUfU8wwTkGbw==,iv:FJpB+WZiE4PKUhIuwBWIB/TLtifwCzGRMtbMx7x6ly8=,tag:NZQXYFnVBqbOONl+Yh3tuA==,type:str]
|
||||
sops:
|
||||
age:
|
||||
- enc: |
|
||||
-----BEGIN AGE ENCRYPTED FILE-----
|
||||
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBkeEdCUncxWS9CUDJmbFow
|
||||
THJpbE9tSmtZcURMcXoyYnd5eHlrcVhNdURrCjJBSFNBTnVpRE9SdkkyWXAwRFFo
|
||||
Um5UUDFTVVl2ZDBBT1hNMHdQZ0RLYjAKLS0tIDUrS3g2a0QralpuN2hiMHRkRVN6
|
||||
MUdvK0FTemxZeGpPTUJiRkcrdWFCL2cKm7EEdZpYdoqQHgTNN1NkR+8xBzYj3ayx
|
||||
2zp9GAJgiEz+XaRkVi52JeDkEr2NuZR8WvcF0hvDMuFBslV6N9JZ+g==
|
||||
-----END AGE ENCRYPTED FILE-----
|
||||
recipient: age18q3lr2z4yeg2f86my42ym4hx0dvcwgjshmchyhdkgwvf4k37dsyq3mcjse
|
||||
- enc: |
|
||||
-----BEGIN AGE ENCRYPTED FILE-----
|
||||
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSAwWjFNOERYbTg4RWQxS3ox
|
||||
cDFycmFkaFRvaHg2aXQzTlk4QTVCYVc1ejNzCjR0bUJEc3ZiaHo2V21xYTlsMGgv
|
||||
ajNPelFUT3JucFRFaDBkeGtVS0trdFEKLS0tIEVtdFZsUHZKNkFlL0NHUnF2UG5s
|
||||
eEpDb1VLZ2dCVERQUXl5enhZYlZaR1UK8xnixMh5Xk5SkeHj30wPb5wbsKeWxh80
|
||||
yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A==
|
||||
-----END AGE ENCRYPTED FILE-----
|
||||
recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg
|
||||
lastmodified: "2026-11-23T20:45:18Z"
|
||||
mac: ENC[AES256_GCM,data:3Rm8olJtCErH+KGisvQENqwFhMF3Y9acXjrBHC7ot3ThRzT8Yo3X1RyxKXzyYzB6Yy2G3ua9yUtgQjydXgjQR1b6KY6ERmyu6H2S1IF/Ps4grYVZ6xEhJMDtjNKDvhtjhRM61eFByeYzJeHWD6K8dsxDcWUI2GKRRH7U8iG95Fo=,iv:/IY6iKamEEoi5vVLRGOmmPpyJte3amLfjVhYIDbMdBE=,tag:gT3RSrnwl0TH14LJvbiPlg==,type:str]
|
||||
unencrypted_suffix: _unencrypted
|
||||
version: 3.13.3
|
||||
@@ -0,0 +1,24 @@
|
||||
[project]
|
||||
name = "homelab-core"
|
||||
version = "0.1.0"
|
||||
description = "Homelab Core platform and orchestration"
|
||||
requires-python = ">=3.13"
|
||||
dependencies = [
|
||||
"pyyaml>=6.0",
|
||||
"pydantic>=2.0,<3.0",
|
||||
]
|
||||
|
||||
[tool.pyright]
|
||||
include = ["scripts"]
|
||||
extraPaths = ["scripts"]
|
||||
venvPath = "."
|
||||
venv = ".venv"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
# Automatically adds app modules and script hooks to the sys.venvPath
|
||||
pythonpath = [
|
||||
".",
|
||||
"scripts"
|
||||
]
|
||||
|
||||
|
||||
+81
-154
@@ -1,185 +1,112 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# appctl - Unified, Manifest-Driven Container Orchestrator
|
||||
# Discovers individual application repositories located in ~/Sites/*/
|
||||
# Injects global homelab secrets, per-app metadata from app.yaml, and monitors Git sync
|
||||
# Thin CLI wrapper delegating operational commands to homelab-appctl.service over UDS
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ENGINE="$SCRIPT_DIR/appctl_engine.py"
|
||||
ENV_FILE="/run/secrets/rendered/traefik-deployments.env"
|
||||
if [ ! -f "$ENV_FILE" ] && [ -f "/run/secrets/traefik-deployments.env" ]; then
|
||||
ENV_FILE="/run/secrets/traefik-deployments.env"
|
||||
if [ -z "$PYTHON_BIN" ]; then
|
||||
if [ -x "$SCRIPT_DIR/../.venv/bin/python3" ]; then
|
||||
PYTHON_BIN="$SCRIPT_DIR/../.venv/bin/python3"
|
||||
else
|
||||
PYTHON_BIN="python3"
|
||||
fi
|
||||
export SITES_DIR="${SITES_DIR:-$HOME/Sites}"
|
||||
export CORE_DIR="${CORE_DIR:-$HOME/Core}"
|
||||
export ENV_FILE
|
||||
fi
|
||||
SOCKET_PATH="${APPCTL_SOCKET_PATH:-/run/homelab/appctl.sock}"
|
||||
CLI_CLIENT="$SCRIPT_DIR/appctl_cli.py"
|
||||
|
||||
# Source global secrets/environment if available
|
||||
if [ -f "$ENV_FILE" ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1090
|
||||
source "$ENV_FILE"
|
||||
set +a
|
||||
# Fast-path local shell completion helpers
|
||||
case "${1:-}" in
|
||||
complete)
|
||||
exec "$PYTHON_BIN" "$ENGINE" complete "${@:2}"
|
||||
;;
|
||||
completion)
|
||||
cat <<'EOF'
|
||||
_appctl_completions() {
|
||||
local cur prev words cword
|
||||
if declare -F _init_completion >/dev/null 2>&1; then
|
||||
_init_completion || return
|
||||
else
|
||||
COMPREPLY=()
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
||||
words=("${COMP_WORDS[@]}")
|
||||
cword=$COMP_CWORD
|
||||
fi
|
||||
|
||||
# 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] List all applications with Git sync & container status"
|
||||
echo " info <service> Display comprehensive application & Git diagnostics"
|
||||
echo " up <service> Start/build a service stack"
|
||||
echo " down <service> Stop and remove a service stack"
|
||||
echo " restart <service> Restart a service stack"
|
||||
echo " update <service> Full stack update (git pull -> compose pull -> recreate)"
|
||||
echo " pull <service> Pull latest images and recreate service"
|
||||
echo " logs <service> Stream service logs"
|
||||
echo " config <service> Validate and view resolved compose configuration"
|
||||
echo " sync Synchronize Homepage dashboard services.yaml from app.yaml"
|
||||
}
|
||||
local commands="list status ssl info up down restart update pull logs config sync health resolve completion"
|
||||
|
||||
# Setup application environment based on resolved metadata
|
||||
setup_app_env() {
|
||||
local query="$1"
|
||||
local resolved_json
|
||||
resolved_json=$(python3 "$ENGINE" resolve "$query" 2>/dev/null || true)
|
||||
|
||||
if [ -z "$resolved_json" ]; then
|
||||
echo "❌ Error: Application '$query' not found under $SITES_DIR"
|
||||
exit 1
|
||||
if [ "$cword" -eq 1 ]; then
|
||||
COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Extract fields via python json
|
||||
APP_DIR=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d['dir_path'])" "$resolved_json")
|
||||
CANONICAL_NAME=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d['name'])" "$resolved_json")
|
||||
RESOLVED_DOMAIN=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d['domain'])" "$resolved_json")
|
||||
local command="${words[1]}"
|
||||
local appctl_cmd="${words[0]}"
|
||||
|
||||
# 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:-roadtotech.me}"
|
||||
|
||||
# 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.)
|
||||
eval "$(python3 -c "
|
||||
import json, sys
|
||||
d = json.loads(sys.argv[1])
|
||||
env_dict = d.get('env', {})
|
||||
for k, v in env_dict.items():
|
||||
if v != '' and v is not None:
|
||||
print(f'export {k}=\"{v}\"')
|
||||
" "$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
|
||||
case "$command" in
|
||||
list|status)
|
||||
python3 "$ENGINE" list "${@:2}"
|
||||
if [[ "$cur" == -* ]]; then
|
||||
COMPREPLY=( $(compgen -W "--fetch -f --core -c --ssl -s --all -a" -- "$cur") )
|
||||
fi
|
||||
;;
|
||||
ssl)
|
||||
if [[ "$cur" == -* ]]; then
|
||||
COMPREPLY=( $(compgen -W "--core -c --all -a" -- "$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
|
||||
;;
|
||||
info)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
python3 "$ENGINE" info "$APP"
|
||||
if [[ "$cur" == -* ]]; then
|
||||
COMPREPLY=( $(compgen -W "--ssl -s" -- "$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
|
||||
;;
|
||||
sync)
|
||||
python3 "$ENGINE" sync "${@:2}"
|
||||
;;
|
||||
up)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
echo "🚀 Starting $CANONICAL_NAME ($APP_DIR)..."
|
||||
cd "$APP_DIR" && docker compose up -d --remove-orphans "${@:3}"
|
||||
python3 "$ENGINE" sync >/dev/null 2>&1 || true
|
||||
;;
|
||||
down)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
echo "🛑 Stopping $CANONICAL_NAME ($APP_DIR)..."
|
||||
cd "$APP_DIR" && docker compose down "${@:3}"
|
||||
python3 "$ENGINE" sync >/dev/null 2>&1 || true
|
||||
;;
|
||||
restart)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
echo "🔄 Restarting $CANONICAL_NAME ($APP_DIR)..."
|
||||
cd "$APP_DIR" && docker compose down && docker compose up -d "${@:3}"
|
||||
python3 "$ENGINE" sync >/dev/null 2>&1 || true
|
||||
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 [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
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
|
||||
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
|
||||
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}"
|
||||
|
||||
python3 "$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"
|
||||
echo "📥 Pulling latest images for $CANONICAL_NAME..."
|
||||
cd "$APP_DIR" && docker compose pull && docker compose up -d --remove-orphans "${@:3}"
|
||||
down|restart|pull|logs|config)
|
||||
local services
|
||||
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
|
||||
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
|
||||
;;
|
||||
logs)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
cd "$APP_DIR" && docker compose logs -f "${@:3}"
|
||||
completion)
|
||||
COMPREPLY=( $(compgen -W "bash" -- "$cur") )
|
||||
;;
|
||||
config)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
cd "$APP_DIR" && docker compose config
|
||||
esac
|
||||
}
|
||||
complete -F _appctl_completions appctl
|
||||
EOF
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
show_help
|
||||
if [ ! -S "$SOCKET_PATH" ]; then
|
||||
echo "❌ Error: appctl daemon socket not found at $SOCKET_PATH. Ensure homelab-appctl.service is running." >&2
|
||||
exit 1
|
||||
fi
|
||||
exec "$PYTHON_BIN" "$CLI_CLIENT" "$@"
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,406 @@
|
||||
"""
|
||||
appctl_audit.py — Append-Only Audit Logger & Per-Target Lock Manager (P4 Slice 2)
|
||||
|
||||
Governs the audit telemetry and concurrency control for homelab-appctl.service:
|
||||
- Append-only JSONL audit writer adhering to RFC-compliant schema (mode 0600)
|
||||
- Pre-execution DISPATCHED fail-closed disk guard
|
||||
- Sensitive parameter and error redaction (*_KEY, *_SECRET, *_PASSWORD, etc.)
|
||||
- Non-blocking per-target flock context manager raising ConcurrentMutationError (409)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import UTC, datetime
|
||||
from enum import StrEnum
|
||||
from pathlib import Path
|
||||
from types import TracebackType
|
||||
from typing import Annotated, Any, Literal, Self
|
||||
|
||||
from appctl_contracts import StrictModel
|
||||
from pydantic import BeforeValidator, ConfigDict, Field, StrictInt, StrictStr
|
||||
|
||||
DEFAULT_AUDIT_LOG = Path("/var/log/homelab/appctl/audit.jsonl")
|
||||
DEFAULT_LOCK_DIR = Path("/var/lib/homelab/appctl/locks")
|
||||
|
||||
REDACT_KEY_PATTERNS = re.compile(
|
||||
r"^(?:.*_)?(?:KEY|SECRET|PASSWORD|TOKEN|PASS|HASH)$", re.IGNORECASE
|
||||
)
|
||||
|
||||
|
||||
class AuditPhase(StrEnum):
|
||||
"""Lifecycle phases for control plane audit events."""
|
||||
|
||||
DISPATCHED = "DISPATCHED"
|
||||
COMPLETED = "COMPLETED"
|
||||
FAILED = "FAILED"
|
||||
DENIED = "DENIED"
|
||||
|
||||
|
||||
def _coerce_phase(v: Any) -> Any:
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
return AuditPhase(v)
|
||||
except ValueError:
|
||||
return v
|
||||
return v
|
||||
|
||||
|
||||
FlexibleAuditPhase = Annotated[
|
||||
AuditPhase,
|
||||
BeforeValidator(_coerce_phase),
|
||||
]
|
||||
|
||||
|
||||
class PrincipalAudit(StrictModel):
|
||||
"""Authenticated principal details captured in audit records."""
|
||||
|
||||
identity: StrictStr
|
||||
role: StrictStr
|
||||
token_id: StrictStr | None = None
|
||||
auth_method: StrictStr
|
||||
|
||||
|
||||
class AuditResult(StrictModel):
|
||||
"""Execution outcome details captured in audit records."""
|
||||
|
||||
status: Literal["SUCCESS", "FAILED", "DENIED", "IN_PROGRESS"]
|
||||
exit_code: StrictInt | None = None
|
||||
duration_ms: StrictInt | None = None
|
||||
commit_sha: StrictStr | None = None
|
||||
error_code: StrictStr | None = None
|
||||
message: StrictStr | None = None
|
||||
|
||||
|
||||
class AuditEvent(StrictModel):
|
||||
"""RFC-compliant single-line JSONL audit event model (ADR-0002 / DEC-03)."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
audit_version: Literal["1.0"] = "1.0"
|
||||
event_id: StrictStr
|
||||
operation_id: StrictStr
|
||||
timestamp: StrictStr
|
||||
phase: FlexibleAuditPhase
|
||||
principal: PrincipalAudit
|
||||
action: StrictStr
|
||||
target: StrictStr | None = None
|
||||
transport: StrictStr
|
||||
origin: StrictStr
|
||||
client: StrictStr
|
||||
parameters: dict[str, Any] = Field(default_factory=dict)
|
||||
result: AuditResult | None = None
|
||||
|
||||
|
||||
class AuditPersistenceError(Exception):
|
||||
"""Raised when an audit record cannot be persisted or flushed to disk."""
|
||||
|
||||
|
||||
class ConcurrentMutationError(Exception):
|
||||
"""Raised when a per-target operation lock cannot be acquired (409 Conflict)."""
|
||||
|
||||
def __init__(self, target: str, message: str | None = None) -> None:
|
||||
self.target = target
|
||||
msg = (
|
||||
message or f"Operation on target '{target}' is locked by a concurrent task."
|
||||
)
|
||||
super().__init__(msg)
|
||||
|
||||
|
||||
def redact_sensitive_data(val: Any) -> Any:
|
||||
"""
|
||||
Recursively redact values whose dictionary keys match sensitive patterns
|
||||
(*_KEY, *_SECRET, *_PASSWORD, *_TOKEN, *_PASS, *_HASH).
|
||||
"""
|
||||
if isinstance(val, dict):
|
||||
return {
|
||||
k: "[REDACTED]"
|
||||
if REDACT_KEY_PATTERNS.match(str(k))
|
||||
else redact_sensitive_data(v)
|
||||
for k, v in val.items()
|
||||
}
|
||||
if isinstance(val, list):
|
||||
return [redact_sensitive_data(v) for v in val]
|
||||
return val
|
||||
|
||||
|
||||
def generate_event_id() -> str:
|
||||
"""Generate a unique event identifier."""
|
||||
return f"evt_{secrets.token_hex(6)}"
|
||||
|
||||
|
||||
def generate_operation_id() -> str:
|
||||
"""Generate a unique operation identifier."""
|
||||
return f"op_{secrets.token_hex(6)}"
|
||||
|
||||
|
||||
def current_iso_timestamp() -> str:
|
||||
"""Current UTC timestamp formatted as ISO 8601 with millisecond precision."""
|
||||
now = datetime.now(UTC)
|
||||
return now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
|
||||
|
||||
|
||||
class AuditLogger:
|
||||
"""
|
||||
Append-only thread-safe audit logger writing single-line JSONL records.
|
||||
Enforces mode 0600 on the log file and provides a fail-closed pre-execution
|
||||
DISPATCHED disk guard.
|
||||
"""
|
||||
|
||||
def __init__(self, log_path: Path | str | None = None) -> None:
|
||||
if log_path is not None:
|
||||
self.log_path = Path(log_path)
|
||||
elif "APPCTL_AUDIT_LOG" in os.environ:
|
||||
self.log_path = Path(os.environ["APPCTL_AUDIT_LOG"])
|
||||
else:
|
||||
self.log_path = DEFAULT_AUDIT_LOG
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def _ensure_log_file(self) -> None:
|
||||
"""Ensure parent directories exist and file is initialized with mode 0600."""
|
||||
self.log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not self.log_path.exists():
|
||||
fd = os.open(
|
||||
self.log_path,
|
||||
os.O_WRONLY | os.O_CREAT | os.O_APPEND,
|
||||
0o600,
|
||||
)
|
||||
os.close(fd)
|
||||
|
||||
def emit_event(self, event: AuditEvent) -> None:
|
||||
"""
|
||||
Append an audit event as a single JSON line to the audit log.
|
||||
Flushes and fsyncs to ensure durability. Raises AuditPersistenceError on failure.
|
||||
"""
|
||||
with self._lock:
|
||||
try:
|
||||
self._ensure_log_file()
|
||||
line = event.model_dump_json() + "\n"
|
||||
fd = os.open(
|
||||
self.log_path,
|
||||
os.O_WRONLY | os.O_APPEND,
|
||||
0o600,
|
||||
)
|
||||
try:
|
||||
os.write(fd, line.encode("utf-8"))
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
except OSError as err:
|
||||
raise AuditPersistenceError(
|
||||
f"Failed to persist audit event '{event.event_id}': {err}"
|
||||
) from err
|
||||
|
||||
def log_dispatched(
|
||||
self,
|
||||
operation_id: str,
|
||||
principal: PrincipalAudit,
|
||||
action: str,
|
||||
target: str | None,
|
||||
transport: str,
|
||||
origin: str,
|
||||
client: str,
|
||||
parameters: dict[str, Any],
|
||||
) -> AuditEvent:
|
||||
"""
|
||||
Fail-closed pre-execution disk guard: logs DISPATCHED phase before any
|
||||
subprocess or filesystem mutation begins. Raises AuditPersistenceError if disk write fails.
|
||||
"""
|
||||
clean_params = redact_sensitive_data(parameters)
|
||||
event = AuditEvent(
|
||||
event_id=generate_event_id(),
|
||||
operation_id=operation_id,
|
||||
timestamp=current_iso_timestamp(),
|
||||
phase=AuditPhase.DISPATCHED,
|
||||
principal=principal,
|
||||
action=action,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=clean_params,
|
||||
result=AuditResult(status="IN_PROGRESS"),
|
||||
)
|
||||
self.emit_event(event)
|
||||
return event
|
||||
|
||||
def log_completed(
|
||||
self,
|
||||
operation_id: str,
|
||||
principal: PrincipalAudit,
|
||||
action: str,
|
||||
target: str | None,
|
||||
transport: str,
|
||||
origin: str,
|
||||
client: str,
|
||||
parameters: dict[str, Any],
|
||||
duration_ms: int,
|
||||
commit_sha: str | None = None,
|
||||
message: str | None = None,
|
||||
) -> AuditEvent:
|
||||
"""Log COMPLETED phase upon clean operation termination."""
|
||||
clean_params = redact_sensitive_data(parameters)
|
||||
event = AuditEvent(
|
||||
event_id=generate_event_id(),
|
||||
operation_id=operation_id,
|
||||
timestamp=current_iso_timestamp(),
|
||||
phase=AuditPhase.COMPLETED,
|
||||
principal=principal,
|
||||
action=action,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=clean_params,
|
||||
result=AuditResult(
|
||||
status="SUCCESS",
|
||||
exit_code=0,
|
||||
duration_ms=duration_ms,
|
||||
commit_sha=commit_sha,
|
||||
error_code=None,
|
||||
message=message or "Operation completed successfully",
|
||||
),
|
||||
)
|
||||
self.emit_event(event)
|
||||
return event
|
||||
|
||||
def log_failed(
|
||||
self,
|
||||
operation_id: str,
|
||||
principal: PrincipalAudit,
|
||||
action: str,
|
||||
target: str | None,
|
||||
transport: str,
|
||||
origin: str,
|
||||
client: str,
|
||||
parameters: dict[str, Any],
|
||||
duration_ms: int | None = None,
|
||||
exit_code: int | None = None,
|
||||
error_code: str | None = None,
|
||||
message: str | None = None,
|
||||
) -> AuditEvent:
|
||||
"""Log FAILED phase when validation or execution fails."""
|
||||
clean_params = redact_sensitive_data(parameters)
|
||||
clean_msg = redact_sensitive_data(message) if message else None
|
||||
event = AuditEvent(
|
||||
event_id=generate_event_id(),
|
||||
operation_id=operation_id,
|
||||
timestamp=current_iso_timestamp(),
|
||||
phase=AuditPhase.FAILED,
|
||||
principal=principal,
|
||||
action=action,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=clean_params,
|
||||
result=AuditResult(
|
||||
status="FAILED",
|
||||
exit_code=exit_code,
|
||||
duration_ms=duration_ms,
|
||||
error_code=error_code,
|
||||
message=clean_msg,
|
||||
),
|
||||
)
|
||||
self.emit_event(event)
|
||||
return event
|
||||
|
||||
def log_denied(
|
||||
self,
|
||||
operation_id: str,
|
||||
principal: PrincipalAudit,
|
||||
action: str,
|
||||
target: str | None,
|
||||
transport: str,
|
||||
origin: str,
|
||||
client: str,
|
||||
parameters: dict[str, Any],
|
||||
error_code: str,
|
||||
message: str,
|
||||
) -> AuditEvent:
|
||||
"""Log DENIED phase when authentication, RBAC, or concurrency lock rejects request."""
|
||||
clean_params = redact_sensitive_data(parameters)
|
||||
event = AuditEvent(
|
||||
event_id=generate_event_id(),
|
||||
operation_id=operation_id,
|
||||
timestamp=current_iso_timestamp(),
|
||||
phase=AuditPhase.DENIED,
|
||||
principal=principal,
|
||||
action=action,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=clean_params,
|
||||
result=AuditResult(
|
||||
status="DENIED",
|
||||
error_code=error_code,
|
||||
message=message,
|
||||
),
|
||||
)
|
||||
self.emit_event(event)
|
||||
return event
|
||||
|
||||
|
||||
class TargetLock:
|
||||
"""Context manager acquiring a non-blocking per-target flock."""
|
||||
|
||||
def __init__(self, lock_path: Path, target: str) -> None:
|
||||
self.lock_path = lock_path
|
||||
self.target = target
|
||||
self._fd: int | None = None
|
||||
|
||||
def __enter__(self) -> Self:
|
||||
self.lock_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd = os.open(
|
||||
self.lock_path,
|
||||
os.O_RDWR | os.O_CREAT,
|
||||
0o600,
|
||||
)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except (BlockingIOError, OSError) as err:
|
||||
os.close(fd)
|
||||
raise ConcurrentMutationError(self.target) from err
|
||||
self._fd = fd
|
||||
return self
|
||||
|
||||
def __exit__(
|
||||
self,
|
||||
exc_type: type[BaseException] | None,
|
||||
exc_val: BaseException | None,
|
||||
exc_tb: TracebackType | None,
|
||||
) -> None:
|
||||
if self._fd is not None:
|
||||
try:
|
||||
fcntl.flock(self._fd, fcntl.LOCK_UN)
|
||||
finally:
|
||||
os.close(self._fd)
|
||||
self._fd = None
|
||||
|
||||
|
||||
class TargetLockManager:
|
||||
"""Manages operational per-target locks under /var/lib/homelab/appctl/locks."""
|
||||
|
||||
def __init__(self, lock_dir: Path | str | None = None) -> None:
|
||||
if lock_dir is not None:
|
||||
self.lock_dir = Path(lock_dir)
|
||||
elif "APPCTL_LOCK_DIR" in os.environ:
|
||||
self.lock_dir = Path(os.environ["APPCTL_LOCK_DIR"])
|
||||
else:
|
||||
self.lock_dir = DEFAULT_LOCK_DIR
|
||||
|
||||
def lock_target(self, target: str) -> TargetLock:
|
||||
"""Return a non-blocking flock context manager for a workload target."""
|
||||
clean_target = re.sub(r"[^a-zA-Z0-9._-]", "_", target)
|
||||
lock_path = self.lock_dir / f"{clean_target}.lock"
|
||||
return TargetLock(lock_path, target)
|
||||
|
||||
def homepage_sync_lock(self) -> TargetLock:
|
||||
"""Return a non-blocking flock context manager for homepage compilation."""
|
||||
lock_path = self.lock_dir / "_homepage_sync.lock"
|
||||
return TargetLock(lock_path, "_homepage_sync")
|
||||
@@ -0,0 +1,398 @@
|
||||
"""
|
||||
appctl_auth.py — Authentication & 3-Role RBAC Policy Enforcement (P4 Slice 3)
|
||||
|
||||
Implements the zero-trust authorization pipeline for homelab-appctl.service:
|
||||
- SOPS-managed SHA-256 Bearer token store loader (mode 0400 check, constant-time compare)
|
||||
- Unix domain socket SO_PEERCRED fallback to homelab-viewer for zero-friction local reads
|
||||
- Mandatory Bearer tokens for all network (HTTP) operations and all mutations / sensitive reads
|
||||
- 3-role RBAC enforcement (homelab-admin, homelab-operator, homelab-viewer)
|
||||
- Workload scope gating against ~/Workloads/deployments.yaml (or HOMELAB_DEPLOYMENTS_FILE / WORKLOADS_DIR override) for homelab-operator
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
from enum import StrEnum
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from appctl_contracts import (
|
||||
ErrorCode,
|
||||
OperationType,
|
||||
StrictModel,
|
||||
)
|
||||
from pydantic import BeforeValidator, ConfigDict, Field, StrictStr
|
||||
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
yaml = None # type: ignore[assignment]
|
||||
|
||||
DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json")
|
||||
DEFAULT_DEPLOYMENTS_FILE = (
|
||||
Path(
|
||||
os.environ.get("WORKLOADS_DIR")
|
||||
or os.environ.get("SITES_DIR")
|
||||
or os.path.expanduser("~/Workloads")
|
||||
)
|
||||
/ "deployments.yaml"
|
||||
)
|
||||
|
||||
CORE_TARGETS: frozenset[str] = frozenset(
|
||||
{
|
||||
"core",
|
||||
"traefik",
|
||||
"authelia",
|
||||
"lldap",
|
||||
"stalwart",
|
||||
"dozzle",
|
||||
"socket-proxy",
|
||||
"homepage",
|
||||
"diun",
|
||||
"watchtower",
|
||||
}
|
||||
)
|
||||
|
||||
SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset(
|
||||
{
|
||||
OperationType.WORKLOAD_CONFIG,
|
||||
OperationType.WORKLOAD_LOGS,
|
||||
}
|
||||
)
|
||||
|
||||
MUTATING_OPERATIONS: frozenset[OperationType] = frozenset(
|
||||
{
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_STOP,
|
||||
OperationType.WORKLOAD_RESTART,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_PULL,
|
||||
OperationType.PLATFORM_SYNC_HOMEPAGE,
|
||||
}
|
||||
)
|
||||
|
||||
READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset(
|
||||
{
|
||||
OperationType.WORKLOAD_LIST,
|
||||
OperationType.WORKLOAD_GET,
|
||||
OperationType.WORKLOAD_RESOLVE,
|
||||
OperationType.PLATFORM_SSL,
|
||||
OperationType.PLATFORM_HEALTH,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class Role(StrEnum):
|
||||
"""Hierarchical authorization roles for homelab-appctl.service."""
|
||||
|
||||
ADMIN = "homelab-admin"
|
||||
OPERATOR = "homelab-operator"
|
||||
VIEWER = "homelab-viewer"
|
||||
|
||||
|
||||
def _coerce_role(v: Any) -> Any:
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
return Role(v)
|
||||
except ValueError:
|
||||
return v
|
||||
return v
|
||||
|
||||
|
||||
FlexibleRole = Annotated[
|
||||
Role,
|
||||
BeforeValidator(_coerce_role),
|
||||
]
|
||||
|
||||
|
||||
class Principal(StrictModel):
|
||||
"""Authenticated caller identity and operational role."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
identity: StrictStr
|
||||
role: FlexibleRole
|
||||
token_id: StrictStr | None = None
|
||||
auth_method: Literal["bearer_token", "unix_peercred"]
|
||||
|
||||
|
||||
class TokenDescriptor(StrictModel):
|
||||
"""Internal model for token entries in SOPS tokens.json store."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
token_id: StrictStr
|
||||
identity: StrictStr
|
||||
role: FlexibleRole
|
||||
sha256: Annotated[StrictStr, Field(pattern=r"^[0-9a-fA-F]{64}$")]
|
||||
|
||||
|
||||
class AuthenticationError(Exception):
|
||||
"""Raised when authentication fails (401 Unauthorized)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Authentication required",
|
||||
code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.http_status = 401
|
||||
|
||||
|
||||
class AuthorizationError(Exception):
|
||||
"""Raised when an authenticated principal lacks required role or scope (403 Forbidden)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Permission denied",
|
||||
code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.http_status = 403
|
||||
|
||||
|
||||
class TokenStore:
|
||||
"""Loads and validates SHA-256 Bearer tokens from a mode 0400 store."""
|
||||
|
||||
def __init__(self, tokens_path: Path | str | None = None) -> None:
|
||||
if tokens_path is not None:
|
||||
self.tokens_path = Path(tokens_path)
|
||||
elif "APPCTL_TOKENS_FILE" in os.environ:
|
||||
self.tokens_path = Path(os.environ["APPCTL_TOKENS_FILE"])
|
||||
else:
|
||||
self.tokens_path = DEFAULT_TOKENS_FILE
|
||||
|
||||
def _verify_permissions(self) -> None:
|
||||
"""Enforce strict 0400 file mode: readable only by owner, no write/exec, no group/world."""
|
||||
if not self.tokens_path.is_file():
|
||||
raise AuthenticationError(
|
||||
f"Token store '{self.tokens_path}' not found",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
# Check permissions: reject if group/world readable or writable (must be 0400)
|
||||
mode = stat.S_IMODE(self.tokens_path.stat().st_mode)
|
||||
if (mode & 0o077) != 0 or (mode & 0o200) != 0:
|
||||
raise AuthenticationError(
|
||||
f"Token store '{self.tokens_path}' has insecure mode {oct(mode)}; mode 0400 required",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
|
||||
def load_tokens(self) -> list[TokenDescriptor]:
|
||||
"""Load and parse token descriptors from the token store."""
|
||||
self._verify_permissions()
|
||||
try:
|
||||
content = self.tokens_path.read_text(encoding="utf-8")
|
||||
data = json.loads(content)
|
||||
if not isinstance(data, list):
|
||||
raise TypeError("Tokens payload must be an array of token descriptors")
|
||||
return [TokenDescriptor.model_validate(item) for item in data]
|
||||
except (OSError, json.JSONDecodeError, ValueError, TypeError) as err:
|
||||
raise AuthenticationError(
|
||||
f"Failed to load token store '{self.tokens_path}': {err}",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
) from err
|
||||
|
||||
def authenticate_bearer(self, secret: str) -> Principal:
|
||||
"""
|
||||
Hash secret with SHA-256 and look up against stored token descriptors using
|
||||
constant-time hmac.compare_digest.
|
||||
"""
|
||||
if not secret:
|
||||
raise AuthenticationError(
|
||||
"Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED
|
||||
)
|
||||
|
||||
secret_hash = hashlib.sha256(secret.encode("utf-8")).hexdigest()
|
||||
tokens = self.load_tokens()
|
||||
|
||||
for token in tokens:
|
||||
if hmac.compare_digest(secret_hash, token.sha256.lower()):
|
||||
return Principal(
|
||||
identity=token.identity,
|
||||
role=token.role,
|
||||
token_id=token.token_id,
|
||||
auth_method="bearer_token",
|
||||
)
|
||||
|
||||
raise AuthenticationError(
|
||||
"Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED
|
||||
)
|
||||
|
||||
|
||||
def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[str]:
|
||||
"""
|
||||
Load admitted repository names and aliases from ~/Workloads/deployments.yaml
|
||||
(or HOMELAB_DEPLOYMENTS_FILE / WORKLOADS_DIR override).
|
||||
Fails closed (empty set) if registry is missing or malformed.
|
||||
"""
|
||||
if deployments_path is not None:
|
||||
reg_file = Path(deployments_path)
|
||||
elif env_deploy := os.environ.get("HOMELAB_DEPLOYMENTS_FILE"):
|
||||
reg_file = Path(env_deploy)
|
||||
elif env_workloads := (
|
||||
os.environ.get("WORKLOADS_DIR") or os.environ.get("SITES_DIR")
|
||||
):
|
||||
reg_file = Path(env_workloads) / "deployments.yaml"
|
||||
else:
|
||||
reg_file = DEFAULT_DEPLOYMENTS_FILE
|
||||
|
||||
if not reg_file.is_file():
|
||||
return set()
|
||||
|
||||
yaml_errors = (yaml.YAMLError,) if yaml is not None else ()
|
||||
try:
|
||||
content = reg_file.read_text(encoding="utf-8")
|
||||
if yaml is not None:
|
||||
data = yaml.safe_load(content)
|
||||
else:
|
||||
data = json.loads(content)
|
||||
if not isinstance(data, dict):
|
||||
return set()
|
||||
|
||||
admitted: set[str] = set()
|
||||
repos = data.get("repositories", {})
|
||||
if isinstance(repos, dict):
|
||||
for name, entry in repos.items():
|
||||
admitted.add(name)
|
||||
if isinstance(entry, dict):
|
||||
aliases = entry.get("aliases", [])
|
||||
if isinstance(aliases, list):
|
||||
for alias in aliases:
|
||||
if isinstance(alias, str) and alias.strip():
|
||||
admitted.add(alias.strip())
|
||||
return admitted
|
||||
except (
|
||||
OSError,
|
||||
UnicodeDecodeError,
|
||||
ValueError,
|
||||
json.JSONDecodeError,
|
||||
*yaml_errors,
|
||||
):
|
||||
return set()
|
||||
|
||||
|
||||
def authenticate_request(
|
||||
transport: Literal["unix_socket", "http"],
|
||||
auth_header: str | None,
|
||||
peer_uid: int | None = None,
|
||||
token_store: TokenStore | None = None,
|
||||
) -> Principal:
|
||||
"""
|
||||
Authenticate an incoming request across transports:
|
||||
- If Authorization header present: parses Bearer secret and verifies against TokenStore.
|
||||
- If Authorization header missing over HTTP: fails closed with 401 ERR_AUTH_REQUIRED.
|
||||
- If Authorization header missing over Unix socket: falls back to homelab-viewer with peer_uid.
|
||||
"""
|
||||
store = token_store or TokenStore()
|
||||
|
||||
if auth_header is not None:
|
||||
header_val = auth_header.strip()
|
||||
if not header_val.startswith("Bearer "):
|
||||
raise AuthenticationError(
|
||||
"Malformed Authorization header: must start with 'Bearer '",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
secret = header_val[7:].strip()
|
||||
if not secret:
|
||||
raise AuthenticationError(
|
||||
"Missing token secret in Authorization header",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
return store.authenticate_bearer(secret)
|
||||
|
||||
# Missing Authorization header
|
||||
if transport == "unix_socket":
|
||||
if peer_uid is not None:
|
||||
return Principal(
|
||||
identity=f"unix_uid_{peer_uid}",
|
||||
role=Role.VIEWER,
|
||||
token_id=None,
|
||||
auth_method="unix_peercred",
|
||||
)
|
||||
raise AuthenticationError(
|
||||
"Missing peer credentials over Unix socket",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
|
||||
# HTTP transport requires Bearer token strictly
|
||||
raise AuthenticationError(
|
||||
"Bearer token required over network transport",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
|
||||
|
||||
def enforce_rbac(
|
||||
principal: Principal,
|
||||
operation: OperationType,
|
||||
target: str | None = None,
|
||||
admitted_workloads: set[str] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Enforce 3-role RBAC policy (homelab-admin, homelab-operator, homelab-viewer).
|
||||
Raises AuthorizationError (403) on violation.
|
||||
"""
|
||||
# 1. homelab-admin has unrestricted access across all operations and targets
|
||||
if principal.role == Role.ADMIN:
|
||||
return
|
||||
|
||||
# 2. homelab-operator:
|
||||
if principal.role == Role.OPERATOR:
|
||||
# Platform homepage sync allowed
|
||||
if operation == OperationType.PLATFORM_SYNC_HOMEPAGE:
|
||||
return
|
||||
|
||||
# Target checks for operations targeting infrastructure
|
||||
if target is not None and target.strip().lower() in CORE_TARGETS:
|
||||
raise AuthorizationError(
|
||||
f"Role 'homelab-operator' is not permitted to target core service '{target}'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
|
||||
# Non-sensitive reads are permitted
|
||||
if operation in READ_ONLY_OPERATIONS:
|
||||
return
|
||||
|
||||
# Sensitive reads and mutations must target an admitted workload from deployments.yaml
|
||||
if operation in SENSITIVE_OPERATIONS or operation in MUTATING_OPERATIONS:
|
||||
if not target:
|
||||
raise AuthorizationError(
|
||||
f"Operation '{operation.value}' requires an explicit workload target",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
registry = (
|
||||
admitted_workloads
|
||||
if admitted_workloads is not None
|
||||
else load_admitted_workloads()
|
||||
)
|
||||
if target not in registry:
|
||||
raise AuthorizationError(
|
||||
f"Target '{target}' is not registered in deployments.yaml for role 'homelab-operator'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
return
|
||||
|
||||
# 3. homelab-viewer:
|
||||
if principal.role == Role.VIEWER:
|
||||
if operation in MUTATING_OPERATIONS:
|
||||
raise AuthorizationError(
|
||||
f"Role 'homelab-viewer' is not permitted to execute mutating operation '{operation.value}'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
if operation in SENSITIVE_OPERATIONS:
|
||||
raise AuthorizationError(
|
||||
f"Role 'homelab-viewer' is not permitted to access sensitive operation '{operation.value}'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
if operation in READ_ONLY_OPERATIONS:
|
||||
return
|
||||
|
||||
raise AuthorizationError(
|
||||
f"Operation '{operation.value}' denied for role '{principal.role.value}'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
Executable
+412
@@ -0,0 +1,412 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
appctl_cli.py — Thin HTTP/1.1 Unix Domain Socket Client for homelab-appctl
|
||||
|
||||
Dispatches CLI commands to the control plane daemon over /run/homelab/appctl.sock.
|
||||
Supports local peercred viewer fallback, Bearer token authentication, and formatted output.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from appctl_contracts import (
|
||||
OperationRequest,
|
||||
OperationResponse,
|
||||
OperationType,
|
||||
)
|
||||
from appctl_daemon import (
|
||||
DEFAULT_SOCKET_PATH,
|
||||
send_daemon_request,
|
||||
)
|
||||
|
||||
|
||||
def resolve_token(cli_token: str | None = None) -> str | None:
|
||||
"""Resolve Bearer token from CLI flag, environment, or user token files."""
|
||||
if cli_token:
|
||||
return cli_token.strip()
|
||||
|
||||
if "APPCTL_TOKEN" in os.environ:
|
||||
return os.environ["APPCTL_TOKEN"].strip()
|
||||
|
||||
token_candidates = [
|
||||
Path.home() / ".config/homelab/token",
|
||||
Path("/run/secrets/appctl/token"),
|
||||
]
|
||||
for path in token_candidates:
|
||||
if path.is_file():
|
||||
try:
|
||||
return path.read_text(encoding="utf-8").strip()
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _format_workload_table(workloads: list[dict[str, Any]]) -> str:
|
||||
"""Format a list of workload dictionaries into a human-readable tabular display."""
|
||||
if not workloads:
|
||||
return "ℹ️ No workloads found."
|
||||
|
||||
has_ssl = any("ssl" in w and isinstance(w["ssl"], dict) for w in workloads)
|
||||
lines: list[str] = []
|
||||
|
||||
if has_ssl:
|
||||
lines.append(
|
||||
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
|
||||
)
|
||||
lines.append(
|
||||
f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
|
||||
)
|
||||
else:
|
||||
lines.append(
|
||||
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN'}"
|
||||
)
|
||||
lines.append(
|
||||
f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------'}"
|
||||
)
|
||||
|
||||
for w in workloads:
|
||||
name = str(w.get("name") or "-")
|
||||
domain = str(w.get("domain") or "-")
|
||||
status = str(w.get("status") or "-")
|
||||
|
||||
if w.get("manifest_error"):
|
||||
dep = "⚠️ Manifest Error"
|
||||
prov = "⚠️ Invalid Manifest"
|
||||
elif "deployment_status" in w:
|
||||
dep = str(w["deployment_status"])
|
||||
prov = str(w.get("provenance_status") or "-")
|
||||
else:
|
||||
dep = "-"
|
||||
prov = str(w.get("provenance_status") or "-")
|
||||
|
||||
if has_ssl:
|
||||
ssl_info = w.get("ssl")
|
||||
cert_status = (
|
||||
str(ssl_info.get("status", "-"))
|
||||
if isinstance(ssl_info, dict)
|
||||
else "-"
|
||||
)
|
||||
lines.append(
|
||||
f"{name:<16} {dep:<22} {prov:<22} {status:<15} {domain:<28} {cert_status}"
|
||||
)
|
||||
else:
|
||||
lines.append(
|
||||
f"{name:<16} {dep:<22} {prov:<24} {status:<15} {domain}"
|
||||
)
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _format_workload_info(workload: dict[str, Any]) -> str:
|
||||
"""Format a single workload metadata dictionary for `appctl info`."""
|
||||
name = workload.get("name", "unknown")
|
||||
w_type = workload.get("type", workload.get("app_type", "app"))
|
||||
header = (
|
||||
f"ℹ️ Core Infrastructure Service: {name}"
|
||||
if w_type in ("core", "core_service")
|
||||
else f"ℹ️ Workload Overview: {name}"
|
||||
)
|
||||
lines = [
|
||||
header,
|
||||
"-" * 50,
|
||||
f"Directory: {workload.get('dir_path', '-')}",
|
||||
f"Domain: {workload.get('domain', '-')}",
|
||||
f"Type: {w_type}",
|
||||
f"Description: {workload.get('description', '-')}",
|
||||
]
|
||||
if workload.get("container"):
|
||||
lines.append(f"Container: {workload['container']}")
|
||||
aliases = workload.get("aliases")
|
||||
if isinstance(aliases, list) and aliases:
|
||||
lines.append(f"Aliases: {', '.join(str(a) for a in aliases)}")
|
||||
networks = workload.get("networks")
|
||||
if isinstance(networks, list) and networks:
|
||||
lines.append(f"Networks: {', '.join(str(n) for n in networks)}")
|
||||
if "auth" in workload:
|
||||
lines.append(f"Auth Protected: {workload['auth']}")
|
||||
if "visible" in workload:
|
||||
lines.append(f"Dashboard: {'Visible' if workload['visible'] else 'Hidden'}")
|
||||
source = workload.get("source")
|
||||
if isinstance(source, dict):
|
||||
lines.append(f"Source URL: {source.get('url', '-')}")
|
||||
lines.append(f"Target Ref: {source.get('ref', '-')}")
|
||||
if workload.get("manifest_error"):
|
||||
lines.append(f"\n⚠️ Manifest Validation Error:\n {workload['manifest_error']}")
|
||||
ssl_info = workload.get("ssl")
|
||||
if isinstance(ssl_info, dict):
|
||||
lines.append("\n🔒 SSL/TLS Certificate:")
|
||||
lines.append(f" Status: {ssl_info.get('status', '-')}")
|
||||
lines.append(f" Issuer: {ssl_info.get('issuer', '-')}")
|
||||
lines.append(f" Expiration: {ssl_info.get('formatted_expiry', '-')}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _format_ssl_info(ssl_info: dict[str, Any]) -> str:
|
||||
"""Format SSL certificate details for `appctl ssl`."""
|
||||
domain = ssl_info.get("domain", "-")
|
||||
lines = [
|
||||
f"🔒 SSL/TLS Certificate: {domain}",
|
||||
"-" * 50,
|
||||
f"Domain: {domain}",
|
||||
f"Status: {ssl_info.get('status', '-')}",
|
||||
f"Issuer: {ssl_info.get('issuer', '-')}",
|
||||
f"Subject: {ssl_info.get('subject', '-')}",
|
||||
f"Expiration: {ssl_info.get('not_after', '-')}",
|
||||
]
|
||||
if ssl_info.get("days_remaining") is not None:
|
||||
lines.append(
|
||||
f"Days Remaining: {ssl_info['days_remaining']} days ({ssl_info.get('formatted_expiry', '-')})"
|
||||
)
|
||||
if ssl_info.get("error"):
|
||||
lines.append(f"Details/Error: {ssl_info['error']}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def format_response(resp: OperationResponse, raw_json: bool = False) -> str:
|
||||
"""Format an OperationResponse for human-friendly terminal display or JSON output."""
|
||||
if raw_json:
|
||||
return resp.model_dump_json(indent=2, exclude_none=True)
|
||||
|
||||
if not resp.success:
|
||||
err_msg = resp.error.message if resp.error else "Unknown error"
|
||||
code = f" [{resp.error.code.value}]" if resp.error else ""
|
||||
return f"❌ Error{code}: {err_msg}"
|
||||
|
||||
# If the engine produced terminal output (e.g. logs, compose config, status table), show it
|
||||
if resp.output:
|
||||
return resp.output
|
||||
|
||||
if resp.result:
|
||||
if "workloads" in resp.result and isinstance(resp.result["workloads"], list):
|
||||
return _format_workload_table(resp.result["workloads"])
|
||||
if resp.operation == OperationType.WORKLOAD_RESOLVE and "workload" in resp.result:
|
||||
return json.dumps(resp.result["workload"])
|
||||
if "workload" in resp.result and isinstance(resp.result["workload"], dict):
|
||||
return _format_workload_info(resp.result["workload"])
|
||||
if "ssl" in resp.result and isinstance(resp.result["ssl"], dict):
|
||||
return _format_ssl_info(resp.result["ssl"])
|
||||
if "message" in resp.result and len(resp.result) <= 3:
|
||||
return f"✨ {resp.result['message']}"
|
||||
return json.dumps(resp.result, indent=2)
|
||||
|
||||
return f"✨ Operation '{resp.operation}' succeeded."
|
||||
|
||||
|
||||
def run_cli(argv: list[str] | None = None) -> int:
|
||||
"""Main CLI command parser and dispatcher."""
|
||||
common_parser = argparse.ArgumentParser(add_help=False)
|
||||
common_parser.add_argument(
|
||||
"--socket",
|
||||
type=Path,
|
||||
default=None,
|
||||
help="Path to appctl Unix domain socket",
|
||||
)
|
||||
common_parser.add_argument(
|
||||
"--token",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Bearer token secret (overrides APPCTL_TOKEN and token files)",
|
||||
)
|
||||
common_parser.add_argument(
|
||||
"--json",
|
||||
action="store_true",
|
||||
help="Output raw JSON response",
|
||||
)
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="appctl",
|
||||
description="Homelab Unified Control Plane Client",
|
||||
parents=[common_parser],
|
||||
)
|
||||
|
||||
subparsers = parser.add_subparsers(dest="command", help="Operational commands")
|
||||
|
||||
# list / status
|
||||
list_p = subparsers.add_parser("list", aliases=["status"], parents=[common_parser], help="List workloads")
|
||||
list_p.add_argument("--core", "-c", "--all", "-a", action="store_true", dest="core", help="Include core platform services")
|
||||
list_p.add_argument("--fetch", "-f", action="store_true", help="Fetch remote git revisions")
|
||||
list_p.add_argument("--ssl", "-s", action="store_true", help="Check SSL certificate status")
|
||||
|
||||
# info
|
||||
info_p = subparsers.add_parser("info", parents=[common_parser], help="Get workload metadata")
|
||||
info_p.add_argument("target", help="Workload name")
|
||||
info_p.add_argument("--ssl", "-s", action="store_true", help="Check SSL certificate status")
|
||||
|
||||
# resolve
|
||||
resolve_p = subparsers.add_parser("resolve", parents=[common_parser], help="Resolve target metadata")
|
||||
resolve_p.add_argument("target", help="Workload or core target")
|
||||
|
||||
# ssl
|
||||
ssl_p = subparsers.add_parser("ssl", parents=[common_parser], help="Inspect platform SSL certificates")
|
||||
ssl_p.add_argument("target", nargs="?", default=None, help="Target workload or platform")
|
||||
|
||||
# health
|
||||
subparsers.add_parser("health", parents=[common_parser], help="Check control plane daemon health")
|
||||
|
||||
# up / deploy
|
||||
up_p = subparsers.add_parser("up", aliases=["deploy"], parents=[common_parser], help="Deploy workload")
|
||||
up_p.add_argument("target", help="Workload or core target")
|
||||
up_p.add_argument("--build", action="store_true", help="Rebuild container images")
|
||||
up_p.add_argument("--no-cache", action="store_true", help="Rebuild container images without cache")
|
||||
|
||||
# down / stop
|
||||
down_p = subparsers.add_parser("down", aliases=["stop"], parents=[common_parser], help="Stop workload")
|
||||
down_p.add_argument("target", help="Workload or core target")
|
||||
|
||||
# restart
|
||||
restart_p = subparsers.add_parser("restart", parents=[common_parser], help="Restart workload")
|
||||
restart_p.add_argument("target", help="Workload or core target")
|
||||
|
||||
# update
|
||||
update_p = subparsers.add_parser("update", parents=[common_parser], help="Update workload revision")
|
||||
update_p.add_argument("target", help="Workload target")
|
||||
update_p.add_argument("--branch", default=None, help="Expected git branch")
|
||||
update_p.add_argument("--build", action="store_true", help="Rebuild container images")
|
||||
update_p.add_argument("--no-cache", action="store_true", help="Rebuild container images without cache")
|
||||
|
||||
# pull
|
||||
pull_p = subparsers.add_parser("pull", parents=[common_parser], help="Pull workload images")
|
||||
pull_p.add_argument("target", help="Workload target")
|
||||
|
||||
# logs
|
||||
logs_p = subparsers.add_parser("logs", parents=[common_parser], help="View workload logs")
|
||||
logs_p.add_argument("target", help="Workload target")
|
||||
logs_p.add_argument("--tail", type=int, default=100, help="Number of log lines")
|
||||
|
||||
# config
|
||||
config_p = subparsers.add_parser("config", parents=[common_parser], help="View workload compose config")
|
||||
config_p.add_argument("target", help="Workload target")
|
||||
|
||||
# sync
|
||||
subparsers.add_parser("sync", parents=[common_parser], help="Synchronize Homepage services.yaml")
|
||||
|
||||
parsed, _ = parser.parse_known_args(argv)
|
||||
|
||||
if not parsed.command:
|
||||
parser.print_help()
|
||||
return 1
|
||||
|
||||
token = resolve_token(parsed.token)
|
||||
socket_path = parsed.socket or Path(os.environ.get("APPCTL_SOCKET_PATH", DEFAULT_SOCKET_PATH))
|
||||
|
||||
# Map command to OperationRequest
|
||||
op_req: OperationRequest
|
||||
cmd = parsed.command
|
||||
|
||||
if cmd in ("list", "status"):
|
||||
params: dict[str, Any] = {
|
||||
"core": getattr(parsed, "core", False),
|
||||
"fetch": getattr(parsed, "fetch", False),
|
||||
"ssl": getattr(parsed, "ssl", False),
|
||||
}
|
||||
op_req = OperationRequest(operation=OperationType.WORKLOAD_LIST, parameters=params)
|
||||
elif cmd == "info":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_GET,
|
||||
target=parsed.target,
|
||||
parameters={"ssl": getattr(parsed, "ssl", False)},
|
||||
)
|
||||
elif cmd == "resolve":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_RESOLVE,
|
||||
target=parsed.target,
|
||||
)
|
||||
elif cmd == "ssl":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.PLATFORM_SSL,
|
||||
target=parsed.target,
|
||||
)
|
||||
elif cmd == "health":
|
||||
op_req = OperationRequest(operation=OperationType.PLATFORM_HEALTH)
|
||||
elif cmd in ("up", "deploy"):
|
||||
build_flag = getattr(parsed, "build", False)
|
||||
no_cache_flag = getattr(parsed, "no_cache", False)
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_DEPLOY,
|
||||
target=parsed.target,
|
||||
parameters={
|
||||
"build": build_flag or no_cache_flag,
|
||||
"no_cache": no_cache_flag,
|
||||
},
|
||||
)
|
||||
elif cmd in ("down", "stop"):
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_STOP,
|
||||
target=parsed.target,
|
||||
)
|
||||
elif cmd == "restart":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_RESTART,
|
||||
target=parsed.target,
|
||||
)
|
||||
elif cmd == "update":
|
||||
params = {}
|
||||
if getattr(parsed, "branch", None):
|
||||
params["expected_branch"] = parsed.branch
|
||||
build_flag = getattr(parsed, "build", False)
|
||||
no_cache_flag = getattr(parsed, "no_cache", False)
|
||||
if build_flag or no_cache_flag:
|
||||
params["build"] = True
|
||||
if no_cache_flag:
|
||||
params["no_cache"] = True
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_UPDATE,
|
||||
target=parsed.target,
|
||||
parameters=params,
|
||||
)
|
||||
elif cmd == "pull":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_PULL,
|
||||
target=parsed.target,
|
||||
)
|
||||
elif cmd == "logs":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_LOGS,
|
||||
target=parsed.target,
|
||||
parameters={"tail": getattr(parsed, "tail", 100)},
|
||||
)
|
||||
elif cmd == "config":
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_CONFIG,
|
||||
target=parsed.target,
|
||||
)
|
||||
elif cmd == "sync":
|
||||
op_req = OperationRequest(operation=OperationType.PLATFORM_SYNC_HOMEPAGE)
|
||||
else:
|
||||
print(f"❌ Unknown command '{cmd}'", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
try:
|
||||
resp = send_daemon_request(
|
||||
endpoint=socket_path,
|
||||
operation_request=op_req,
|
||||
token=token,
|
||||
timeout=330.0,
|
||||
)
|
||||
print(format_response(resp, raw_json=parsed.json))
|
||||
return 0 if resp.success else 1
|
||||
except FileNotFoundError:
|
||||
print(f"❌ Error: appctl daemon socket not found at {socket_path}", file=sys.stderr)
|
||||
return 1
|
||||
except ConnectionRefusedError:
|
||||
print(f"❌ Error: appctl daemon is not accepting connections at {socket_path}", file=sys.stderr)
|
||||
return 1
|
||||
except (
|
||||
OSError,
|
||||
json.JSONDecodeError,
|
||||
TimeoutError,
|
||||
ValueError,
|
||||
) as e:
|
||||
print(f"❌ Error: Failed to communicate with appctl daemon: {e}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(run_cli())
|
||||
@@ -0,0 +1,352 @@
|
||||
"""
|
||||
appctl_contracts.py — Authoritative Control Plane API Contracts & Schema Validation
|
||||
|
||||
Defines the wire protocol and Pydantic v2 domain schemas for homelab-appctl.service:
|
||||
- Canonical 13 domain operations (workload.*, platform.*)
|
||||
- Fail-closed strict typing (ConfigDict(extra="forbid", strict=True))
|
||||
- Operation-specific parameter models (DeployParams, UpdateParams, LogsParams, ListParams, GetParams)
|
||||
- Closed 6-code error taxonomy mapped to HTTP/1.1 semantics
|
||||
- Information-disclosure-preventing error sanitizer (stripping input and url)
|
||||
- Dual-transport request/response models
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import StrEnum
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from pydantic import (
|
||||
AliasChoices,
|
||||
BaseModel,
|
||||
BeforeValidator,
|
||||
ConfigDict,
|
||||
Field,
|
||||
StrictBool,
|
||||
StrictInt,
|
||||
StrictStr,
|
||||
ValidationError,
|
||||
field_validator,
|
||||
model_validator,
|
||||
)
|
||||
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
"""Base model propagating strict validation across all control plane models — ADR-0003."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True, ignored_types=(dict,))
|
||||
|
||||
|
||||
|
||||
class OperationType(StrEnum):
|
||||
"""The 13 canonical domain operations exposed by homelab-appctl.service."""
|
||||
|
||||
# Read-Only Operations
|
||||
WORKLOAD_LIST = "workload.list"
|
||||
WORKLOAD_GET = "workload.get"
|
||||
WORKLOAD_RESOLVE = "workload.resolve"
|
||||
PLATFORM_SSL = "platform.ssl"
|
||||
PLATFORM_HEALTH = "platform.health"
|
||||
WORKLOAD_CONFIG = "workload.config"
|
||||
WORKLOAD_LOGS = "workload.logs"
|
||||
|
||||
# Mutating Operations
|
||||
WORKLOAD_DEPLOY = "workload.deploy"
|
||||
WORKLOAD_STOP = "workload.stop"
|
||||
WORKLOAD_RESTART = "workload.restart"
|
||||
WORKLOAD_UPDATE = "workload.update"
|
||||
WORKLOAD_PULL = "workload.pull"
|
||||
PLATFORM_SYNC_HOMEPAGE = "platform.sync_homepage"
|
||||
|
||||
|
||||
# Backward-compatibility alias
|
||||
WorkloadAction = OperationType
|
||||
CanonicalOperation = OperationType
|
||||
|
||||
MUTATING_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_STOP,
|
||||
OperationType.WORKLOAD_RESTART,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_PULL,
|
||||
OperationType.PLATFORM_SYNC_HOMEPAGE,
|
||||
})
|
||||
|
||||
READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_LIST,
|
||||
OperationType.WORKLOAD_GET,
|
||||
OperationType.WORKLOAD_RESOLVE,
|
||||
OperationType.PLATFORM_SSL,
|
||||
OperationType.PLATFORM_HEALTH,
|
||||
OperationType.WORKLOAD_CONFIG,
|
||||
OperationType.WORKLOAD_LOGS,
|
||||
})
|
||||
|
||||
SENSITIVE_READ_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_CONFIG,
|
||||
OperationType.WORKLOAD_LOGS,
|
||||
})
|
||||
|
||||
TARGET_REQUIRED_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_GET,
|
||||
OperationType.WORKLOAD_RESOLVE,
|
||||
OperationType.WORKLOAD_CONFIG,
|
||||
OperationType.WORKLOAD_LOGS,
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_STOP,
|
||||
OperationType.WORKLOAD_RESTART,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_PULL,
|
||||
})
|
||||
|
||||
|
||||
def _coerce_operation(v: Any) -> Any:
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
return OperationType(v)
|
||||
except ValueError:
|
||||
return v
|
||||
return v
|
||||
|
||||
|
||||
FlexibleOperationType = Annotated[
|
||||
OperationType,
|
||||
BeforeValidator(_coerce_operation),
|
||||
]
|
||||
FlexibleWorkloadAction = FlexibleOperationType
|
||||
|
||||
|
||||
class ErrorCode(StrEnum):
|
||||
"""Canonical 7-code error taxonomy for homelab-appctl.service."""
|
||||
|
||||
ERR_VALIDATION_FAILED = "ERR_VALIDATION_FAILED"
|
||||
ERR_AUTH_REQUIRED = "ERR_AUTH_REQUIRED"
|
||||
ERR_PERMISSION_DENIED = "ERR_PERMISSION_DENIED"
|
||||
ERR_CAPABILITY_NOT_GRANTED = "ERR_CAPABILITY_NOT_GRANTED"
|
||||
ERR_TARGET_NOT_FOUND = "ERR_TARGET_NOT_FOUND"
|
||||
ERR_CONCURRENT_MUTATION = "ERR_CONCURRENT_MUTATION"
|
||||
ERR_EXECUTION_FAILED = "ERR_EXECUTION_FAILED"
|
||||
|
||||
@property
|
||||
def http_status(self) -> int:
|
||||
return ERROR_HTTP_STATUS[self]
|
||||
|
||||
|
||||
ERROR_HTTP_STATUS: dict[ErrorCode, int] = {
|
||||
ErrorCode.ERR_VALIDATION_FAILED: 400,
|
||||
ErrorCode.ERR_AUTH_REQUIRED: 401,
|
||||
ErrorCode.ERR_PERMISSION_DENIED: 403,
|
||||
ErrorCode.ERR_CAPABILITY_NOT_GRANTED: 403,
|
||||
ErrorCode.ERR_TARGET_NOT_FOUND: 404,
|
||||
ErrorCode.ERR_CONCURRENT_MUTATION: 409,
|
||||
ErrorCode.ERR_EXECUTION_FAILED: 500,
|
||||
}
|
||||
|
||||
|
||||
def _coerce_error_code(v: Any) -> Any:
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
return ErrorCode(v)
|
||||
except ValueError:
|
||||
return v
|
||||
return v
|
||||
|
||||
|
||||
FlexibleErrorCode = Annotated[
|
||||
ErrorCode,
|
||||
BeforeValidator(_coerce_error_code),
|
||||
]
|
||||
|
||||
|
||||
class DeployParams(StrictModel):
|
||||
"""Parameters for workload.deploy."""
|
||||
|
||||
recreate: StrictBool = True
|
||||
remove_orphans: StrictBool = True
|
||||
build: StrictBool = False
|
||||
no_cache: StrictBool = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def imply_build_from_no_cache(self) -> DeployParams:
|
||||
if self.no_cache:
|
||||
self.build = True
|
||||
return self
|
||||
|
||||
|
||||
class UpdateParams(StrictModel):
|
||||
"""Parameters for workload.update."""
|
||||
|
||||
expected_branch: Annotated[StrictStr, Field(min_length=1)] | None = None
|
||||
build: StrictBool = False
|
||||
no_cache: StrictBool = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def imply_build_from_no_cache(self) -> UpdateParams:
|
||||
if self.no_cache:
|
||||
self.build = True
|
||||
return self
|
||||
|
||||
|
||||
class LogsParams(StrictModel):
|
||||
"""Parameters for workload.logs."""
|
||||
|
||||
tail: StrictInt = Field(default=100, ge=1, le=1000)
|
||||
|
||||
|
||||
class ListParams(StrictModel):
|
||||
"""Parameters for workload.list."""
|
||||
|
||||
fetch: StrictBool = False
|
||||
core: StrictBool = False
|
||||
ssl: StrictBool = False
|
||||
|
||||
|
||||
class GetParams(StrictModel):
|
||||
"""Parameters for workload.get."""
|
||||
|
||||
ssl: StrictBool = False
|
||||
|
||||
|
||||
class EmptyParams(StrictModel):
|
||||
"""Parameters model for operations that accept no arguments."""
|
||||
|
||||
|
||||
OPERATION_PARAMS_MAP: dict[OperationType, type[StrictModel]] = {
|
||||
OperationType.WORKLOAD_DEPLOY: DeployParams,
|
||||
OperationType.WORKLOAD_UPDATE: UpdateParams,
|
||||
OperationType.WORKLOAD_LOGS: LogsParams,
|
||||
OperationType.WORKLOAD_LIST: ListParams,
|
||||
OperationType.WORKLOAD_GET: GetParams,
|
||||
OperationType.WORKLOAD_STOP: EmptyParams,
|
||||
OperationType.WORKLOAD_RESTART: EmptyParams,
|
||||
OperationType.WORKLOAD_PULL: EmptyParams,
|
||||
OperationType.WORKLOAD_RESOLVE: EmptyParams,
|
||||
OperationType.PLATFORM_SSL: EmptyParams,
|
||||
OperationType.PLATFORM_HEALTH: EmptyParams,
|
||||
OperationType.WORKLOAD_CONFIG: EmptyParams,
|
||||
OperationType.PLATFORM_SYNC_HOMEPAGE: EmptyParams,
|
||||
}
|
||||
|
||||
|
||||
class OperationError(StrictModel):
|
||||
"""Standardized error payload returned in failed OperationResponse payloads."""
|
||||
|
||||
code: FlexibleErrorCode
|
||||
message: StrictStr
|
||||
details: list[dict[str, Any]] | None = None
|
||||
|
||||
|
||||
def sanitize_validation_error(exc: ValidationError) -> OperationError:
|
||||
"""
|
||||
Format and sanitize a Pydantic ValidationError into an OperationError with ERR_VALIDATION_FAILED,
|
||||
stripping raw user input and documentation URLs to prevent information disclosure.
|
||||
"""
|
||||
raw_details = exc.errors(include_input=False, include_url=False)
|
||||
clean_details: list[dict[str, Any]] = []
|
||||
for d in raw_details:
|
||||
clean_details.append({
|
||||
"type": d.get("type"),
|
||||
"loc": list(d.get("loc", ())),
|
||||
"msg": d.get("msg"),
|
||||
})
|
||||
return OperationError(
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message="Request payload validation failed",
|
||||
details=clean_details,
|
||||
)
|
||||
|
||||
|
||||
class OperationRequest(StrictModel):
|
||||
"""Defines the body requirements of an HTTP/1.1 operation request."""
|
||||
|
||||
model_config = ConfigDict(
|
||||
extra="forbid",
|
||||
strict=True,
|
||||
populate_by_name=True,
|
||||
ignored_types=(dict,),
|
||||
)
|
||||
|
||||
|
||||
version: Literal["1.0"] = "1.0"
|
||||
operation: FlexibleOperationType = Field(
|
||||
validation_alias=AliasChoices("operation", "action")
|
||||
)
|
||||
target: Annotated[StrictStr, Field(min_length=1)] | None = None
|
||||
parameters: dict[str, Any] = Field(
|
||||
default_factory=dict,
|
||||
validation_alias=AliasChoices("parameters", "params"),
|
||||
)
|
||||
|
||||
@property
|
||||
def action(self) -> OperationType:
|
||||
return self.operation
|
||||
|
||||
@property
|
||||
def params(self) -> dict[str, Any]:
|
||||
return self.parameters
|
||||
|
||||
@field_validator("parameters", mode="before")
|
||||
@classmethod
|
||||
def _coerce_parameters(cls, v: Any) -> Any:
|
||||
if isinstance(v, BaseModel):
|
||||
return v.model_dump()
|
||||
return v
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_request(self) -> OperationRequest:
|
||||
if self.operation in TARGET_REQUIRED_OPERATIONS and not self.target:
|
||||
raise ValueError(f"Operation '{self.operation.value}' requires a non-empty target")
|
||||
param_model = OPERATION_PARAMS_MAP[self.operation]
|
||||
param_model.model_validate(self.parameters)
|
||||
return self
|
||||
|
||||
def parse_parameters(self) -> StrictModel:
|
||||
"""Parse and return the typed parameter model for this operation."""
|
||||
param_model = OPERATION_PARAMS_MAP[self.operation]
|
||||
return param_model.model_validate(self.parameters)
|
||||
|
||||
|
||||
|
||||
class OperationResponse(StrictModel):
|
||||
"""Defines the standard response payload for control plane operations."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True, populate_by_name=True)
|
||||
|
||||
version: Literal["1.0"] = "1.0"
|
||||
success: StrictBool | None = None
|
||||
status: Literal["success", "error"] | None = None
|
||||
operation_id: StrictStr = Field(min_length=1)
|
||||
operation: FlexibleOperationType | StrictStr | None = Field(
|
||||
default=None,
|
||||
validation_alias=AliasChoices("operation", "action"),
|
||||
)
|
||||
target: StrictStr | None = None
|
||||
output: StrictStr = ""
|
||||
result: dict[str, Any] | None = None
|
||||
error: OperationError | None = None
|
||||
timestamp: StrictStr | None = None
|
||||
duration_ms: StrictInt | None = None
|
||||
|
||||
@property
|
||||
def action(self) -> OperationType | str | None:
|
||||
return self.operation
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_consistency(self) -> OperationResponse:
|
||||
if self.success is None and self.status is None:
|
||||
raise ValueError("Either 'success' or 'status' must be provided")
|
||||
if self.success is None and self.status is not None:
|
||||
self.success = self.status == "success"
|
||||
elif self.status is None and self.success is not None:
|
||||
self.status = "success" if self.success else "error"
|
||||
elif (
|
||||
self.success is not None
|
||||
and self.status is not None
|
||||
and (self.status == "success") != self.success
|
||||
):
|
||||
raise ValueError("'status' and 'success' must agree")
|
||||
|
||||
if self.success and self.error is not None:
|
||||
raise ValueError("Successful operation cannot contain an error")
|
||||
if not self.success and self.error is None:
|
||||
raise ValueError("Failed operation must contain an error")
|
||||
return self
|
||||
Executable
+604
@@ -0,0 +1,604 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
appctl_daemon.py — Dual-Transport HTTP/1.1 Control Plane Daemon for Homelab
|
||||
|
||||
Implements Milestone P4 Control Plane Daemon:
|
||||
- Multi-threaded Unix domain socket listener (/run/homelab/appctl.sock, mode 0660)
|
||||
- Multi-threaded loopback HTTP listener (127.0.0.1:9001)
|
||||
- Bounded 64 KiB request body enforcement
|
||||
- Endpoints: GET /v1/health, POST /v1/operations
|
||||
- Linux SO_PEERCRED credential extraction on UDS transport
|
||||
- Bearer token authentication + RBAC gating + append-only audit logging
|
||||
- Pure-Python Unix domain socket HTTP client helper
|
||||
- Graceful SIGINT and SIGTERM shutdown unlinking socket file
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import http.server
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import socketserver
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from appctl_audit import (
|
||||
AuditLogger,
|
||||
PrincipalAudit,
|
||||
TargetLockManager,
|
||||
current_iso_timestamp,
|
||||
generate_operation_id,
|
||||
)
|
||||
from appctl_auth import (
|
||||
AuthenticationError,
|
||||
TokenStore,
|
||||
authenticate_request,
|
||||
)
|
||||
from appctl_contracts import (
|
||||
ErrorCode,
|
||||
OperationError,
|
||||
OperationRequest,
|
||||
OperationResponse,
|
||||
OperationType,
|
||||
sanitize_validation_error,
|
||||
)
|
||||
from appctl_router import OperationalRouter
|
||||
from pydantic import ValidationError
|
||||
|
||||
logger = logging.getLogger("appctl_daemon")
|
||||
|
||||
CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent))
|
||||
WORKLOADS_DIR = Path(
|
||||
os.environ.get("WORKLOADS_DIR")
|
||||
or os.environ.get("SITES_DIR")
|
||||
or os.path.expanduser("~/Workloads")
|
||||
)
|
||||
SITES_DIR = WORKLOADS_DIR
|
||||
DEPLOYMENTS_FILE = Path(
|
||||
os.environ.get("HOMELAB_DEPLOYMENTS_FILE") or (WORKLOADS_DIR / "deployments.yaml")
|
||||
)
|
||||
|
||||
DEFAULT_SOCKET_PATH = Path(
|
||||
os.environ.get("APPCTL_SOCKET_PATH", "/run/homelab/appctl.sock")
|
||||
)
|
||||
DEFAULT_HTTP_HOST = os.environ.get("APPCTL_HTTP_HOST", "127.0.0.1")
|
||||
DEFAULT_HTTP_PORT = int(os.environ.get("APPCTL_HTTP_PORT", "9001"))
|
||||
MAX_REQUEST_BODY = 64 * 1024 # 64 KiB
|
||||
|
||||
|
||||
def extract_peer_credentials(sock: socket.socket) -> tuple[int, int, int] | None:
|
||||
"""
|
||||
Extract (pid, uid, gid) from a connected Unix domain socket on Linux via SO_PEERCRED.
|
||||
Returns None if unsupported or on error.
|
||||
"""
|
||||
try:
|
||||
so_peercred = getattr(socket, "SO_PEERCRED", 17)
|
||||
creds = sock.getsockopt(socket.SOL_SOCKET, so_peercred, struct.calcsize("3i"))
|
||||
pid, uid, gid = struct.unpack("3i", creds)
|
||||
return pid, uid, gid
|
||||
except (OSError, struct.error, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
class UnixHTTPConnection(http.client.HTTPConnection):
|
||||
"""HTTP client connection over a local Unix domain socket."""
|
||||
|
||||
def __init__(self, socket_path: str, timeout: float = 30.0) -> None:
|
||||
super().__init__("localhost", timeout=timeout)
|
||||
self.socket_path = socket_path
|
||||
|
||||
def connect(self) -> None:
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
if self.timeout is not None:
|
||||
sock.settimeout(self.timeout)
|
||||
sock.connect(self.socket_path)
|
||||
self.sock = sock
|
||||
|
||||
|
||||
def send_daemon_request(
|
||||
endpoint: str | Path,
|
||||
operation_request: OperationRequest | dict[str, Any],
|
||||
token: str | None = None,
|
||||
timeout: float = 30.0,
|
||||
) -> OperationResponse:
|
||||
"""
|
||||
Client helper to send an OperationRequest over UDS or HTTP to the daemon.
|
||||
Accepts:
|
||||
- Path object or path ending in .sock -> UnixHTTPConnection
|
||||
- URL starting with http:// or host:port -> standard HTTPConnection
|
||||
"""
|
||||
if isinstance(operation_request, OperationRequest):
|
||||
req_body = operation_request.model_dump_json(exclude_none=True)
|
||||
elif isinstance(operation_request, dict):
|
||||
req_body = json.dumps(operation_request)
|
||||
else:
|
||||
raise TypeError("operation_request must be OperationRequest or dict")
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Host": "localhost",
|
||||
}
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
|
||||
is_unix = False
|
||||
endpoint_str = str(endpoint)
|
||||
|
||||
if (
|
||||
isinstance(endpoint, Path)
|
||||
or endpoint_str.endswith(".sock")
|
||||
or ("/" in endpoint_str and not endpoint_str.startswith("http"))
|
||||
):
|
||||
is_unix = True
|
||||
|
||||
if is_unix:
|
||||
conn = UnixHTTPConnection(endpoint_str, timeout=timeout)
|
||||
else:
|
||||
if endpoint_str.startswith(("http://", "https://")):
|
||||
parsed = urlparse(endpoint_str)
|
||||
host = parsed.hostname or "127.0.0.1"
|
||||
port = parsed.port or (443 if parsed.scheme == "https" else 80)
|
||||
elif ":" in endpoint_str:
|
||||
host, port_str = endpoint_str.split(":", 1)
|
||||
port = int(port_str)
|
||||
else:
|
||||
host = endpoint_str
|
||||
port = DEFAULT_HTTP_PORT
|
||||
conn = http.client.HTTPConnection(host, port, timeout=timeout)
|
||||
|
||||
try:
|
||||
conn.request("POST", "/v1/operations", body=req_body.encode("utf-8"), headers=headers)
|
||||
res = conn.getresponse()
|
||||
resp_data = res.read().decode("utf-8")
|
||||
parsed_json = json.loads(resp_data)
|
||||
return OperationResponse.model_validate(parsed_json)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
|
||||
"""
|
||||
HTTP/1.1 request handler for appctl control plane operations.
|
||||
Supports both UDS and loopback TCP listeners.
|
||||
"""
|
||||
|
||||
server_version = "AppctlDaemon/1.0"
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
@property
|
||||
def appctl_server(self) -> ThreadingUnixStreamServer | ThreadingHTTPServer:
|
||||
return cast("ThreadingUnixStreamServer | ThreadingHTTPServer", self.server)
|
||||
|
||||
def address_string(self) -> str:
|
||||
"""Safely format client address avoiding slow DNS lookups or UDS unpack errors."""
|
||||
client_addr = self.client_address
|
||||
if isinstance(client_addr, tuple) and len(client_addr) >= 2:
|
||||
return f"{client_addr[0]}:{client_addr[1]}"
|
||||
if isinstance(client_addr, str) and client_addr:
|
||||
return client_addr
|
||||
return "unix_socket"
|
||||
|
||||
def log_message(self, format: str, *args: Any) -> None:
|
||||
"""Forward access logs to Python standard logger."""
|
||||
logger.info("%s - %s", self.address_string(), format % args)
|
||||
|
||||
def _send_json(self, status_code: int, data: dict[str, Any] | str) -> None:
|
||||
"""Send formatted JSON HTTP response."""
|
||||
body_bytes = data.encode("utf-8") if isinstance(data, str) else json.dumps(data, indent=2).encode("utf-8")
|
||||
self.send_response(status_code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body_bytes)))
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
self.wfile.write(body_bytes)
|
||||
|
||||
def _send_operation_response(self, status_code: int, response: OperationResponse) -> None:
|
||||
"""Serialize and send an OperationResponse payload."""
|
||||
payload_str = response.model_dump_json(exclude_none=True)
|
||||
self._send_json(status_code, payload_str)
|
||||
|
||||
def _send_operation_error(
|
||||
self,
|
||||
status_code: int,
|
||||
error: OperationError,
|
||||
operation: Any = None,
|
||||
target: str | None = None,
|
||||
op_id: str | None = None,
|
||||
) -> None:
|
||||
"""Send standardized OperationResponse representing a failure."""
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=False,
|
||||
status="error",
|
||||
operation_id=op_id or generate_operation_id(),
|
||||
operation=operation if isinstance(operation, (OperationType, str)) else None,
|
||||
target=target if isinstance(target, str) else None,
|
||||
error=error,
|
||||
timestamp=current_iso_timestamp(),
|
||||
)
|
||||
self._send_operation_response(status_code, resp)
|
||||
|
||||
def _send_error_response(
|
||||
self,
|
||||
status_code: int,
|
||||
code: ErrorCode,
|
||||
message: str,
|
||||
details: list[dict[str, Any]] | None = None,
|
||||
op_id: str | None = None,
|
||||
operation: Any = None,
|
||||
target: str | None = None,
|
||||
) -> None:
|
||||
"""Send structured error response with canonical error code."""
|
||||
error = OperationError(code=code, message=message, details=details)
|
||||
self._send_operation_error(
|
||||
status_code=status_code,
|
||||
error=error,
|
||||
operation=operation,
|
||||
target=target,
|
||||
op_id=op_id,
|
||||
)
|
||||
|
||||
def do_GET(self) -> None:
|
||||
"""Handle health check endpoint."""
|
||||
if self.path in ("/v1/health", "/health"):
|
||||
health = self.appctl_server.daemon_instance.get_health_status()
|
||||
self._send_json(200, health)
|
||||
return
|
||||
|
||||
self._send_error_response(
|
||||
status_code=404,
|
||||
code=ErrorCode.ERR_TARGET_NOT_FOUND,
|
||||
message=f"Endpoint '{self.path}' not found",
|
||||
)
|
||||
|
||||
def do_POST(self) -> None:
|
||||
"""Handle operational dispatch requests."""
|
||||
if self.path != "/v1/operations":
|
||||
self._send_error_response(
|
||||
status_code=404,
|
||||
code=ErrorCode.ERR_TARGET_NOT_FOUND,
|
||||
message=f"Endpoint '{self.path}' not found. Supported endpoint: POST /v1/operations",
|
||||
)
|
||||
return
|
||||
|
||||
cl_header = self.headers.get("Content-Length")
|
||||
if cl_header is None:
|
||||
self._send_error_response(
|
||||
status_code=400,
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message="Missing Content-Length header",
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
content_length = int(cl_header.strip())
|
||||
except ValueError:
|
||||
self._send_error_response(
|
||||
status_code=400,
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message="Malformed Content-Length header",
|
||||
)
|
||||
return
|
||||
|
||||
if content_length < 0:
|
||||
self._send_error_response(
|
||||
status_code=400,
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message="Content-Length cannot be negative",
|
||||
)
|
||||
return
|
||||
|
||||
if content_length > MAX_REQUEST_BODY:
|
||||
self._send_error_response(
|
||||
status_code=400,
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message=f"Request body ({content_length} bytes) exceeds limit of {MAX_REQUEST_BODY} bytes",
|
||||
)
|
||||
return
|
||||
|
||||
raw_body = self.rfile.read(content_length)
|
||||
|
||||
try:
|
||||
body_dict = json.loads(raw_body.decode("utf-8"))
|
||||
except (json.JSONDecodeError, UnicodeDecodeError) as e:
|
||||
self._send_error_response(
|
||||
status_code=400,
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message=f"Invalid JSON payload: {e}",
|
||||
)
|
||||
return
|
||||
|
||||
if not isinstance(body_dict, dict):
|
||||
self._send_error_response(
|
||||
status_code=400,
|
||||
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||
message="Payload root must be a JSON object mapping",
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
req = OperationRequest.model_validate(body_dict)
|
||||
except ValidationError as exc:
|
||||
sanitized = sanitize_validation_error(exc)
|
||||
self._send_operation_error(
|
||||
status_code=400,
|
||||
error=sanitized,
|
||||
operation=body_dict.get("operation") or body_dict.get("action"),
|
||||
target=body_dict.get("target"),
|
||||
)
|
||||
return
|
||||
|
||||
# Determine transport scheme and peer credentials
|
||||
is_unix = getattr(self.connection, "family", None) == socket.AF_UNIX
|
||||
transport = "unix_socket" if is_unix else "http"
|
||||
peer_uid: int | None = None
|
||||
|
||||
if is_unix:
|
||||
creds = extract_peer_credentials(self.connection)
|
||||
if creds is not None:
|
||||
_, peer_uid, _ = creds
|
||||
origin = f"peer_uid_{peer_uid}" if peer_uid is not None else "unix_socket"
|
||||
else:
|
||||
origin = self.address_string()
|
||||
|
||||
client_header = self.headers.get("User-Agent", "appctl-client/1.0")
|
||||
auth_header = self.headers.get("Authorization")
|
||||
|
||||
# Authenticate principal
|
||||
try:
|
||||
principal = authenticate_request(
|
||||
auth_header=auth_header,
|
||||
transport=transport,
|
||||
peer_uid=peer_uid,
|
||||
token_store=self.appctl_server.token_store,
|
||||
)
|
||||
except AuthenticationError as auth_err:
|
||||
op_id = generate_operation_id()
|
||||
auth_msg = str(auth_err)
|
||||
self.appctl_server.audit_logger.log_denied(
|
||||
operation_id=op_id,
|
||||
principal=PrincipalAudit(
|
||||
identity=f"peer_uid_{peer_uid}" if peer_uid is not None else "unknown",
|
||||
role="homelab-viewer" if is_unix else "unknown",
|
||||
token_id=None,
|
||||
auth_method="unix_peercred" if is_unix and auth_header is None else "bearer_token",
|
||||
),
|
||||
action=req.operation.value,
|
||||
target=req.target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client_header,
|
||||
parameters=req.parameters,
|
||||
error_code=auth_err.code.value,
|
||||
message=auth_msg,
|
||||
)
|
||||
self._send_operation_error(
|
||||
status_code=auth_err.code.http_status,
|
||||
error=OperationError(code=auth_err.code, message=auth_msg),
|
||||
operation=req.operation,
|
||||
target=req.target,
|
||||
op_id=op_id,
|
||||
)
|
||||
return
|
||||
|
||||
# Dispatch operation to OperationalRouter
|
||||
try:
|
||||
resp = self.appctl_server.router.dispatch(
|
||||
request=req,
|
||||
principal=principal,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client_header,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Top-level unhandled exception during operation dispatch")
|
||||
self._send_operation_error(
|
||||
status_code=500,
|
||||
error=OperationError(
|
||||
code=ErrorCode.ERR_EXECUTION_FAILED,
|
||||
message=f"Internal daemon execution error: {exc}",
|
||||
),
|
||||
operation=req.operation,
|
||||
target=req.target,
|
||||
op_id=generate_operation_id(),
|
||||
)
|
||||
return
|
||||
|
||||
status_code = resp.error.code.http_status if (not resp.success and resp.error) else 200
|
||||
self._send_operation_response(status_code, resp)
|
||||
|
||||
|
||||
class ThreadingUnixStreamServer(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
|
||||
"""Multi-threaded Unix Domain Socket HTTP server."""
|
||||
|
||||
daemon_threads = True
|
||||
allow_reuse_address = True
|
||||
|
||||
router: OperationalRouter
|
||||
token_store: TokenStore
|
||||
audit_logger: AuditLogger
|
||||
daemon_instance: AppctlDaemon
|
||||
|
||||
|
||||
class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
|
||||
"""Multi-threaded TCP Loopback HTTP server."""
|
||||
|
||||
daemon_threads = True
|
||||
allow_reuse_address = True
|
||||
|
||||
router: OperationalRouter
|
||||
token_store: TokenStore
|
||||
audit_logger: AuditLogger
|
||||
daemon_instance: AppctlDaemon
|
||||
|
||||
|
||||
class AppctlDaemon:
|
||||
"""
|
||||
Control Plane Daemon managing dual-transport operational listeners (UDS + TCP).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
router: OperationalRouter | None = None,
|
||||
token_store: TokenStore | None = None,
|
||||
audit_logger: AuditLogger | None = None,
|
||||
lock_manager: TargetLockManager | None = None,
|
||||
socket_path: Path | str | None = None,
|
||||
http_host: str | None = None,
|
||||
http_port: int | None = None,
|
||||
sites_dir: Path | str | None = None,
|
||||
core_dir: Path | str | None = None,
|
||||
deployments_file: Path | str | None = None,
|
||||
) -> None:
|
||||
self.socket_path = Path(socket_path or os.environ.get("APPCTL_SOCKET_PATH", DEFAULT_SOCKET_PATH))
|
||||
self.http_host = str(http_host or os.environ.get("APPCTL_HTTP_HOST", DEFAULT_HTTP_HOST))
|
||||
self.http_port = int(http_port or os.environ.get("APPCTL_HTTP_PORT", str(DEFAULT_HTTP_PORT)))
|
||||
|
||||
self.audit_logger = audit_logger or AuditLogger()
|
||||
self.token_store = token_store or TokenStore()
|
||||
self.lock_manager = lock_manager or TargetLockManager()
|
||||
|
||||
self.router = router or OperationalRouter(
|
||||
audit_logger=self.audit_logger,
|
||||
lock_manager=self.lock_manager,
|
||||
sites_dir=sites_dir or SITES_DIR,
|
||||
core_dir=core_dir or CORE_DIR,
|
||||
)
|
||||
|
||||
self.uds_server: ThreadingUnixStreamServer | None = None
|
||||
self.tcp_server: ThreadingHTTPServer | None = None
|
||||
self.uds_thread: threading.Thread | None = None
|
||||
self.tcp_thread: threading.Thread | None = None
|
||||
|
||||
self.running = False
|
||||
self.start_time: float = 0.0
|
||||
|
||||
def start(self) -> None:
|
||||
"""Bind both transports and start listener worker threads."""
|
||||
if self.running:
|
||||
return
|
||||
|
||||
self.start_time = time.time()
|
||||
|
||||
# 1. Prepare and bind UDS listener
|
||||
self.socket_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if self.socket_path.exists() or self.socket_path.is_socket():
|
||||
self.socket_path.unlink(missing_ok=True)
|
||||
|
||||
self.uds_server = ThreadingUnixStreamServer(str(self.socket_path), AppctlHTTPHandler)
|
||||
self.uds_server.router = self.router
|
||||
self.uds_server.token_store = self.token_store
|
||||
self.uds_server.audit_logger = self.audit_logger
|
||||
self.uds_server.daemon_instance = self
|
||||
|
||||
try:
|
||||
os.chmod(self.socket_path, 0o660)
|
||||
except OSError as e:
|
||||
logger.warning("Could not set mode 0660 on socket %s: %s", self.socket_path, e)
|
||||
|
||||
# 2. Prepare and bind TCP listener
|
||||
self.tcp_server = ThreadingHTTPServer((self.http_host, self.http_port), AppctlHTTPHandler)
|
||||
self.tcp_server.router = self.router
|
||||
self.tcp_server.token_store = self.token_store
|
||||
self.tcp_server.audit_logger = self.audit_logger
|
||||
self.tcp_server.daemon_instance = self
|
||||
|
||||
# 3. Start listener threads
|
||||
self.uds_thread = threading.Thread(target=self.uds_server.serve_forever, daemon=True, name="uds-listener")
|
||||
self.uds_thread.start()
|
||||
|
||||
self.tcp_thread = threading.Thread(target=self.tcp_server.serve_forever, daemon=True, name="tcp-listener")
|
||||
self.tcp_thread.start()
|
||||
|
||||
self.running = True
|
||||
logger.info(
|
||||
"appctl daemon started: UDS=%s, HTTP=%s:%d",
|
||||
self.socket_path,
|
||||
self.http_host,
|
||||
self.http_port,
|
||||
)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Gracefully shut down both transport servers and unlink socket."""
|
||||
if not self.running:
|
||||
return
|
||||
|
||||
self.running = False
|
||||
logger.info("Shutting down appctl daemon...")
|
||||
|
||||
if self.uds_server:
|
||||
self.uds_server.shutdown()
|
||||
self.uds_server.server_close()
|
||||
self.uds_server = None
|
||||
|
||||
if self.socket_path.exists() or self.socket_path.is_socket():
|
||||
self.socket_path.unlink(missing_ok=True)
|
||||
|
||||
if self.tcp_server:
|
||||
self.tcp_server.shutdown()
|
||||
self.tcp_server.server_close()
|
||||
self.tcp_server = None
|
||||
|
||||
if self.uds_thread and self.uds_thread.is_alive():
|
||||
self.uds_thread.join(timeout=2.0)
|
||||
self.uds_thread = None
|
||||
|
||||
if self.tcp_thread and self.tcp_thread.is_alive():
|
||||
self.tcp_thread.join(timeout=2.0)
|
||||
self.tcp_thread = None
|
||||
|
||||
logger.info("appctl daemon shut down successfully.")
|
||||
|
||||
def get_health_status(self) -> dict[str, Any]:
|
||||
"""Produce non-sensitive health metadata."""
|
||||
uptime = round(time.time() - self.start_time, 2) if self.running else 0.0
|
||||
return {
|
||||
"status": "healthy" if self.running else "stopped",
|
||||
"version": "1.0",
|
||||
"uptime_seconds": uptime,
|
||||
"transports": {
|
||||
"unix_socket": str(self.socket_path),
|
||||
"http_loopback": f"{self.http_host}:{self.http_port}",
|
||||
},
|
||||
"timestamp": current_iso_timestamp(),
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""CLI entrypoint for running the daemon."""
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] [appctl-daemon] %(message)s",
|
||||
handlers=[logging.StreamHandler(sys.stdout)],
|
||||
)
|
||||
|
||||
daemon = AppctlDaemon()
|
||||
|
||||
def handle_signal(sig: int, _frame: Any) -> None:
|
||||
logger.info("Received signal %d, stopping daemon...", sig)
|
||||
daemon.stop()
|
||||
sys.exit(0)
|
||||
|
||||
signal.signal(signal.SIGINT, handle_signal)
|
||||
signal.signal(signal.SIGTERM, handle_signal)
|
||||
|
||||
daemon.start()
|
||||
|
||||
try:
|
||||
while daemon.running:
|
||||
time.sleep(1.0)
|
||||
except KeyboardInterrupt:
|
||||
daemon.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+896
-392
File diff suppressed because it is too large.
Load diff
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())
|
||||
@@ -1,39 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# List of domains to check
|
||||
DOMAINS=(
|
||||
"arch-services.mywire.org"
|
||||
"auth.arch-services.mywire.org"
|
||||
"excalidraw.arch-services.mywire.org"
|
||||
"gitea.arch-services.mywire.org"
|
||||
"jellyfin.arch-services.mywire.org"
|
||||
"learning.arch-services.mywire.org"
|
||||
"logs.arch-services.mywire.org"
|
||||
"mermaid.arch-services.mywire.org"
|
||||
"ollama.arch-services.mywire.org"
|
||||
"portainer.arch-services.mywire.org"
|
||||
"traefik.arch-services.mywire.org"
|
||||
)
|
||||
|
||||
printf "%-40s | %-30s | %-30s | %-20s\n" "Domain" "Issuer (CN)" "Subject (CN)" "Expiry"
|
||||
printf "%-40s-|-%-30s-|-%-30s-|-%-20s\n" "----------------------------------------" "------------------------------" "------------------------------" "--------------------"
|
||||
|
||||
for domain in "${DOMAINS[@]}"; do
|
||||
# Use timeout to avoid hanging on failed connections
|
||||
cert_info=$(timeout 5 bash -c "echo | openssl s_client -showcerts -servername $domain -connect $domain:443 2>/dev/null | openssl x509 -noout -issuer -subject -enddate 2>/dev/null")
|
||||
|
||||
if [ -z "$cert_info" ]; then
|
||||
printf "%-40s | %-30s | %-30s | %-20s\n" "$domain" "CONNECTION FAILED" "-" "-"
|
||||
else
|
||||
# Extract CN from issuer and subject
|
||||
issuer_cn=$(echo "$cert_info" | grep "issuer" | sed -n 's/.*CN = \([^,]*\).*/\1/p')
|
||||
[ -z "$issuer_cn" ] && issuer_cn=$(echo "$cert_info" | grep "issuer" | sed 's/issuer= //')
|
||||
|
||||
subject_cn=$(echo "$cert_info" | grep "subject" | sed -n 's/.*CN = \([^,]*\).*/\1/p')
|
||||
[ -z "$subject_cn" ] && subject_cn=$(echo "$cert_info" | grep "subject" | sed 's/subject= //')
|
||||
|
||||
expiry=$(echo "$cert_info" | grep "notAfter" | sed 's/notAfter=//')
|
||||
|
||||
printf "%-40s | %-30s | %-30s | %-20s\n" "$domain" "$issuer_cn" "$subject_cn" "$expiry"
|
||||
fi
|
||||
done
|
||||
@@ -0,0 +1,519 @@
|
||||
"""
|
||||
core_manifest.py — Authoritative Workload Manifest Schema (v1.0) & Parser Library
|
||||
|
||||
Governs the contract for all ~/Sites workloads:
|
||||
- Strongly-typed Pydantic v2 representations (Manifest, SourceConfig, DeploymentConfig, HomepageConfig)
|
||||
- Strict source transport scheme validation (https://, ssh://, git@)
|
||||
- Explicit ref classification (moving branches vs. pinned tags vs. commit SHAs)
|
||||
- Workload classification: Class A (Source-Backed) vs. Class B (Image-Only)
|
||||
- Fail-closed schema enforcement with ConfigDict(extra="forbid")
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from pydantic import (
|
||||
BaseModel,
|
||||
ConfigDict,
|
||||
Field,
|
||||
ValidationError,
|
||||
field_validator,
|
||||
model_validator,
|
||||
)
|
||||
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
yaml = None # type: ignore[assignment]
|
||||
|
||||
|
||||
class ManifestValidationError(Exception):
|
||||
"""Raised when an application manifest violates schema or security constraints."""
|
||||
|
||||
|
||||
class RefType(str, Enum):
|
||||
"""Semantic classification of an upstream git reference."""
|
||||
|
||||
BRANCH = "branch" # Moving branch (e.g. main, master, develop, release/v1)
|
||||
TAG = "tag" # Pinned release tag (e.g. v1.0.0, 2.3.1)
|
||||
COMMIT = "commit" # Immutable commit SHA (40-character hex)
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
class TransportScheme(str, Enum):
|
||||
"""Supported secure git network transports."""
|
||||
|
||||
HTTPS = "https"
|
||||
SSH = "ssh"
|
||||
GIT_SCP = "git_scp"
|
||||
|
||||
|
||||
# Security regexes
|
||||
NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]*$")
|
||||
COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$")
|
||||
SHORT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,12}$")
|
||||
SEMVER_TAG_RE = re.compile(r"^v?[0-9]+(\.[0-9]+)+([a-zA-Z0-9._-]*)$")
|
||||
SCP_URL_RE = re.compile(
|
||||
r"^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:([0-9]+/)?([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+(\.git)?$"
|
||||
)
|
||||
ENV_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
|
||||
RESERVED_ENV_KEYS = {
|
||||
"PATH",
|
||||
"LD_PRELOAD",
|
||||
"IFS",
|
||||
"SHELL",
|
||||
"USER",
|
||||
"CORE_DIR",
|
||||
"SITES_DIR",
|
||||
"ENV_FILE",
|
||||
"HOMESERVER_ENV",
|
||||
"HOMELAB_DOMAIN",
|
||||
"DOMAIN_SUFFIX",
|
||||
"DOMAIN",
|
||||
"PROXY_NETWORK",
|
||||
"CERT_RESOLVER",
|
||||
"DOCKER_CONFIG",
|
||||
"SERVICE_NAME",
|
||||
"CONTAINER_NAME",
|
||||
"SERVICE_DOMAIN",
|
||||
"HOMELAB_GRANTS_FILE",
|
||||
}
|
||||
|
||||
ALLOWED_STRATEGIES = {"compose"}
|
||||
ALLOWED_ACTIONS = {
|
||||
"git_pull",
|
||||
"compose_pull",
|
||||
"compose_up",
|
||||
"compose_build",
|
||||
"compose_restart",
|
||||
}
|
||||
|
||||
|
||||
def validate_transport(url: str) -> tuple[TransportScheme, str]:
|
||||
"""
|
||||
Validate that an upstream source URL uses an approved secure transport.
|
||||
Rejects raw host paths, traversal attempts, and insecure protocols (e.g. http://, file://).
|
||||
"""
|
||||
if not isinstance(url, str) or not url.strip():
|
||||
raise ManifestValidationError("Source URL cannot be empty.")
|
||||
|
||||
clean_url = url.strip()
|
||||
|
||||
# Reject path traversal / directory escapes
|
||||
if ".." in clean_url or "\\" in clean_url or clean_url.startswith(("/", "~")):
|
||||
raise ManifestValidationError(
|
||||
f"Prohibited filesystem path or traversal in source URL: '{clean_url}'"
|
||||
)
|
||||
|
||||
# 1. HTTPS transport
|
||||
if clean_url.startswith("https://"):
|
||||
parsed = urlparse(clean_url)
|
||||
if not parsed.netloc:
|
||||
raise ManifestValidationError(
|
||||
f"Malformed HTTPS source URL (missing host): '{clean_url}'"
|
||||
)
|
||||
if not parsed.path or parsed.path == "/":
|
||||
raise ManifestValidationError(
|
||||
f"Malformed HTTPS source URL (missing repository path): '{clean_url}'"
|
||||
)
|
||||
return TransportScheme.HTTPS, clean_url
|
||||
|
||||
# 2. Standard SSH transport (ssh://[user@]host[:port]/path)
|
||||
if clean_url.startswith("ssh://"):
|
||||
parsed = urlparse(clean_url)
|
||||
if not parsed.netloc:
|
||||
raise ManifestValidationError(
|
||||
f"Malformed SSH source URL (missing host): '{clean_url}'"
|
||||
)
|
||||
if not parsed.path or parsed.path == "/":
|
||||
raise ManifestValidationError(
|
||||
f"Malformed SSH source URL (missing repository path): '{clean_url}'"
|
||||
)
|
||||
return TransportScheme.SSH, clean_url
|
||||
|
||||
# 3. SCP-style SSH transport (git@host:owner/repo.git)
|
||||
if clean_url.startswith("git@") or (
|
||||
"@" in clean_url and ":" in clean_url and not clean_url.startswith("http")
|
||||
):
|
||||
if SCP_URL_RE.match(clean_url):
|
||||
return TransportScheme.GIT_SCP, clean_url
|
||||
raise ManifestValidationError(f"Malformed SCP-style source URL: '{clean_url}'")
|
||||
|
||||
# Reject plaintext HTTP or unsupported schemes
|
||||
if clean_url.startswith("http://"):
|
||||
raise ManifestValidationError(
|
||||
f"Insecure HTTP source URL rejected (HTTPS or SSH required): '{clean_url}'"
|
||||
)
|
||||
|
||||
raise ManifestValidationError(
|
||||
f"Invalid source.url scheme: '{clean_url}'. "
|
||||
"Allowed transports are https://, ssh://, or git@<host>:<path>."
|
||||
)
|
||||
|
||||
|
||||
def classify_ref(ref_str: str) -> tuple[RefType, str]:
|
||||
"""
|
||||
Classify a git ref into semantic categories (BRANCH, TAG, COMMIT)
|
||||
and return the normalized identifier.
|
||||
"""
|
||||
if not isinstance(ref_str, str) or not ref_str.strip():
|
||||
return RefType.BRANCH, "main"
|
||||
|
||||
ref = ref_str.strip()
|
||||
|
||||
# Explicit git ref namespace
|
||||
if ref.startswith("refs/heads/"):
|
||||
return RefType.BRANCH, ref.removeprefix("refs/heads/")
|
||||
if ref.startswith("refs/tags/"):
|
||||
return RefType.TAG, ref.removeprefix("refs/tags/")
|
||||
|
||||
# Full 40-character commit SHA
|
||||
if COMMIT_SHA_RE.match(ref):
|
||||
return RefType.COMMIT, ref
|
||||
|
||||
# Version tags (e.g. v1.0.0, 2.4.1, v0.2-alpha)
|
||||
if SEMVER_TAG_RE.match(ref):
|
||||
return RefType.TAG, ref
|
||||
|
||||
# Non-versioned arbitrary string treated as branch
|
||||
return RefType.BRANCH, ref
|
||||
|
||||
|
||||
class SourceConfig(BaseModel):
|
||||
"""Upstream source provenance descriptor."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||
|
||||
url: str
|
||||
ref: str = "main"
|
||||
type: str = "git"
|
||||
ref_type: RefType = RefType.BRANCH
|
||||
transport: TransportScheme = TransportScheme.HTTPS
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def validate_source(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict):
|
||||
src_type = str(data.get("type", "git")).strip().lower()
|
||||
if src_type != "git":
|
||||
raise ManifestValidationError(
|
||||
f"Unsupported source type '{src_type}'. Only 'git' is supported."
|
||||
)
|
||||
data["type"] = src_type
|
||||
|
||||
raw_url = data.get("url")
|
||||
if raw_url is not None:
|
||||
transport, validated_url = validate_transport(str(raw_url))
|
||||
data["url"] = validated_url
|
||||
if "transport" not in data or data["transport"] is None:
|
||||
data["transport"] = transport
|
||||
|
||||
raw_ref = data.get("ref", "main")
|
||||
if raw_ref is not None:
|
||||
ref_type, clean_ref = classify_ref(str(raw_ref))
|
||||
data["ref"] = clean_ref
|
||||
if "ref_type" not in data or data["ref_type"] is None:
|
||||
data["ref_type"] = ref_type
|
||||
|
||||
return data
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"type": self.type,
|
||||
"url": self.url,
|
||||
"ref": self.ref,
|
||||
"ref_type": self.ref_type.value,
|
||||
"transport": self.transport.value,
|
||||
}
|
||||
|
||||
|
||||
class DeploymentConfig(BaseModel):
|
||||
"""Continuous deployment strategy and action policy."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||
|
||||
strategy: str = "compose"
|
||||
branch: str = "main"
|
||||
actions: list[str] = Field(default_factory=lambda: ["git_pull", "compose_up"])
|
||||
|
||||
@field_validator("strategy", mode="before")
|
||||
@classmethod
|
||||
def validate_strategy(cls, v: Any) -> str:
|
||||
clean = str(v).strip().lower()
|
||||
if clean not in ALLOWED_STRATEGIES:
|
||||
raise ManifestValidationError(
|
||||
f"Unsupported deployment strategy '{clean}'. Allowed: {sorted(ALLOWED_STRATEGIES)}"
|
||||
)
|
||||
return clean
|
||||
|
||||
@field_validator("actions", mode="before")
|
||||
@classmethod
|
||||
def validate_actions(cls, v: Any) -> list[str]:
|
||||
if isinstance(v, list):
|
||||
actions: list[str] = []
|
||||
for act in v:
|
||||
act_str = str(act).strip().lower()
|
||||
if act_str not in ALLOWED_ACTIONS:
|
||||
raise ManifestValidationError(
|
||||
f"Unsupported deployment action '{act_str}' (Prohibited deployment action '{act_str}'). Allowed: {sorted(ALLOWED_ACTIONS)}"
|
||||
)
|
||||
actions.append(act_str)
|
||||
if not actions:
|
||||
return ["compose_up"]
|
||||
return actions
|
||||
return ["compose_up"]
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return self.model_dump(mode="python")
|
||||
|
||||
|
||||
class HomepageConfig(BaseModel):
|
||||
"""Dashboard card metadata for Homepage."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||
|
||||
title: str
|
||||
group: str = "Applications"
|
||||
icon: str = "default.png"
|
||||
container: str = ""
|
||||
weight: int = 50
|
||||
|
||||
@field_validator("weight", mode="before")
|
||||
@classmethod
|
||||
def normalize_weight(cls, v: Any) -> int:
|
||||
try:
|
||||
return int(v)
|
||||
except (ValueError, TypeError):
|
||||
return 50
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return self.model_dump(mode="python")
|
||||
|
||||
|
||||
class Manifest(BaseModel):
|
||||
"""
|
||||
Authoritative Workload Manifest Model (Schema v1.0).
|
||||
Represents the full contract declared in a workload's app.yaml.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(
|
||||
extra="forbid",
|
||||
populate_by_name=True,
|
||||
ignored_types=(dict,),
|
||||
)
|
||||
|
||||
name: str
|
||||
schema_version: str = Field(default="1.0", alias="schemaVersion")
|
||||
domain: str = ""
|
||||
description: str = ""
|
||||
aliases: list[str] = Field(default_factory=list)
|
||||
visible: bool = True
|
||||
auth: bool = True
|
||||
networks: list[str] = Field(default_factory=lambda: ["proxy-net"])
|
||||
env: dict[str, str] = Field(default_factory=dict)
|
||||
deployment: DeploymentConfig = Field(default_factory=DeploymentConfig)
|
||||
source: SourceConfig | None = None
|
||||
homepage: HomepageConfig | None = None
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def prepare_manifest(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict):
|
||||
raw_name = data.get("name")
|
||||
if (
|
||||
raw_name is None
|
||||
or not isinstance(raw_name, str)
|
||||
or not raw_name.strip()
|
||||
):
|
||||
raise ManifestValidationError(
|
||||
"Manifest is missing mandatory string field 'name'."
|
||||
)
|
||||
clean_name = raw_name.strip()
|
||||
if not NAME_RE.match(clean_name):
|
||||
raise ManifestValidationError(
|
||||
f"Invalid workload name '{clean_name}'. Must be alphanumeric with optional '.' '_' '-', starting with alphanumeric."
|
||||
)
|
||||
data["name"] = clean_name
|
||||
|
||||
# Source: treat empty dict or missing url as None
|
||||
src = data.get("source")
|
||||
if isinstance(src, dict) and not src.get("url"):
|
||||
data["source"] = None
|
||||
|
||||
# Homepage default propagation
|
||||
hp = data.get("homepage")
|
||||
if isinstance(hp, dict):
|
||||
hp.setdefault("title", clean_name)
|
||||
hp.setdefault("container", clean_name)
|
||||
|
||||
return data
|
||||
|
||||
@field_validator("visible", "auth", mode="before")
|
||||
@classmethod
|
||||
def cast_bool(cls, v: Any) -> bool:
|
||||
if v is None:
|
||||
return True
|
||||
return bool(v)
|
||||
|
||||
@field_validator("aliases", mode="before")
|
||||
@classmethod
|
||||
def normalize_aliases(cls, v: Any) -> list[str]:
|
||||
|
||||
if isinstance(v, str):
|
||||
return [v.strip()] if v.strip() else []
|
||||
if isinstance(v, list):
|
||||
return [str(a).strip() for a in v if isinstance(a, str) and str(a).strip()]
|
||||
return []
|
||||
|
||||
@field_validator("networks", mode="before")
|
||||
@classmethod
|
||||
def normalize_networks(cls, v: Any) -> list[str]:
|
||||
if isinstance(v, list):
|
||||
clean = [str(n).strip() for n in v if str(n).strip()]
|
||||
if clean:
|
||||
return clean
|
||||
return ["proxy-net"]
|
||||
|
||||
@field_validator("env", mode="before")
|
||||
@classmethod
|
||||
def validate_env(cls, v: Any) -> dict[str, str]:
|
||||
if not isinstance(v, dict):
|
||||
return {}
|
||||
env: dict[str, str] = {}
|
||||
for raw_k, raw_v in v.items():
|
||||
k_str = str(raw_k).strip()
|
||||
if not ENV_KEY_RE.match(k_str) or k_str in RESERVED_ENV_KEYS:
|
||||
raise ManifestValidationError(
|
||||
f"Invalid or reserved environment variable key '{k_str}'. "
|
||||
f"Keys must match ^[a-zA-Z_][a-zA-Z0-9_]*$ and cannot be reserved."
|
||||
)
|
||||
env[k_str] = str(raw_v) if raw_v is not None else ""
|
||||
return env
|
||||
|
||||
@property
|
||||
def is_class_a(self) -> bool:
|
||||
"""Class A: Source-backed workload requiring upstream repository checkout & build."""
|
||||
return self.source is not None
|
||||
|
||||
@property
|
||||
def is_class_b(self) -> bool:
|
||||
"""Class B: Image-only workload deploying directly from container registries."""
|
||||
return self.source is None
|
||||
|
||||
@property
|
||||
def is_internal(self) -> bool:
|
||||
"""True if the workload does not expose a public TLS endpoint."""
|
||||
return (
|
||||
not self.domain
|
||||
or self.domain == "internal"
|
||||
or self.domain.endswith(".local")
|
||||
or ":" in self.domain
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
data: dict[str, Any] = {
|
||||
"schemaVersion": self.schema_version,
|
||||
"name": self.name,
|
||||
"domain": self.domain,
|
||||
"description": self.description,
|
||||
"aliases": list(self.aliases),
|
||||
"visible": self.visible,
|
||||
"auth": self.auth,
|
||||
"networks": list(self.networks),
|
||||
"env": dict(self.env),
|
||||
"deployment": self.deployment.to_dict(),
|
||||
"is_class_a": self.is_class_a,
|
||||
"is_class_b": self.is_class_b,
|
||||
"is_internal": self.is_internal,
|
||||
}
|
||||
if self.source:
|
||||
data["source"] = self.source.to_dict()
|
||||
if self.homepage:
|
||||
data["homepage"] = self.homepage.to_dict()
|
||||
return data
|
||||
|
||||
|
||||
def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest:
|
||||
"""
|
||||
Parse and strictly validate an app.yaml manifest into an authoritative Manifest object.
|
||||
|
||||
Accepts:
|
||||
- Path object pointing to an app.yaml
|
||||
- Raw YAML string content
|
||||
- Pre-parsed dictionary
|
||||
"""
|
||||
data: dict[str, Any] = {}
|
||||
|
||||
if isinstance(raw_input, Path):
|
||||
if not raw_input.is_file():
|
||||
raise ManifestValidationError(f"Manifest file not found: {raw_input}")
|
||||
try:
|
||||
content = raw_input.read_text(encoding="utf-8")
|
||||
except OSError as e:
|
||||
raise ManifestValidationError(
|
||||
f"Failed to read manifest {raw_input}: {e}"
|
||||
) from e
|
||||
try:
|
||||
data = (
|
||||
yaml.safe_load(content) if yaml else _parse_yaml_basic(content)
|
||||
) or {}
|
||||
except Exception as e:
|
||||
raise ManifestValidationError(
|
||||
f"YAML parsing error in {raw_input}: {e}"
|
||||
) from e
|
||||
elif isinstance(raw_input, str):
|
||||
try:
|
||||
data = (
|
||||
yaml.safe_load(raw_input) if yaml else _parse_yaml_basic(raw_input)
|
||||
) or {}
|
||||
except Exception as e:
|
||||
raise ManifestValidationError(f"YAML parsing error: {e}") from e
|
||||
elif isinstance(raw_input, dict):
|
||||
data = raw_input
|
||||
else:
|
||||
raise ManifestValidationError(
|
||||
f"Invalid input type for manifest parsing: {type(raw_input)}"
|
||||
)
|
||||
|
||||
if not isinstance(data, dict):
|
||||
raise ManifestValidationError(
|
||||
"Manifest root must be a YAML dictionary mapping."
|
||||
)
|
||||
|
||||
try:
|
||||
return Manifest.model_validate(data)
|
||||
except ValidationError as e:
|
||||
for err in e.errors():
|
||||
ctx = err.get("ctx", {})
|
||||
orig_err = ctx.get("error")
|
||||
if isinstance(orig_err, ManifestValidationError):
|
||||
raise orig_err from e
|
||||
first_error = e.errors()[0]
|
||||
msg = first_error.get("msg", str(e))
|
||||
if msg.startswith("Value error, "):
|
||||
msg = msg.removeprefix("Value error, ")
|
||||
loc = ".".join(str(p) for p in first_error.get("loc", []))
|
||||
if loc and first_error.get("type") == "extra_forbidden":
|
||||
raise ManifestValidationError(
|
||||
f"Manifest contains unrecognized or forbidden field '{loc}'."
|
||||
) from e
|
||||
raise ManifestValidationError(msg) from e
|
||||
|
||||
|
||||
def _parse_yaml_basic(content: str) -> dict[str, Any]:
|
||||
"""Lightweight fallback parser when PyYAML is unavailable."""
|
||||
result: dict[str, Any] = {}
|
||||
for line in content.splitlines():
|
||||
trimmed = line.strip()
|
||||
if not trimmed or trimmed.startswith("#") or ":" not in trimmed:
|
||||
continue
|
||||
k, v = trimmed.split(":", 1)
|
||||
k = k.strip()
|
||||
v = v.strip().strip("\"'")
|
||||
result[k] = v
|
||||
return result
|
||||
+1776
-82
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,354 @@
|
||||
"""
|
||||
provenance.py — Two-Axis Inspection & Upstream Provenance Resolver
|
||||
|
||||
Evaluates workload health along two independent axes:
|
||||
1. Local Deployment Axis: Local checkout cleanliness (* Dirty vs. ✓ Clean), branch, commit, and container runtime state.
|
||||
2. Upstream Provenance Axis: Upstream git repository state resolved via bounded `git ls-remote` (10s timeout).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
|
||||
from core_manifest import Manifest, RefType, SourceConfig
|
||||
|
||||
|
||||
class ProvenanceStatus(str, Enum):
|
||||
"""Evaluation result of local state vs. upstream software provenance."""
|
||||
|
||||
SYNCED = "✓ Synced"
|
||||
UPDATE_AVAILABLE = "↓ Update Available"
|
||||
IMAGE_ONLY = "— Image-Only (Class B)"
|
||||
DIRTY = "* Dirty"
|
||||
UNREACHABLE = "⚠ Unreachable"
|
||||
TIMEOUT = "⏱ Timed Out (10s)"
|
||||
UNKNOWN = "— Not Checked"
|
||||
NOT_CLONED = "✕ Missing Checkout"
|
||||
|
||||
|
||||
@dataclass
|
||||
class CheckoutStatus:
|
||||
"""Axis 1: Local deployment checkout state."""
|
||||
|
||||
is_git: bool
|
||||
is_dirty: bool
|
||||
branch: str
|
||||
commit_sha: str
|
||||
status_label: str
|
||||
|
||||
def to_dict(self) -> dict[str, str | bool]:
|
||||
return {
|
||||
"is_git": self.is_git,
|
||||
"is_dirty": self.is_dirty,
|
||||
"branch": self.branch,
|
||||
"commit_sha": self.commit_sha,
|
||||
"status_label": self.status_label,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class UpstreamProvenance:
|
||||
"""Axis 2: Upstream software provenance state."""
|
||||
|
||||
status: ProvenanceStatus
|
||||
remote_sha: str = ""
|
||||
target_ref: str = ""
|
||||
message: str = ""
|
||||
|
||||
def to_dict(self) -> dict[str, str]:
|
||||
return {
|
||||
"status": self.status.value,
|
||||
"remote_sha": self.remote_sha,
|
||||
"target_ref": self.target_ref,
|
||||
"message": self.message,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class TwoAxisStatus:
|
||||
"""Unified inspection combining local deployment and upstream provenance."""
|
||||
|
||||
app_name: str
|
||||
checkout: CheckoutStatus
|
||||
provenance: UpstreamProvenance
|
||||
docker_status: str
|
||||
image_revision: str | None = None
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"app_name": self.app_name,
|
||||
"checkout": self.checkout.to_dict(),
|
||||
"provenance": self.provenance.to_dict(),
|
||||
"docker_status": self.docker_status,
|
||||
"image_revision": self.image_revision,
|
||||
}
|
||||
|
||||
|
||||
def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
|
||||
"""
|
||||
Inspect local git repository checkout state.
|
||||
Reports clean/dirty status, active branch/ref, and current commit SHA.
|
||||
Supports standalone <dir_path>/.git checkouts (checked first) and
|
||||
unified monorepo checkouts where <dir_path>.parent/.git exists.
|
||||
"""
|
||||
path = Path(dir_path)
|
||||
subpath: str | None = None
|
||||
if (path / ".git").exists():
|
||||
git_root = path
|
||||
elif (path.parent / ".git").exists():
|
||||
git_root = path.parent
|
||||
subpath = f"{path.name}/"
|
||||
else:
|
||||
return CheckoutStatus(
|
||||
is_git=False,
|
||||
is_dirty=False,
|
||||
branch="",
|
||||
commit_sha="",
|
||||
status_label="— No Git Repo",
|
||||
)
|
||||
|
||||
# Clean git environment so calls are not polluted by outer hooks
|
||||
git_env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
||||
|
||||
# 1. Check cleanliness (scoped to workload subpath in monorepo mode)
|
||||
is_dirty = False
|
||||
git_error: str | None = None
|
||||
status_cmd = ["git", "-C", str(git_root), "status", "--porcelain"]
|
||||
if subpath is not None:
|
||||
status_cmd.extend(["--", subpath])
|
||||
try:
|
||||
status_res = subprocess.run(
|
||||
status_cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=5.0,
|
||||
env=git_env,
|
||||
)
|
||||
if status_res.returncode == 0:
|
||||
if status_res.stdout.strip():
|
||||
is_dirty = True
|
||||
else:
|
||||
git_error = f"⚠️ Git Error (exit {status_res.returncode})"
|
||||
except (subprocess.SubprocessError, OSError) as exc:
|
||||
is_dirty = False
|
||||
git_error = f"⚠️ Git Error ({exc.__class__.__name__})"
|
||||
|
||||
# 2. Get active branch
|
||||
branch = ""
|
||||
try:
|
||||
branch_res = subprocess.run(
|
||||
["git", "-C", str(git_root), "rev-parse", "--abbrev-ref", "HEAD"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=5.0,
|
||||
env=git_env,
|
||||
)
|
||||
if branch_res.returncode == 0:
|
||||
branch = branch_res.stdout.strip()
|
||||
if branch == "HEAD":
|
||||
# Detached HEAD, check describe
|
||||
desc_res = subprocess.run(
|
||||
["git", "-C", str(git_root), "describe", "--tags", "--exact-match"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=5.0,
|
||||
env=git_env,
|
||||
)
|
||||
if desc_res.returncode == 0 and desc_res.stdout.strip():
|
||||
branch = desc_res.stdout.strip()
|
||||
except (subprocess.SubprocessError, OSError):
|
||||
branch = "unknown"
|
||||
|
||||
# 3. Get commit SHA
|
||||
commit_sha = ""
|
||||
try:
|
||||
sha_res = subprocess.run(
|
||||
["git", "-C", str(git_root), "rev-parse", "--short", "HEAD"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=5.0,
|
||||
env=git_env,
|
||||
)
|
||||
if sha_res.returncode == 0:
|
||||
commit_sha = sha_res.stdout.strip()
|
||||
except (subprocess.SubprocessError, OSError):
|
||||
commit_sha = ""
|
||||
|
||||
# 4. Format status label
|
||||
if git_error:
|
||||
status_label = git_error
|
||||
else:
|
||||
state_symbol = "* Dirty" if is_dirty else "✓ Clean"
|
||||
ref_desc = f"{branch}@{commit_sha}" if commit_sha else branch
|
||||
status_label = f"{state_symbol} ({ref_desc})" if ref_desc else state_symbol
|
||||
|
||||
return CheckoutStatus(
|
||||
is_git=True,
|
||||
is_dirty=is_dirty,
|
||||
branch=branch,
|
||||
commit_sha=commit_sha,
|
||||
status_label=status_label,
|
||||
)
|
||||
|
||||
|
||||
def resolve_upstream_provenance(
|
||||
source: SourceConfig | None,
|
||||
local_commit: str = "",
|
||||
timeout: float = 10.0,
|
||||
) -> UpstreamProvenance:
|
||||
"""
|
||||
Resolve upstream provenance via bounded `git ls-remote`.
|
||||
Compares the declared upstream ref with the deployed local commit.
|
||||
Bounded by a 10-second timeout to prevent hanging on unresponsive remotes.
|
||||
"""
|
||||
if source is None:
|
||||
return UpstreamProvenance(
|
||||
status=ProvenanceStatus.IMAGE_ONLY,
|
||||
message="Class B workload deploys prebuilt container images directly",
|
||||
)
|
||||
|
||||
target_ref = source.ref
|
||||
remote_url = source.url
|
||||
|
||||
# Commits pinned directly in manifest cannot be checked via ls-remote ref matching
|
||||
if source.ref_type == RefType.COMMIT:
|
||||
is_match = local_commit and (
|
||||
source.ref.startswith(local_commit) or local_commit.startswith(source.ref)
|
||||
)
|
||||
status = (
|
||||
ProvenanceStatus.SYNCED if is_match else ProvenanceStatus.UPDATE_AVAILABLE
|
||||
)
|
||||
return UpstreamProvenance(
|
||||
status=status,
|
||||
remote_sha=source.ref,
|
||||
target_ref=source.ref[:7],
|
||||
message="Pinned immutable commit SHA",
|
||||
)
|
||||
|
||||
cmd = ["git", "ls-remote", "--exit-code", remote_url, target_ref]
|
||||
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=timeout,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return UpstreamProvenance(
|
||||
status=ProvenanceStatus.TIMEOUT,
|
||||
target_ref=target_ref,
|
||||
message=f"Upstream check timed out after {int(timeout)}s ({remote_url})",
|
||||
)
|
||||
except (subprocess.SubprocessError, OSError) as e:
|
||||
return UpstreamProvenance(
|
||||
status=ProvenanceStatus.UNREACHABLE,
|
||||
target_ref=target_ref,
|
||||
message=f"Network error querying upstream: {e}",
|
||||
)
|
||||
|
||||
if proc.returncode != 0:
|
||||
# Check if ref was not found on remote (exit code 2 for git ls-remote)
|
||||
err_msg = proc.stderr.strip() or f"Ref '{target_ref}' not found on remote."
|
||||
return UpstreamProvenance(
|
||||
status=ProvenanceStatus.UNREACHABLE,
|
||||
target_ref=target_ref,
|
||||
message=f"Failed to query remote ({remote_url}): {err_msg}",
|
||||
)
|
||||
|
||||
# Parse remote SHA from ls-remote output (Format: <SHA>\t<ref_name>)
|
||||
remote_sha = ""
|
||||
for line in proc.stdout.splitlines():
|
||||
parts = line.strip().split()
|
||||
if len(parts) >= 2 and (
|
||||
parts[1] == target_ref
|
||||
or parts[1] == f"refs/heads/{target_ref}"
|
||||
or parts[1] == f"refs/tags/{target_ref}"
|
||||
or parts[1] == f"refs/tags/{target_ref}^{{}}"
|
||||
):
|
||||
remote_sha = parts[0]
|
||||
# Peaked tags (^{}) take precedence over lightweight tag refs
|
||||
if parts[1].endswith("^{}"):
|
||||
break
|
||||
|
||||
if not remote_sha and proc.stdout.strip():
|
||||
# Fallback: take first match SHA
|
||||
remote_sha = proc.stdout.strip().split()[0]
|
||||
|
||||
if not remote_sha:
|
||||
return UpstreamProvenance(
|
||||
status=ProvenanceStatus.UNREACHABLE,
|
||||
target_ref=target_ref,
|
||||
message=f"No matching ref found for '{target_ref}' at {remote_url}",
|
||||
)
|
||||
|
||||
# Compare local commit with remote SHA
|
||||
is_synced = False
|
||||
if local_commit and (
|
||||
remote_sha.startswith(local_commit) or local_commit.startswith(remote_sha[:7])
|
||||
):
|
||||
is_synced = True
|
||||
|
||||
status = ProvenanceStatus.SYNCED if is_synced else ProvenanceStatus.UPDATE_AVAILABLE
|
||||
short_remote = remote_sha[:7]
|
||||
msg = f"Upstream at {short_remote}" if not is_synced else "Up to date with upstream"
|
||||
|
||||
return UpstreamProvenance(
|
||||
status=status,
|
||||
remote_sha=remote_sha,
|
||||
target_ref=target_ref,
|
||||
message=msg,
|
||||
)
|
||||
|
||||
|
||||
def inspect_workload_two_axis(
|
||||
app_dir: Path | str,
|
||||
manifest: Manifest,
|
||||
fetch_upstream: bool = False,
|
||||
docker_status: str = "⚪ Not Stack",
|
||||
image_revision: str | None = None,
|
||||
timeout: float = 10.0,
|
||||
) -> TwoAxisStatus:
|
||||
"""
|
||||
Perform two-axis status inspection of a single workload.
|
||||
"""
|
||||
path = Path(app_dir)
|
||||
|
||||
# Axis 1: Local Deployment Checkout
|
||||
checkout = get_local_checkout_status(path)
|
||||
|
||||
# Axis 2: Upstream Provenance
|
||||
if manifest.is_class_b:
|
||||
provenance = UpstreamProvenance(
|
||||
status=ProvenanceStatus.IMAGE_ONLY,
|
||||
message="Class B (Image-Only)",
|
||||
)
|
||||
elif not fetch_upstream:
|
||||
provenance = UpstreamProvenance(
|
||||
status=ProvenanceStatus.UNKNOWN,
|
||||
target_ref=manifest.source.ref if manifest.source else "",
|
||||
message="Pass --fetch to query upstream repository",
|
||||
)
|
||||
else:
|
||||
provenance = resolve_upstream_provenance(
|
||||
manifest.source,
|
||||
local_commit=checkout.commit_sha,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
return TwoAxisStatus(
|
||||
app_name=manifest.name,
|
||||
checkout=checkout,
|
||||
provenance=provenance,
|
||||
docker_status=docker_status,
|
||||
image_revision=image_revision,
|
||||
)
|
||||
@@ -1,49 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Path to your configuration
|
||||
# Changed to project relative path
|
||||
ENV_FILE="${ENV_FILE:-.env}"
|
||||
|
||||
# 1. Load Environment Variables
|
||||
if [ -f "$ENV_FILE" ]; then
|
||||
export $(grep -v '^#' "$ENV_FILE" | xargs)
|
||||
else
|
||||
echo "Error: .env file not found at $ENV_FILE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 2. Fetch Domain ID dynamically using the DOMAIN variable
|
||||
echo "Fetching Domain ID for $DOMAIN..."
|
||||
DOMAIN_ID=$(curl -s -X GET "https://api.dynu.com/v2/dns" \
|
||||
-H "API-Key: $DYNU_API_KEY" | \
|
||||
jq -r --arg DOMAIN "$DOMAIN" '.domains[] | select(.name==$DOMAIN) | .id')
|
||||
|
||||
if [ -z "$DOMAIN_ID" ] || [ "$DOMAIN_ID" == "null" ]; then
|
||||
echo "Error: Could not find Domain ID for $DOMAIN. Check your API key and domain name."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Targeting Domain ID: $DOMAIN_ID"
|
||||
|
||||
# 3. Identify and Delete all TXT records
|
||||
echo "Searching for stale TXT records..."
|
||||
TXT_RECORD_IDS=$(curl -s -X GET "https://api.dynu.com/v2/dns/$DOMAIN_ID/record" \
|
||||
-H "API-Key: $DYNU_API_KEY" | \
|
||||
jq -r '.dnsRecords[] | select(.recordType=="TXT") | .id')
|
||||
|
||||
if [ -z "$TXT_RECORD_IDS" ] || [ "$TXT_RECORD_IDS" == "null" ]; then
|
||||
echo "No TXT records found. Quota should be clear."
|
||||
else
|
||||
for ID in $TXT_RECORD_IDS; do
|
||||
echo "Deleting TXT Record ID: $ID"
|
||||
curl -s -X DELETE "https://api.dynu.com/v2/dns/$DOMAIN_ID/record/$ID" \
|
||||
-H "API-Key: $DYNU_API_KEY" > /dev/null
|
||||
done
|
||||
echo "Purge complete."
|
||||
fi
|
||||
|
||||
# 4. Restart Traefik to trigger new challenge
|
||||
echo "Restarting Traefik..."
|
||||
docker compose restart traefik
|
||||
|
||||
echo "Process complete. Monitor logs with: docker logs traefik 2>&1 | grep -iE 'acme|dynu'"
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
# scripts/run-tests - Automated test & invariant verification runner for Homelab Core
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
echo "🔍 Running code linters (ruff)..."
|
||||
if command -v ruff &>/dev/null; then
|
||||
ruff check .
|
||||
else
|
||||
nix develop --command ruff check .
|
||||
fi
|
||||
|
||||
echo "🔎 Running static type analysis (pyright)..."
|
||||
if command -v pyright &>/dev/null; then
|
||||
pyright
|
||||
else
|
||||
nix develop --command pyright
|
||||
fi
|
||||
|
||||
echo "🧪 Running architecture & security test suite (pytest)..."
|
||||
if [ -x ".venv/bin/pytest" ]; then
|
||||
.venv/bin/pytest tests/
|
||||
elif command -v pytest &>/dev/null; then
|
||||
pytest tests/
|
||||
else
|
||||
nix develop --command pytest tests/
|
||||
fi
|
||||
|
||||
echo "❄️ Verifying NixOS flake & sandbox checks..."
|
||||
nix flake check
|
||||
nix eval .#nixosConfigurations.server.config.system.build.toplevel.drvPath --json >/dev/null
|
||||
|
||||
echo "✨ All tests and architectural invariants passed successfully!"
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
workload_grants.py — Host-Granted Workload Capability Loader & Schema (ADR-0005)
|
||||
|
||||
Loads and validates /etc/homelab/grants.json (or HOMELAB_GRANTS_FILE) using strict
|
||||
Pydantic v2 models (ConfigDict(extra="forbid")).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
|
||||
|
||||
DEFAULT_GRANTS_FILE = Path("/etc/homelab/grants.json")
|
||||
PRIVILEGED_GROUPS: frozenset[str] = frozenset({"0", "root", "wheel", "docker"})
|
||||
|
||||
|
||||
class WorkloadGrantsError(Exception):
|
||||
"""Raised when the host capability grants file fails integrity or schema checks."""
|
||||
|
||||
|
||||
class WorkloadGrant(BaseModel):
|
||||
"""Explicit host-granted capabilities for a single workload."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
devices: list[str] = Field(default_factory=list)
|
||||
groups: list[str] = Field(default_factory=list)
|
||||
readOnlyPaths: list[str] = Field(default_factory=list)
|
||||
|
||||
@field_validator("groups")
|
||||
@classmethod
|
||||
def _validate_groups(cls, values: list[str]) -> list[str]:
|
||||
cleaned: list[str] = []
|
||||
for raw in values:
|
||||
group = raw.strip()
|
||||
if not group:
|
||||
raise ValueError("Granted group entry cannot be empty.")
|
||||
if group.lower() in PRIVILEGED_GROUPS:
|
||||
raise ValueError(
|
||||
f"Privileged group '{group}' cannot be granted to workloads."
|
||||
)
|
||||
cleaned.append(group)
|
||||
return cleaned
|
||||
|
||||
@field_validator("devices", "readOnlyPaths")
|
||||
@classmethod
|
||||
def _validate_absolute_paths(cls, values: list[str]) -> list[str]:
|
||||
cleaned: list[str] = []
|
||||
for raw in values:
|
||||
path_str = raw.strip()
|
||||
if not path_str:
|
||||
raise ValueError("Granted path entry cannot be empty.")
|
||||
posix = PurePosixPath(path_str)
|
||||
if not posix.is_absolute():
|
||||
raise ValueError(
|
||||
f"Granted path '{path_str}' must be an absolute path."
|
||||
)
|
||||
if ".." in posix.parts:
|
||||
raise ValueError(
|
||||
f"Granted path '{path_str}' must not contain '..' traversal."
|
||||
)
|
||||
cleaned.append(path_str)
|
||||
return cleaned
|
||||
|
||||
|
||||
class GrantsRegistry(BaseModel):
|
||||
"""Root schema for /etc/homelab/grants.json."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
schemaVersion: Literal["1.0"] = "1.0"
|
||||
workloads: dict[str, WorkloadGrant] = Field(default_factory=dict)
|
||||
|
||||
|
||||
def load_workload_grants(
|
||||
grants_file: Path | None = None,
|
||||
*,
|
||||
verify_permissions: bool | None = None,
|
||||
) -> dict[str, WorkloadGrant]:
|
||||
"""
|
||||
Load host-granted workload capabilities from grants_file or HOMELAB_GRANTS_FILE.
|
||||
|
||||
- If the target file does not exist (and is not a symlink), returns {} (zero grants).
|
||||
- If the file is present (or is a symlink) and fails permission/integrity checks,
|
||||
is unreadable, or fails JSON/Pydantic validation, raises WorkloadGrantsError.
|
||||
"""
|
||||
if grants_file is None:
|
||||
env_path = os.environ.get("HOMELAB_GRANTS_FILE", "").strip()
|
||||
target_path = Path(env_path) if env_path else DEFAULT_GRANTS_FILE
|
||||
else:
|
||||
target_path = grants_file
|
||||
|
||||
should_verify = (
|
||||
(target_path == DEFAULT_GRANTS_FILE)
|
||||
if verify_permissions is None
|
||||
else verify_permissions
|
||||
)
|
||||
|
||||
if not target_path.exists() and not target_path.is_symlink():
|
||||
return {}
|
||||
|
||||
if should_verify:
|
||||
try:
|
||||
st = os.lstat(target_path)
|
||||
except OSError as exc:
|
||||
raise WorkloadGrantsError(
|
||||
f"Failed to stat grants file '{target_path}': {exc}"
|
||||
) from exc
|
||||
|
||||
if stat.S_ISLNK(st.st_mode) or not stat.S_ISREG(st.st_mode):
|
||||
raise WorkloadGrantsError(
|
||||
f"Grants file '{target_path}' must be a regular non-symlink file."
|
||||
)
|
||||
if st.st_uid != 0:
|
||||
raise WorkloadGrantsError(
|
||||
f"Grants file '{target_path}' must be owned by root (uid 0)."
|
||||
)
|
||||
if (st.st_mode & 0o022) != 0:
|
||||
raise WorkloadGrantsError(
|
||||
f"Grants file '{target_path}' must not be group- or world-writable."
|
||||
)
|
||||
|
||||
try:
|
||||
raw_text = target_path.read_text(encoding="utf-8")
|
||||
except OSError as exc:
|
||||
raise WorkloadGrantsError(
|
||||
f"Failed to read grants file '{target_path}': {exc}"
|
||||
) from exc
|
||||
|
||||
try:
|
||||
payload = json.loads(raw_text)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise WorkloadGrantsError(
|
||||
f"Malformed JSON in grants file '{target_path}': {exc}"
|
||||
) from exc
|
||||
|
||||
try:
|
||||
registry = GrantsRegistry.model_validate(payload)
|
||||
except ValidationError as exc:
|
||||
raise WorkloadGrantsError(
|
||||
f"Invalid schema in grants file '{target_path}': {exc}"
|
||||
) from exc
|
||||
|
||||
return registry.workloads
|
||||
@@ -0,0 +1,6 @@
|
||||
[mutmut]
|
||||
also_copy=
|
||||
pyproject.toml
|
||||
docker-compose.yml
|
||||
config
|
||||
scripts
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Shared pytest fixtures for Canopy NixOS Core test suites."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
import pytest
|
||||
|
||||
_STRIPPED_WORKLOAD_ENV_VARS = frozenset(
|
||||
{"HOMELAB_DEPLOYMENTS_FILE", "WORKLOADS_DIR", "SITES_DIR"}
|
||||
)
|
||||
_SCRIPTS_DIR = Path(__file__).resolve().parent.parent / "scripts"
|
||||
|
||||
|
||||
class IsolatedScriptRunner(Protocol):
|
||||
"""Callable protocol for executing a Python expression in an isolated env."""
|
||||
|
||||
def __call__(
|
||||
self, expr: str, extra_env: dict[str, str] | None = None
|
||||
) -> str: ...
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def run_isolated_script_expr(tmp_path: Path) -> IsolatedScriptRunner:
|
||||
"""
|
||||
Execute a Python expression in a clean subprocess with workload env vars stripped.
|
||||
|
||||
Strips ``HOMELAB_DEPLOYMENTS_FILE``, ``WORKLOADS_DIR``, and ``SITES_DIR``,
|
||||
sets ``HOME`` to ``tmp_path`` and ``PYTHONPATH`` to ``scripts/``, and
|
||||
merges any optional ``extra_env`` overrides.
|
||||
"""
|
||||
|
||||
def _run(expr: str, extra_env: dict[str, str] | None = None) -> str:
|
||||
env = {
|
||||
k: v
|
||||
for k, v in os.environ.items()
|
||||
if k not in _STRIPPED_WORKLOAD_ENV_VARS
|
||||
}
|
||||
env["HOME"] = str(tmp_path)
|
||||
env["PYTHONPATH"] = str(_SCRIPTS_DIR)
|
||||
if extra_env:
|
||||
env.update(extra_env)
|
||||
return subprocess.check_output(
|
||||
[sys.executable, "-c", expr],
|
||||
env=env,
|
||||
text=True,
|
||||
).strip()
|
||||
|
||||
return _run
|
||||
@@ -0,0 +1,338 @@
|
||||
"""
|
||||
Security and structural tests for the read-only `agents` SSH user,
|
||||
`ForceCommand` allowlist wrapper, and loopback-only `socket-proxy` binding.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
NIXOS_CONFIG = CORE_ROOT / "nixos" / "configuration.nix"
|
||||
COMPOSE_FILE = CORE_ROOT / "docker-compose.yml"
|
||||
FORCE_COMMAND_SCRIPT = CORE_ROOT / "nixos" / "scripts" / "agents-force-command.sh"
|
||||
|
||||
EXPECTED_AGENT_PUBKEY = (
|
||||
"ssh-ed25519 "
|
||||
"AAAAC3NzaC1lZDI1NTE5AAAAIE1pxTdygG5696q0jT7clfJZWtx48ugfUjpzvkHzovVd "
|
||||
"canopy-agents"
|
||||
)
|
||||
|
||||
|
||||
def _extract_nix_block(content: str, header_pattern: str) -> str:
|
||||
"""Extract a brace-delimited Nix attribute block starting at header_pattern."""
|
||||
match = re.search(header_pattern, content)
|
||||
assert match is not None, f"Missing Nix block matching: {header_pattern}"
|
||||
pos = match.end()
|
||||
# Skip `let ... in` bindings if present before the attribute set `{ ... }`
|
||||
tail = content[pos:]
|
||||
if re.match(r"\s*let\b", tail):
|
||||
in_match = re.search(r"\bin\s*\{", tail)
|
||||
assert in_match is not None, f"Missing 'in {{' for let-block: {header_pattern}"
|
||||
start = pos + in_match.end() - 1
|
||||
else:
|
||||
start = content.find("{", pos)
|
||||
assert start != -1, f"Opening brace not found for: {header_pattern}"
|
||||
depth = 0
|
||||
for idx in range(start, len(content)):
|
||||
ch = content[idx]
|
||||
if ch == "{":
|
||||
depth += 1
|
||||
elif ch == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return content[start : idx + 1]
|
||||
raise AssertionError(f"Unclosed Nix block for: {header_pattern}")
|
||||
|
||||
|
||||
def _setup_mock_bin(tmp_path: Path) -> tuple[Path, Path]:
|
||||
"""Create mock docker, journalctl, and appctl binaries that log invocations."""
|
||||
mock_bin = tmp_path / "mock_bin"
|
||||
mock_bin.mkdir()
|
||||
invocations_log = tmp_path / "invocations.log"
|
||||
bash_bin = shutil.which("bash") or "/bin/bash"
|
||||
|
||||
for cmd in ("docker", "journalctl", "appctl"):
|
||||
stub = mock_bin / cmd
|
||||
stub.write_text(
|
||||
f"#!{bash_bin}\n"
|
||||
f'printf "%s|%s|%s|%s|%s\\n" '
|
||||
f'"{cmd}" "$*" "${{CORE_DIR:-}}" "${{WORKLOADS_DIR:-}}" "${{DOCKER_HOST:-}}" '
|
||||
f'>> "{invocations_log}"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
stub.chmod(0o755)
|
||||
|
||||
return mock_bin, invocations_log
|
||||
|
||||
|
||||
def _run_force_command(
|
||||
ssh_original_command: str | None,
|
||||
tmp_path: Path,
|
||||
) -> tuple[subprocess.CompletedProcess[str], Path]:
|
||||
"""Execute agents-force-command.sh with isolated mock PATH and SSH_ORIGINAL_COMMAND."""
|
||||
assert FORCE_COMMAND_SCRIPT.exists(), (
|
||||
f"ForceCommand script not found at {FORCE_COMMAND_SCRIPT}"
|
||||
)
|
||||
mock_bin, invocations_log = _setup_mock_bin(tmp_path)
|
||||
env = {
|
||||
"PATH": f"{mock_bin}:{os.environ.get('PATH', '/usr/bin:/bin')}",
|
||||
"HOME": str(tmp_path),
|
||||
}
|
||||
if ssh_original_command is not None:
|
||||
env["SSH_ORIGINAL_COMMAND"] = ssh_original_command
|
||||
|
||||
bash_bin = shutil.which("bash") or "/bin/bash"
|
||||
proc = subprocess.run(
|
||||
[bash_bin, str(FORCE_COMMAND_SCRIPT)],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
return proc, invocations_log
|
||||
|
||||
|
||||
def test_socket_proxy_binds_loopback_only():
|
||||
"""Ensure socket-proxy publishes port 2375 strictly on 127.0.0.1."""
|
||||
compose = yaml.safe_load(COMPOSE_FILE.read_text(encoding="utf-8"))
|
||||
services = compose.get("services", {})
|
||||
assert "socket-proxy" in services, "socket-proxy service must exist"
|
||||
|
||||
ports = services["socket-proxy"].get("ports", [])
|
||||
assert isinstance(ports, list) and len(ports) > 0, (
|
||||
"socket-proxy must declare non-empty ports list"
|
||||
)
|
||||
assert all(isinstance(p, str) and p.startswith("127.0.0.1:") for p in ports), (
|
||||
f"Every socket-proxy port must bind strictly to 127.0.0.1, got: {ports!r}"
|
||||
)
|
||||
assert "127.0.0.1:2375:2375" in ports, (
|
||||
"socket-proxy must bind 127.0.0.1:2375:2375"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_agents_user_least_privilege():
|
||||
"""Verify users.users.agents has read-only groups and excludes wheel/docker."""
|
||||
content = NIXOS_CONFIG.read_text(encoding="utf-8")
|
||||
agents_block = _extract_nix_block(content, r"users\.users\.agents\s*=")
|
||||
|
||||
assert re.search(r"isNormalUser\s*=\s*true\s*;", agents_block), (
|
||||
"users.users.agents must set isNormalUser = true"
|
||||
)
|
||||
assert EXPECTED_AGENT_PUBKEY in agents_block, (
|
||||
"users.users.agents must configure the canopy-agents SSH public key"
|
||||
)
|
||||
|
||||
groups_match = re.search(r"extraGroups\s*=\s*\[(.*?)\]\s*;", agents_block, re.DOTALL)
|
||||
assert groups_match is not None, "users.users.agents must declare extraGroups"
|
||||
groups_text = groups_match.group(1)
|
||||
|
||||
actual_groups = set(re.findall(r'"([^"]+)"', groups_text))
|
||||
assert actual_groups == {"homelab-operators", "systemd-journal"}, (
|
||||
f"agents extraGroups must be strictly {{'homelab-operators', 'systemd-journal'}}, got: {actual_groups!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_openssh_match_user_agents_hardening():
|
||||
"""Verify services.openssh configures Match User agents with ForceCommand and hardening."""
|
||||
content = NIXOS_CONFIG.read_text(encoding="utf-8")
|
||||
ssh_block = _extract_nix_block(content, r"services\.openssh\s*=")
|
||||
|
||||
assert "Match User agents" in ssh_block, (
|
||||
"services.openssh must configure Match User agents"
|
||||
)
|
||||
match_section = ssh_block[ssh_block.index("Match User agents") :]
|
||||
|
||||
required_directives = [
|
||||
r"ForceCommand\s+\S*agents-force-command\b",
|
||||
r"AllowTcpForwarding\s+no",
|
||||
r"X11Forwarding\s+no",
|
||||
r"AllowAgentForwarding\s+no",
|
||||
r"PermitTTY\s+no",
|
||||
r"PasswordAuthentication\s+no",
|
||||
]
|
||||
for pattern in required_directives:
|
||||
assert re.search(pattern, match_section), (
|
||||
f"Match User agents must include directive matching: {pattern}"
|
||||
)
|
||||
|
||||
|
||||
def test_force_command_script_has_no_eval_or_sh_c():
|
||||
"""Ensure agents-force-command.sh never uses eval or subshell invocation."""
|
||||
assert FORCE_COMMAND_SCRIPT.exists(), (
|
||||
f"ForceCommand script not found at {FORCE_COMMAND_SCRIPT}"
|
||||
)
|
||||
content = FORCE_COMMAND_SCRIPT.read_text(encoding="utf-8")
|
||||
assert "eval " not in content, "Dangerous 'eval' detected in ForceCommand script"
|
||||
assert "sh -c" not in content, "Dangerous 'sh -c' detected in ForceCommand script"
|
||||
assert "bash -c" not in content, "Dangerous 'bash -c' detected in ForceCommand script"
|
||||
|
||||
|
||||
def test_force_command_exports_expected_environment(tmp_path: Path):
|
||||
"""Verify ForceCommand exports CORE_DIR, WORKLOADS_DIR, and loopback DOCKER_HOST."""
|
||||
proc, invocations_log = _run_force_command("docker ps", tmp_path)
|
||||
assert proc.returncode == 0, f"Unexpected failure: {proc.stderr}"
|
||||
lines = invocations_log.read_text(encoding="utf-8").strip().splitlines()
|
||||
assert len(lines) == 1
|
||||
cmd, args, core_dir, workloads_dir, docker_host = lines[0].split("|")
|
||||
assert cmd == "docker"
|
||||
assert args == "ps"
|
||||
assert core_dir == "/home/operator/Core"
|
||||
assert workloads_dir == "/home/operator/Workloads"
|
||||
assert docker_host == "tcp://127.0.0.1:2375"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("command", "expected_bin", "expected_args"),
|
||||
[
|
||||
("docker ps", "docker", "ps"),
|
||||
("docker ps -a --format {{.Names}}", "docker", "ps -a --format {{.Names}}"),
|
||||
("docker logs --tail 50 traefik", "docker", "logs --tail 50 traefik"),
|
||||
("docker inspect traefik", "docker", "inspect traefik"),
|
||||
(
|
||||
"journalctl -u homelab-appctl -n 50 --no-pager",
|
||||
"journalctl",
|
||||
"-u homelab-appctl -n 50 --no-pager",
|
||||
),
|
||||
("appctl list --core", "appctl", "list --core"),
|
||||
("appctl status", "appctl", "status"),
|
||||
("appctl info traefik", "appctl", "info traefik"),
|
||||
("appctl logs traefik", "appctl", "logs traefik"),
|
||||
("appctl ssl --all", "appctl", "ssl --all"),
|
||||
("appctl health", "appctl", "health"),
|
||||
("appctl resolve traefik", "appctl", "resolve traefik"),
|
||||
],
|
||||
)
|
||||
def test_force_command_allows_read_only_commands(
|
||||
tmp_path: Path, command: str, expected_bin: str, expected_args: str
|
||||
):
|
||||
"""Verify allowlisted read-only commands execute cleanly with exact arguments."""
|
||||
proc, invocations_log = _run_force_command(command, tmp_path)
|
||||
assert proc.returncode == 0, f"Allowed command '{command}' failed: {proc.stderr}"
|
||||
lines = invocations_log.read_text(encoding="utf-8").strip().splitlines()
|
||||
assert len(lines) == 1
|
||||
cmd, args, *_ = lines[0].split("|")
|
||||
assert cmd == expected_bin
|
||||
assert args == expected_args
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad_command",
|
||||
[
|
||||
None,
|
||||
"",
|
||||
" ",
|
||||
"docker ps; id",
|
||||
"docker ps && id",
|
||||
"docker ps || id",
|
||||
"docker ps | cat",
|
||||
"docker ps `id`",
|
||||
"docker ps $(id)",
|
||||
"docker ps > /tmp/pwn",
|
||||
"docker ps < /etc/passwd",
|
||||
"docker ps\nid",
|
||||
"docker ps\rid",
|
||||
"docker ps 'traefik'",
|
||||
'docker ps "traefik"',
|
||||
"docker ps \\ id",
|
||||
],
|
||||
)
|
||||
def test_force_command_rejects_empty_and_metacharacters(
|
||||
tmp_path: Path, bad_command: str | None
|
||||
):
|
||||
"""Verify empty commands and shell metacharacters are rejected without execution."""
|
||||
proc, invocations_log = _run_force_command(bad_command, tmp_path)
|
||||
assert proc.returncode != 0, f"Dangerous input was unexpectedly allowed: {bad_command!r}"
|
||||
assert not invocations_log.exists(), (
|
||||
f"Command stub should not have been executed for: {bad_command!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"disallowed_command",
|
||||
[
|
||||
"sudo id",
|
||||
"su root",
|
||||
"sh",
|
||||
"bash",
|
||||
"cat /etc/shadow",
|
||||
"rm -rf /tmp/foo",
|
||||
"systemctl restart docker",
|
||||
"docker",
|
||||
"docker run alpine",
|
||||
"docker exec -it traefik sh",
|
||||
"docker rm traefik",
|
||||
"docker build .",
|
||||
"docker stop traefik",
|
||||
"docker start traefik",
|
||||
"docker restart traefik",
|
||||
"docker kill traefik",
|
||||
"docker compose up -d",
|
||||
"docker -H unix:///var/run/docker.sock ps",
|
||||
"journalctl --flush",
|
||||
"journalctl --rotate",
|
||||
"journalctl --vacuum-size=1M",
|
||||
"journalctl --vacuum-time=1d",
|
||||
"journalctl --vacuum-files=1",
|
||||
"journalctl --relinquish-var",
|
||||
"journalctl --sync",
|
||||
"journalctl --setup-keys",
|
||||
"journalctl --update-catalog",
|
||||
"appctl",
|
||||
"appctl up traefik",
|
||||
"appctl down traefik",
|
||||
"appctl restart traefik",
|
||||
"appctl update traefik",
|
||||
"appctl pull traefik",
|
||||
"appctl sync",
|
||||
"appctl config",
|
||||
"appctl deploy traefik",
|
||||
"appctl complete services",
|
||||
],
|
||||
)
|
||||
def test_force_command_rejects_disallowed_commands_and_subcommands(
|
||||
tmp_path: Path, disallowed_command: str
|
||||
):
|
||||
"""Verify disallowed binaries, mutating subcommands, and mutating flags are rejected."""
|
||||
proc, invocations_log = _run_force_command(disallowed_command, tmp_path)
|
||||
assert proc.returncode != 0, (
|
||||
f"Disallowed command was unexpectedly allowed: {disallowed_command!r}"
|
||||
)
|
||||
assert not invocations_log.exists(), (
|
||||
f"Command stub should not have been executed for: {disallowed_command!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("subcmd", ["ps", "logs", "inspect"])
|
||||
@pytest.mark.parametrize(
|
||||
"override_flag",
|
||||
[
|
||||
"-H unix:///var/run/docker.sock",
|
||||
"-H=unix:///var/run/docker.sock",
|
||||
"--host unix:///var/run/docker.sock",
|
||||
"--host=unix:///var/run/docker.sock",
|
||||
"--context default",
|
||||
"--context=default",
|
||||
"-c default",
|
||||
"-c=default",
|
||||
"--config /tmp",
|
||||
"--config=/tmp",
|
||||
],
|
||||
)
|
||||
def test_force_command_rejects_post_subcommand_docker_override_flags(
|
||||
tmp_path: Path, subcmd: str, override_flag: str
|
||||
):
|
||||
"""Verify Docker connection/context/config override flags are rejected after valid subcommands."""
|
||||
command = f"docker {subcmd} {override_flag}"
|
||||
proc, invocations_log = _run_force_command(command, tmp_path)
|
||||
assert proc.returncode != 0, (
|
||||
f"Docker override flag was unexpectedly allowed: {command!r}"
|
||||
)
|
||||
assert not invocations_log.exists(), (
|
||||
f"Command stub should not have been executed for: {command!r}"
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,573 @@
|
||||
"""
|
||||
Security invariant tests for Docker Compose and container isolation.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
from appctl_audit import AuditLogger, TargetLockManager
|
||||
from appctl_auth import Principal, Role
|
||||
from appctl_contracts import OperationRequest
|
||||
from appctl_router import OperationalRouter, assemble_workload_env
|
||||
from core_manifest import parse_manifest
|
||||
|
||||
# Comment-out reason: testing pyproject-level pythonpath definition
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
|
||||
|
||||
def test_socket_proxy_is_strictly_read_only():
|
||||
"""Ensure socket-proxy container blocks state-modifying requests (POST=0, DELETE=0)."""
|
||||
compose_path = CORE_ROOT / "docker-compose.yml"
|
||||
with open(compose_path, encoding="utf-8") as f:
|
||||
compose = yaml.safe_load(f)
|
||||
|
||||
services = compose.get("services", {})
|
||||
assert "socket-proxy" in services, "socket-proxy service must exist"
|
||||
|
||||
env = services["socket-proxy"].get("environment", [])
|
||||
env_dict = {}
|
||||
for item in env:
|
||||
if "=" in item:
|
||||
k, v = item.split("=", 1)
|
||||
env_dict[k.strip()] = v.strip()
|
||||
|
||||
assert env_dict.get("POST") == "0", "socket-proxy must strictly enforce POST=0"
|
||||
assert env_dict.get("DELETE") == "0", "socket-proxy must strictly enforce DELETE=0"
|
||||
assert env_dict.get("BUILD") == "0", "socket-proxy must strictly enforce BUILD=0"
|
||||
assert env_dict.get("EXEC") == "0", "socket-proxy must strictly enforce EXEC=0"
|
||||
|
||||
|
||||
def test_no_direct_docker_sock_mounts_except_socket_proxy():
|
||||
"""Ensure no application or control service mounts /var/run/docker.sock except socket-proxy:ro."""
|
||||
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", {})
|
||||
for name, svc in services.items():
|
||||
volumes = svc.get("volumes", [])
|
||||
for vol in volumes:
|
||||
if isinstance(vol, str) and "/var/run/docker.sock" in vol:
|
||||
assert name == "socket-proxy", (
|
||||
f"Service '{name}' directly mounts docker.sock!"
|
||||
)
|
||||
assert vol.endswith(":ro"), (
|
||||
"socket-proxy docker.sock mount must be read-only (:ro)"
|
||||
)
|
||||
|
||||
|
||||
def test_no_privileged_containers():
|
||||
"""Ensure no service in core docker-compose runs with privileged: true."""
|
||||
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", {})
|
||||
for name, svc in services.items():
|
||||
privileged = svc.get("privileged", False)
|
||||
assert privileged is not True, (
|
||||
f"Service '{name}' is configured as privileged: true!"
|
||||
)
|
||||
|
||||
|
||||
def test_no_shell_true_in_core_scripts():
|
||||
"""Ensure shell=True is completely absent from gitops execution engines."""
|
||||
scripts_dir = CORE_ROOT / "scripts"
|
||||
for py_file in scripts_dir.glob("*.py"):
|
||||
content = py_file.read_text(encoding="utf-8")
|
||||
assert "shell=True" not in content, f"shell=True detected in {py_file.name}!"
|
||||
|
||||
|
||||
def test_portainer_is_deprecated_and_absent():
|
||||
"""Ensure portainer service and volume are completely absent from core docker-compose."""
|
||||
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 "portainer" not in services, (
|
||||
"Deprecated service 'portainer' must not exist in docker-compose.yml"
|
||||
)
|
||||
|
||||
volumes = compose.get("volumes", {}) or {}
|
||||
assert "portainer_data" not in volumes, (
|
||||
"Deprecated volume 'portainer_data' must not exist in docker-compose.yml"
|
||||
)
|
||||
|
||||
|
||||
def test_no_eval_in_appctl_script():
|
||||
"""Ensure scripts/appctl never uses eval on dynamic environment or manifest payloads."""
|
||||
appctl_path = CORE_ROOT / "scripts" / "appctl"
|
||||
content = appctl_path.read_text(encoding="utf-8")
|
||||
assert "eval " not in content, "Dangerous 'eval' detected in scripts/appctl!"
|
||||
|
||||
|
||||
def test_appctl_env_injection_resilience(tmp_path: Path, monkeypatch):
|
||||
"""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.
|
||||
"""
|
||||
canary = tmp_path / "pwned.txt"
|
||||
payload = f"$(touch {canary})"
|
||||
|
||||
# 1. Setup mock Sites directory with vulnerable app.yaml and docker-compose.yml
|
||||
sites_dir = tmp_path / "Sites"
|
||||
app_dir = sites_dir / "vuln-app"
|
||||
app_dir.mkdir(parents=True)
|
||||
|
||||
app_yaml = f"""
|
||||
name: vuln-app
|
||||
domain: vuln.example.test
|
||||
env:
|
||||
INJECTION_TEST: '{payload}'
|
||||
NORMAL_VAR: 'safe_value'
|
||||
"""
|
||||
|
||||
(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"
|
||||
)
|
||||
|
||||
# 2. Verify unit-level pure Python environment assembly
|
||||
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
|
||||
manifest = parse_manifest(app_dir / "app.yaml")
|
||||
assembled_env = assemble_workload_env(app_dir, manifest, "vuln-app")
|
||||
assert not canary.exists(), "Command substitution executed during assemble_workload_env!"
|
||||
assert assembled_env["INJECTION_TEST"] == payload
|
||||
assert assembled_env["NORMAL_VAR"] == "safe_value"
|
||||
|
||||
# 3. Setup mock docker binary to capture environment without requiring a running Docker daemon
|
||||
mock_bin = tmp_path / "bin"
|
||||
mock_bin.mkdir()
|
||||
mock_docker = mock_bin / "docker"
|
||||
bash_bin = shutil.which("bash") or "bash"
|
||||
|
||||
mock_docker_script = f"""#!{bash_bin}
|
||||
if [ "$1" = "compose" ] && [ "$4" = "config" ]; then
|
||||
echo "MOCK_DOCKER_COMPOSE_CONFIG"
|
||||
echo "CAPTURED_INJECTION=$INJECTION_TEST"
|
||||
echo "CAPTURED_NORMAL=$NORMAL_VAR"
|
||||
exit 0
|
||||
fi
|
||||
exit 0
|
||||
"""
|
||||
mock_docker.write_text(mock_docker_script, encoding="utf-8")
|
||||
mock_docker.chmod(0o755)
|
||||
|
||||
# 4. Dispatch workload.config through OperationalRouter
|
||||
monkeypatch.setenv("PATH", f"{mock_bin}:{os.environ.get('PATH', '')}")
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=sites_dir,
|
||||
core_dir=CORE_ROOT,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "workload.config",
|
||||
"target": "vuln-app",
|
||||
})
|
||||
admin_principal = Principal(
|
||||
identity="operator",
|
||||
role=Role.ADMIN,
|
||||
token_id="tok_admin",
|
||||
auth_method="bearer_token",
|
||||
)
|
||||
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
|
||||
# 5. Assertions: command substitution was not executed, router succeeded, mock docker received literal value
|
||||
assert not canary.exists(), (
|
||||
"Command substitution was executed on the host during environment setup!"
|
||||
)
|
||||
assert resp.success is True, (
|
||||
f"OperationalRouter dispatch failed: {resp.error}"
|
||||
)
|
||||
assert resp.result is not None
|
||||
output = resp.result.get("output", "")
|
||||
assert "MOCK_DOCKER_COMPOSE_CONFIG" in output
|
||||
assert f"CAPTURED_INJECTION={payload}" in output
|
||||
assert "CAPTURED_NORMAL=safe_value" in output
|
||||
|
||||
|
||||
def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests():
|
||||
"""Ensure personal domains and operator usernames are absent from scripts, tests, and documentation."""
|
||||
forbidden = ["roadtotech.me", "kiskaadee"]
|
||||
root_dirs = [
|
||||
CORE_ROOT / "scripts",
|
||||
CORE_ROOT / "tests",
|
||||
CORE_ROOT / "docs",
|
||||
CORE_ROOT / "nixos" / "modules",
|
||||
CORE_ROOT / "config",
|
||||
]
|
||||
root_files = [
|
||||
CORE_ROOT / "README.md",
|
||||
CORE_ROOT / "ROADMAP.md",
|
||||
CORE_ROOT / "AGENTS.md",
|
||||
CORE_ROOT / "SECURITY.md",
|
||||
CORE_ROOT / "flake.nix",
|
||||
CORE_ROOT / "docker-compose.yml",
|
||||
CORE_ROOT / "nixos" / "configuration.nix",
|
||||
CORE_ROOT / "nixos" / "instance.example.nix",
|
||||
]
|
||||
violations = []
|
||||
|
||||
candidate_files = list(root_files)
|
||||
for root_dir in root_dirs:
|
||||
candidate_files.extend(root_dir.rglob("*"))
|
||||
|
||||
for file_path in candidate_files:
|
||||
if (
|
||||
file_path.is_file()
|
||||
and file_path.suffix
|
||||
in (".py", ".sh", ".bash", ".yml", ".yaml", ".md", ".nix", "")
|
||||
and file_path.name != "test_security_invariants.py"
|
||||
):
|
||||
content = file_path.read_text(encoding="utf-8", errors="ignore")
|
||||
for term in forbidden:
|
||||
if term in content:
|
||||
violations.append(
|
||||
f"{file_path.relative_to(CORE_ROOT)}: contains prohibited literal '{term}'"
|
||||
)
|
||||
|
||||
assert not violations, "Platform genericism violations detected:\n" + "\n".join(
|
||||
violations
|
||||
)
|
||||
|
||||
|
||||
def test_docker_compose_authelia_and_lldap_base_dn():
|
||||
"""Ensure both lldap and authelia services receive LLDAP_LDAP_BASE_DN in docker-compose.yml."""
|
||||
compose_path = CORE_ROOT / "docker-compose.yml"
|
||||
with open(compose_path, encoding="utf-8") as f:
|
||||
compose = yaml.safe_load(f)
|
||||
|
||||
services = compose.get("services", {})
|
||||
assert "lldap" in services, "lldap service must exist in docker-compose.yml"
|
||||
assert "authelia" in services, "authelia service must exist in docker-compose.yml"
|
||||
|
||||
def get_env_map(svc_def: dict) -> dict[str, str]:
|
||||
env_items = svc_def.get("environment", [])
|
||||
res = {}
|
||||
for item in env_items:
|
||||
if isinstance(item, str) and "=" in item:
|
||||
k, v = item.split("=", 1)
|
||||
res[k.strip()] = v.strip()
|
||||
return res
|
||||
|
||||
lldap_env = get_env_map(services["lldap"])
|
||||
authelia_env = get_env_map(services["authelia"])
|
||||
|
||||
assert "LLDAP_LDAP_BASE_DN" in lldap_env, (
|
||||
"LLDAP_LDAP_BASE_DN must be declared in lldap environment"
|
||||
)
|
||||
assert "LLDAP_LDAP_BASE_DN" in authelia_env, (
|
||||
"LLDAP_LDAP_BASE_DN must be passed to authelia environment for LDAP template expansion"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_homeserver_env_template_defines_dynamic_base_dn():
|
||||
"""Ensure homeserver.nix derives LLDAP_LDAP_BASE_DN dynamically from homelab.domain."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert "LLDAP_LDAP_BASE_DN" in content, (
|
||||
"homeserver.nix must define LLDAP_LDAP_BASE_DN in homeserver.env template"
|
||||
)
|
||||
assert 'lib.splitString "."' in content or "splitString" in content, (
|
||||
"homeserver.nix must compute LDAP base DN dynamically from domain components"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_tmpfiles_rules_use_recursive_acls():
|
||||
"""Ensure tmpfiles.rules uses uppercase A+ for recursive ACL inheritance on sites and homepage."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert '"A+ ${config.homelab.sitesDir}' in content, (
|
||||
"tmpfiles.rules must use uppercase 'A+' for recursive ACL inheritance on sitesDir"
|
||||
)
|
||||
assert '"A+ ${config.homelab.coreDir}/config/homepage' in content, (
|
||||
"tmpfiles.rules must use uppercase 'A+' for recursive ACL inheritance on homepage config"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_tmpfiles_rules_creates_operator_var_lib_homelab():
|
||||
"""Ensure tmpfiles.rules creates operator var/lib/homelab state dir before ACL assignment (#22)."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
expected_create = '"d /home/${config.homelab.operatorUser}/var/lib/homelab 0755 ${config.homelab.operatorUser} users -"'
|
||||
expected_acl = '"A+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"'
|
||||
|
||||
assert expected_create in content, (
|
||||
"tmpfiles.rules must declare creation of operator var/lib/homelab directory"
|
||||
)
|
||||
assert expected_acl in content, (
|
||||
"tmpfiles.rules must declare ACLs for operator var/lib/homelab directory"
|
||||
)
|
||||
assert content.index(expected_create) < content.index(expected_acl), (
|
||||
"operator var/lib/homelab directory creation must precede its ACL rule"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_appctl_readwritepaths_optional_prefixes():
|
||||
"""Ensure appctl service ReadWritePaths uses '-' prefix for optional runtime paths (#22)."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert '"-/home/${config.homelab.operatorUser}/var/lib/homelab"' in content
|
||||
assert '"-${config.homelab.coreDir}/config/homepage"' in content
|
||||
assert '"-/var/lib/homelab/appctl"' in content
|
||||
assert '"-/run/homelab"' in content
|
||||
|
||||
|
||||
def test_nixos_gitops_orders_after_appctl():
|
||||
"""Ensure homelab-gitops service declares after and wants dependency on homelab-appctl.service (#22)."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert '"homelab-appctl.service"' in content
|
||||
|
||||
nix_bin = shutil.which("nix")
|
||||
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
|
||||
for attr in ["after", "wants"]:
|
||||
cmd = [
|
||||
nix_bin,
|
||||
"eval",
|
||||
f".#nixosConfigurations.server.config.systemd.services.homelab-gitops.{attr}",
|
||||
"--json",
|
||||
]
|
||||
res = subprocess.run(
|
||||
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
|
||||
)
|
||||
data = json.loads(res.stdout)
|
||||
assert "homelab-appctl.service" in data, (
|
||||
f"homelab-gitops {attr} must include homelab-appctl.service"
|
||||
)
|
||||
|
||||
|
||||
def test_default_homelab_domain_evaluates_to_example_test():
|
||||
"""Assert default homelab.domain in NixOS config evaluates to 'example.test'."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
assert 'default = "example.test";' in content, (
|
||||
"homeserver.nix must set default homelab.domain to 'example.test'"
|
||||
)
|
||||
|
||||
nix_bin = shutil.which("nix")
|
||||
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
|
||||
cmd = [
|
||||
nix_bin,
|
||||
"eval",
|
||||
".#nixosConfigurations.server.config.homelab.domain",
|
||||
"--raw",
|
||||
]
|
||||
res = subprocess.run(
|
||||
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
|
||||
)
|
||||
assert res.stdout.strip() == "example.test", (
|
||||
f"Default homelab.domain must be 'example.test', got '{res.stdout.strip()}'"
|
||||
)
|
||||
|
||||
|
||||
def test_dynamic_lldap_base_dn_splits_domain_components():
|
||||
"""Assert dynamic LLDAP_LDAP_BASE_DN splits domain into dc=... components for any domain."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
assert "LLDAP_LDAP_BASE_DN = ldapBaseDn;" in content, (
|
||||
"homeserver.nix must bind LLDAP_LDAP_BASE_DN to ldapBaseDn in homeserver.env template"
|
||||
)
|
||||
assert 'domainParts = lib.splitString "." config.homelab.domain;' in content, (
|
||||
"homeserver.nix must split homelab.domain by '.'"
|
||||
)
|
||||
assert 'ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts);' in content, (
|
||||
"homeserver.nix must map domain components into dc=${part}"
|
||||
)
|
||||
|
||||
nix_bin = shutil.which("nix")
|
||||
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
|
||||
cases = [
|
||||
("example.test", "dc=example,dc=test"),
|
||||
("my.homelab.internal", "dc=my,dc=homelab,dc=internal"),
|
||||
("local", "dc=local"),
|
||||
]
|
||||
for domain, expected_dn in cases:
|
||||
expr = (
|
||||
f'let flake = builtins.getFlake (toString ./.); lib = flake.inputs.nixpkgs.lib; '
|
||||
f'domainParts = lib.splitString "." "{domain}"; '
|
||||
f'in lib.concatStringsSep "," (map (part: "dc=${{part}}") domainParts)'
|
||||
)
|
||||
cmd = [
|
||||
nix_bin,
|
||||
"eval",
|
||||
"--impure",
|
||||
"--expr",
|
||||
expr,
|
||||
"--raw",
|
||||
]
|
||||
res = subprocess.run(
|
||||
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
|
||||
)
|
||||
assert res.stdout.strip() == expected_dn, (
|
||||
f"Expected {expected_dn} for domain {domain}, got {res.stdout.strip()}"
|
||||
)
|
||||
|
||||
# Also assert rendered sops template in default configuration contains correct LLDAP_LDAP_BASE_DN
|
||||
cmd_tpl = [
|
||||
nix_bin,
|
||||
"eval",
|
||||
'.#nixosConfigurations.server.config.sops.templates."homeserver.env".content',
|
||||
"--raw",
|
||||
]
|
||||
res_tpl = subprocess.run(
|
||||
cmd_tpl, cwd=CORE_ROOT, capture_output=True, text=True, check=True
|
||||
)
|
||||
assert "LLDAP_LDAP_BASE_DN=dc=example,dc=test" in res_tpl.stdout
|
||||
|
||||
|
||||
def test_dual_path_import_overrides_homelab_domain():
|
||||
"""Assert dual-path import overrides homelab.domain when ./nixos/instance.nix is present."""
|
||||
nix_bin = shutil.which("nix")
|
||||
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
|
||||
instance_nix = CORE_ROOT / "nixos" / "instance.nix"
|
||||
try:
|
||||
instance_nix.write_text(
|
||||
'{ homelab.domain = "custom.internal"; }\n', encoding="utf-8"
|
||||
)
|
||||
cmd = [
|
||||
nix_bin,
|
||||
"eval",
|
||||
"--impure",
|
||||
"path:.#nixosConfigurations.server.config.homelab.domain",
|
||||
"--raw",
|
||||
]
|
||||
res = subprocess.run(
|
||||
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
|
||||
)
|
||||
assert res.stdout.strip() == "custom.internal", (
|
||||
f"Expected homelab.domain to be overridden to 'custom.internal', got '{res.stdout.strip()}'"
|
||||
)
|
||||
finally:
|
||||
if instance_nix.exists():
|
||||
instance_nix.unlink()
|
||||
|
||||
|
||||
def test_nixos_configuration_declares_dual_path_instance_imports():
|
||||
"""Ensure nixos/configuration.nix includes optional dual-path instance imports."""
|
||||
config_nix = CORE_ROOT / "nixos" / "configuration.nix"
|
||||
content = config_nix.read_text(encoding="utf-8")
|
||||
assert "builtins.pathExists ./instance.nix" in content, (
|
||||
"nixos/configuration.nix must check for ./instance.nix via builtins.pathExists"
|
||||
)
|
||||
assert "builtins.pathExists /etc/nixos/homelab-instance.nix" in content, (
|
||||
"nixos/configuration.nix must check for /etc/nixos/homelab-instance.nix via builtins.pathExists"
|
||||
)
|
||||
|
||||
|
||||
def test_gitignore_includes_instance_nix():
|
||||
"""Ensure nixos/instance.nix is ignored in .gitignore to preserve platform genericism."""
|
||||
gitignore = CORE_ROOT / ".gitignore"
|
||||
content = gitignore.read_text(encoding="utf-8")
|
||||
lines = [line.strip() for line in content.splitlines()]
|
||||
assert "nixos/instance.nix" in lines, (
|
||||
"nixos/instance.nix must be explicitly ignored in .gitignore"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_switch_alias_uses_path_and_impure():
|
||||
"""Ensure nix-switch alias in nixos/modules/shell.nix uses path: and --impure to prevent silent fail-open."""
|
||||
shell_nix = CORE_ROOT / "nixos" / "modules" / "shell.nix"
|
||||
content = shell_nix.read_text(encoding="utf-8")
|
||||
assert 'nix-switch = "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure";' in content, (
|
||||
"nixos/modules/shell.nix must configure nix-switch alias with path:$HOME/Core#server --impure"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_safe_directory_includes_core_and_sites():
|
||||
"""Ensure programs.git.config.safe.directory includes Core, Workloads, and Sites to prevent dubious ownership errors."""
|
||||
config_nix = CORE_ROOT / "nixos" / "configuration.nix"
|
||||
content = config_nix.read_text(encoding="utf-8")
|
||||
assert '"/home/${config.homelab.operatorUser}/Core"' in content, (
|
||||
"nixos/configuration.nix must include Core in git safe.directory"
|
||||
)
|
||||
assert '"/home/${config.homelab.operatorUser}/Workloads"' in content, (
|
||||
"nixos/configuration.nix must include Workloads in git safe.directory"
|
||||
)
|
||||
assert '"/home/${config.homelab.operatorUser}/Workloads/*"' in content, (
|
||||
"nixos/configuration.nix must include Workloads/* in git safe.directory"
|
||||
)
|
||||
assert '"/home/${config.homelab.operatorUser}/Sites/*"' in content, (
|
||||
"nixos/configuration.nix must include Sites/* in git safe.directory"
|
||||
)
|
||||
|
||||
nix_bin = shutil.which("nix")
|
||||
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
|
||||
cmd = [
|
||||
nix_bin,
|
||||
"eval",
|
||||
".#nixosConfigurations.server.config.programs.git.config",
|
||||
"--json",
|
||||
]
|
||||
res = subprocess.run(
|
||||
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
|
||||
)
|
||||
import json
|
||||
|
||||
configs = json.loads(res.stdout)
|
||||
safe_dirs = []
|
||||
for cfg in configs:
|
||||
if isinstance(cfg, dict) and "safe" in cfg and "directory" in cfg["safe"]:
|
||||
dirs = cfg["safe"]["directory"]
|
||||
if isinstance(dirs, list):
|
||||
safe_dirs.extend(dirs)
|
||||
else:
|
||||
safe_dirs.append(dirs)
|
||||
|
||||
assert "/home/operator/Core" in safe_dirs, (
|
||||
f"Expected '/home/operator/Core' in git safe.directory, got {safe_dirs}"
|
||||
)
|
||||
assert "/home/operator/Workloads" in safe_dirs, (
|
||||
f"Expected '/home/operator/Workloads' in git safe.directory, got {safe_dirs}"
|
||||
)
|
||||
assert "/home/operator/Workloads/*" in safe_dirs, (
|
||||
f"Expected '/home/operator/Workloads/*' in git safe.directory, got {safe_dirs}"
|
||||
)
|
||||
assert "/home/operator/Sites/*" in safe_dirs, (
|
||||
f"Expected '/home/operator/Sites/*' in git safe.directory, got {safe_dirs}"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_homeserver_defaults_to_workloads_dir():
|
||||
"""Ensure homeserver.nix defaults sitesDir to ~/Workloads and exports WORKLOADS_DIR + SITES_DIR (#33)."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert 'default = "/home/${config.homelab.operatorUser}/Workloads";' in content, (
|
||||
"homelab.sitesDir must default to /home/${config.homelab.operatorUser}/Workloads"
|
||||
)
|
||||
assert "WORKLOADS_DIR = config.homelab.sitesDir;" in content, (
|
||||
"homeserver.nix must export WORKLOADS_DIR"
|
||||
)
|
||||
assert "SITES_DIR = config.homelab.sitesDir;" in content, (
|
||||
"homeserver.nix must export SITES_DIR for backward compatibility"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_workload_grants_option_and_projection():
|
||||
"""Ensure homeserver.nix defines homelab.workloadGrants, /etc/homelab/grants.json, and HOMELAB_GRANTS_FILE."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert "workloadGrants = lib.mkOption" in content
|
||||
assert 'environment.etc."homelab/grants.json"' in content
|
||||
assert 'user = "root";' in content
|
||||
assert 'group = "homelab-operators";' in content
|
||||
assert 'mode = "0640";' in content
|
||||
assert content.count('HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";') >= 2
|
||||
assert "PrivateUsers" not in content
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
Structural invariant tests for Homelab Core repository layout.
|
||||
Ensures required architectural components exist and deprecated paths do not return.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
|
||||
|
||||
def test_required_architectural_paths_exist():
|
||||
"""Ensure core architectural files and directories exist."""
|
||||
required_paths = [
|
||||
"docker-compose.yml",
|
||||
"flake.nix",
|
||||
"UNLICENSE",
|
||||
"AGENTS.md",
|
||||
"README.md",
|
||||
"SECURITY.md",
|
||||
"nixos",
|
||||
"nixos/configuration.nix",
|
||||
"nixos/instance.example.nix",
|
||||
"nixos/modules/homeserver.nix",
|
||||
"nixos/secrets.yaml",
|
||||
"scripts/gitops_dispatcher.py",
|
||||
"scripts/appctl",
|
||||
"scripts/appctl_engine.py",
|
||||
"config/homepage",
|
||||
".githooks/pre-commit",
|
||||
"tests",
|
||||
]
|
||||
|
||||
for p in required_paths:
|
||||
target = CORE_ROOT / p
|
||||
assert target.exists(), f"Required architectural path missing: {p}"
|
||||
|
||||
pre_commit = CORE_ROOT / ".githooks" / "pre-commit"
|
||||
assert pre_commit.is_file(), ".githooks/pre-commit must be a regular file"
|
||||
assert os.access(pre_commit, os.X_OK), (
|
||||
".githooks/pre-commit must be marked executable"
|
||||
)
|
||||
|
||||
|
||||
def test_deprecated_legacy_structures_are_absent():
|
||||
"""Ensure deprecated files and legacy layouts are not reintroduced."""
|
||||
prohibited_paths = [
|
||||
"infra/core",
|
||||
"up.sh",
|
||||
"down.sh",
|
||||
"scripts/check-ssl.sh",
|
||||
"scripts/purge-dynu.sh",
|
||||
"scripts/ip-monitor.sh",
|
||||
"docs/legacy",
|
||||
]
|
||||
|
||||
for p in prohibited_paths:
|
||||
target = CORE_ROOT / p
|
||||
assert not target.exists(), f"Prohibited deprecated path detected: {p}"
|
||||
|
||||
|
||||
def test_unlicense_preserved():
|
||||
"""Ensure The Unlicense (public domain invariant) is maintained."""
|
||||
unlicense = CORE_ROOT / "UNLICENSE"
|
||||
assert unlicense.is_file(), "UNLICENSE file must be present"
|
||||
content = unlicense.read_text(encoding="utf-8")
|
||||
assert (
|
||||
"This is free and unencumbered software released into the public domain."
|
||||
in content
|
||||
)
|
||||
@@ -0,0 +1,373 @@
|
||||
"""
|
||||
tests/unit/test_appctl_audit.py — Unit Tests for Audit Logger & Concurrency Lock (P4 Slice 2)
|
||||
|
||||
Behavior-driven test naming convention:
|
||||
test_<subject>_<accepts|rejects|enforces>_<condition>
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import stat
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from appctl_audit import (
|
||||
AuditEvent,
|
||||
AuditLogger,
|
||||
AuditPersistenceError,
|
||||
AuditPhase,
|
||||
ConcurrentMutationError,
|
||||
PrincipalAudit,
|
||||
TargetLockManager,
|
||||
redact_sensitive_data,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_audit_file(tmp_path: Path) -> Path:
|
||||
return tmp_path / "audit" / "audit.jsonl"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_lock_dir(tmp_path: Path) -> Path:
|
||||
lock_dir = tmp_path / "locks"
|
||||
lock_dir.mkdir(parents=True, exist_ok=True)
|
||||
return lock_dir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_principal() -> PrincipalAudit:
|
||||
return PrincipalAudit(
|
||||
identity="operator",
|
||||
role="homelab-admin",
|
||||
token_id="tok_admin_01",
|
||||
auth_method="bearer_token",
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# File Permissions & Initialization
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_audit_logger_enforces_0600_permissions_on_creation(
|
||||
temp_audit_file: Path, sample_principal: PrincipalAudit
|
||||
):
|
||||
logger = AuditLogger(temp_audit_file)
|
||||
logger.log_dispatched(
|
||||
operation_id="op_100",
|
||||
principal=sample_principal,
|
||||
action="workload.deploy",
|
||||
target="snappymail",
|
||||
transport="unix_socket",
|
||||
origin="peer_uid_1000",
|
||||
client="appctl-cli/2.0",
|
||||
parameters={"recreate": True},
|
||||
)
|
||||
|
||||
assert temp_audit_file.exists()
|
||||
mode = stat.S_IMODE(temp_audit_file.stat().st_mode)
|
||||
assert mode == 0o600
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Audit Phases & RFC JSONL Schema
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_audit_logger_writes_valid_jsonl_lifecycle(
|
||||
temp_audit_file: Path, sample_principal: PrincipalAudit
|
||||
):
|
||||
logger = AuditLogger(temp_audit_file)
|
||||
|
||||
# 1. DISPATCHED
|
||||
evt_disp = logger.log_dispatched(
|
||||
operation_id="op_101",
|
||||
principal=sample_principal,
|
||||
action="workload.update",
|
||||
target="jellyfin",
|
||||
transport="http",
|
||||
origin="127.0.0.1:48291",
|
||||
client="gitops-dispatcher/1.0",
|
||||
parameters={"expected_branch": "main", "build": False},
|
||||
)
|
||||
assert evt_disp.phase == AuditPhase.DISPATCHED
|
||||
assert evt_disp.result is not None
|
||||
assert evt_disp.result.status == "IN_PROGRESS"
|
||||
|
||||
# 2. COMPLETED
|
||||
evt_comp = logger.log_completed(
|
||||
operation_id="op_101",
|
||||
principal=sample_principal,
|
||||
action="workload.update",
|
||||
target="jellyfin",
|
||||
transport="http",
|
||||
origin="127.0.0.1:48291",
|
||||
client="gitops-dispatcher/1.0",
|
||||
parameters={"expected_branch": "main", "build": False},
|
||||
duration_ms=1450,
|
||||
commit_sha="a1b2c3d",
|
||||
message="Workload updated and reconciled successfully",
|
||||
)
|
||||
assert evt_comp.phase == AuditPhase.COMPLETED
|
||||
assert evt_comp.target == "jellyfin"
|
||||
assert evt_comp.parameters == {"expected_branch": "main", "build": False}
|
||||
assert evt_comp.result is not None
|
||||
assert evt_comp.result.status == "SUCCESS"
|
||||
assert evt_comp.result.exit_code == 0
|
||||
assert evt_comp.result.duration_ms == 1450
|
||||
assert evt_comp.result.message == "Workload updated and reconciled successfully"
|
||||
assert evt_comp.result.commit_sha == "a1b2c3d"
|
||||
|
||||
# Read and validate JSONL file contents
|
||||
lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines()
|
||||
assert len(lines) == 2
|
||||
|
||||
parsed_disp = AuditEvent.model_validate(json.loads(lines[0]))
|
||||
assert parsed_disp.phase == AuditPhase.DISPATCHED
|
||||
assert parsed_disp.operation_id == "op_101"
|
||||
|
||||
parsed_comp = AuditEvent.model_validate(json.loads(lines[1]))
|
||||
assert parsed_comp.phase == AuditPhase.COMPLETED
|
||||
assert parsed_comp.operation_id == "op_101"
|
||||
|
||||
|
||||
def test_audit_logger_writes_failed_event(
|
||||
temp_audit_file: Path, sample_principal: PrincipalAudit
|
||||
):
|
||||
logger = AuditLogger(temp_audit_file)
|
||||
logger.log_failed(
|
||||
operation_id="op_102",
|
||||
principal=sample_principal,
|
||||
action="workload.deploy",
|
||||
target="jellyfin",
|
||||
transport="unix_socket",
|
||||
origin="peer_uid_1000",
|
||||
client="appctl-cli/2.0",
|
||||
parameters={"recreate": True},
|
||||
duration_ms=320,
|
||||
exit_code=1,
|
||||
error_code="ERR_EXECUTION_FAILED",
|
||||
message="Docker compose failed with exit code 1",
|
||||
)
|
||||
|
||||
lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines()
|
||||
assert len(lines) == 1
|
||||
event = AuditEvent.model_validate(json.loads(lines[0]))
|
||||
assert event.phase == AuditPhase.FAILED
|
||||
assert event.target == "jellyfin"
|
||||
assert event.parameters == {"recreate": True}
|
||||
assert event.result is not None
|
||||
assert event.result.status == "FAILED"
|
||||
assert event.result.exit_code == 1
|
||||
assert event.result.error_code == "ERR_EXECUTION_FAILED"
|
||||
assert event.result.duration_ms == 320
|
||||
assert event.result.message == "Docker compose failed with exit code 1"
|
||||
|
||||
|
||||
def test_audit_logger_writes_denied_event(
|
||||
temp_audit_file: Path, sample_principal: PrincipalAudit
|
||||
):
|
||||
logger = AuditLogger(temp_audit_file)
|
||||
logger.log_denied(
|
||||
operation_id="op_103",
|
||||
principal=sample_principal,
|
||||
action="workload.config",
|
||||
target="core",
|
||||
transport="http",
|
||||
origin="127.0.0.1:49000",
|
||||
client="curl/8.1",
|
||||
parameters={},
|
||||
error_code="ERR_PERMISSION_DENIED",
|
||||
message="Role homelab-operator cannot target core stack",
|
||||
)
|
||||
|
||||
lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines()
|
||||
assert len(lines) == 1
|
||||
event = AuditEvent.model_validate(json.loads(lines[0]))
|
||||
assert event.phase == AuditPhase.DENIED
|
||||
assert event.result is not None
|
||||
assert event.result.status == "DENIED"
|
||||
assert event.result.error_code == "ERR_PERMISSION_DENIED"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Secret Redaction
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_redact_sensitive_data_masks_secret_keys():
|
||||
raw_params = {
|
||||
"API_KEY": "supersecretkey123",
|
||||
"WEBHOOK_SECRET": "whsec_9999",
|
||||
"db_password": "mypassword",
|
||||
"AUTH_TOKEN": "tok_12345",
|
||||
"SSH_KEY": "ssh-ed25519 AAA...",
|
||||
"PASSWORD_HASH": "$2b$12$...",
|
||||
"recreate": True,
|
||||
"nested": {
|
||||
"SECRET_PASS": "pass123",
|
||||
"normal_config": "enabled",
|
||||
"list_items": [
|
||||
{"ITEM_SECRET": "leak", "id": 1},
|
||||
"safe_string",
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
redacted = redact_sensitive_data(raw_params)
|
||||
assert redacted["API_KEY"] == "[REDACTED]"
|
||||
assert redacted["WEBHOOK_SECRET"] == "[REDACTED]"
|
||||
assert redacted["db_password"] == "[REDACTED]"
|
||||
assert redacted["AUTH_TOKEN"] == "[REDACTED]"
|
||||
assert redacted["SSH_KEY"] == "[REDACTED]"
|
||||
assert redacted["PASSWORD_HASH"] == "[REDACTED]"
|
||||
assert redacted["recreate"] is True
|
||||
assert redacted["nested"]["SECRET_PASS"] == "[REDACTED]"
|
||||
assert redacted["nested"]["normal_config"] == "enabled"
|
||||
assert redacted["nested"]["list_items"][0]["ITEM_SECRET"] == "[REDACTED]"
|
||||
assert redacted["nested"]["list_items"][0]["id"] == 1
|
||||
assert redacted["nested"]["list_items"][1] == "safe_string"
|
||||
|
||||
|
||||
def test_redact_sensitive_data_masks_bare_keys():
|
||||
"""Ensure bare keys (token, secret, password, key, pass, hash) without underscores are redacted (CR-DI-04)."""
|
||||
raw_params = {
|
||||
"token": "tok_12345",
|
||||
"secret": "shh_secret",
|
||||
"password": "mypassword",
|
||||
"key": "encryption_key",
|
||||
"pass": "quick_pass",
|
||||
"hash": "$2b$12$hashval",
|
||||
"TOKEN": "uppercase_tok",
|
||||
"SECRET": "uppercase_sec",
|
||||
"normal_field": "keep_this",
|
||||
}
|
||||
redacted = redact_sensitive_data(raw_params)
|
||||
assert redacted["token"] == "[REDACTED]"
|
||||
assert redacted["secret"] == "[REDACTED]"
|
||||
assert redacted["password"] == "[REDACTED]"
|
||||
assert redacted["key"] == "[REDACTED]"
|
||||
assert redacted["pass"] == "[REDACTED]"
|
||||
assert redacted["hash"] == "[REDACTED]"
|
||||
assert redacted["TOKEN"] == "[REDACTED]"
|
||||
assert redacted["SECRET"] == "[REDACTED]"
|
||||
assert redacted["normal_field"] == "keep_this"
|
||||
|
||||
|
||||
def test_audit_logger_automatically_redacts_sensitive_parameters(
|
||||
temp_audit_file: Path, sample_principal: PrincipalAudit
|
||||
):
|
||||
logger = AuditLogger(temp_audit_file)
|
||||
logger.log_dispatched(
|
||||
operation_id="op_104",
|
||||
principal=sample_principal,
|
||||
action="workload.deploy",
|
||||
target="vaultwarden",
|
||||
transport="unix_socket",
|
||||
origin="peer_uid_1000",
|
||||
client="appctl-cli/2.0",
|
||||
parameters={"ADMIN_TOKEN": "super_token_leak", "recreate": True},
|
||||
)
|
||||
|
||||
content = temp_audit_file.read_text(encoding="utf-8")
|
||||
assert "super_token_leak" not in content
|
||||
assert "[REDACTED]" in content
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pre-Execution Fail-Closed Disk Guard
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_audit_logger_fails_closed_when_audit_log_unwritable(
|
||||
tmp_path: Path, sample_principal: PrincipalAudit
|
||||
):
|
||||
# Using a directory as the audit path causes os.open with O_WRONLY to fail with
|
||||
# EISDIR / OSError across all platforms and environments (including root containers).
|
||||
unwritable_target = tmp_path / "unwritable_audit_dir"
|
||||
unwritable_target.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
logger = AuditLogger(unwritable_target)
|
||||
with pytest.raises(AuditPersistenceError) as exc_info:
|
||||
logger.log_dispatched(
|
||||
operation_id="op_105",
|
||||
principal=sample_principal,
|
||||
action="workload.deploy",
|
||||
target="jellyfin",
|
||||
transport="unix_socket",
|
||||
origin="peer_uid_1000",
|
||||
client="appctl-cli/2.0",
|
||||
parameters={"recreate": True},
|
||||
)
|
||||
assert "Failed to persist audit event" in str(exc_info.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Concurrency & Non-Blocking Flock Manager
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_target_lock_manager_acquires_and_releases_lock(temp_lock_dir: Path):
|
||||
manager = TargetLockManager(temp_lock_dir)
|
||||
|
||||
with manager.lock_target("snappymail") as lock:
|
||||
assert lock.target == "snappymail"
|
||||
assert lock.lock_path.exists()
|
||||
# Verify mode 0600 on lock file
|
||||
assert stat.S_IMODE(lock.lock_path.stat().st_mode) == 0o600
|
||||
|
||||
# Lock can be re-acquired immediately after release
|
||||
with manager.lock_target("snappymail"):
|
||||
pass
|
||||
|
||||
|
||||
def test_target_lock_manager_rejects_concurrent_mutation(temp_lock_dir: Path):
|
||||
manager = TargetLockManager(temp_lock_dir)
|
||||
|
||||
with (
|
||||
manager.lock_target("jellyfin"),
|
||||
pytest.raises(ConcurrentMutationError) as exc_info,
|
||||
manager.lock_target("jellyfin"),
|
||||
):
|
||||
pass
|
||||
|
||||
assert exc_info.value.target == "jellyfin"
|
||||
assert "locked by a concurrent task" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_target_lock_manager_permits_independent_targets_concurrently(
|
||||
temp_lock_dir: Path,
|
||||
):
|
||||
manager = TargetLockManager(temp_lock_dir)
|
||||
|
||||
with manager.lock_target("app1"), manager.lock_target("app2"):
|
||||
pass
|
||||
|
||||
|
||||
def test_homepage_sync_lock_acquires_designated_file(temp_lock_dir: Path):
|
||||
manager = TargetLockManager(temp_lock_dir)
|
||||
|
||||
with (
|
||||
manager.homepage_sync_lock() as lock,
|
||||
pytest.raises(ConcurrentMutationError) as exc_info,
|
||||
manager.homepage_sync_lock(),
|
||||
):
|
||||
pass
|
||||
|
||||
assert lock.lock_path.name == "_homepage_sync.lock"
|
||||
assert exc_info.value.target == "_homepage_sync"
|
||||
|
||||
|
||||
def test_target_lock_manager_sanitizes_special_characters_and_supports_env(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
custom_lock_dir = tmp_path / "custom_locks"
|
||||
monkeypatch.setenv("APPCTL_LOCK_DIR", str(custom_lock_dir))
|
||||
manager = TargetLockManager()
|
||||
assert manager.lock_dir == custom_lock_dir
|
||||
|
||||
with manager.lock_target("special/tenant:workload@v1!#$") as lock:
|
||||
assert lock.lock_path.name == "special_tenant_workload_v1___.lock"
|
||||
assert lock.lock_path.exists()
|
||||
@@ -0,0 +1,536 @@
|
||||
"""
|
||||
tests/unit/test_appctl_auth.py — Unit Tests for Authentication & 3-Role RBAC (P4 Slice 3)
|
||||
|
||||
Behavior-driven test naming convention:
|
||||
test_<subject>_<accepts|rejects|enforces>_<condition>
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from appctl_auth import (
|
||||
AuthenticationError,
|
||||
AuthorizationError,
|
||||
Principal,
|
||||
Role,
|
||||
TokenStore,
|
||||
authenticate_request,
|
||||
enforce_rbac,
|
||||
load_admitted_workloads,
|
||||
)
|
||||
from appctl_contracts import ErrorCode, OperationType
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def secret_tokens() -> dict[str, str]:
|
||||
return {
|
||||
"admin_secret": "sec_admin_9876543210abcdef",
|
||||
"operator_secret": "sec_operator_1234567890abcdef",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_tokens_file(tmp_path: Path, secret_tokens: dict[str, str]) -> Path:
|
||||
tokens_path = tmp_path / "tokens.json"
|
||||
admin_hash = hashlib.sha256(
|
||||
secret_tokens["admin_secret"].encode("utf-8")
|
||||
).hexdigest()
|
||||
op_hash = hashlib.sha256(
|
||||
secret_tokens["operator_secret"].encode("utf-8")
|
||||
).hexdigest()
|
||||
|
||||
data = [
|
||||
{
|
||||
"token_id": "tok_admin_01",
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"sha256": admin_hash,
|
||||
},
|
||||
{
|
||||
"token_id": "tok_gitops_01",
|
||||
"identity": "gitops-dispatcher",
|
||||
"role": "homelab-operator",
|
||||
"sha256": op_hash,
|
||||
},
|
||||
]
|
||||
tokens_path.write_text(json.dumps(data), encoding="utf-8")
|
||||
os.chmod(tokens_path, 0o400)
|
||||
return tokens_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admitted_workloads() -> set[str]:
|
||||
return {"snappymail", "mail", "webmail", "jellyfin", "media", "docs"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TokenStore & Strict Permissions (0400)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_token_store_accepts_valid_0400_store(temp_tokens_file: Path):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
tokens = store.load_tokens()
|
||||
assert len(tokens) == 2
|
||||
assert tokens[0].role == Role.ADMIN
|
||||
assert tokens[1].role == Role.OPERATOR
|
||||
|
||||
|
||||
def test_token_store_rejects_insecure_file_permissions(tmp_path: Path):
|
||||
bad_tokens_file = tmp_path / "insecure_tokens.json"
|
||||
bad_tokens_file.write_text("[]", encoding="utf-8")
|
||||
|
||||
# Insecure modes: 0644, 0600, 0777
|
||||
for insecure_mode in [0o644, 0o600, 0o777, 0o444]:
|
||||
os.chmod(bad_tokens_file, insecure_mode)
|
||||
store = TokenStore(bad_tokens_file)
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
store.load_tokens()
|
||||
assert "mode 0400 required" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||
|
||||
|
||||
def test_token_store_rejects_missing_file(tmp_path: Path):
|
||||
missing_file = tmp_path / "nonexistent.json"
|
||||
store = TokenStore(missing_file)
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
store.load_tokens()
|
||||
assert "not found" in str(exc_info.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bearer Token Authentication
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_token_store_authenticates_valid_bearer_secrets(
|
||||
temp_tokens_file: Path, secret_tokens: dict[str, str]
|
||||
):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
p_admin = store.authenticate_bearer(secret_tokens["admin_secret"])
|
||||
assert p_admin.identity == "operator"
|
||||
assert p_admin.role == Role.ADMIN
|
||||
assert p_admin.token_id == "tok_admin_01"
|
||||
assert p_admin.auth_method == "bearer_token"
|
||||
|
||||
p_op = store.authenticate_bearer(secret_tokens["operator_secret"])
|
||||
assert p_op.identity == "gitops-dispatcher"
|
||||
assert p_op.role == Role.OPERATOR
|
||||
assert p_op.token_id == "tok_gitops_01"
|
||||
|
||||
|
||||
def test_token_store_authenticates_uppercase_hex_descriptor(tmp_path: Path):
|
||||
"""Ensure tokens with uppercase hex characters in tokens.json authenticate cleanly (CR-DI-10)."""
|
||||
raw_secret = "my_custom_secret_token"
|
||||
raw_hash_upper = hashlib.sha256(raw_secret.encode("utf-8")).hexdigest().upper()
|
||||
tokens_file = tmp_path / "upper_tokens.json"
|
||||
tokens_file.write_text(
|
||||
json.dumps(
|
||||
[
|
||||
{
|
||||
"token_id": "tok_upper_01",
|
||||
"identity": "upper-user",
|
||||
"role": "homelab-operator",
|
||||
"sha256": raw_hash_upper,
|
||||
}
|
||||
]
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
os.chmod(tokens_file, 0o400)
|
||||
store = TokenStore(tokens_file)
|
||||
principal = store.authenticate_bearer(raw_secret)
|
||||
assert principal.identity == "upper-user"
|
||||
assert principal.role == Role.OPERATOR
|
||||
|
||||
|
||||
def test_token_store_rejects_invalid_bearer_secret(temp_tokens_file: Path):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
store.authenticate_bearer("wrong_secret_token_123")
|
||||
assert "Invalid or unknown Bearer token" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||
|
||||
|
||||
def test_token_store_rejects_empty_bearer_secret(temp_tokens_file: Path):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
store.authenticate_bearer("")
|
||||
assert "Empty Bearer token provided" in str(exc_info.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Transport Authentication Rules (HTTP vs. Unix Domain Socket)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_authenticate_request_over_http_requires_valid_bearer(
|
||||
temp_tokens_file: Path, secret_tokens: dict[str, str]
|
||||
):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
# Valid Bearer token
|
||||
auth_header = f"Bearer {secret_tokens['admin_secret']}"
|
||||
p = authenticate_request("http", auth_header, token_store=store)
|
||||
assert p.role == Role.ADMIN
|
||||
|
||||
# Missing Authorization header -> 401
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
authenticate_request("http", None, token_store=store)
|
||||
assert "Bearer token required over network transport" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||
|
||||
# Malformed Authorization header -> 401
|
||||
with pytest.raises(AuthenticationError):
|
||||
authenticate_request("http", "Basic dXNlcjpwYXNz", token_store=store)
|
||||
|
||||
|
||||
def test_authenticate_request_over_uds_falls_back_to_viewer(
|
||||
temp_tokens_file: Path, secret_tokens: dict[str, str]
|
||||
):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
# Missing Authorization header over UDS with peer_uid=1000
|
||||
p = authenticate_request("unix_socket", None, peer_uid=1000, token_store=store)
|
||||
assert p.identity == "unix_uid_1000"
|
||||
assert p.role == Role.VIEWER
|
||||
assert p.token_id is None
|
||||
assert p.auth_method == "unix_peercred"
|
||||
|
||||
# Explicit Bearer token over UDS confers full privileges
|
||||
auth_header = f"Bearer {secret_tokens['admin_secret']}"
|
||||
p_admin = authenticate_request(
|
||||
"unix_socket", auth_header, peer_uid=1000, token_store=store
|
||||
)
|
||||
assert p_admin.role == Role.ADMIN
|
||||
assert p_admin.auth_method == "bearer_token"
|
||||
|
||||
|
||||
def test_authenticate_request_over_uds_rejects_missing_peer_uid():
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
authenticate_request("unix_socket", None, peer_uid=None)
|
||||
assert "Missing peer credentials" in str(exc_info.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Deployments Registry Scope Loader
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_load_admitted_workloads_parses_names_and_aliases(tmp_path: Path):
|
||||
deploy_file = tmp_path / "deployments.yaml"
|
||||
deploy_file.write_text(
|
||||
"""
|
||||
schemaVersion: "1.0"
|
||||
repositories:
|
||||
snappymail:
|
||||
path: "/home/operator/Sites/snappymail"
|
||||
aliases:
|
||||
- "mail"
|
||||
- "webmail"
|
||||
jellyfin:
|
||||
path: "/home/operator/Sites/homelab-jellyfin"
|
||||
aliases:
|
||||
- "media"
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
admitted = load_admitted_workloads(deploy_file)
|
||||
assert "snappymail" in admitted
|
||||
assert "mail" in admitted
|
||||
assert "webmail" in admitted
|
||||
assert "jellyfin" in admitted
|
||||
assert "media" in admitted
|
||||
assert "unknown_app" not in admitted
|
||||
|
||||
|
||||
def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: Path):
|
||||
deploy_file = tmp_path / "deployments.json"
|
||||
deploy_file.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"repositories": {
|
||||
"app1": {
|
||||
"path": "/home/operator/Sites/app1",
|
||||
"aliases": [123, None, " ", "valid_alias"],
|
||||
}
|
||||
}
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
admitted = load_admitted_workloads(deploy_file)
|
||||
assert "app1" in admitted
|
||||
assert "valid_alias" in admitted
|
||||
assert 123 not in admitted
|
||||
assert None not in admitted
|
||||
assert "" not in admitted
|
||||
|
||||
|
||||
def test_load_admitted_workloads_fails_closed_on_missing_file(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
admitted = load_admitted_workloads(tmp_path / "missing.yaml")
|
||||
assert admitted == set()
|
||||
|
||||
# Test HOMELAB_DEPLOYMENTS_FILE fallback
|
||||
deploy_file = tmp_path / "env_deploy.yaml"
|
||||
deploy_file.write_text(
|
||||
"repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8"
|
||||
)
|
||||
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deploy_file))
|
||||
admitted_env = load_admitted_workloads(None)
|
||||
assert "env_app" in admitted_env
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# RBAC Policy Matrix Enforcement
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_rbac_admin_permitted_across_all_operations_and_targets(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
admin = Principal(
|
||||
identity="admin_user", role=Role.ADMIN, auth_method="bearer_token"
|
||||
)
|
||||
|
||||
# Mutations across Core and Sites
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "traefik", admitted_workloads)
|
||||
enforce_rbac(
|
||||
admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads
|
||||
)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_CONFIG, "core", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_LOGS, "traefik", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_LIST, None, admitted_workloads)
|
||||
|
||||
|
||||
def test_rbac_operator_permitted_on_admitted_workloads(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(
|
||||
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
|
||||
)
|
||||
|
||||
# Permitted on admitted workload
|
||||
enforce_rbac(
|
||||
operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads
|
||||
)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_UPDATE, "mail", admitted_workloads)
|
||||
enforce_rbac(
|
||||
operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads
|
||||
)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_LOGS, "docs", admitted_workloads)
|
||||
enforce_rbac(
|
||||
operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads
|
||||
)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_LIST, None, admitted_workloads)
|
||||
|
||||
|
||||
def test_rbac_operator_denied_on_core_targets(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(
|
||||
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
|
||||
)
|
||||
|
||||
# Targeting "core" stack
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(
|
||||
operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads
|
||||
)
|
||||
assert "not permitted to target core service 'core'" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
# Targeting core services (traefik, stalwart, etc.)
|
||||
for core_svc in ["traefik", "authelia", "stalwart", "socket-proxy"]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(
|
||||
operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads
|
||||
)
|
||||
assert f"not permitted to target core service '{core_svc}'" in str(
|
||||
exc_info.value
|
||||
)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_operator_denied_on_case_variant_core_targets(admitted_workloads: set[str]):
|
||||
"""Ensure case variants ('Core', 'TRAEFIK', 'Authelia') are rejected for operator role (CR-DI-06)."""
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
for variant in ["Core", "CORE", "Traefik", "TRAEFIK", "Authelia"]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, variant, admitted_workloads)
|
||||
assert "not permitted to target core service" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
|
||||
def test_rbac_operator_denied_without_target_on_mutating_or_sensitive_ops(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(
|
||||
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
|
||||
)
|
||||
|
||||
for op in [
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_CONFIG,
|
||||
OperationType.WORKLOAD_LOGS,
|
||||
]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, op, None, admitted_workloads)
|
||||
assert f"Operation '{op.value}' requires an explicit workload target" in str(
|
||||
exc_info.value
|
||||
)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, op, "", admitted_workloads)
|
||||
assert f"Operation '{op.value}' requires an explicit workload target" in str(
|
||||
exc_info.value
|
||||
)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_operator_with_default_admitted_workloads(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
):
|
||||
deployments_file = tmp_path / "deployments.yaml"
|
||||
deployments_file.write_text(
|
||||
"repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8"
|
||||
)
|
||||
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file))
|
||||
|
||||
operator = Principal(
|
||||
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
|
||||
)
|
||||
enforce_rbac(
|
||||
operator, OperationType.WORKLOAD_DEPLOY, "customapp", admitted_workloads=None
|
||||
)
|
||||
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(
|
||||
operator,
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
"unknownapp",
|
||||
admitted_workloads=None,
|
||||
)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_operator_denied_on_unregistered_workload(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(
|
||||
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
|
||||
)
|
||||
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(
|
||||
operator,
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
"unregistered_app",
|
||||
admitted_workloads,
|
||||
)
|
||||
assert "not registered in deployments.yaml" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_viewer_permitted_only_on_non_sensitive_reads():
|
||||
viewer = Principal(
|
||||
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
|
||||
)
|
||||
|
||||
# Permitted reads
|
||||
enforce_rbac(viewer, OperationType.WORKLOAD_LIST, None)
|
||||
enforce_rbac(viewer, OperationType.WORKLOAD_GET, "snappymail")
|
||||
enforce_rbac(viewer, OperationType.WORKLOAD_RESOLVE, "snappymail")
|
||||
enforce_rbac(viewer, OperationType.PLATFORM_SSL, "snappymail")
|
||||
enforce_rbac(viewer, OperationType.PLATFORM_HEALTH, None)
|
||||
|
||||
|
||||
def test_rbac_viewer_denied_on_mutations():
|
||||
viewer = Principal(
|
||||
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
|
||||
)
|
||||
|
||||
mutations = [
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_STOP,
|
||||
OperationType.WORKLOAD_RESTART,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_PULL,
|
||||
OperationType.PLATFORM_SYNC_HOMEPAGE,
|
||||
]
|
||||
for mut in mutations:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(viewer, mut, "snappymail")
|
||||
assert "not permitted to execute mutating operation" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_viewer_denied_on_sensitive_reads():
|
||||
viewer = Principal(
|
||||
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
|
||||
)
|
||||
|
||||
for sens_op in [OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(viewer, sens_op, "snappymail")
|
||||
assert "not permitted to access sensitive operation" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_default_deployments_file_resolves_to_workloads_dir(
|
||||
tmp_path: Path, run_isolated_script_expr
|
||||
):
|
||||
"""DEFAULT_DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml."""
|
||||
resolved = run_isolated_script_expr(
|
||||
"import appctl_auth; print(appctl_auth.DEFAULT_DEPLOYMENTS_FILE)"
|
||||
)
|
||||
assert Path(resolved) == tmp_path / "Workloads" / "deployments.yaml"
|
||||
|
||||
|
||||
def test_load_admitted_workloads_fails_closed_when_absent(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
"""Absent ~/Workloads/deployments.yaml fails closed (empty set, no CORE_DIR fallback)."""
|
||||
import appctl_auth
|
||||
|
||||
monkeypatch.delenv("HOMELAB_DEPLOYMENTS_FILE", raising=False)
|
||||
monkeypatch.delenv("WORKLOADS_DIR", raising=False)
|
||||
monkeypatch.delenv("SITES_DIR", raising=False)
|
||||
monkeypatch.setattr(
|
||||
appctl_auth, "DEFAULT_DEPLOYMENTS_FILE", tmp_path / "Workloads" / "deployments.yaml"
|
||||
)
|
||||
assert appctl_auth.load_admitted_workloads() == set()
|
||||
|
||||
|
||||
def test_load_admitted_workloads_honors_workloads_dir_override(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
"""WORKLOADS_DIR takes precedence when HOMELAB_DEPLOYMENTS_FILE is unset."""
|
||||
import appctl_auth
|
||||
|
||||
custom_workloads = tmp_path / "CustomWorkloads"
|
||||
custom_workloads.mkdir()
|
||||
(custom_workloads / "deployments.yaml").write_text(
|
||||
"repositories:\n custom_app:\n path: ~/Workloads/custom_app\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.delenv("HOMELAB_DEPLOYMENTS_FILE", raising=False)
|
||||
monkeypatch.setenv("WORKLOADS_DIR", str(custom_workloads))
|
||||
assert appctl_auth.load_admitted_workloads() == {"custom_app"}
|
||||
@@ -0,0 +1,596 @@
|
||||
"""
|
||||
test_appctl_cli.py — Unit Tests for Thin UDS Client (scripts/appctl_cli.py)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from appctl_cli import format_response, resolve_token, run_cli
|
||||
from appctl_contracts import (
|
||||
ErrorCode,
|
||||
OperationError,
|
||||
OperationRequest,
|
||||
OperationResponse,
|
||||
OperationType,
|
||||
)
|
||||
|
||||
|
||||
def test_cli_token_resolution(tmp_path: Path, monkeypatch):
|
||||
"""Ensure token resolution checks CLI flag, environment, and config file."""
|
||||
# 1. Direct CLI argument precedence
|
||||
assert resolve_token("explicit-secret") == "explicit-secret"
|
||||
|
||||
# 2. Environment variable precedence
|
||||
monkeypatch.setenv("APPCTL_TOKEN", "env-secret")
|
||||
assert resolve_token(None) == "env-secret"
|
||||
|
||||
# 3. File fallback
|
||||
monkeypatch.delenv("APPCTL_TOKEN", raising=False)
|
||||
cfg_token = tmp_path / "token"
|
||||
cfg_token.write_text("file-secret\n", encoding="utf-8")
|
||||
with patch("pathlib.Path.home", return_value=tmp_path):
|
||||
dot_config = tmp_path / ".config" / "homelab"
|
||||
dot_config.mkdir(parents=True)
|
||||
(dot_config / "token").write_text("user-file-secret\n", encoding="utf-8")
|
||||
assert resolve_token(None) == "user-file-secret"
|
||||
|
||||
|
||||
def test_cli_format_response_success_and_error():
|
||||
"""Ensure response formatter produces human-friendly strings and JSON."""
|
||||
success_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_123",
|
||||
operation=OperationType.WORKLOAD_DEPLOY,
|
||||
output="Container started successfully",
|
||||
)
|
||||
formatted = format_response(success_resp, raw_json=False)
|
||||
assert "Container started successfully" in formatted
|
||||
|
||||
raw_json = format_response(success_resp, raw_json=True)
|
||||
assert '"operation": "workload.deploy"' in raw_json
|
||||
assert '"success": true' in raw_json
|
||||
|
||||
error_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=False,
|
||||
operation_id="op_456",
|
||||
operation=OperationType.WORKLOAD_DEPLOY,
|
||||
error=OperationError(code=ErrorCode.ERR_PERMISSION_DENIED, message="Forbidden"),
|
||||
)
|
||||
formatted_err = format_response(error_resp, raw_json=False)
|
||||
assert "❌ Error [ERR_PERMISSION_DENIED]: Forbidden" in formatted_err
|
||||
|
||||
|
||||
def test_cli_dispatches_list_command():
|
||||
"""Ensure appctl list dispatches OperationRequest(workload.list)."""
|
||||
mock_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_001",
|
||||
operation=OperationType.WORKLOAD_LIST,
|
||||
output="NAME STATUS\ndocs running\n",
|
||||
)
|
||||
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
|
||||
ret = run_cli(["list", "--core"])
|
||||
assert ret == 0
|
||||
assert mock_send.call_count == 1
|
||||
req: OperationRequest = mock_send.call_args[1]["operation_request"]
|
||||
assert req.operation == OperationType.WORKLOAD_LIST
|
||||
assert req.parameters["core"] is True
|
||||
assert "NAME STATUS" in mock_stdout.getvalue()
|
||||
|
||||
|
||||
def test_cli_dispatches_mutation_command():
|
||||
"""Ensure appctl up <target> dispatches OperationRequest(workload.deploy)."""
|
||||
mock_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_002",
|
||||
operation=OperationType.WORKLOAD_DEPLOY,
|
||||
target="jellyfin",
|
||||
result={"action": "deployed", "message": "Workload deployed"},
|
||||
)
|
||||
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
|
||||
ret = run_cli(["up", "jellyfin", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
assert mock_send.call_count == 1
|
||||
assert mock_send.call_args[1]["token"] == "tok_secret"
|
||||
req: OperationRequest = mock_send.call_args[1]["operation_request"]
|
||||
assert req.operation == OperationType.WORKLOAD_DEPLOY
|
||||
assert req.target == "jellyfin"
|
||||
assert "Workload deployed" in mock_stdout.getvalue()
|
||||
|
||||
|
||||
def test_cli_up_and_deploy_build_and_no_cache_flags():
|
||||
"""Ensure appctl up/deploy with --build and --no-cache flags dispatches correct parameters."""
|
||||
mock_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_build_01",
|
||||
operation=OperationType.WORKLOAD_DEPLOY,
|
||||
target="jellyfin",
|
||||
result={"action": "deployed", "message": "Workload deployed"},
|
||||
)
|
||||
|
||||
# 1. up with --build
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["up", "jellyfin", "--build", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req: OperationRequest = mock_send.call_args[1]["operation_request"]
|
||||
assert req.operation == OperationType.WORKLOAD_DEPLOY
|
||||
assert req.parameters.get("build") is True
|
||||
assert req.parameters.get("no_cache") is False
|
||||
|
||||
# 2. up with --no-cache implies build=True
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["up", "jellyfin", "--no-cache", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req = mock_send.call_args[1]["operation_request"]
|
||||
assert req.parameters.get("no_cache") is True
|
||||
assert req.parameters.get("build") is True
|
||||
|
||||
# 3. deploy alias with --no-cache
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["deploy", "jellyfin", "--no-cache", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req = mock_send.call_args[1]["operation_request"]
|
||||
assert req.parameters.get("no_cache") is True
|
||||
assert req.parameters.get("build") is True
|
||||
|
||||
|
||||
def test_cli_update_build_and_no_cache_flags():
|
||||
"""Ensure appctl update with --build and --no-cache flags dispatches correct parameters."""
|
||||
mock_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_upd_01",
|
||||
operation=OperationType.WORKLOAD_UPDATE,
|
||||
target="jellyfin",
|
||||
result={"action": "updated", "message": "Workload updated"},
|
||||
)
|
||||
|
||||
# 1. update with --build
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["update", "jellyfin", "--build", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req: OperationRequest = mock_send.call_args[1]["operation_request"]
|
||||
assert req.operation == OperationType.WORKLOAD_UPDATE
|
||||
assert req.parameters.get("build") is True
|
||||
assert req.parameters.get("no_cache", False) is False
|
||||
|
||||
# 2. update with --no-cache implies build=True
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["update", "jellyfin", "--no-cache", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req = mock_send.call_args[1]["operation_request"]
|
||||
assert req.parameters.get("no_cache") is True
|
||||
assert req.parameters.get("build") is True
|
||||
|
||||
# 3. update with --branch and --no-cache
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["update", "jellyfin", "--branch", "main", "--no-cache", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req = mock_send.call_args[1]["operation_request"]
|
||||
assert req.parameters.get("expected_branch") == "main"
|
||||
assert req.parameters.get("no_cache") is True
|
||||
assert req.parameters.get("build") is True
|
||||
|
||||
|
||||
def test_cli_handles_missing_socket():
|
||||
"""Ensure friendly stderr message when socket is absent."""
|
||||
with patch("appctl_cli.send_daemon_request", side_effect=FileNotFoundError), patch("sys.stderr", new_callable=io.StringIO) as mock_stderr:
|
||||
ret = run_cli(["list", "--socket", "/nonexistent/appctl.sock"])
|
||||
assert ret == 1
|
||||
assert "socket not found" in mock_stderr.getvalue()
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_list_table():
|
||||
"""Ensure workload.list renders the canonical 5-column layout matching docs/appctl.md."""
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_list_01",
|
||||
operation=OperationType.WORKLOAD_LIST,
|
||||
result={
|
||||
"total": 2,
|
||||
"workloads": [
|
||||
{
|
||||
"name": "snappymail",
|
||||
"type": "app",
|
||||
"domain": "mail.example.test",
|
||||
"deployment_status": "✓ Synced (main)",
|
||||
"provenance_status": "✓ Synced",
|
||||
"status": "🟢 Running (1)",
|
||||
},
|
||||
{
|
||||
"name": "traefik",
|
||||
"type": "core_service",
|
||||
"domain": "traefik.example.test",
|
||||
"deployment_status": "",
|
||||
"provenance_status": "— Core Platform",
|
||||
"status": "🟢 Running (1)",
|
||||
},
|
||||
],
|
||||
"message": "Found 2 workloads",
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
lines = rendered.splitlines()
|
||||
assert len(lines) >= 4
|
||||
assert lines[0] == "SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN"
|
||||
assert lines[1] == "------- ---------- ---------- ------ ------"
|
||||
assert "snappymail" in lines[2]
|
||||
assert "✓ Synced (main)" in lines[2]
|
||||
assert "✓ Synced" in lines[2]
|
||||
assert "🟢 Running (1)" in lines[2]
|
||||
assert "mail.example.test" in lines[2]
|
||||
|
||||
assert "traefik" in lines[3]
|
||||
assert "— Core Platform" in lines[3]
|
||||
assert "🟢 Running (1)" in lines[3]
|
||||
assert "traefik.example.test" in lines[3]
|
||||
assert "✨ Found 2 workloads" not in rendered
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_list_table_with_ssl():
|
||||
"""Ensure workload.list with SSL renders the canonical 6-column layout with CERT."""
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_list_ssl_01",
|
||||
operation=OperationType.WORKLOAD_LIST,
|
||||
result={
|
||||
"total": 1,
|
||||
"workloads": [
|
||||
{
|
||||
"name": "snappymail",
|
||||
"type": "app",
|
||||
"domain": "mail.example.test",
|
||||
"deployment_status": "✓ Synced (main)",
|
||||
"provenance_status": "✓ Synced",
|
||||
"status": "🟢 Running (1)",
|
||||
"ssl": {"status": "🟢 80d remaining"},
|
||||
},
|
||||
],
|
||||
"message": "Found 1 workloads",
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
lines = rendered.splitlines()
|
||||
assert len(lines) >= 3
|
||||
assert lines[0] == "SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN CERT"
|
||||
assert lines[1] == "------- ---------- ---------- ------ ------ ----"
|
||||
assert "snappymail" in lines[2]
|
||||
assert "🟢 80d remaining" in lines[2]
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_list_table_with_manifest_error():
|
||||
"""Ensure workload.list renders ⚠️ Manifest Error and ⚠️ Invalid Manifest, and status=None renders as '-'."""
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_list_err",
|
||||
operation=OperationType.WORKLOAD_LIST,
|
||||
result={
|
||||
"total": 1,
|
||||
"workloads": [
|
||||
{
|
||||
"name": "broken-app",
|
||||
"type": "app",
|
||||
"domain": "broken.example.test",
|
||||
"manifest_error": "Syntax error in app.yaml",
|
||||
"status": None,
|
||||
},
|
||||
],
|
||||
"message": "Found 1 workloads",
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
lines = rendered.splitlines()
|
||||
assert len(lines) >= 3
|
||||
assert "broken-app" in lines[2]
|
||||
assert "⚠️ Manifest Error" in lines[2]
|
||||
assert "⚠️ Invalid Manifest" in lines[2]
|
||||
# Ensure status is '-' and NOT 'None'
|
||||
assert " None " not in lines[2]
|
||||
assert " - " in lines[2]
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_get_info():
|
||||
"""Ensure workload.get (appctl info) renders structured workload metadata."""
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_get_01",
|
||||
operation=OperationType.WORKLOAD_GET,
|
||||
target="snappymail",
|
||||
result={
|
||||
"workload": {
|
||||
"name": "snappymail",
|
||||
"type": "app",
|
||||
"dir_path": "/home/operator/Sites/snappymail",
|
||||
"domain": "mail.example.test",
|
||||
"description": "Lightweight Webmail",
|
||||
"aliases": ["webmail", "mail"],
|
||||
"networks": ["proxy-net"],
|
||||
"auth": True,
|
||||
"visible": True,
|
||||
},
|
||||
"message": "Retrieved metadata for snappymail",
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert "Workload Overview: snappymail" in rendered
|
||||
assert "/home/operator/Sites/snappymail" in rendered
|
||||
assert "mail.example.test" in rendered
|
||||
assert "webmail, mail" in rendered
|
||||
assert "✨ Retrieved metadata" not in rendered
|
||||
|
||||
|
||||
def test_cli_format_response_renders_empty_workload_list():
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_list_empty",
|
||||
operation=OperationType.WORKLOAD_LIST,
|
||||
result={"total": 0, "workloads": []},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert rendered == "ℹ️ No workloads found."
|
||||
|
||||
|
||||
def test_cli_format_response_renders_core_service_and_rich_metadata():
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_get_core",
|
||||
operation=OperationType.WORKLOAD_GET,
|
||||
target="traefik",
|
||||
result={
|
||||
"workload": {
|
||||
"name": "traefik",
|
||||
"type": "core_service",
|
||||
"dir_path": "/home/operator/Core",
|
||||
"domain": "traefik.example.test",
|
||||
"container": "traefik-proxy",
|
||||
"description": "Edge Ingress",
|
||||
"aliases": ["edge"],
|
||||
"networks": ["proxy-net", "internal"],
|
||||
"auth": False,
|
||||
"visible": False,
|
||||
"source": {
|
||||
"url": "https://git.example.com/repo.git",
|
||||
"ref": "main",
|
||||
},
|
||||
"manifest_error": "Syntax error in app.yaml",
|
||||
"ssl": {
|
||||
"status": "valid",
|
||||
"issuer": "Let's Encrypt",
|
||||
"formatted_expiry": "2027-01-01",
|
||||
},
|
||||
},
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert "ℹ️ Core Infrastructure Service: traefik" in rendered
|
||||
assert "Container: traefik-proxy" in rendered
|
||||
assert "Aliases: edge" in rendered
|
||||
assert "Networks: proxy-net, internal" in rendered
|
||||
assert "Auth Protected: False" in rendered
|
||||
assert "Dashboard: Hidden" in rendered
|
||||
assert "Source URL: https://git.example.com/repo.git" in rendered
|
||||
assert "Target Ref: main" in rendered
|
||||
assert "⚠️ Manifest Validation Error:" in rendered
|
||||
assert "Syntax error in app.yaml" in rendered
|
||||
assert "🔒 SSL/TLS Certificate:" in rendered
|
||||
assert "Status: valid" in rendered
|
||||
|
||||
|
||||
def test_cli_format_response_renders_ssl_info():
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_ssl_01",
|
||||
operation=OperationType.PLATFORM_SSL,
|
||||
result={
|
||||
"ssl": {
|
||||
"domain": "app.example.test",
|
||||
"status": "valid",
|
||||
"issuer": "Let's Encrypt Authority X3",
|
||||
"subject": "CN=app.example.test",
|
||||
"not_after": "2027-01-01 00:00:00 GMT",
|
||||
"days_remaining": 75,
|
||||
"formatted_expiry": "in 75 days",
|
||||
"error": "Near expiration warning",
|
||||
}
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert "🔒 SSL/TLS Certificate: app.example.test" in rendered
|
||||
assert "Domain: app.example.test" in rendered
|
||||
assert "Status: valid" in rendered
|
||||
assert "Issuer: Let's Encrypt Authority X3" in rendered
|
||||
assert "Subject: CN=app.example.test" in rendered
|
||||
assert "Expiration: 2027-01-01 00:00:00 GMT" in rendered
|
||||
assert "Days Remaining: 75 days (in 75 days)" in rendered
|
||||
assert "Details/Error: Near expiration warning" in rendered
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_resolve_json():
|
||||
import json
|
||||
workload_data = {"name": "app1", "dir": "/sites/app1"}
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_resolve_01",
|
||||
operation=OperationType.WORKLOAD_RESOLVE,
|
||||
result={"workload": workload_data},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert json.loads(rendered) == workload_data
|
||||
|
||||
|
||||
def test_cli_format_response_error_without_error_payload():
|
||||
from unittest.mock import MagicMock
|
||||
resp = MagicMock(spec=OperationResponse)
|
||||
resp.success = False
|
||||
resp.error = None
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert rendered == "❌ Error: Unknown error"
|
||||
|
||||
|
||||
|
||||
def test_cli_format_response_default_success_message():
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_succ",
|
||||
operation=OperationType.PLATFORM_HEALTH,
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert rendered == "✨ Operation 'platform.health' succeeded."
|
||||
|
||||
|
||||
|
||||
def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path, monkeypatch):
|
||||
"""Ensure scripts/appctl executes `complete` and `completion` via appctl_engine.py even when socket exists."""
|
||||
import os
|
||||
import shutil
|
||||
import socket as std_socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
bash_bin = shutil.which("bash") or "bash"
|
||||
sock_dir = tempfile.TemporaryDirectory(prefix="appctl_sock_", dir="/tmp")
|
||||
sock_path = Path(sock_dir.name) / "appctl.sock"
|
||||
srv = std_socket.socket(std_socket.AF_UNIX, std_socket.SOCK_STREAM)
|
||||
srv.bind(str(sock_path))
|
||||
try:
|
||||
appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl"
|
||||
env = {
|
||||
"PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"),
|
||||
"PYTHON_BIN": sys.executable,
|
||||
"HOMELAB_DOMAIN": "example.test",
|
||||
"APPCTL_SOCKET_PATH": str(sock_path),
|
||||
"SITES_DIR": str(tmp_path),
|
||||
}
|
||||
if "PYTHONPATH" in os.environ:
|
||||
env["PYTHONPATH"] = os.environ["PYTHONPATH"]
|
||||
|
||||
res_comp = subprocess.run(
|
||||
[bash_bin, str(appctl_script), "completion", "bash"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert res_comp.returncode == 0
|
||||
assert "_appctl_completions()" in res_comp.stdout
|
||||
|
||||
res_words = subprocess.run(
|
||||
[bash_bin, str(appctl_script), "complete", "services"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert res_words.returncode == 0
|
||||
assert "traefik" in res_words.stdout
|
||||
assert "core" in res_words.stdout
|
||||
finally:
|
||||
srv.close()
|
||||
sock_dir.cleanup()
|
||||
|
||||
|
||||
def test_appctl_wrapper_fails_closed_when_socket_is_missing(tmp_path: Path):
|
||||
"""Ensure scripts/appctl fails closed with exit code 1 and diagnostic stderr when socket is missing."""
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
bash_bin = shutil.which("bash") or "bash"
|
||||
non_existent_sock = tmp_path / "missing_appctl.sock"
|
||||
appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl"
|
||||
|
||||
env = {
|
||||
"PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"),
|
||||
"PYTHON_BIN": sys.executable,
|
||||
"HOMELAB_DOMAIN": "example.test",
|
||||
"APPCTL_SOCKET_PATH": str(non_existent_sock),
|
||||
"SITES_DIR": str(tmp_path),
|
||||
}
|
||||
if "PYTHONPATH" in os.environ:
|
||||
env["PYTHONPATH"] = os.environ["PYTHONPATH"]
|
||||
|
||||
res = subprocess.run(
|
||||
[bash_bin, str(appctl_script), "status"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert res.returncode == 1
|
||||
assert "daemon socket not found" in res.stderr
|
||||
|
||||
|
||||
def test_appctl_wrapper_fast_paths_completion_without_socket(tmp_path: Path):
|
||||
"""Ensure scripts/appctl completes offline via appctl_engine.py even when socket is missing."""
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
bash_bin = shutil.which("bash") or "bash"
|
||||
non_existent_sock = tmp_path / "missing_appctl.sock"
|
||||
appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl"
|
||||
|
||||
env = {
|
||||
"PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"),
|
||||
"PYTHON_BIN": sys.executable,
|
||||
"HOMELAB_DOMAIN": "example.test",
|
||||
"APPCTL_SOCKET_PATH": str(non_existent_sock),
|
||||
"SITES_DIR": str(tmp_path),
|
||||
}
|
||||
if "PYTHONPATH" in os.environ:
|
||||
env["PYTHONPATH"] = os.environ["PYTHONPATH"]
|
||||
|
||||
res_comp = subprocess.run(
|
||||
[bash_bin, str(appctl_script), "completion", "bash"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert res_comp.returncode == 0
|
||||
assert "_appctl_completions()" in res_comp.stdout
|
||||
assert "up|deploy)" in res_comp.stdout
|
||||
assert "--build --no-cache" in res_comp.stdout
|
||||
|
||||
res_words = subprocess.run(
|
||||
[bash_bin, str(appctl_script), "complete", "services"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert res_words.returncode == 0
|
||||
assert "traefik" in res_words.stdout
|
||||
assert "core" in res_words.stdout
|
||||
|
||||
|
||||
@@ -0,0 +1,695 @@
|
||||
"""
|
||||
tests/unit/test_appctl_contracts.py — Unit Tests for Control Plane API Contracts (P4 Slice 1)
|
||||
|
||||
Behavior-driven test naming convention:
|
||||
test_<subject>_<accepts|rejects>_<condition>
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from appctl_contracts import (
|
||||
MUTATING_OPERATIONS,
|
||||
READ_ONLY_OPERATIONS,
|
||||
TARGET_REQUIRED_OPERATIONS,
|
||||
DeployParams,
|
||||
EmptyParams,
|
||||
ErrorCode,
|
||||
GetParams,
|
||||
ListParams,
|
||||
LogsParams,
|
||||
OperationError,
|
||||
OperationRequest,
|
||||
OperationResponse,
|
||||
OperationType,
|
||||
UpdateParams,
|
||||
sanitize_validation_error,
|
||||
)
|
||||
from core_manifest import ALLOWED_ACTIONS, Manifest
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def get_validation_error_locs(data: dict) -> list[str | int]:
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationRequest.model_validate(data)
|
||||
return [err["loc"][0] for err in exc_info.value.errors()]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Canonical 13 Operations
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_operation_type_contains_exactly_13_canonical_operations():
|
||||
assert len(OperationType) == 13
|
||||
expected = {
|
||||
"workload.list",
|
||||
"workload.get",
|
||||
"workload.resolve",
|
||||
"platform.ssl",
|
||||
"platform.health",
|
||||
"workload.config",
|
||||
"workload.logs",
|
||||
"workload.deploy",
|
||||
"workload.stop",
|
||||
"workload.restart",
|
||||
"workload.update",
|
||||
"workload.pull",
|
||||
"platform.sync_homepage",
|
||||
}
|
||||
assert {op.value for op in OperationType} == expected
|
||||
|
||||
|
||||
def test_operation_sets_partition_canonical_operations():
|
||||
assert MUTATING_OPERATIONS | READ_ONLY_OPERATIONS == set(OperationType)
|
||||
assert MUTATING_OPERATIONS.isdisjoint(READ_ONLY_OPERATIONS)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("op", list(OperationType))
|
||||
def test_operation_request_accepts_all_canonical_operations(op: OperationType):
|
||||
target = "jellyfin" if op in TARGET_REQUIRED_OPERATIONS else None
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": op.value,
|
||||
"target": target,
|
||||
"parameters": {},
|
||||
}
|
||||
validated = OperationRequest.model_validate(request)
|
||||
assert validated.operation == op
|
||||
assert validated.action == op
|
||||
|
||||
|
||||
def test_operation_request_rejects_unknown_operation():
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": "workload.unknown_action",
|
||||
"target": "jellyfin",
|
||||
"parameters": {},
|
||||
}
|
||||
locs = get_validation_error_locs(request)
|
||||
assert "operation" in locs
|
||||
|
||||
|
||||
def test_operation_request_rejects_empty_operation():
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": "",
|
||||
"target": "jellyfin",
|
||||
"parameters": {},
|
||||
}
|
||||
locs = get_validation_error_locs(request)
|
||||
assert "operation" in locs
|
||||
|
||||
|
||||
def test_operation_request_rejects_non_string_operation():
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": 12345,
|
||||
"target": "jellyfin",
|
||||
"parameters": {},
|
||||
}
|
||||
locs = get_validation_error_locs(request)
|
||||
assert "operation" in locs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Version "1.0"
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_operation_request_accepts_default_and_explicit_version_1_0():
|
||||
# Explicit "1.0"
|
||||
r1 = OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "platform.health",
|
||||
})
|
||||
assert r1.version == "1.0"
|
||||
|
||||
# Default "1.0"
|
||||
r2 = OperationRequest.model_validate({
|
||||
"operation": "platform.health",
|
||||
})
|
||||
assert r2.version == "1.0"
|
||||
|
||||
|
||||
def test_operation_request_rejects_non_1_0_version():
|
||||
for bad_ver in ["2.0", "0.9", "1.1", ""]:
|
||||
request = {
|
||||
"version": bad_ver,
|
||||
"operation": "platform.health",
|
||||
}
|
||||
locs = get_validation_error_locs(request)
|
||||
assert "version" in locs
|
||||
|
||||
|
||||
def test_operation_request_rejects_numeric_version():
|
||||
request = {
|
||||
"version": 1.0,
|
||||
"operation": "platform.health",
|
||||
}
|
||||
locs = get_validation_error_locs(request)
|
||||
assert "version" in locs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Target Validation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_operation_request_rejects_empty_target():
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": "workload.deploy",
|
||||
"target": "",
|
||||
"parameters": {},
|
||||
}
|
||||
locs = get_validation_error_locs(request)
|
||||
assert "target" in locs
|
||||
|
||||
|
||||
@pytest.mark.parametrize("op", list(TARGET_REQUIRED_OPERATIONS))
|
||||
def test_operation_request_rejects_missing_target_when_required(op: OperationType):
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": op.value,
|
||||
"target": None,
|
||||
"parameters": {},
|
||||
}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationRequest.model_validate(request)
|
||||
assert "requires a non-empty target" in str(exc_info.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("op", [
|
||||
OperationType.WORKLOAD_LIST,
|
||||
OperationType.PLATFORM_HEALTH,
|
||||
OperationType.PLATFORM_SYNC_HOMEPAGE,
|
||||
])
|
||||
def test_operation_request_accepts_missing_target_when_optional(op: OperationType):
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": op.value,
|
||||
"parameters": {},
|
||||
}
|
||||
validated = OperationRequest.model_validate(request)
|
||||
assert validated.target is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Parameter Models & Bounds Validation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_deploy_params_defaults_and_explicit_bounds():
|
||||
# Defaults
|
||||
p_default = DeployParams()
|
||||
assert p_default.recreate is True
|
||||
assert p_default.remove_orphans is True
|
||||
assert p_default.build is False
|
||||
assert p_default.no_cache is False
|
||||
|
||||
# Explicit
|
||||
p_custom = DeployParams(recreate=False, remove_orphans=False, build=True, no_cache=False)
|
||||
assert p_custom.recreate is False
|
||||
assert p_custom.remove_orphans is False
|
||||
assert p_custom.build is True
|
||||
assert p_custom.no_cache is False
|
||||
|
||||
# no_cache implies build=True
|
||||
p_no_cache = DeployParams(no_cache=True)
|
||||
assert p_no_cache.no_cache is True
|
||||
assert p_no_cache.build is True
|
||||
|
||||
# no_cache overrides explicit build=False
|
||||
p_override = DeployParams(build=False, no_cache=True)
|
||||
assert p_override.no_cache is True
|
||||
assert p_override.build is True
|
||||
|
||||
|
||||
def test_deploy_params_rejects_non_strict_types():
|
||||
for bad_bool in ["true", "false", 1, 0, None, [True]]:
|
||||
with pytest.raises(ValidationError):
|
||||
DeployParams(recreate=bad_bool) # type: ignore[arg-type]
|
||||
with pytest.raises(ValidationError):
|
||||
DeployParams(remove_orphans=bad_bool) # type: ignore[arg-type]
|
||||
with pytest.raises(ValidationError):
|
||||
DeployParams(build=bad_bool) # type: ignore[arg-type]
|
||||
with pytest.raises(ValidationError):
|
||||
DeployParams(no_cache=bad_bool) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_deploy_params_rejects_extra_fields():
|
||||
with pytest.raises(ValidationError):
|
||||
DeployParams.model_validate({"recreate": True, "unexpected": "extra"})
|
||||
|
||||
|
||||
def test_update_params_defaults_and_explicit():
|
||||
# Defaults
|
||||
p_default = UpdateParams()
|
||||
assert p_default.expected_branch is None
|
||||
assert p_default.build is False
|
||||
assert p_default.no_cache is False
|
||||
|
||||
# Explicit
|
||||
p_custom = UpdateParams(expected_branch="main", build=True, no_cache=False)
|
||||
assert p_custom.expected_branch == "main"
|
||||
assert p_custom.build is True
|
||||
assert p_custom.no_cache is False
|
||||
|
||||
# no_cache implies build=True
|
||||
p_no_cache = UpdateParams(no_cache=True)
|
||||
assert p_no_cache.no_cache is True
|
||||
assert p_no_cache.build is True
|
||||
|
||||
# no_cache overrides explicit build=False
|
||||
p_override = UpdateParams(build=False, no_cache=True)
|
||||
assert p_override.no_cache is True
|
||||
assert p_override.build is True
|
||||
|
||||
|
||||
def test_update_params_rejects_empty_branch_and_non_strict_types():
|
||||
for bad_bool in ["true", "false", 1, 0, None, [True]]:
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(build=bad_bool) # type: ignore[arg-type]
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(no_cache=bad_bool) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(expected_branch="") # min_length=1
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(expected_branch=123) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams.model_validate({"build": False, "extra": "prohibited"})
|
||||
|
||||
|
||||
def test_logs_params_defaults_and_bounds():
|
||||
# Default
|
||||
p_default = LogsParams()
|
||||
assert p_default.tail == 100
|
||||
|
||||
# Bounds
|
||||
assert LogsParams(tail=1).tail == 1
|
||||
assert LogsParams(tail=1000).tail == 1000
|
||||
assert LogsParams(tail=500).tail == 500
|
||||
|
||||
# Below minimum
|
||||
with pytest.raises(ValidationError):
|
||||
LogsParams(tail=0)
|
||||
|
||||
# Above maximum
|
||||
with pytest.raises(ValidationError):
|
||||
LogsParams(tail=1001)
|
||||
|
||||
# Non-strict integer (string / float)
|
||||
with pytest.raises(ValidationError):
|
||||
LogsParams(tail="100") # type: ignore[arg-type]
|
||||
with pytest.raises(ValidationError):
|
||||
LogsParams(tail=100.5) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
LogsParams.model_validate({"tail": 50, "follow": True})
|
||||
|
||||
|
||||
def test_list_params_defaults_and_explicit():
|
||||
p_default = ListParams()
|
||||
assert p_default.fetch is False
|
||||
assert p_default.core is False
|
||||
assert p_default.ssl is False
|
||||
|
||||
p_custom = ListParams(fetch=True, core=True, ssl=True)
|
||||
assert p_custom.fetch is True
|
||||
assert p_custom.core is True
|
||||
assert p_custom.ssl is True
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
ListParams(fetch="yes") # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
ListParams.model_validate({"fetch": False, "extra": 1})
|
||||
|
||||
|
||||
def test_get_params_defaults_and_explicit():
|
||||
p_default = GetParams()
|
||||
assert p_default.ssl is False
|
||||
|
||||
p_custom = GetParams(ssl=True)
|
||||
assert p_custom.ssl is True
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
GetParams(ssl="true") # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_empty_params_rejects_extra_fields():
|
||||
p = EmptyParams()
|
||||
assert p.model_dump() == {}
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
EmptyParams.model_validate({"any_field": "disallowed"})
|
||||
|
||||
|
||||
def test_operation_request_validates_and_parses_operation_specific_params():
|
||||
# Deploy
|
||||
req_deploy = OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
"parameters": {"recreate": True, "build": True},
|
||||
})
|
||||
params = req_deploy.parse_parameters()
|
||||
assert isinstance(params, DeployParams)
|
||||
assert params.build is True
|
||||
|
||||
# Logs
|
||||
req_logs = OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "workload.logs",
|
||||
"target": "snappymail",
|
||||
"parameters": {"tail": 250},
|
||||
})
|
||||
log_params = req_logs.parse_parameters()
|
||||
assert isinstance(log_params, LogsParams)
|
||||
assert log_params.tail == 250
|
||||
|
||||
# Stop (accepts EmptyParams)
|
||||
req_stop = OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "workload.stop",
|
||||
"target": "snappymail",
|
||||
"parameters": {},
|
||||
})
|
||||
assert isinstance(req_stop.parse_parameters(), EmptyParams)
|
||||
|
||||
|
||||
def test_operation_request_rejects_invalid_params_for_operation():
|
||||
# Deploy with bad tail
|
||||
with pytest.raises(ValidationError):
|
||||
OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
"parameters": {"tail": 50}, # Deploy does not accept tail
|
||||
})
|
||||
|
||||
# Logs with out-of-bounds tail
|
||||
with pytest.raises(ValidationError):
|
||||
OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "workload.logs",
|
||||
"target": "snappymail",
|
||||
"parameters": {"tail": 9999},
|
||||
})
|
||||
|
||||
# Stop with extra params
|
||||
with pytest.raises(ValidationError):
|
||||
OperationRequest.model_validate({
|
||||
"version": "1.0",
|
||||
"operation": "workload.stop",
|
||||
"target": "snappymail",
|
||||
"parameters": {"force": True},
|
||||
})
|
||||
|
||||
|
||||
def test_operation_request_rejects_extra_top_level_fields():
|
||||
request = {
|
||||
"version": "1.0",
|
||||
"operation": "platform.health",
|
||||
"prohibited_extra": "attack",
|
||||
}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationRequest.model_validate(request)
|
||||
assert "extra_forbidden" in [e["type"] for e in exc_info.value.errors()]
|
||||
|
||||
|
||||
def test_operation_request_backward_compatibility_aliases():
|
||||
# Accepts 'action' alias for 'operation', and 'params' alias for 'parameters'
|
||||
request = {
|
||||
"action": "workload.deploy",
|
||||
"target": "jellyfin",
|
||||
"params": {"recreate": True},
|
||||
}
|
||||
validated = OperationRequest.model_validate(request)
|
||||
assert validated.operation == OperationType.WORKLOAD_DEPLOY
|
||||
assert validated.action == OperationType.WORKLOAD_DEPLOY
|
||||
assert validated.parameters == {"recreate": True}
|
||||
assert validated.params == {"recreate": True}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Closed 6-Code Error Taxonomy
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_error_code_taxonomy_contains_exactly_7_canonical_codes():
|
||||
assert len(ErrorCode) == 7
|
||||
expected_codes = {
|
||||
"ERR_VALIDATION_FAILED",
|
||||
"ERR_AUTH_REQUIRED",
|
||||
"ERR_PERMISSION_DENIED",
|
||||
"ERR_CAPABILITY_NOT_GRANTED",
|
||||
"ERR_TARGET_NOT_FOUND",
|
||||
"ERR_CONCURRENT_MUTATION",
|
||||
"ERR_EXECUTION_FAILED",
|
||||
}
|
||||
assert {code.value for code in ErrorCode} == expected_codes
|
||||
|
||||
|
||||
def test_error_code_http_status_mapping():
|
||||
assert ErrorCode.ERR_VALIDATION_FAILED.http_status == 400
|
||||
assert ErrorCode.ERR_AUTH_REQUIRED.http_status == 401
|
||||
assert ErrorCode.ERR_PERMISSION_DENIED.http_status == 403
|
||||
assert ErrorCode.ERR_CAPABILITY_NOT_GRANTED.http_status == 403
|
||||
assert ErrorCode.ERR_TARGET_NOT_FOUND.http_status == 404
|
||||
assert ErrorCode.ERR_CONCURRENT_MUTATION.http_status == 409
|
||||
assert ErrorCode.ERR_EXECUTION_FAILED.http_status == 500
|
||||
|
||||
|
||||
def test_operation_error_accepts_valid_error_code():
|
||||
err = OperationError(
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
message="Bearer token required",
|
||||
)
|
||||
assert err.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||
assert err.message == "Bearer token required"
|
||||
assert err.details is None
|
||||
|
||||
|
||||
def test_operation_error_accepts_string_error_code_coercion():
|
||||
err = OperationError.model_validate({
|
||||
"code": "ERR_CONCURRENT_MUTATION",
|
||||
"message": "Operation locked by concurrent task",
|
||||
})
|
||||
assert err.code == ErrorCode.ERR_CONCURRENT_MUTATION
|
||||
|
||||
|
||||
def test_operation_error_rejects_invalid_error_code():
|
||||
with pytest.raises(ValidationError):
|
||||
OperationError.model_validate({
|
||||
"code": "ERR_CUSTOM_CODE",
|
||||
"message": "Invalid code",
|
||||
})
|
||||
|
||||
|
||||
def test_operation_error_rejects_extra_fields():
|
||||
with pytest.raises(ValidationError):
|
||||
OperationError.model_validate({
|
||||
"code": "ERR_VALIDATION_FAILED",
|
||||
"message": "Failed",
|
||||
"secret_leak": "value",
|
||||
})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Error Sanitizer (Information Disclosure Prevention)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_sanitize_validation_error_strips_input_and_url():
|
||||
# Create a model with secret value that fails validation
|
||||
class SecretPayload(BaseModel):
|
||||
token: str = "default"
|
||||
|
||||
try:
|
||||
LogsParams.model_validate({
|
||||
"tail": "SUPER_SECRET_TOKEN_DO_NOT_LEAK",
|
||||
})
|
||||
except ValidationError as exc:
|
||||
op_err = sanitize_validation_error(exc)
|
||||
|
||||
assert op_err.code == ErrorCode.ERR_VALIDATION_FAILED
|
||||
assert op_err.message == "Request payload validation failed"
|
||||
assert op_err.details is not None
|
||||
assert len(op_err.details) == 1
|
||||
detail = op_err.details[0]
|
||||
|
||||
# Ensure neither input nor url appears in any details dictionary
|
||||
assert "input" not in detail
|
||||
assert "url" not in detail
|
||||
assert "SUPER_SECRET_TOKEN_DO_NOT_LEAK" not in str(detail)
|
||||
assert detail["loc"] == ["tail"]
|
||||
assert detail["type"] == "int_type"
|
||||
assert "Input should be a valid integer" in detail["msg"]
|
||||
|
||||
# Verify defense-in-depth: exc.errors called with include_input=False and include_url=False
|
||||
from unittest.mock import MagicMock
|
||||
mock_exc = MagicMock(spec=ValidationError)
|
||||
mock_exc.errors.return_value = [{"loc": ("field",), "type": "value_error", "msg": "Invalid"}]
|
||||
sanitize_validation_error(mock_exc)
|
||||
mock_exc.errors.assert_called_once_with(include_input=False, include_url=False)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OperationResponse Consistency & Edge Cases
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_operation_response_accepts_success_without_error():
|
||||
response_data = {
|
||||
"version": "1.0",
|
||||
"success": True,
|
||||
"operation_id": "op_123",
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
"output": "Snappymail deployment complete",
|
||||
}
|
||||
validated = OperationResponse.model_validate(response_data)
|
||||
assert validated.success is True
|
||||
assert validated.status == "success"
|
||||
assert validated.error is None
|
||||
assert validated.operation == OperationType.WORKLOAD_DEPLOY
|
||||
assert validated.action == OperationType.WORKLOAD_DEPLOY
|
||||
assert validated.operation_id == "op_123"
|
||||
|
||||
|
||||
def test_operation_response_accepts_status_field_reconciliation():
|
||||
# Pass 'status': 'success' without 'success'
|
||||
r1 = OperationResponse.model_validate({
|
||||
"version": "1.0",
|
||||
"status": "success",
|
||||
"operation_id": "op_123",
|
||||
"operation": "platform.health",
|
||||
})
|
||||
assert r1.success is True
|
||||
assert r1.status == "success"
|
||||
|
||||
# Pass 'status': 'error' without 'success'
|
||||
r2 = OperationResponse.model_validate({
|
||||
"version": "1.0",
|
||||
"status": "error",
|
||||
"operation_id": "op_124",
|
||||
"operation": "platform.health",
|
||||
"error": {
|
||||
"code": "ERR_EXECUTION_FAILED",
|
||||
"message": "Health probe failed",
|
||||
},
|
||||
})
|
||||
assert r2.success is False
|
||||
assert r2.status == "error"
|
||||
|
||||
|
||||
def test_operation_response_accepts_failure_with_nested_error():
|
||||
response_data = {
|
||||
"version": "1.0",
|
||||
"success": False,
|
||||
"operation_id": "op_456",
|
||||
"operation": "workload.deploy",
|
||||
"target": "capybara",
|
||||
"error": {
|
||||
"code": "ERR_TARGET_NOT_FOUND",
|
||||
"message": "Workload `capybara` does not exist",
|
||||
},
|
||||
}
|
||||
validated = OperationResponse.model_validate(response_data)
|
||||
assert validated.success is False
|
||||
assert validated.target == "capybara"
|
||||
assert validated.operation_id == "op_456"
|
||||
assert validated.operation == OperationType.WORKLOAD_DEPLOY
|
||||
assert isinstance(validated.error, OperationError)
|
||||
assert validated.error.code == ErrorCode.ERR_TARGET_NOT_FOUND
|
||||
assert validated.error.message == "Workload `capybara` does not exist"
|
||||
|
||||
|
||||
def test_operation_response_rejects_success_with_error():
|
||||
response_data = {
|
||||
"version": "1.0",
|
||||
"success": True,
|
||||
"operation": "workload.deploy",
|
||||
"target": "microservice1",
|
||||
"operation_id": "op_124",
|
||||
"error": {
|
||||
"code": "ERR_VALIDATION_FAILED",
|
||||
"message": "This error should not appear on success response",
|
||||
},
|
||||
}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationResponse.model_validate(response_data)
|
||||
assert "cannot contain an error" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_operation_response_rejects_failure_without_error():
|
||||
response_data = {
|
||||
"version": "1.0",
|
||||
"success": False,
|
||||
"operation": "workload.deploy",
|
||||
"target": "microservice2",
|
||||
"operation_id": "op_125",
|
||||
}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationResponse.model_validate(response_data)
|
||||
assert "must contain an error" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_operation_response_rejects_inconsistent_status_and_success():
|
||||
response_data = {
|
||||
"version": "1.0",
|
||||
"success": True,
|
||||
"status": "error",
|
||||
"operation": "platform.health",
|
||||
"operation_id": "op_126",
|
||||
}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationResponse.model_validate(response_data)
|
||||
assert "'status' and 'success' must agree" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_operation_response_rejects_extra_fields():
|
||||
response_data = {
|
||||
"version": "1.0",
|
||||
"success": True,
|
||||
"operation": "platform.health",
|
||||
"operation_id": "op_127",
|
||||
"unauthorized_field": "data",
|
||||
}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
OperationResponse.model_validate(response_data)
|
||||
assert "extra_forbidden" in [e["type"] for e in exc_info.value.errors()]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Core Manifest compose_pull Action
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_core_manifest_allows_compose_pull_action():
|
||||
assert "compose_pull" in ALLOWED_ACTIONS
|
||||
|
||||
valid_manifest = {
|
||||
"schema_version": "1.0",
|
||||
"name": "snappymail",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/example/snappymail.git",
|
||||
"ref": "main",
|
||||
},
|
||||
"deployment": {
|
||||
"strategy": "compose",
|
||||
"actions": ["git_pull", "compose_pull", "compose_up"],
|
||||
},
|
||||
}
|
||||
parsed = Manifest.model_validate(valid_manifest)
|
||||
assert parsed.deployment.actions == ["git_pull", "compose_pull", "compose_up"]
|
||||
@@ -0,0 +1,645 @@
|
||||
"""
|
||||
test_appctl_daemon.py — Unit and Integration Test Suite for Milestone P4 Daemon
|
||||
|
||||
Asserts:
|
||||
- Dual-transport equivalence between UDS (/run/homelab/appctl.sock) and TCP (127.0.0.1:9001)
|
||||
- 64 KiB request body limit enforcement (400 ERR_VALIDATION_FAILED)
|
||||
- Health check route GET /v1/health
|
||||
- Unauthenticated rejection fails closed (401 ERR_AUTH_REQUIRED)
|
||||
- UDS SO_PEERCRED viewer fallback boundary
|
||||
- 3-role RBAC enforcement across daemon transports
|
||||
- Pre-flight and inert dotenv safety through daemon
|
||||
- Concurrency conflict (409 ERR_CONCURRENT_MUTATION)
|
||||
- Truthful execution failure reporting (500 ERR_EXECUTION_FAILED)
|
||||
- Fail-closed pre-execution audit guard
|
||||
- Daemon restart socket unlinking and clean rebinding
|
||||
- gitops_dispatcher delegation to daemon UDS
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
import socket
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import gitops_dispatcher
|
||||
import pytest
|
||||
from appctl_audit import AuditLogger, AuditPersistenceError, TargetLockManager
|
||||
from appctl_auth import Role, TokenDescriptor, TokenStore
|
||||
from appctl_contracts import ErrorCode, OperationRequest, OperationType
|
||||
from appctl_daemon import (
|
||||
AppctlDaemon,
|
||||
UnixHTTPConnection,
|
||||
send_daemon_request,
|
||||
)
|
||||
from appctl_router import OperationalRouter
|
||||
|
||||
ADMIN_SECRET = "secret-admin-key-789"
|
||||
OPERATOR_SECRET = "secret-operator-key-456"
|
||||
|
||||
ADMIN_HASH = hashlib.sha256(ADMIN_SECRET.encode()).hexdigest()
|
||||
OPERATOR_HASH = hashlib.sha256(OPERATOR_SECRET.encode()).hexdigest()
|
||||
|
||||
|
||||
def get_free_port() -> int:
|
||||
"""Find an available TCP port on loopback."""
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def daemon_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
|
||||
"""
|
||||
Spins up an isolated AppctlDaemon instance with:
|
||||
- Dedicated UDS socket in tmp_path
|
||||
- Dynamic loopback TCP port
|
||||
- Mock Sites directory with admitted 'docs' and unregistered 'rogue' workloads
|
||||
- Valid 0400 tokens store with admin and operator tokens
|
||||
- Valid 0600 audit log file
|
||||
"""
|
||||
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
|
||||
sock_dir = tempfile.TemporaryDirectory(prefix="appctl_sock_", dir="/tmp")
|
||||
socket_path = Path(sock_dir.name) / "appctl.sock"
|
||||
http_port = get_free_port()
|
||||
http_host = "127.0.0.1"
|
||||
|
||||
# Tokens store
|
||||
tokens_file = tmp_path / "tokens.json"
|
||||
tokens_data = [
|
||||
TokenDescriptor(
|
||||
token_id="tok_admin",
|
||||
identity="operator",
|
||||
role=Role.ADMIN,
|
||||
sha256=ADMIN_HASH,
|
||||
).model_dump(),
|
||||
TokenDescriptor(
|
||||
token_id="tok_gitops",
|
||||
identity="gitops-dispatcher",
|
||||
role=Role.OPERATOR,
|
||||
sha256=OPERATOR_HASH,
|
||||
).model_dump(),
|
||||
]
|
||||
tokens_file.write_text(json.dumps(tokens_data), encoding="utf-8")
|
||||
tokens_file.chmod(0o400)
|
||||
token_store = TokenStore(tokens_file)
|
||||
|
||||
# Audit log
|
||||
audit_file = tmp_path / "audit.jsonl"
|
||||
audit_file.touch()
|
||||
audit_file.chmod(0o600)
|
||||
audit_logger = AuditLogger(audit_file)
|
||||
|
||||
# Locks
|
||||
lock_dir = tmp_path / "locks"
|
||||
lock_dir.mkdir()
|
||||
lock_manager = TargetLockManager(lock_dir)
|
||||
|
||||
# Workloads
|
||||
sites_dir = tmp_path / "Sites"
|
||||
sites_dir.mkdir()
|
||||
core_dir = tmp_path / "Core"
|
||||
core_dir.mkdir()
|
||||
|
||||
# Admitted workload: docs
|
||||
docs_dir = sites_dir / "docs"
|
||||
docs_dir.mkdir()
|
||||
(docs_dir / "app.yaml").write_text(
|
||||
"name: docs\n"
|
||||
"domain: docs\n"
|
||||
"deployment:\n"
|
||||
" branch: main\n"
|
||||
" actions:\n"
|
||||
" - compose_up\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
(docs_dir / "docker-compose.yml").write_text(
|
||||
"services:\n"
|
||||
" web:\n"
|
||||
" image: nginx:alpine\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
# Unregistered workload: rogue
|
||||
rogue_dir = sites_dir / "rogue"
|
||||
rogue_dir.mkdir()
|
||||
(rogue_dir / "app.yaml").write_text(
|
||||
"name: rogue\n"
|
||||
"deployment:\n"
|
||||
" branch: main\n"
|
||||
" actions:\n"
|
||||
" - compose_up\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
(rogue_dir / "docker-compose.yml").write_text(
|
||||
"services:\n"
|
||||
" web:\n"
|
||||
" image: alpine:latest\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
# deployments.yaml
|
||||
deployments_file = tmp_path / "deployments.yaml"
|
||||
deployments_file.write_text(
|
||||
'schemaVersion: "1.0"\n'
|
||||
"repositories:\n"
|
||||
" docs:\n"
|
||||
f' path: "{docs_dir}"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file))
|
||||
|
||||
router = OperationalRouter(
|
||||
audit_logger=audit_logger,
|
||||
lock_manager=lock_manager,
|
||||
sites_dir=sites_dir,
|
||||
core_dir=core_dir,
|
||||
)
|
||||
|
||||
daemon = AppctlDaemon(
|
||||
router=router,
|
||||
token_store=token_store,
|
||||
audit_logger=audit_logger,
|
||||
lock_manager=lock_manager,
|
||||
socket_path=socket_path,
|
||||
http_host=http_host,
|
||||
http_port=http_port,
|
||||
sites_dir=sites_dir,
|
||||
core_dir=core_dir,
|
||||
deployments_file=deployments_file,
|
||||
)
|
||||
|
||||
daemon.start()
|
||||
|
||||
class Context:
|
||||
def __init__(self):
|
||||
self.daemon = daemon
|
||||
self.socket_path = socket_path
|
||||
self.http_url = f"http://{http_host}:{http_port}"
|
||||
self.sites_dir = sites_dir
|
||||
self.core_dir = core_dir
|
||||
self.audit_file = audit_file
|
||||
self.deployments_file = deployments_file
|
||||
self.docs_dir = docs_dir
|
||||
self.rogue_dir = rogue_dir
|
||||
|
||||
ctx = Context()
|
||||
try:
|
||||
yield ctx
|
||||
finally:
|
||||
daemon.stop()
|
||||
sock_dir.cleanup()
|
||||
|
||||
|
||||
def test_health_endpoint(daemon_env):
|
||||
"""GET /v1/health returns HTTP 200 with health metadata over UDS and TCP."""
|
||||
# Over UDS
|
||||
conn_uds = UnixHTTPConnection(str(daemon_env.socket_path))
|
||||
conn_uds.request("GET", "/v1/health")
|
||||
res_uds = conn_uds.getresponse()
|
||||
assert res_uds.status == 200
|
||||
data_uds = json.loads(res_uds.read().decode())
|
||||
assert data_uds["status"] == "healthy"
|
||||
assert data_uds["version"] == "1.0"
|
||||
assert "uptime_seconds" in data_uds
|
||||
conn_uds.close()
|
||||
|
||||
# Over TCP
|
||||
import http.client
|
||||
conn_tcp = http.client.HTTPConnection("127.0.0.1", daemon_env.daemon.http_port)
|
||||
conn_tcp.request("GET", "/v1/health")
|
||||
res_tcp = conn_tcp.getresponse()
|
||||
assert res_tcp.status == 200
|
||||
data_tcp = json.loads(res_tcp.read().decode())
|
||||
assert data_tcp["status"] == "healthy"
|
||||
assert data_tcp["version"] == "1.0"
|
||||
conn_tcp.close()
|
||||
|
||||
|
||||
def test_transport_dual_equivalence(daemon_env):
|
||||
"""
|
||||
Compare responses of POST /v1/operations over Unix socket vs HTTP 127.0.0.1.
|
||||
Asserts 100% schema and status parity.
|
||||
"""
|
||||
list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST)
|
||||
|
||||
# 1. Successful query with admin token
|
||||
resp_uds = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=list_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
resp_http = send_daemon_request(
|
||||
endpoint=daemon_env.http_url,
|
||||
operation_request=list_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
|
||||
assert resp_uds.success is True
|
||||
assert resp_http.success is True
|
||||
assert resp_uds.status == resp_http.status
|
||||
assert resp_uds.operation == resp_http.operation
|
||||
assert resp_uds.version == resp_http.version
|
||||
assert resp_uds.result == resp_http.result
|
||||
|
||||
# 2. Error case parity (404 target not found)
|
||||
get_req = OperationRequest(operation=OperationType.WORKLOAD_GET, target="nonexistent")
|
||||
err_uds = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=get_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
err_http = send_daemon_request(
|
||||
endpoint=daemon_env.http_url,
|
||||
operation_request=get_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
|
||||
assert err_uds.success is False
|
||||
assert err_http.success is False
|
||||
assert err_uds.error is not None and err_http.error is not None
|
||||
assert err_uds.error.code == ErrorCode.ERR_TARGET_NOT_FOUND
|
||||
assert err_http.error.code == ErrorCode.ERR_TARGET_NOT_FOUND
|
||||
assert err_uds.error.code.http_status == 404
|
||||
assert err_http.error.code.http_status == 404
|
||||
|
||||
|
||||
def test_request_body_size_limit(daemon_env):
|
||||
"""Requests exceeding 64 KiB are rejected with 400 ERR_VALIDATION_FAILED."""
|
||||
oversized_data = {"version": "1.0", "operation": "workload.list", "padding": "x" * (65 * 1024)}
|
||||
body_str = json.dumps(oversized_data)
|
||||
|
||||
conn = UnixHTTPConnection(str(daemon_env.socket_path))
|
||||
headers = {"Content-Type": "application/json", "Host": "localhost"}
|
||||
conn.request("POST", "/v1/operations", body=body_str, headers=headers)
|
||||
res = conn.getresponse()
|
||||
assert res.status == 400
|
||||
data = json.loads(res.read().decode())
|
||||
assert data["status"] == "error"
|
||||
assert data["error"]["code"] == ErrorCode.ERR_VALIDATION_FAILED.value
|
||||
assert "exceeds limit" in data["error"]["message"]
|
||||
conn.close()
|
||||
|
||||
|
||||
def test_auth_missing_token_fails_closed(daemon_env):
|
||||
"""
|
||||
Mutating operations and sensitive reads without Bearer token return 401 ERR_AUTH_REQUIRED
|
||||
and execute zero subprocesses.
|
||||
"""
|
||||
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
|
||||
with patch("appctl_router.run_bounded_subprocess") as mock_subproc:
|
||||
# Over HTTP without token
|
||||
resp_http = send_daemon_request(
|
||||
endpoint=daemon_env.http_url,
|
||||
operation_request=deploy_req,
|
||||
token=None,
|
||||
)
|
||||
assert resp_http.success is False
|
||||
assert resp_http.error is not None
|
||||
assert resp_http.error.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||
assert resp_http.error.code.http_status == 401
|
||||
assert mock_subproc.call_count == 0
|
||||
|
||||
# Over UDS without token (deploy is mutating, peercred viewer fallback must be rejected)
|
||||
resp_uds = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=None,
|
||||
)
|
||||
assert resp_uds.success is False
|
||||
assert resp_uds.error is not None
|
||||
assert resp_uds.error.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
assert resp_uds.error.code.http_status == 403
|
||||
assert mock_subproc.call_count == 0
|
||||
|
||||
|
||||
def test_uds_peercred_viewer_boundary(daemon_env):
|
||||
"""
|
||||
Tokenless UDS call from operator UID succeeds for workload.list (auth_method: unix_peercred),
|
||||
but fails with 403 on mutation or sensitive reads.
|
||||
"""
|
||||
# Read-only query over UDS without token succeeds as viewer
|
||||
list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST)
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=list_req,
|
||||
token=None,
|
||||
)
|
||||
assert resp.success is True
|
||||
assert resp.result is not None
|
||||
assert "workloads" in resp.result
|
||||
|
||||
# Sensitive read (workload.config) without token fails
|
||||
config_req = OperationRequest(operation=OperationType.WORKLOAD_CONFIG, target="docs")
|
||||
resp_cfg = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=config_req,
|
||||
token=None,
|
||||
)
|
||||
assert resp_cfg.success is False
|
||||
assert resp_cfg.error is not None
|
||||
assert resp_cfg.error.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
assert resp_cfg.error.code.http_status == 403
|
||||
|
||||
|
||||
def test_rbac_role_matrix(daemon_env):
|
||||
"""
|
||||
homelab-operator allowed on deployments.yaml workloads but denied on unregistered workloads;
|
||||
homelab-admin allowed on all valid targets.
|
||||
"""
|
||||
deploy_registered = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
deploy_unregistered = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="rogue")
|
||||
|
||||
with patch("appctl_router.run_bounded_subprocess") as mock_subproc, patch("appctl_router.OperationalRouter._trigger_homepage_sync"):
|
||||
mock_subproc.return_value = (0, "Container docs created", "")
|
||||
|
||||
# Operator on registered target -> SUCCESS
|
||||
resp_op_reg = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_registered,
|
||||
token=OPERATOR_SECRET,
|
||||
)
|
||||
assert resp_op_reg.success is True
|
||||
assert resp_op_reg.result is not None
|
||||
assert resp_op_reg.result["action"] == "deployed"
|
||||
|
||||
# Operator on unregistered target -> 403 ERR_PERMISSION_DENIED
|
||||
resp_op_unreg = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_unregistered,
|
||||
token=OPERATOR_SECRET,
|
||||
)
|
||||
assert resp_op_unreg.success is False
|
||||
assert resp_op_unreg.error is not None
|
||||
assert resp_op_unreg.error.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
assert resp_op_unreg.error.code.http_status == 403
|
||||
|
||||
# Admin on unregistered target -> SUCCESS
|
||||
resp_adm_unreg = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_unregistered,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
assert resp_adm_unreg.success is True
|
||||
assert resp_adm_unreg.result is not None
|
||||
assert resp_adm_unreg.result["action"] == "deployed"
|
||||
|
||||
|
||||
def test_daemon_preflight_and_dotenv_safety(daemon_env):
|
||||
"""
|
||||
Workload with prohibited Compose directive (privileged: true) is blocked by Compose AST
|
||||
pre-flight before any subprocess runs.
|
||||
"""
|
||||
bad_compose = daemon_env.docs_dir / "docker-compose.yml"
|
||||
bad_compose.write_text(
|
||||
"services:\n"
|
||||
" web:\n"
|
||||
" image: nginx\n"
|
||||
" privileged: true\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
|
||||
with patch("appctl_router.run_bounded_subprocess") as mock_subproc:
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_VALIDATION_FAILED
|
||||
assert resp.error.code.http_status == 400
|
||||
assert "privileged: true" in resp.error.message
|
||||
assert mock_subproc.call_count == 0
|
||||
|
||||
|
||||
def test_concurrent_mutation_conflict(daemon_env):
|
||||
"""
|
||||
Second concurrent mutation on the same target returns 409 ERR_CONCURRENT_MUTATION.
|
||||
"""
|
||||
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
|
||||
# Manually hold lock on target
|
||||
lock_ctx = daemon_env.daemon.lock_manager.lock_target("docs")
|
||||
with lock_ctx:
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_CONCURRENT_MUTATION
|
||||
assert resp.error.code.http_status == 409
|
||||
|
||||
|
||||
def test_daemon_multi_threaded_lock_contention_rejects_concurrent_mutation(daemon_env):
|
||||
"""
|
||||
Simultaneous mutating requests for the same target result in one 200 SUCCESS
|
||||
and one 409 ERR_CONCURRENT_MUTATION via multi-threaded lock contention.
|
||||
"""
|
||||
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
first_started = threading.Event()
|
||||
|
||||
def slow_subproc(cmd, *args, **kwargs):
|
||||
first_started.set()
|
||||
time.sleep(0.2)
|
||||
return (0, "Started", "")
|
||||
|
||||
def send_first():
|
||||
return send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
|
||||
def send_second():
|
||||
first_started.wait(timeout=2.0)
|
||||
return send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
|
||||
with (
|
||||
patch("appctl_router.run_bounded_subprocess", side_effect=slow_subproc),
|
||||
patch("appctl_router.OperationalRouter._trigger_homepage_sync"),
|
||||
concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor,
|
||||
):
|
||||
fut1 = executor.submit(send_first)
|
||||
fut2 = executor.submit(send_second)
|
||||
resp1 = fut1.result(timeout=5.0)
|
||||
resp2 = fut2.result(timeout=5.0)
|
||||
|
||||
responses = [resp1, resp2]
|
||||
successes = [r for r in responses if r.success]
|
||||
conflicts = [r for r in responses if not r.success and r.error and r.error.code == ErrorCode.ERR_CONCURRENT_MUTATION]
|
||||
|
||||
assert len(successes) == 1
|
||||
assert len(conflicts) == 1
|
||||
assert successes[0].result is not None
|
||||
assert successes[0].result["action"] == "deployed"
|
||||
assert conflicts[0].error.code.http_status == 409
|
||||
|
||||
|
||||
def test_execution_failure_audit(daemon_env):
|
||||
"""
|
||||
Failing Docker subprocess returns 500 ERR_EXECUTION_FAILED and records phase: FAILED.
|
||||
"""
|
||||
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
|
||||
with patch("appctl_router.run_bounded_subprocess") as mock_subproc:
|
||||
mock_subproc.return_value = (1, "", "Error: docker daemon not reachable")
|
||||
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED
|
||||
assert resp.error.code.http_status == 500
|
||||
|
||||
# Verify audit.jsonl contains FAILED event
|
||||
lines = [json.loads(line) for line in daemon_env.audit_file.read_text().splitlines() if line.strip()]
|
||||
failed_events = [ev for ev in lines if ev.get("phase") == "FAILED"]
|
||||
assert len(failed_events) >= 1
|
||||
assert failed_events[-1]["target"] == "docs"
|
||||
assert failed_events[-1]["result"]["error_code"] == ErrorCode.ERR_EXECUTION_FAILED.value
|
||||
|
||||
|
||||
def test_audit_failure_blocks_mutation(daemon_env):
|
||||
"""
|
||||
Unwritable audit.jsonl aborts mutating command with 500 ERR_EXECUTION_FAILED
|
||||
and zero Docker invocations.
|
||||
"""
|
||||
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
daemon_env.daemon.audit_logger,
|
||||
"emit_event",
|
||||
side_effect=AuditPersistenceError("Simulated disk full or permission error"),
|
||||
),
|
||||
patch("appctl_router.run_bounded_subprocess") as mock_subproc,
|
||||
):
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED
|
||||
assert resp.error.code.http_status == 500
|
||||
assert mock_subproc.call_count == 0
|
||||
|
||||
|
||||
def test_daemon_restart_preserves_state(daemon_env):
|
||||
"""
|
||||
Clean stop and restart of daemon unlinks and rebinds socket cleanly.
|
||||
"""
|
||||
daemon_env.daemon.stop()
|
||||
assert not daemon_env.socket_path.exists()
|
||||
|
||||
# Restart
|
||||
daemon_env.daemon.start()
|
||||
assert daemon_env.socket_path.is_socket()
|
||||
|
||||
# Re-verify communication
|
||||
list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST)
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=list_req,
|
||||
token=ADMIN_SECRET,
|
||||
)
|
||||
assert resp.success is True
|
||||
|
||||
|
||||
def test_gitops_dispatcher_delegates_to_daemon(daemon_env, monkeypatch):
|
||||
"""
|
||||
When daemon socket is active, gitops_dispatcher calls daemon over UDS with Bearer token.
|
||||
"""
|
||||
monkeypatch.setattr(gitops_dispatcher, "DEFAULT_APPCTL_SOCKET_PATH", daemon_env.socket_path)
|
||||
monkeypatch.setenv("GITOPS_APPCTL_TOKEN", OPERATOR_SECRET)
|
||||
monkeypatch.setenv("APPCTL_SOCKET_PATH", str(daemon_env.socket_path))
|
||||
|
||||
def mock_subproc(cmd, *args, **kwargs):
|
||||
if "status" in cmd:
|
||||
return (0, "", "")
|
||||
if "rev-parse" in cmd:
|
||||
return (0, "sha12345", "")
|
||||
return (0, "ok", "")
|
||||
|
||||
with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc) as mock_sub, patch(
|
||||
"appctl_router.OperationalRouter._trigger_homepage_sync"
|
||||
):
|
||||
success = gitops_dispatcher.execute_deployment(
|
||||
target_dir=daemon_env.docs_dir,
|
||||
deployment_config={"branch": "main", "actions": ["git_pull", "compose_up"]},
|
||||
branch="main",
|
||||
)
|
||||
assert success is True
|
||||
assert mock_sub.call_count >= 1
|
||||
|
||||
|
||||
def test_daemon_deployments_file_defaults_to_workloads(
|
||||
tmp_path: Path, run_isolated_script_expr
|
||||
):
|
||||
"""DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml."""
|
||||
resolved_default = run_isolated_script_expr(
|
||||
"import appctl_daemon; print(appctl_daemon.DEPLOYMENTS_FILE)"
|
||||
)
|
||||
assert Path(resolved_default) == tmp_path / "Workloads" / "deployments.yaml"
|
||||
|
||||
|
||||
def test_daemon_deployments_file_honors_workloads_dir_override(
|
||||
tmp_path: Path, run_isolated_script_expr
|
||||
):
|
||||
"""DEPLOYMENTS_FILE honors WORKLOADS_DIR override when HOMELAB_DEPLOYMENTS_FILE is unset."""
|
||||
custom_workloads = tmp_path / "CustomWorkloads"
|
||||
resolved_override = run_isolated_script_expr(
|
||||
"import appctl_daemon; print(appctl_daemon.DEPLOYMENTS_FILE)",
|
||||
extra_env={"WORKLOADS_DIR": str(custom_workloads)},
|
||||
)
|
||||
assert Path(resolved_override) == custom_workloads / "deployments.yaml"
|
||||
|
||||
|
||||
def test_daemon_operator_fails_closed_when_deployments_file_absent(
|
||||
daemon_env, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
"""homelab-operator fails closed (403 ERR_PERMISSION_DENIED) when ~/Workloads/deployments.yaml is absent."""
|
||||
import appctl_auth
|
||||
|
||||
# When HOMELAB_DEPLOYMENTS_FILE is unset and ~/Workloads/deployments.yaml is absent,
|
||||
# homelab-operator must be denied (403) without falling back to CORE_DIR/config/deployments.yaml.
|
||||
monkeypatch.delenv("HOMELAB_DEPLOYMENTS_FILE", raising=False)
|
||||
monkeypatch.delenv("WORKLOADS_DIR", raising=False)
|
||||
monkeypatch.delenv("SITES_DIR", raising=False)
|
||||
monkeypatch.setattr(
|
||||
appctl_auth,
|
||||
"DEFAULT_DEPLOYMENTS_FILE",
|
||||
tmp_path / "empty-home" / "Workloads" / "deployments.yaml",
|
||||
)
|
||||
deploy_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_DEPLOY, target="docs"
|
||||
)
|
||||
resp = send_daemon_request(
|
||||
endpoint=daemon_env.socket_path,
|
||||
operation_request=deploy_req,
|
||||
token=OPERATOR_SECRET,
|
||||
)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
assert resp.error.code.http_status == 403
|
||||
@@ -0,0 +1,609 @@
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import appctl_engine as engine
|
||||
import pytest
|
||||
|
||||
# Import appctl engine
|
||||
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
|
||||
|
||||
@dataclass
|
||||
class AppFactory:
|
||||
"""Helper class to generate mock app directories and configurations"""
|
||||
|
||||
sites_dir: Path
|
||||
|
||||
def create(
|
||||
self,
|
||||
dir_name: str,
|
||||
manifest_yaml: str = "",
|
||||
has_compose: bool = True,
|
||||
) -> Path:
|
||||
app_dir: Path = self.sites_dir / dir_name
|
||||
app_dir.mkdir(parents=True, exist_ok=True)
|
||||
if manifest_yaml:
|
||||
(app_dir / "app.yaml").write_text(manifest_yaml, encoding="utf-8")
|
||||
if has_compose:
|
||||
(app_dir / "docker-compose.yml").write_text(
|
||||
"services: {}\n", encoding="utf-8"
|
||||
)
|
||||
return app_dir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
"""Fixture that creates an isolated Sites directory and points engine.SITES_DIR to it"""
|
||||
sites = tmp_path / "Sites"
|
||||
monkeypatch.setattr(engine, "SITES_DIR", str(sites))
|
||||
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "mydomain.test")
|
||||
return sites
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app_factory(mock_sites_dir: Path) -> AppFactory:
|
||||
"""Fixture that provides the AppFactory instance to test"""
|
||||
return AppFactory(mock_sites_dir)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_core_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
"""Fixture that creates an isolated Core directory and points engine.CORE_DIR to it"""
|
||||
core = tmp_path / "CORE"
|
||||
core.mkdir(parents=True, exist_ok=True)
|
||||
return core
|
||||
|
||||
|
||||
## GREEN TEST: Existing implementation should not break
|
||||
|
||||
|
||||
def test_resolve_app_hierarchy(app_factory: AppFactory):
|
||||
"""Ensure resolution follows: Canonical Name > Alias > Dir Name > Prefix"""
|
||||
app_factory.create(
|
||||
dir_name="homelab-jellyfin",
|
||||
manifest_yaml="""
|
||||
name: media-server
|
||||
aliases:
|
||||
- movies
|
||||
""",
|
||||
)
|
||||
apps = engine.get_sites_apps()
|
||||
|
||||
assert engine.resolve_app("media-server", apps) is not None
|
||||
assert engine.resolve_app("movies", apps) is not None
|
||||
assert engine.resolve_app("homelab-jellyfin", apps) is not None
|
||||
assert engine.resolve_app("unknown", apps) is None
|
||||
|
||||
|
||||
def test_manifest_data_overrides_default_values(app_factory: AppFactory):
|
||||
"""Ensure app.yaml values successfully override the system defaults"""
|
||||
app_factory.create(
|
||||
dir_name="homelab-custom",
|
||||
manifest_yaml="""
|
||||
name: custom-app
|
||||
domain: custom.example.test
|
||||
auth: false
|
||||
visible: false
|
||||
networks:
|
||||
- custom-net
|
||||
""",
|
||||
)
|
||||
|
||||
apps = engine.get_sites_apps()
|
||||
app = engine.resolve_app("custom-app", apps)
|
||||
|
||||
assert app is not None
|
||||
assert app.domain == "custom.example.test"
|
||||
assert app.auth is False
|
||||
assert app.networks == ["custom-net"]
|
||||
|
||||
|
||||
def test_sites_app_normalization(app_factory: AppFactory):
|
||||
"""Ensure missing or badly typed manifest fields are safely normalized"""
|
||||
app_factory.create(
|
||||
dir_name="homelab-custom",
|
||||
manifest_yaml="""
|
||||
name: testapp
|
||||
# Missing domain - should fallback to <name>.<HOMELAB_DOMAIN>
|
||||
aliases: single-string-alias # should become a list[str]
|
||||
auth: "False" # should evaluate based on boolean casting
|
||||
homepage:
|
||||
weight: "99" # this should be casted as an int
|
||||
""",
|
||||
)
|
||||
apps = engine.get_sites_apps()
|
||||
app = engine.resolve_app("testapp", apps)
|
||||
|
||||
assert app is not None
|
||||
assert app.name == "testapp"
|
||||
assert app.domain == "testapp.mydomain.test"
|
||||
assert app.aliases == ["single-string-alias"]
|
||||
assert app.auth is True
|
||||
assert app.homepage is not None
|
||||
assert app.homepage.weight == 99
|
||||
|
||||
|
||||
def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
||||
"""Ensure source provenance block is correctly parsed into SourceConfig"""
|
||||
# 1. Source-backed app with explicit ref
|
||||
app_factory.create(
|
||||
dir_name="homelab-bitetrack",
|
||||
manifest_yaml="""
|
||||
name: bitetrack
|
||||
source:
|
||||
type: git
|
||||
url: https://git.example.com/operator/bitetrack.git
|
||||
ref: v1.2.0
|
||||
""",
|
||||
)
|
||||
# 2. Source-backed app with default ref (main)
|
||||
app_factory.create(
|
||||
dir_name="homelab-doc2site",
|
||||
manifest_yaml="""
|
||||
name: doc2site
|
||||
source:
|
||||
url: https://git.example.com/operator/doc2site.git
|
||||
""",
|
||||
)
|
||||
# 3. Image-only app (no source block)
|
||||
app_factory.create(
|
||||
dir_name="homelab-jellyfin",
|
||||
manifest_yaml="""
|
||||
name: jellyfin
|
||||
""",
|
||||
)
|
||||
|
||||
apps = engine.get_sites_apps()
|
||||
|
||||
bitetrack = engine.resolve_app("bitetrack", apps)
|
||||
assert bitetrack is not None
|
||||
assert bitetrack.source is not None
|
||||
assert bitetrack.source.type == "git"
|
||||
assert bitetrack.source.url == "https://git.example.com/operator/bitetrack.git"
|
||||
assert bitetrack.source.ref == "v1.2.0"
|
||||
assert bitetrack.to_dict()["source"]["ref"] == "v1.2.0"
|
||||
|
||||
doc2site = engine.resolve_app("doc2site", apps)
|
||||
assert doc2site is not None
|
||||
assert doc2site.source is not None
|
||||
assert doc2site.source.ref == "main"
|
||||
|
||||
jellyfin = engine.resolve_app("jellyfin", apps)
|
||||
assert jellyfin is not None
|
||||
assert jellyfin.source is None
|
||||
assert jellyfin.to_dict()["source"] is None
|
||||
|
||||
# 4. App with illegal source transport (e.g. file://)
|
||||
app_factory.create(
|
||||
dir_name="homelab-malformed",
|
||||
manifest_yaml="""
|
||||
name: malformed
|
||||
source:
|
||||
url: file:///etc/passwd
|
||||
""",
|
||||
)
|
||||
apps_updated = engine.get_sites_apps()
|
||||
malformed = engine.resolve_app("malformed", apps_updated)
|
||||
assert malformed is not None
|
||||
assert malformed.source is None
|
||||
assert malformed.manifest_error is not None
|
||||
assert "Invalid source.url scheme" in malformed.manifest_error
|
||||
|
||||
|
||||
## RED TESTS: TDD Goals for next implementation
|
||||
|
||||
|
||||
def test_docker_status_parser_running(monkeypatch):
|
||||
"""Ensure get_docker_status reports running compose stack when all containers are running."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
mock.returncode = 0
|
||||
if "ps" in args:
|
||||
mock.stdout = "container123\n"
|
||||
if "inspect" in args:
|
||||
mock.stdout = "true\n"
|
||||
return mock
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
|
||||
status = engine.get_docker_status("/fake/dir")
|
||||
assert status == "🟢 Running (1)"
|
||||
|
||||
|
||||
def test_docker_status_parser_stopped(monkeypatch):
|
||||
"""Ensure get_docker_status reports stopped when no containers exist."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
mock.returncode = 0
|
||||
if "ps" in args:
|
||||
mock.stdout = ""
|
||||
return mock
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
|
||||
status = engine.get_docker_status("/fake/dir")
|
||||
assert status == "🔴 Stopped"
|
||||
|
||||
|
||||
def test_docker_status_parser_degraded(monkeypatch):
|
||||
"""Ensure get_docker_status reports degraded when partial containers are running."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
mock.returncode = 0
|
||||
if "ps" in args:
|
||||
mock.stdout = "c1\nc2\n"
|
||||
if "inspect" in args:
|
||||
mock.stdout = "true\nfalse\n"
|
||||
return mock
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
|
||||
status = engine.get_docker_status("/fake/dir")
|
||||
assert status == "🟡 Degraded (1/2)"
|
||||
|
||||
|
||||
def test_docker_status_parser_not_stack(tmp_path: Path):
|
||||
"""Ensure get_docker_status reports Not Stack for real directory without compose file."""
|
||||
empty_dir = tmp_path / "empty_service"
|
||||
empty_dir.mkdir()
|
||||
assert engine.get_docker_status(empty_dir) == "⚪ Not Stack"
|
||||
|
||||
|
||||
def test_docker_status_single_container(monkeypatch):
|
||||
"""Ensure get_docker_status inspects single Core container by name."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
mock.returncode = 0
|
||||
if "authelia" in args:
|
||||
mock.stdout = "true\n"
|
||||
else:
|
||||
mock.stdout = "false\n"
|
||||
return mock
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
|
||||
assert engine.get_docker_status("", container_name="authelia") == "🟢 Running (1)"
|
||||
assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped"
|
||||
|
||||
|
||||
def test_docker_status_compose_ps_daemon_error(monkeypatch):
|
||||
"""Ensure get_docker_status returns '❓ Unknown' when docker compose ps fails (e.g. daemon unreachable)."""
|
||||
import subprocess
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
return subprocess.CompletedProcess(
|
||||
args=args,
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
|
||||
)
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_status("/fake/dir") == "❓ Unknown"
|
||||
|
||||
|
||||
def test_docker_status_compose_inspect_error(monkeypatch):
|
||||
"""Ensure get_docker_status returns '❓ Unknown' when docker inspect fails for compose containers."""
|
||||
import subprocess
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
if "ps" in args:
|
||||
return subprocess.CompletedProcess(args=args, returncode=0, stdout="c1\n", stderr="")
|
||||
return subprocess.CompletedProcess(
|
||||
args=args,
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
|
||||
)
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_status("/fake/dir") == "❓ Unknown"
|
||||
|
||||
|
||||
def test_docker_status_single_container_daemon_error(monkeypatch):
|
||||
"""Ensure get_docker_status returns '❓ Unknown' when inspecting single container fails due to daemon error."""
|
||||
import subprocess
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
return subprocess.CompletedProcess(
|
||||
args=args,
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
|
||||
)
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_status("", container_name="traefik") == "❓ Unknown"
|
||||
|
||||
|
||||
def test_docker_status_single_container_no_such_object(monkeypatch):
|
||||
"""Ensure get_docker_status returns '🔴 Stopped' when container does not exist."""
|
||||
import subprocess
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
return subprocess.CompletedProcess(
|
||||
args=args,
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="Error: No such object: traefik",
|
||||
)
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped"
|
||||
|
||||
|
||||
def test_docker_status_error_handling(monkeypatch):
|
||||
"""Ensure get_docker_status handles subprocess failures gracefully."""
|
||||
|
||||
def mock_err(*args, **kwargs):
|
||||
raise OSError("Docker socket unreachable")
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_err)
|
||||
assert engine.get_docker_status("/fake/dir") == "❓ Unknown"
|
||||
|
||||
|
||||
def test_docker_image_revision_extraction(monkeypatch):
|
||||
"""Ensure get_docker_image_revision extracts org.opencontainers.image.revision."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
if "ps" in args:
|
||||
mock.stdout = "container123\n"
|
||||
if "inspect" in args:
|
||||
mock.stdout = "9d82577f489f0d478e465a36077538d0ded16ba5\n"
|
||||
return mock
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert (
|
||||
engine.get_docker_image_revision("/fake/dir")
|
||||
== "9d82577f489f0d478e465a36077538d0ded16ba5"
|
||||
)
|
||||
|
||||
def mock_run_empty(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
if "ps" in args:
|
||||
mock.stdout = "container123\n"
|
||||
if "inspect" in args:
|
||||
mock.stdout = "<no value>\n"
|
||||
return mock
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run_empty)
|
||||
assert engine.get_docker_image_revision("/fake/dir") is None
|
||||
|
||||
|
||||
def test_homepage_sync_groups_and_sorts_correctly(
|
||||
mock_core_dir: Path, app_factory: AppFactory, monkeypatch
|
||||
):
|
||||
"""
|
||||
TDD Goal: Port `cmd_sync_homepage` to V2 using the new Dataclass structure.
|
||||
It must group by `homepage.group` and sort by `homepage.weight`.
|
||||
"""
|
||||
hp_config_dir = mock_core_dir / "config" / "homepage"
|
||||
hp_config_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
app_factory.create(
|
||||
dir_name="homelab-app1",
|
||||
manifest_yaml="""
|
||||
name: App1
|
||||
domain: app1.local.test
|
||||
homepage:
|
||||
title: App1
|
||||
group: Group B
|
||||
weight: 20
|
||||
""",
|
||||
)
|
||||
|
||||
app_factory.create(
|
||||
dir_name="homelab-app2",
|
||||
manifest_yaml="""
|
||||
name: App2
|
||||
domain: app2.local.test
|
||||
homepage:
|
||||
title: App2
|
||||
group: Group A
|
||||
weight: 10
|
||||
""",
|
||||
)
|
||||
|
||||
monkeypatch.setattr(engine, "get_core_services", list)
|
||||
engine.cmd_sync_homepage(["--homepage-dir=" + str(hp_config_dir)])
|
||||
|
||||
output_file = hp_config_dir / "services.yaml"
|
||||
assert output_file.exists(), "The services.yaml file must be generated"
|
||||
|
||||
content = output_file.read_text()
|
||||
assert content.find("- Group A") < content.find(
|
||||
"- Group B"
|
||||
) # Group A should appear before Group B
|
||||
assert "App2" in content # App 2 is in the file
|
||||
|
||||
|
||||
def test_homepage_sync_core_services_domain_isolation(
|
||||
mock_core_dir: Path,
|
||||
monkeypatch,
|
||||
):
|
||||
"""
|
||||
Ensure Core Infrastructure services use HOMELAB_DOMAIN and do not leak
|
||||
an application's domain if DOMAIN is overridden by appctl.
|
||||
"""
|
||||
hp_config_dir = mock_core_dir / "config" / "homepage"
|
||||
hp_config_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "example.com")
|
||||
monkeypatch.setenv("DOMAIN", "mermaid.example.com")
|
||||
|
||||
engine.cmd_sync_homepage(["--homepage-dir=" + str(hp_config_dir)])
|
||||
|
||||
output_file = hp_config_dir / "services.yaml"
|
||||
assert output_file.exists()
|
||||
content = output_file.read_text()
|
||||
|
||||
assert "https://dashboard.example.com" in content
|
||||
assert "https://traefik.example.com" in content
|
||||
assert "https://auth.example.com" in content
|
||||
assert "mermaid.example.com" not in content
|
||||
|
||||
|
||||
def test_resolve_core_stack_type():
|
||||
"""
|
||||
Ensure resolving 'core' returns app_type='core' (entire stack),
|
||||
while individual core services return app_type='core_service'.
|
||||
"""
|
||||
core = engine.resolve_app("core")
|
||||
assert core is not None
|
||||
assert core.to_dict()["type"] == "core"
|
||||
assert core.container == ""
|
||||
|
||||
traefik = engine.resolve_app("traefik")
|
||||
assert traefik is not None
|
||||
assert traefik.to_dict()["type"] == "core_service"
|
||||
assert traefik.container == "traefik"
|
||||
|
||||
|
||||
def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(
|
||||
app_factory: AppFactory,
|
||||
):
|
||||
"""Ensure manifest parsing uses core_manifest and catches invalid env keys."""
|
||||
app_factory.create(
|
||||
dir_name="homelab-badenv",
|
||||
manifest_yaml="""
|
||||
name: badenv
|
||||
env:
|
||||
PATH: /override/bin
|
||||
""",
|
||||
)
|
||||
apps = engine.get_sites_apps()
|
||||
app = engine.resolve_app("badenv", apps)
|
||||
assert app is not None
|
||||
assert app.manifest_error is not None
|
||||
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
|
||||
):
|
||||
"""Ensure cmd_resolve exits with non-zero on workload with manifest errors."""
|
||||
app_factory.create(
|
||||
dir_name="homelab-corrupt",
|
||||
manifest_yaml="""
|
||||
name: corrupt
|
||||
env:
|
||||
ILLEGAL-KEY: forbidden
|
||||
""",
|
||||
)
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
engine.cmd_resolve(["corrupt"])
|
||||
assert exc_info.value.code != 0
|
||||
captured = capsys.readouterr()
|
||||
assert "invalid manifest" in captured.err.lower() or "error" in captured.err.lower()
|
||||
|
||||
|
||||
def test_cmd_resolve_fails_closed_on_missing_app_yaml(mock_sites_dir: Path):
|
||||
"""Ensure cmd_resolve exits with non-zero if workload has no app.yaml."""
|
||||
no_manifest_dir = mock_sites_dir / "homelab-nomanifest"
|
||||
no_manifest_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
engine.cmd_resolve(["nomanifest"])
|
||||
assert exc_info.value.code != 0
|
||||
|
||||
|
||||
def test_unification_uses_core_manifest_dataclasses(app_factory: AppFactory):
|
||||
"""Ensure SitesApp uses core_manifest SourceConfig and HomepageConfig."""
|
||||
import core_manifest
|
||||
|
||||
app_factory.create(
|
||||
dir_name="homelab-unified",
|
||||
manifest_yaml="""
|
||||
name: unified
|
||||
source:
|
||||
url: https://git.example.com/operator/unified.git
|
||||
ref: v1.0.0
|
||||
homepage:
|
||||
title: Unified App
|
||||
weight: 30
|
||||
""",
|
||||
)
|
||||
apps = engine.get_sites_apps()
|
||||
app = engine.resolve_app("unified", apps)
|
||||
assert app is not None
|
||||
assert isinstance(app.source, core_manifest.SourceConfig)
|
||||
assert isinstance(app.homepage, core_manifest.HomepageConfig)
|
||||
assert app.source.ref_type == core_manifest.RefType.TAG
|
||||
assert app.source.transport == core_manifest.TransportScheme.HTTPS
|
||||
|
||||
|
||||
def test_cmd_list_flags_manifest_error(
|
||||
app_factory: AppFactory, capsys: pytest.CaptureFixture
|
||||
):
|
||||
"""Ensure cmd_list flags workloads with manifest errors instead of swallowing them."""
|
||||
app_factory.create(
|
||||
dir_name="homelab-broken",
|
||||
manifest_yaml="""
|
||||
name: broken
|
||||
env:
|
||||
SHELL: /bin/sh
|
||||
""",
|
||||
)
|
||||
engine.cmd_list([])
|
||||
captured = capsys.readouterr()
|
||||
assert "Manifest Error" in captured.out
|
||||
|
||||
|
||||
def test_workloads_dir_env_precedence_and_fallback(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
"""Ensure WORKLOADS_DIR > SITES_DIR > ~/Workloads fallback across core modules (#33)."""
|
||||
import importlib
|
||||
|
||||
import appctl_daemon
|
||||
import gitops_dispatcher
|
||||
|
||||
workloads_override = tmp_path / "custom-workloads"
|
||||
sites_override = tmp_path / "legacy-sites"
|
||||
fake_home = tmp_path / "home"
|
||||
fake_core = tmp_path / "repo" / "core"
|
||||
fake_core.mkdir(parents=True)
|
||||
|
||||
try:
|
||||
# 1. WORKLOADS_DIR takes precedence over SITES_DIR
|
||||
monkeypatch.setenv("CORE_DIR", str(fake_core))
|
||||
monkeypatch.setenv("WORKLOADS_DIR", str(workloads_override))
|
||||
monkeypatch.setenv("SITES_DIR", str(sites_override))
|
||||
importlib.reload(engine)
|
||||
importlib.reload(appctl_daemon)
|
||||
importlib.reload(gitops_dispatcher)
|
||||
assert engine.SITES_DIR == str(workloads_override)
|
||||
assert appctl_daemon.SITES_DIR == workloads_override
|
||||
assert gitops_dispatcher.SITES_DIR == workloads_override
|
||||
|
||||
# 2. SITES_DIR acts as fallback when WORKLOADS_DIR is unset
|
||||
monkeypatch.delenv("WORKLOADS_DIR", raising=False)
|
||||
importlib.reload(engine)
|
||||
importlib.reload(appctl_daemon)
|
||||
importlib.reload(gitops_dispatcher)
|
||||
assert engine.SITES_DIR == str(sites_override)
|
||||
assert appctl_daemon.SITES_DIR == sites_override
|
||||
assert gitops_dispatcher.SITES_DIR == sites_override
|
||||
|
||||
# 3. Default resolves to ~/Workloads when neither env var is set
|
||||
monkeypatch.delenv("SITES_DIR", raising=False)
|
||||
monkeypatch.setenv("HOME", str(fake_home))
|
||||
importlib.reload(engine)
|
||||
importlib.reload(appctl_daemon)
|
||||
importlib.reload(gitops_dispatcher)
|
||||
expected_default = fake_home / "Workloads"
|
||||
assert engine.SITES_DIR == str(expected_default)
|
||||
assert appctl_daemon.SITES_DIR == expected_default
|
||||
assert gitops_dispatcher.SITES_DIR == expected_default
|
||||
finally:
|
||||
monkeypatch.undo()
|
||||
importlib.reload(engine)
|
||||
importlib.reload(appctl_daemon)
|
||||
importlib.reload(gitops_dispatcher)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,176 @@
|
||||
"""
|
||||
tests/unit/test_bootstrap_token.py — Unit Tests for Operator Admin Token Bootstrap Helper (WP4)
|
||||
|
||||
Verifies:
|
||||
- 256-bit secure token generation (64 hex characters) and matching SHA-256 digest
|
||||
- Strict 0600 file mode and 0700 parent directory creation
|
||||
- TokenDescriptor Pydantic validation (scripts/appctl_auth.py)
|
||||
- Refusal to overwrite existing token file without --force
|
||||
- Overwriting existing token file when --force is supplied
|
||||
- Secrets leakage prevention: raw Bearer token never appears in stdout/stderr
|
||||
- Machine-readable JSON output via --print-json
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import stat
|
||||
import string
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from appctl_auth import Role, TokenDescriptor
|
||||
from bootstrap_token import (
|
||||
bootstrap_token,
|
||||
generate_token,
|
||||
main,
|
||||
write_token_file,
|
||||
)
|
||||
|
||||
|
||||
def test_generate_token_produces_64_hex_token_and_valid_sha256() -> None:
|
||||
raw_token, digest = generate_token()
|
||||
assert len(raw_token) == 64
|
||||
assert all(c in string.hexdigits for c in raw_token)
|
||||
assert len(digest) == 64
|
||||
assert all(c in string.hexdigits for c in digest)
|
||||
expected_digest = hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
|
||||
assert digest == expected_digest
|
||||
|
||||
|
||||
def test_write_token_file_creates_file_and_enforces_0600(tmp_path: Path) -> None:
|
||||
token_file = tmp_path / "subdir" / "token"
|
||||
write_token_file(token_file, "secret-token-12345")
|
||||
assert token_file.is_file()
|
||||
assert stat.S_IMODE(token_file.stat().st_mode) == 0o600
|
||||
assert stat.S_IMODE(token_file.parent.stat().st_mode) == 0o700
|
||||
assert token_file.read_text(encoding="utf-8") == "secret-token-12345\n"
|
||||
|
||||
|
||||
def test_bootstrap_token_generates_file_with_strict_mode_0600(tmp_path: Path) -> None:
|
||||
nested_dir = tmp_path / "nested" / "homelab"
|
||||
token_file = nested_dir / "token"
|
||||
|
||||
descriptor = bootstrap_token(output_path=token_file)
|
||||
|
||||
assert token_file.is_file()
|
||||
# Check parent directory mode is 0700
|
||||
parent_mode = stat.S_IMODE(nested_dir.stat().st_mode)
|
||||
assert parent_mode == 0o700, f"Expected parent mode 0700, got {oct(parent_mode)}"
|
||||
|
||||
# Check token file mode is 0600
|
||||
file_mode = stat.S_IMODE(token_file.stat().st_mode)
|
||||
assert file_mode == 0o600, f"Expected file mode 0600, got {oct(file_mode)}"
|
||||
|
||||
raw_token = token_file.read_text(encoding="utf-8").strip()
|
||||
assert len(raw_token) == 64
|
||||
assert hashlib.sha256(raw_token.encode("utf-8")).hexdigest() == descriptor["sha256"]
|
||||
|
||||
|
||||
def test_bootstrap_token_descriptor_validates_against_token_descriptor(tmp_path: Path) -> None:
|
||||
token_file = tmp_path / "custom_token"
|
||||
descriptor = bootstrap_token(
|
||||
output_path=token_file,
|
||||
token_id="custom-admin",
|
||||
identity="operator",
|
||||
role="homelab-admin",
|
||||
)
|
||||
|
||||
validated = TokenDescriptor.model_validate(descriptor)
|
||||
assert validated.token_id == "custom-admin"
|
||||
assert validated.identity == "operator"
|
||||
assert validated.role == Role.ADMIN
|
||||
assert len(validated.sha256) == 64
|
||||
|
||||
|
||||
def test_bootstrap_token_refuses_overwrite_without_force(tmp_path: Path) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
bootstrap_token(output_path=token_file)
|
||||
original_token = token_file.read_text(encoding="utf-8")
|
||||
|
||||
with pytest.raises(FileExistsError, match="already exists"):
|
||||
bootstrap_token(output_path=token_file, force=False)
|
||||
|
||||
assert token_file.read_text(encoding="utf-8") == original_token
|
||||
|
||||
|
||||
def test_bootstrap_token_overwrites_with_force(tmp_path: Path) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
descriptor1 = bootstrap_token(output_path=token_file)
|
||||
first_token = token_file.read_text(encoding="utf-8").strip()
|
||||
|
||||
descriptor2 = bootstrap_token(output_path=token_file, force=True)
|
||||
second_token = token_file.read_text(encoding="utf-8").strip()
|
||||
|
||||
assert first_token != second_token
|
||||
assert descriptor1["sha256"] != descriptor2["sha256"]
|
||||
assert descriptor2["sha256"] == hashlib.sha256(second_token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def test_bootstrap_cli_never_prints_raw_secret_to_stdout_or_stderr(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
ret = main(["--output", str(token_file)])
|
||||
assert ret == 0
|
||||
|
||||
raw_token = token_file.read_text(encoding="utf-8").strip()
|
||||
captured = capsys.readouterr()
|
||||
|
||||
# RAW SECRET MUST NEVER APPEAR IN STDOUT OR STDERR
|
||||
assert raw_token not in captured.out, "Leak: raw token found in stdout!"
|
||||
assert raw_token not in captured.err, "Leak: raw token found in stderr!"
|
||||
|
||||
# Ensure stdout provides helpful human guidance
|
||||
assert "operator-admin" in captured.out
|
||||
assert "sops nixos/secrets.yaml" in captured.out
|
||||
assert "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure" in captured.out
|
||||
|
||||
|
||||
def test_bootstrap_cli_print_json_outputs_valid_json_descriptor(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
ret = main(["--output", str(token_file), "--print-json"])
|
||||
assert ret == 0
|
||||
|
||||
raw_token = token_file.read_text(encoding="utf-8").strip()
|
||||
captured = capsys.readouterr()
|
||||
|
||||
assert raw_token not in captured.out
|
||||
assert captured.err == ""
|
||||
|
||||
# Must be cleanly parseable as pure JSON
|
||||
data: dict[str, Any] = json.loads(captured.out.strip())
|
||||
validated = TokenDescriptor.model_validate(data)
|
||||
assert validated.token_id == "operator-admin"
|
||||
assert validated.identity == "operator"
|
||||
assert validated.role == Role.ADMIN
|
||||
assert validated.sha256 == hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def test_bootstrap_cli_refuses_overwrite_and_exits_nonzero(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
assert main(["--output", str(token_file)]) == 0
|
||||
|
||||
ret = main(["--output", str(token_file)])
|
||||
assert ret != 0
|
||||
captured = capsys.readouterr()
|
||||
assert "already exists" in captured.err
|
||||
|
||||
|
||||
def test_bootstrap_cli_force_overwrites(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
assert main(["--output", str(token_file)]) == 0
|
||||
tok1 = token_file.read_text(encoding="utf-8").strip()
|
||||
|
||||
assert main(["--output", str(token_file), "--force"]) == 0
|
||||
tok2 = token_file.read_text(encoding="utf-8").strip()
|
||||
|
||||
assert tok1 != tok2
|
||||
@@ -0,0 +1,369 @@
|
||||
"""
|
||||
Unit test suite for scripts/core_manifest.py (Schema v1.0 & Parser Library).
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
# # Add scripts directory to path
|
||||
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
from core_manifest import (
|
||||
Manifest,
|
||||
ManifestValidationError,
|
||||
RefType,
|
||||
TransportScheme,
|
||||
classify_ref,
|
||||
parse_manifest,
|
||||
validate_transport,
|
||||
)
|
||||
|
||||
|
||||
def test_validate_transport_https():
|
||||
|
||||
scheme, url = validate_transport(
|
||||
"https://git.example.com/operator/homelab-snappymail.git"
|
||||
)
|
||||
assert scheme == TransportScheme.HTTPS
|
||||
assert url == "https://git.example.com/operator/homelab-snappymail.git"
|
||||
|
||||
|
||||
def test_validate_transport_ssh():
|
||||
scheme, url = validate_transport(
|
||||
"ssh://git@git.example.com:2223/operator/homelab-docs.git"
|
||||
)
|
||||
assert scheme == TransportScheme.SSH
|
||||
assert url == "ssh://git@git.example.com:2223/operator/homelab-docs.git"
|
||||
|
||||
|
||||
def test_validate_transport_git_scp():
|
||||
scheme, url = validate_transport("git@github.com:operator/custom-workload.git")
|
||||
assert scheme == TransportScheme.GIT_SCP
|
||||
assert url == "git@github.com:operator/custom-workload.git"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"insecure_url",
|
||||
[
|
||||
"http://insecure.example.com/repo.git",
|
||||
"http://github.com/repo.git",
|
||||
],
|
||||
)
|
||||
def test_validate_transport_rejects_http(insecure_url: str):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="Insecure HTTP source URL rejected"
|
||||
):
|
||||
validate_transport(insecure_url)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"empty_or_invalid_url",
|
||||
[
|
||||
"",
|
||||
" ",
|
||||
None,
|
||||
],
|
||||
)
|
||||
def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match=r"^Source URL cannot be empty\.$"
|
||||
):
|
||||
validate_transport(empty_or_invalid_url) # type: ignore[arg-type]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("root_path_url", "scheme"),
|
||||
[
|
||||
("https://git.example.com/", "HTTPS"),
|
||||
("ssh://git.example.com/", "SSH"),
|
||||
],
|
||||
)
|
||||
def test_validate_transport_rejects_root_repository_path(
|
||||
root_path_url: str, scheme: str
|
||||
):
|
||||
with pytest.raises(
|
||||
ManifestValidationError,
|
||||
match=rf"^Malformed {scheme} source URL \(missing repository path\)",
|
||||
):
|
||||
validate_transport(root_path_url)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"traversal_url",
|
||||
[
|
||||
"../../etc/shadow",
|
||||
"/home/operator/secret",
|
||||
"~/vault",
|
||||
r"repo\windows\payload",
|
||||
r"..\traversal",
|
||||
],
|
||||
)
|
||||
def test_validate_transport_rejects_paths_and_traversal(traversal_url: str):
|
||||
with pytest.raises(
|
||||
ManifestValidationError,
|
||||
match="Prohibited filesystem path or traversal in source URL",
|
||||
):
|
||||
validate_transport(traversal_url)
|
||||
|
||||
|
||||
def test_validate_transport_rejects_file_scheme():
|
||||
with pytest.raises(
|
||||
ManifestValidationError,
|
||||
match="Invalid source.url scheme: 'file:///etc/passwd'",
|
||||
):
|
||||
validate_transport("file:///etc/passwd")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"empty_ref",
|
||||
[
|
||||
"",
|
||||
" ",
|
||||
None,
|
||||
12345,
|
||||
],
|
||||
)
|
||||
def test_classify_ref_empty_or_invalid_defaults_to_main(empty_ref):
|
||||
assert classify_ref(empty_ref) == (RefType.BRANCH, "main") # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_classify_ref_branches():
|
||||
assert classify_ref("main") == (RefType.BRANCH, "main")
|
||||
assert classify_ref("refs/heads/develop") == (RefType.BRANCH, "develop")
|
||||
assert classify_ref("feat/manifest-engine") == (
|
||||
RefType.BRANCH,
|
||||
"feat/manifest-engine",
|
||||
)
|
||||
assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0")
|
||||
assert classify_ref("custom-adhoc-branch") == (
|
||||
RefType.BRANCH,
|
||||
"custom-adhoc-branch",
|
||||
)
|
||||
|
||||
|
||||
def test_classify_ref_tags():
|
||||
assert classify_ref("v1.0.0") == (RefType.TAG, "v1.0.0")
|
||||
assert classify_ref("refs/tags/2.4.1") == (RefType.TAG, "2.4.1")
|
||||
assert classify_ref("v0.1.0-alpha") == (RefType.TAG, "v0.1.0-alpha")
|
||||
|
||||
|
||||
def test_classify_ref_commit_sha():
|
||||
sha = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
|
||||
assert classify_ref(sha) == (RefType.COMMIT, sha)
|
||||
|
||||
|
||||
def test_parse_manifest_class_a_source_backed():
|
||||
raw_yaml = """
|
||||
schemaVersion: "1.0"
|
||||
name: "bitetrack"
|
||||
aliases:
|
||||
- "bt"
|
||||
domain: "bitetrack.example.com"
|
||||
description: "Nutrition and macro tracking application"
|
||||
visible: true
|
||||
auth: true
|
||||
networks:
|
||||
- proxy-net
|
||||
env:
|
||||
PORT: 8080
|
||||
source:
|
||||
type: git
|
||||
url: "https://git.example.com/operator/bitetrack.git"
|
||||
ref: "v1.2.0"
|
||||
deployment:
|
||||
strategy: compose
|
||||
branch: main
|
||||
actions:
|
||||
- git_pull
|
||||
- compose_build
|
||||
- compose_up
|
||||
homepage:
|
||||
title: "BiteTrack"
|
||||
group: "Productivity"
|
||||
icon: "food.png"
|
||||
weight: 25
|
||||
"""
|
||||
manifest = parse_manifest(raw_yaml)
|
||||
assert manifest.name == "bitetrack"
|
||||
assert manifest.schema_version == "1.0"
|
||||
assert manifest.aliases == ["bt"]
|
||||
assert manifest.is_class_a is True
|
||||
assert manifest.is_class_b is False
|
||||
assert manifest.is_internal is False
|
||||
assert manifest.source is not None
|
||||
assert manifest.source.url == "https://git.example.com/operator/bitetrack.git"
|
||||
assert manifest.source.ref == "v1.2.0"
|
||||
assert manifest.source.ref_type == RefType.TAG
|
||||
assert manifest.source.transport == TransportScheme.HTTPS
|
||||
assert manifest.deployment.actions == ["git_pull", "compose_build", "compose_up"]
|
||||
assert manifest.homepage is not None
|
||||
assert manifest.homepage.weight == 25
|
||||
|
||||
|
||||
def test_parse_manifest_class_b_image_only():
|
||||
raw_yaml = """
|
||||
name: "snappymail"
|
||||
domain: "mail.example.com"
|
||||
description: "Webmail Client"
|
||||
deployment:
|
||||
actions:
|
||||
- compose_up
|
||||
"""
|
||||
manifest = parse_manifest(raw_yaml)
|
||||
assert manifest.name == "snappymail"
|
||||
assert manifest.is_class_a is False
|
||||
assert manifest.is_class_b is True
|
||||
assert manifest.source is None
|
||||
assert manifest.deployment.actions == ["compose_up"]
|
||||
|
||||
|
||||
def test_parse_manifest_rejects_missing_name():
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="missing mandatory string field 'name'"
|
||||
):
|
||||
parse_manifest("domain: test.example.com\n")
|
||||
|
||||
|
||||
def test_parse_manifest_rejects_invalid_name():
|
||||
with pytest.raises(ManifestValidationError, match="Invalid workload name"):
|
||||
parse_manifest("name: 'invalid/name'\n")
|
||||
|
||||
|
||||
def test_parse_manifest_rejects_prohibited_deployment_actions():
|
||||
raw_yaml = """
|
||||
name: "app"
|
||||
deployment:
|
||||
actions:
|
||||
- compose_up
|
||||
- rm_rf_root
|
||||
"""
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="Prohibited deployment action 'rm_rf_root'"
|
||||
):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
|
||||
def test_parse_manifest_rejects_prohibited_strategy():
|
||||
raw_yaml = """
|
||||
name: "app"
|
||||
deployment:
|
||||
strategy: "swarm"
|
||||
"""
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="Unsupported deployment strategy 'swarm'"
|
||||
):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
|
||||
def test_parse_manifest_from_path(tmp_path: Path):
|
||||
manifest_file = tmp_path / "app.yaml"
|
||||
manifest_file.write_text("name: file-app\ndomain: internal\n", encoding="utf-8")
|
||||
|
||||
manifest = parse_manifest(manifest_file)
|
||||
assert manifest.name == "file-app"
|
||||
assert manifest.is_internal is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"invalid_key",
|
||||
[
|
||||
"123_BAD",
|
||||
"INVALID-KEY",
|
||||
"FOO;BAR",
|
||||
"KEY WITH SPACE",
|
||||
"PATH",
|
||||
"LD_PRELOAD",
|
||||
"IFS",
|
||||
"CORE_DIR",
|
||||
"SITES_DIR",
|
||||
"HOMELAB_DOMAIN",
|
||||
"DOMAIN_SUFFIX",
|
||||
"DOMAIN",
|
||||
"PROXY_NETWORK",
|
||||
"CERT_RESOLVER",
|
||||
"DOCKER_CONFIG",
|
||||
"SERVICE_NAME",
|
||||
"CONTAINER_NAME",
|
||||
"SERVICE_DOMAIN",
|
||||
],
|
||||
)
|
||||
def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str):
|
||||
raw_yaml = f"""
|
||||
name: "app"
|
||||
env:
|
||||
"{invalid_key}": "some_value"
|
||||
"""
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="Invalid or reserved environment variable key"
|
||||
):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
|
||||
def test_parse_manifest_accepts_valid_env_keys():
|
||||
raw_yaml = """
|
||||
name: "app"
|
||||
env:
|
||||
PROJECT_PATH: "/mnt/data"
|
||||
CUSTOM_PORT_1: "8080"
|
||||
_INTERNAL_FLAG: "true"
|
||||
"""
|
||||
manifest = parse_manifest(raw_yaml)
|
||||
assert manifest.env["PROJECT_PATH"] == "/mnt/data"
|
||||
assert manifest.env["CUSTOM_PORT_1"] == "8080"
|
||||
assert manifest.env["_INTERNAL_FLAG"] == "true"
|
||||
|
||||
|
||||
def test_parse_manifest_rejects_extra_fields():
|
||||
"""Ensure extra='forbid' rejects unrecognized top-level manifest keys."""
|
||||
raw_yaml = """
|
||||
name: "app"
|
||||
unrecognized_field: "should_fail"
|
||||
"""
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="unrecognized or forbidden field"
|
||||
):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
|
||||
def test_parse_manifest_rejects_extra_fields_in_nested_blocks():
|
||||
"""Ensure extra='forbid' rejects unrecognized keys in nested configuration blocks."""
|
||||
raw_yaml = """
|
||||
name: "app"
|
||||
deployment:
|
||||
strategy: compose
|
||||
unknown_deploy_option: "forbidden"
|
||||
"""
|
||||
with pytest.raises(ManifestValidationError):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
|
||||
def test_manifest_pydantic_serialization():
|
||||
"""Ensure Manifest operates as a Pydantic v2 model with correct serialization."""
|
||||
from pydantic import BaseModel
|
||||
|
||||
raw_yaml = """
|
||||
name: "serialized-app"
|
||||
domain: "app.example.test"
|
||||
description: "Pydantic serialization test"
|
||||
"""
|
||||
manifest = parse_manifest(raw_yaml)
|
||||
assert isinstance(manifest, Manifest)
|
||||
assert isinstance(manifest, BaseModel)
|
||||
|
||||
dumped = manifest.model_dump(by_alias=True)
|
||||
assert dumped["name"] == "serialized-app"
|
||||
assert dumped["schemaVersion"] == "1.0"
|
||||
assert manifest.to_dict()["name"] == "serialized-app"
|
||||
|
||||
|
||||
def test_parse_manifest_rejects_homelab_grants_file_in_env():
|
||||
"""Ensure HOMELAB_GRANTS_FILE is in RESERVED_ENV_KEYS and cannot be overridden by app.yaml."""
|
||||
raw_yaml = """
|
||||
name: "grants-override-app"
|
||||
env:
|
||||
HOMELAB_GRANTS_FILE: "/tmp/evil-grants.json"
|
||||
"""
|
||||
with pytest.raises(ManifestValidationError):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
"""
|
||||
Unit test suite for scripts/provenance.py (Two-Axis Inspection & Provenance Resolver).
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
# # Add scripts directory to path
|
||||
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
from core_manifest import Manifest, RefType, SourceConfig, TransportScheme
|
||||
from provenance import (
|
||||
ProvenanceStatus,
|
||||
get_local_checkout_status,
|
||||
inspect_workload_two_axis,
|
||||
resolve_upstream_provenance,
|
||||
)
|
||||
|
||||
|
||||
def _clean_git_env() -> dict[str, str]:
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
||||
env["GIT_AUTHOR_NAME"] = "Test"
|
||||
env["GIT_AUTHOR_EMAIL"] = "test@example.com"
|
||||
env["GIT_COMMITTER_NAME"] = "Test"
|
||||
env["GIT_COMMITTER_EMAIL"] = "test@example.com"
|
||||
return env
|
||||
|
||||
|
||||
def test_get_local_checkout_status_non_git(tmp_path: Path):
|
||||
non_git = tmp_path / "app"
|
||||
non_git.mkdir()
|
||||
status = get_local_checkout_status(non_git)
|
||||
assert status.is_git is False
|
||||
assert status.is_dirty is False
|
||||
assert "No Git Repo" in status.status_label
|
||||
|
||||
|
||||
def test_get_local_checkout_status_clean_repo(tmp_path: Path):
|
||||
app_dir = tmp_path / "git_app"
|
||||
app_dir.mkdir()
|
||||
env = _clean_git_env()
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "init", "-b", "main"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "config", "user.email", "test@example.com"],
|
||||
check=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env
|
||||
)
|
||||
(app_dir / "file.txt").write_text("hello", encoding="utf-8")
|
||||
subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "commit", "-m", "init"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
status = get_local_checkout_status(app_dir)
|
||||
assert status.is_git is True
|
||||
assert status.is_dirty is False
|
||||
assert status.branch == "main"
|
||||
assert status.commit_sha != ""
|
||||
assert "✓ Clean" in status.status_label
|
||||
|
||||
|
||||
def test_get_local_checkout_status_dirty_repo(tmp_path: Path):
|
||||
app_dir = tmp_path / "git_dirty_app"
|
||||
app_dir.mkdir()
|
||||
env = _clean_git_env()
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "init", "-b", "main"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "config", "user.email", "test@example.com"],
|
||||
check=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env
|
||||
)
|
||||
(app_dir / "file.txt").write_text("hello", encoding="utf-8")
|
||||
subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "commit", "-m", "init"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
# Modify file to create dirty state
|
||||
(app_dir / "file.txt").write_text("modified", encoding="utf-8")
|
||||
|
||||
status = get_local_checkout_status(app_dir)
|
||||
assert status.is_git is True
|
||||
assert status.is_dirty is True
|
||||
assert "* Dirty" in status.status_label
|
||||
|
||||
|
||||
def test_resolve_upstream_provenance_image_only():
|
||||
prov = resolve_upstream_provenance(None)
|
||||
assert prov.status == ProvenanceStatus.IMAGE_ONLY
|
||||
|
||||
|
||||
def test_resolve_upstream_provenance_synced():
|
||||
source = SourceConfig(
|
||||
url="https://git.example.com/operator/app.git",
|
||||
ref="main",
|
||||
ref_type=RefType.BRANCH,
|
||||
transport=TransportScheme.HTTPS,
|
||||
)
|
||||
mock_sha = "abc1234567890abcdef1234567890abcdef12345"
|
||||
mock_output = f"{mock_sha}\trefs/heads/main\n"
|
||||
|
||||
with patch("subprocess.run") as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=0, stdout=mock_output)
|
||||
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
|
||||
|
||||
assert prov.status == ProvenanceStatus.SYNCED
|
||||
assert prov.remote_sha == mock_sha
|
||||
assert "Up to date" in prov.message
|
||||
# Verify 10s timeout was passed to subprocess.run
|
||||
assert mock_run.call_args[1]["timeout"] == 10.0
|
||||
|
||||
|
||||
def test_resolve_upstream_provenance_update_available():
|
||||
source = SourceConfig(
|
||||
url="https://git.example.com/operator/app.git",
|
||||
ref="main",
|
||||
ref_type=RefType.BRANCH,
|
||||
transport=TransportScheme.HTTPS,
|
||||
)
|
||||
mock_sha = "fff9999999990abcdef1234567890abcdef12345"
|
||||
mock_output = f"{mock_sha}\trefs/heads/main\n"
|
||||
|
||||
with patch("subprocess.run") as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=0, stdout=mock_output)
|
||||
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
|
||||
|
||||
assert prov.status == ProvenanceStatus.UPDATE_AVAILABLE
|
||||
assert prov.remote_sha == mock_sha
|
||||
assert "Upstream at fff9999" in prov.message
|
||||
|
||||
|
||||
def test_resolve_upstream_provenance_timeout():
|
||||
source = SourceConfig(
|
||||
url="https://slow-remote.test/repo.git",
|
||||
ref="main",
|
||||
ref_type=RefType.BRANCH,
|
||||
transport=TransportScheme.HTTPS,
|
||||
)
|
||||
|
||||
with patch(
|
||||
"subprocess.run",
|
||||
side_effect=subprocess.TimeoutExpired(cmd=["git"], timeout=10.0),
|
||||
):
|
||||
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
|
||||
|
||||
assert prov.status == ProvenanceStatus.TIMEOUT
|
||||
assert "timed out after 10s" in prov.message
|
||||
|
||||
|
||||
def test_resolve_upstream_provenance_unreachable():
|
||||
source = SourceConfig(
|
||||
url="https://bad-remote.test/repo.git",
|
||||
ref="main",
|
||||
ref_type=RefType.BRANCH,
|
||||
transport=TransportScheme.HTTPS,
|
||||
)
|
||||
|
||||
with patch("subprocess.run") as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=128, stderr="fatal: remote error")
|
||||
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
|
||||
|
||||
assert prov.status == ProvenanceStatus.UNREACHABLE
|
||||
assert "Failed to query remote" in prov.message
|
||||
|
||||
|
||||
def test_resolve_upstream_provenance_pinned_commit():
|
||||
sha = "1234567890abcdef1234567890abcdef12345678"
|
||||
source = SourceConfig(
|
||||
url="https://git.example.com/app.git",
|
||||
ref=sha,
|
||||
ref_type=RefType.COMMIT,
|
||||
transport=TransportScheme.HTTPS,
|
||||
)
|
||||
# Matched local commit
|
||||
prov = resolve_upstream_provenance(source, local_commit="1234567")
|
||||
assert prov.status == ProvenanceStatus.SYNCED
|
||||
|
||||
# Differing local commit
|
||||
prov_diff = resolve_upstream_provenance(source, local_commit="9999999")
|
||||
assert prov_diff.status == ProvenanceStatus.UPDATE_AVAILABLE
|
||||
|
||||
|
||||
def test_inspect_workload_two_axis(tmp_path: Path):
|
||||
manifest = Manifest(
|
||||
name="test-app",
|
||||
source=SourceConfig(
|
||||
url="https://git.test/app.git",
|
||||
ref="main",
|
||||
ref_type=RefType.BRANCH,
|
||||
transport=TransportScheme.HTTPS,
|
||||
),
|
||||
)
|
||||
|
||||
# Without fetch_upstream: Axis 2 returns UNKNOWN
|
||||
status_no_fetch = inspect_workload_two_axis(
|
||||
tmp_path, manifest, fetch_upstream=False
|
||||
)
|
||||
assert status_no_fetch.provenance.status == ProvenanceStatus.UNKNOWN
|
||||
assert "Pass --fetch" in status_no_fetch.provenance.message
|
||||
|
||||
# With fetch_upstream: Axis 2 queries remote
|
||||
with patch("provenance.resolve_upstream_provenance") as mock_resolve:
|
||||
mock_resolve.return_value = MagicMock(status=ProvenanceStatus.SYNCED)
|
||||
status_fetch = inspect_workload_two_axis(
|
||||
tmp_path, manifest, fetch_upstream=True
|
||||
)
|
||||
assert status_fetch.provenance.status == ProvenanceStatus.SYNCED
|
||||
mock_resolve.assert_called_once()
|
||||
|
||||
|
||||
def test_resolve_upstream_provenance_class_b_and_default_timeout():
|
||||
# 1. Class B workload (source is None)
|
||||
prov_class_b = resolve_upstream_provenance(None)
|
||||
assert prov_class_b.status == ProvenanceStatus.IMAGE_ONLY
|
||||
assert prov_class_b.message == "Class B workload deploys prebuilt container images directly"
|
||||
|
||||
# 2. Default timeout (10.0s) verification
|
||||
source = SourceConfig(
|
||||
url="https://git.example.com/operator/app.git",
|
||||
ref="main",
|
||||
ref_type=RefType.BRANCH,
|
||||
transport=TransportScheme.HTTPS,
|
||||
)
|
||||
with patch("subprocess.run") as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=0, stdout="abc1234567890abcdef1234567890abcdef12345\trefs/heads/main\n")
|
||||
prov = resolve_upstream_provenance(source, local_commit="abc1234")
|
||||
assert prov.status == ProvenanceStatus.SYNCED
|
||||
assert mock_run.call_args[1]["timeout"] == 10.0
|
||||
|
||||
|
||||
def test_get_local_checkout_status_git_error(tmp_path: Path):
|
||||
app_dir = tmp_path / "git_error_app"
|
||||
app_dir.mkdir()
|
||||
(app_dir / ".git").mkdir()
|
||||
|
||||
with patch("subprocess.run") as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
returncode=128, stdout="", stderr="fatal: dubious ownership"
|
||||
)
|
||||
status = get_local_checkout_status(app_dir)
|
||||
assert status.is_git is True
|
||||
assert status.is_dirty is False
|
||||
assert status.status_label == "⚠️ Git Error (exit 128)"
|
||||
|
||||
|
||||
def _init_git_repo(repo_dir: Path, branch: str = "main") -> None:
|
||||
env = _clean_git_env()
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_dir), "init", "-b", branch],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_dir), "config", "user.email", "test@example.com"],
|
||||
check=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_dir), "config", "user.name", "Test"],
|
||||
check=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
|
||||
def test_get_local_checkout_status_monorepo_subpath_isolation(tmp_path: Path):
|
||||
"""Ensure monorepo subpath inspection isolates dirty state per workload directory (#33)."""
|
||||
workloads_dir = tmp_path / "Workloads"
|
||||
app_a = workloads_dir / "app_a"
|
||||
app_b = workloads_dir / "app_b"
|
||||
app_a.mkdir(parents=True)
|
||||
app_b.mkdir(parents=True)
|
||||
_init_git_repo(workloads_dir, branch="main")
|
||||
|
||||
(app_a / "app.yaml").write_text("name: app_a\n", encoding="utf-8")
|
||||
(app_b / "app.yaml").write_text("name: app_b\n", encoding="utf-8")
|
||||
|
||||
env = _clean_git_env()
|
||||
subprocess.run(["git", "-C", str(workloads_dir), "add", "."], check=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(workloads_dir), "commit", "-m", "init monorepo"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
# Dirty only app_b
|
||||
(app_b / "app.yaml").write_text("name: app_b_dirty\n", encoding="utf-8")
|
||||
(app_b / "untracked.txt").write_text("dirty\n", encoding="utf-8")
|
||||
|
||||
status_a = get_local_checkout_status(app_a)
|
||||
assert status_a.is_git is True
|
||||
assert status_a.is_dirty is False
|
||||
assert status_a.branch == "main"
|
||||
assert status_a.commit_sha != ""
|
||||
assert "✓ Clean" in status_a.status_label
|
||||
|
||||
status_b = get_local_checkout_status(app_b)
|
||||
assert status_b.is_git is True
|
||||
assert status_b.is_dirty is True
|
||||
assert status_b.branch == "main"
|
||||
assert "* Dirty" in status_b.status_label
|
||||
|
||||
|
||||
def test_get_local_checkout_status_hybrid_precedence_standalone_over_monorepo(
|
||||
tmp_path: Path,
|
||||
):
|
||||
"""Ensure standalone <app>/.git takes precedence over parent monorepo .git (#33)."""
|
||||
workloads_dir = tmp_path / "Workloads"
|
||||
app_a = workloads_dir / "app_a"
|
||||
app_a.mkdir(parents=True)
|
||||
_init_git_repo(workloads_dir, branch="main")
|
||||
|
||||
env = _clean_git_env()
|
||||
(workloads_dir / "README.md").write_text("monorepo\n", encoding="utf-8")
|
||||
subprocess.run(
|
||||
["git", "-C", str(workloads_dir), "add", "README.md"], check=True, env=env
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(workloads_dir), "commit", "-m", "monorepo root"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
# Nested standalone .git inside app_a on a distinct branch
|
||||
_init_git_repo(app_a, branch="standalone-branch")
|
||||
(app_a / "app.yaml").write_text("name: app_a\n", encoding="utf-8")
|
||||
subprocess.run(["git", "-C", str(app_a), "add", "app.yaml"], check=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_a), "commit", "-m", "standalone commit"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
status_a = get_local_checkout_status(app_a)
|
||||
assert status_a.is_git is True
|
||||
assert status_a.is_dirty is False
|
||||
assert status_a.branch == "standalone-branch"
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Unit tests for Pydantic v2 workload capability grants loader (ADR-0005)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
from workload_grants import (
|
||||
GrantsRegistry,
|
||||
WorkloadGrant,
|
||||
WorkloadGrantsError,
|
||||
load_workload_grants,
|
||||
)
|
||||
|
||||
|
||||
def test_load_workload_grants_absent_file_returns_empty(tmp_path: Path) -> None:
|
||||
missing = tmp_path / "does-not-exist.json"
|
||||
assert load_workload_grants(missing) == {}
|
||||
|
||||
|
||||
def test_load_workload_grants_honors_env_var_when_none(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
grants_path = tmp_path / "grants.json"
|
||||
grants_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"schemaVersion": "1.0",
|
||||
"workloads": {
|
||||
"media": {
|
||||
"devices": ["/dev/dri/renderD128"],
|
||||
"groups": ["render", "303"],
|
||||
"readOnlyPaths": ["/mnt/media"],
|
||||
}
|
||||
},
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setenv("HOMELAB_GRANTS_FILE", str(grants_path))
|
||||
loaded = load_workload_grants(verify_permissions=False)
|
||||
assert "media" in loaded
|
||||
assert loaded["media"].devices == ["/dev/dri/renderD128"]
|
||||
assert loaded["media"].groups == ["render", "303"]
|
||||
assert loaded["media"].readOnlyPaths == ["/mnt/media"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad_group", ["0", "root", "wheel", "docker", "ROOT", " wheel "])
|
||||
def test_workload_grant_rejects_privileged_groups(bad_group: str) -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
WorkloadGrant(groups=[bad_group])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad_path",
|
||||
[
|
||||
"dev/dri/renderD128",
|
||||
"../etc/passwd",
|
||||
"/dev/../etc/shadow",
|
||||
"/mnt/media/..",
|
||||
"",
|
||||
],
|
||||
)
|
||||
def test_workload_grant_rejects_relative_and_traversal_paths(bad_path: str) -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
WorkloadGrant(devices=[bad_path])
|
||||
with pytest.raises(ValidationError):
|
||||
WorkloadGrant(readOnlyPaths=[bad_path])
|
||||
|
||||
|
||||
def test_grants_registry_rejects_extra_fields() -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
GrantsRegistry.model_validate(
|
||||
{
|
||||
"schemaVersion": "1.0",
|
||||
"workloads": {"app": {"devices": [], "extra_field": True}},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_grants_registry_rejects_bad_schema_version() -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
GrantsRegistry.model_validate({"schemaVersion": "2.0", "workloads": {}})
|
||||
|
||||
|
||||
def test_load_workload_grants_malformed_json_fails_closed(tmp_path: Path) -> None:
|
||||
grants_path = tmp_path / "grants.json"
|
||||
grants_path.write_text("{not valid json", encoding="utf-8")
|
||||
with pytest.raises(WorkloadGrantsError):
|
||||
load_workload_grants(grants_path)
|
||||
|
||||
|
||||
def test_load_workload_grants_unreadable_file_fails_closed(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
grants_path = tmp_path / "grants.json"
|
||||
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
|
||||
|
||||
def raise_perm_error(self: Path, *args: object, **kwargs: object) -> str:
|
||||
raise PermissionError("Permission denied")
|
||||
|
||||
monkeypatch.setattr(Path, "read_text", raise_perm_error)
|
||||
with pytest.raises(WorkloadGrantsError, match="read"):
|
||||
load_workload_grants(grants_path)
|
||||
|
||||
|
||||
def test_load_workload_grants_verify_permissions_rejects_symlink(tmp_path: Path) -> None:
|
||||
real_file = tmp_path / "real.json"
|
||||
real_file.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
|
||||
link_file = tmp_path / "grants.json"
|
||||
link_file.symlink_to(real_file)
|
||||
|
||||
with pytest.raises(WorkloadGrantsError, match="symlink"):
|
||||
load_workload_grants(link_file, verify_permissions=True)
|
||||
|
||||
|
||||
def test_load_workload_grants_verify_permissions_rejects_non_root_owner(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
grants_path = tmp_path / "grants.json"
|
||||
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(
|
||||
os,
|
||||
"lstat",
|
||||
lambda _p: SimpleNamespace(st_mode=0o100640, st_uid=1000),
|
||||
)
|
||||
with pytest.raises(WorkloadGrantsError, match="root"):
|
||||
load_workload_grants(grants_path, verify_permissions=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad_mode", [0o100664, 0o100660, 0o100642, 0o100646])
|
||||
def test_load_workload_grants_verify_permissions_rejects_writable_mode(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bad_mode: int
|
||||
) -> None:
|
||||
grants_path = tmp_path / "grants.json"
|
||||
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(
|
||||
os,
|
||||
"lstat",
|
||||
lambda _p: SimpleNamespace(st_mode=bad_mode, st_uid=0),
|
||||
)
|
||||
with pytest.raises(WorkloadGrantsError, match="writable"):
|
||||
load_workload_grants(grants_path, verify_permissions=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("good_mode", [0o100640, 0o100644])
|
||||
def test_load_workload_grants_verify_permissions_accepts_non_writable_mode(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, good_mode: int
|
||||
) -> None:
|
||||
grants_path = tmp_path / "grants.json"
|
||||
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(
|
||||
os,
|
||||
"lstat",
|
||||
lambda _p: SimpleNamespace(st_mode=good_mode, st_uid=0),
|
||||
)
|
||||
assert load_workload_grants(grants_path, verify_permissions=True) == {}
|
||||
@@ -0,0 +1,47 @@
|
||||
x 2026-10-13 (A) Create core_manifest.py schema and parser with strict transport validation (https, ssh, git) and ref classification in scripts/core_manifest.py +manifest @core
|
||||
x 2026-10-13 (A) Implement unit tests for core_manifest.py covering valid manifests, invalid URLs, and ref types in tests/unit/test_core_manifest.py +test @core
|
||||
x 2026-10-13 (B) Implement two-axis inspection engine in appctl evaluating local checkout state independently from upstream provenance +provenance @appctl
|
||||
x 2026-10-13 (B) Implement bounded git ls-remote provenance resolver with 10s timeout for appctl status --fetch +provenance @appctl
|
||||
x 2026-10-13 (B) Add unit tests for provenance resolution and timeout handling with mocked network fixtures in tests/unit/test_provenance.py +test @appctl
|
||||
x 2026-10-13 (C) Promote scripts/appctl_engine_v2.py to authoritative scripts/appctl_engine.py +engine @appctl
|
||||
x 2026-10-13 (C) Verify full test suite and update CLI wrappers for appctl v2 engine promotion +test @appctl
|
||||
x 2026-10-13 (A) Reconcile appctl implementation inventory and document caller/dependency map in docs/plans/p4-readiness-plan.md +inventory @p4-gate
|
||||
x 2026-10-13 (A) Define canonical command and error contract across dual transports in docs/plans/p4-readiness-plan.md +contract @p4-gate
|
||||
x 2026-10-13 (A) Close authorization design enforcing token-everywhere policy in docs/plans/p4-readiness-plan.md +auth @p4-gate
|
||||
x 2026-10-13 (B) Specify daemon execution and privilege boundaries for Docker, subprocesses, and filesystem roots in docs/plans/p4-readiness-plan.md +security @p4-gate
|
||||
x 2026-10-13 (B) Define append-only audit telemetry schema, lifecycle, and failure handling semantics in docs/plans/p4-readiness-plan.md +audit @p4-gate
|
||||
x 2026-10-13 (C) Establish P4 acceptance test matrix and definition of done before daemon implementation in docs/plans/p4-readiness-plan.md +test @p4-gate
|
||||
x 2026-10-14 (A) Eliminate eval in scripts/appctl and enforce strict env key validation in scripts/core_manifest.py +security @appctl
|
||||
x 2026-10-15 (A) Enforce deployments.yaml as sole registry and remove dynamic discovery fallback in scripts/gitops_dispatcher.py +registry @gitops
|
||||
x 2026-10-15 (A) Harden validate_compose_security in scripts/gitops_dispatcher.py blocking relative traversal, cross-tenant mounts, and privilege escalation +compose @gitops
|
||||
x 2026-10-15 (A) Unify manifest parsing on core_manifest.py and eliminate duplicate parsers in scripts/appctl_engine.py +manifest @engine
|
||||
x 2026-10-15 (A) Codify Platform Genericism invariant in AGENTS.md and add Pydantic to flake.nix, pyproject.toml, and scripts/test +invariant @core
|
||||
x 2026-10-15 (A) Add pydantic to host NixOS runtime and constrain dependency range in flake.nix and nixos/configuration.nix +nixos @core
|
||||
x 2026-10-15 (A) Wire app_name and harden compose validator for env_file and undeclared volumes in scripts/gitops_dispatcher.py +compose @gitops
|
||||
x 2026-10-15 (B) Scrub hardcoded domain defaults across scripts and tests enforcing instance-agnostic parameterization +generic @core
|
||||
x 2026-10-15 (A) De-tautologize appctl env injection test to execute scripts/appctl directly with mock docker in tests/security/test_security_invariants.py +test @security
|
||||
x 2026-10-15 (A) Clarify Pydantic v2 target architecture, strict typing rules, and domain precedence in docs/plans/p4-readiness-plan.md +docs @p4-gate
|
||||
x 2026-10-15 (A) Migrate core_manifest.py to Pydantic v2 models for strict type validation and serialization +manifest @schema
|
||||
x 2026-10-19 (A) Implement strict Pydantic v2 API contracts, error sanitizer, and compose_pull action in scripts/appctl_contracts.py and scripts/core_manifest.py +contracts @p4
|
||||
x 2026-10-19 (A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4
|
||||
x 2026-10-19 (A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4
|
||||
x 2026-10-19 (B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4
|
||||
x 2026-10-19 (B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) and wire gitops_dispatcher.py worker to daemon in scripts/appctl_daemon.py +daemon @p4
|
||||
x 2026-10-19 (B) Add comprehensive unit and security test suite for P4 contracts, RBAC, audit guard, concurrency, and dual-transport parity in tests/unit/test_appctl_daemon.py +test @p4
|
||||
x 2026-10-19 (C) Re-implement scripts/appctl as a thin UDS HTTP client and declare homelab-appctl.service with POSIX ACLs in nixos/modules/homeserver.nix +cli @p4
|
||||
x 2026-10-19 (C) Scrub remaining hardcoded domain and username literals across NixOS modules, Compose stack, and config/deployments.yaml and add pyright to flake.nix checks +generic @core
|
||||
x 2026-10-19 (A) Enable Core platform stack and core_service container-scoped dispatch in OperationalRouter in scripts/appctl_router.py +router @p4
|
||||
x 2026-10-19 (A) Restore human-readable tabular output, list filter parameters, and bash autocompletion fast-path in scripts/appctl_cli.py and scripts/appctl +cli @p4
|
||||
x 2026-10-19 (A) Add operatorUser to homelab-operators group and configure daemon systemd sandbox HOME and DOCKER_CONFIG in nixos/modules/homeserver.nix +nixos @p4
|
||||
x 2026-10-19 (A) Provision SOPS appctl/tokens_json and gitops/appctl_token secrets and wire GITOPS_APPCTL_TOKEN_FILE in nixos/secrets.yaml and nixos/modules/homeserver.nix +secrets @p4
|
||||
x 2026-10-19 (B) Reconcile operational documentation and ROADMAP.md with Milestone P4 control plane daemon architecture +docs @p4
|
||||
x 2026-10-23 (A) Migrate operator user from kiskaadee to operator in nixos/configuration.nix and homeserver.nix +nixos @core
|
||||
x 2026-10-23 (A) Derive LLDAP_LDAP_BASE_DN dynamically from homelab.domain in nixos/modules/homeserver.nix and docker-compose.yml +nixos @auth
|
||||
x 2026-10-23 (A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms
|
||||
x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git
|
||||
x 2026-10-30 (B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security
|
||||
x 2026-10-30 (B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux
|
||||
x 2026-10-30 (B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth
|
||||
x 2026-10-30 (B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4
|
||||
x 2026-10-30 (C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap
|
||||
x 2026-10-30 (A) Implement instance domain injection dual-path import and operator cutover runbook in nixos/configuration.nix and docs/ +generic @nixos
|
||||
@@ -0,0 +1,186 @@
|
||||
version = 1
|
||||
revision = 5
|
||||
requires-python = ">=3.13"
|
||||
|
||||
[[package]]
|
||||
name = "annotated-types"
|
||||
version = "0.8.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "homelab-core"
|
||||
version = "0.1.0"
|
||||
source = { virtual = "." }
|
||||
dependencies = [
|
||||
{ name = "pydantic" },
|
||||
{ name = "pyyaml" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "pydantic", specifier = ">=2.0,<3.0" },
|
||||
{ name = "pyyaml", specifier = ">=6.0" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pydantic"
|
||||
version = "2.14.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "annotated-types" },
|
||||
{ name = "pydantic-core" },
|
||||
{ name = "typing-extensions" },
|
||||
{ name = "typing-inspection" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/7c/0b/8e10b2e693af8ec54346a14caf36221334775975a747c9ceaa3f8371d96d/pydantic-2.14.1.tar.gz", hash = "sha256:94f478203dd03404682a1ada216965651dd74b1d2d5ffd62e00e0837caab5c26", size = 900362, upload-time = "2026-10-11T18:37:55.396Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/35/ea/a56b9fe5066f3537b7882f77e9c5dfb26d8c2eefdaed9b5fc73d57b4dc22/pydantic-2.14.1-py3-none-any.whl", hash = "sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454", size = 488106, upload-time = "2026-10-11T18:37:53.437Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pydantic-core"
|
||||
version = "2.50.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a6/24/af4ec4be49fbc810f35b0bdcacc3d433b56bbfa469fd3bfd4ae116cd9bf1/pydantic_core-2.50.1.tar.gz", hash = "sha256:e50d7b94baac6c7d09927fa5ca5800a0c7ee5015c7fcff65beb3a1931b5a6e09", size = 513515, upload-time = "2026-10-11T18:35:44.82Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ae/57/0e237d7091d2cd44a35d243b7344227f90440166860469cd036afc23a04d/pydantic_core-2.50.1-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:d5e062c01286d861fd6a1c4ff6e063547b3e713067f2df033c0ff97ac2ca006b", size = 2222774, upload-time = "2026-10-11T18:32:43.103Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f7/b9/c720e56858d4e1539503297ed37063e0c08e0f3541c41b777f6a800f75fa/pydantic_core-2.50.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0c003c3b7f49debb893d2d85ae099ac5959c9839e2f330fadb1fcdf7a6594482", size = 2024738, upload-time = "2026-10-11T18:32:44.587Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4d/b8/fbfc25875219cc060e613170ff10e850c6d8924beb4910da57c2ee3ba1d2/pydantic_core-2.50.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:409e0ea40ec30d9158f33574fd758e689f6045a0f2596701828c27816ca9687d", size = 2047049, upload-time = "2026-10-11T18:32:46.164Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d7/43/34210124d504c553688f2f04b48500b131237528ac545b445e0d6d30e0d5/pydantic_core-2.50.1-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:131059670f1d2444269b8585cb888963994871932447c08b39ac6a51fcfef658", size = 2173415, upload-time = "2026-10-11T18:32:47.722Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/65/cf/6e178e8fdc11da5965bef980983bf46326a42f436871dd51ba0a57f39df1/pydantic_core-2.50.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6dbcbee53bf17196a7f745aa9bf5a9603953a1e365b1f020be3207c676a3e7c4", size = 2361719, upload-time = "2026-10-11T18:32:49.217Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/11/14/bd5169d356aa91bf777e28ba0b281c192d286d03c2812c9c9db023a2f00e/pydantic_core-2.50.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:325c23f3e35cfbf0fe3486fa5f7260d1e45885173002d30a28ca019994124255", size = 2439803, upload-time = "2026-10-11T18:32:51.025Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1c/bc/d79d000e5203ebef39af839f2ce77a777fcad6e08ad26af9a2fcd114ffc8/pydantic_core-2.50.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:17e722e156d0444ecaefbe640bdb60928752bf2013e2b7a11cdb099aaae19bec", size = 2158402, upload-time = "2026-10-11T18:32:52.714Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1b/a5/4902cb5fd599422c130bd3124ab31ee8b771199bd56662702eed07d3fec7/pydantic_core-2.50.1-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:aa8224f10880d9bf1b5993988ba153d42a8b4f3f4f511f93b1f09c93ff613c72", size = 2229755, upload-time = "2026-10-11T18:32:54.126Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1a/f5/c1481f8669f6060d89110c9b1374173fc8767ca276b84f4870bd8acd5e3f/pydantic_core-2.50.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:41bc8237121bd8dc8d888dfd6279fc166ffc88c1f1bf3a8bf00869680533ca4c", size = 2242303, upload-time = "2026-10-11T18:32:55.641Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/04/f9/77fc3c7653ba9b6e42049e17e96b25388187d4a7c274ab1cb07f58ac8419/pydantic_core-2.50.1-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:45c6266d071c241f2a168d45bf8c54344f0effce35e7e6b73afdec11f3687568", size = 2278345, upload-time = "2026-10-11T18:32:57.38Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/95/9b/0579c5d12e7f2b16b27e6782427987341fcce07b0725e02ddb0b74add0c4/pydantic_core-2.50.1-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:1deeacb112d14d3f4fcb16b165f7dbaf76c70ba6e82f37ba042bdab51970a0b8", size = 2449947, upload-time = "2026-10-11T18:32:58.896Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/ac/1b677db91eba54cc5922f4de6edc46ba45c2bd712dfdc0130382d158e214/pydantic_core-2.50.1-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:1c96fd793b73d1b92e65570132505498fe7b21eaef73cdf74e67e5dfba7ac9e4", size = 2476889, upload-time = "2026-10-11T18:33:00.665Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4d/2a/3a9f6624ee3ea9ccba5249dde11418bb4c35780a7a92608f8768bd3fea39/pydantic_core-2.50.1-cp313-cp313-win32.whl", hash = "sha256:06ead20d39ffd6f2f6f2a8f8a6de67ff8bb1b4f14a8a30e058502514ee2ac685", size = 2101118, upload-time = "2026-10-11T18:33:02.329Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2d/1f/323f78ddd9d9938aac420c1abb4e8ba799fc8bdab0acc67c0593b837c979/pydantic_core-2.50.1-cp313-cp313-win_amd64.whl", hash = "sha256:7816e98acc08119dc0f340ab167048ecc54126316330c1f0caf7c6756c88e28f", size = 2170840, upload-time = "2026-10-11T18:33:03.919Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cb/09/8497c52a739ae425c3ac2f7f56414cbc711c67d374346174f40fe2062644/pydantic_core-2.50.1-cp313-cp313-win_arm64.whl", hash = "sha256:c17799a62c142d61b8a3c51752a7cbc87fe2ad4ccfab10e628a77b405075c662", size = 2161633, upload-time = "2026-10-11T18:33:05.518Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/49/33/28b96e81677153715e3eafb9f26663a80841e859fde282a380359b0d3fa1/pydantic_core-2.50.1-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:1cf41f1ae3fa155cf167a72689ad044bcc1e3c97e064123677149bdfb5dafc4a", size = 2224428, upload-time = "2026-10-11T18:33:07.153Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/94/40/15c06410c9b7b8da5805d27b64e09bd3f900e986728106db2689dbc51513/pydantic_core-2.50.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4df197990c15b5a37c5a277d131d9f2c67de6133f2e5dafd80d9bba4b99f46f9", size = 2023740, upload-time = "2026-10-11T18:33:08.763Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a1/4e/5eb629f6efc2a27e421d789dd4bfacbb5f6d09c80c28b13d1e87d73163d5/pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0036473f5583e6a60e50b8b21651511564277a3f05cc5dab8cf579f552cd5f6c", size = 2049435, upload-time = "2026-10-11T18:33:10.366Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ba/8e/f195aebec49ad12318876ac2368c197a7939f5d52f8e156d2238ef8a4588/pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:992c3514ec891fa7858099183e4d64e6bd5a5d4ff452fae29df22faa77a006bb", size = 2172975, upload-time = "2026-10-11T18:33:12.368Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e0/f5/7ad9fb83010cd5ea0948409db105676ed779c4e709e2d3d89b9fe2558794/pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:739dc730e6be3bd5ec2f4ab5cfc7eb047cc45fc1497b3bafec74ff2ed07df597", size = 2364197, upload-time = "2026-10-11T18:33:14.244Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ca/fb/bf0aab3e78301d202b82a0322ec968cd703b11fc0623fde9a28708936f62/pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:32fad3a91e51b6d2039c572db04a5a873260b399f6bd62c3552671fa7a4a2899", size = 2444259, upload-time = "2026-10-11T18:33:15.79Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/45/35/38f6d6564fae57d9b12e5676dfa947e0e7d5c46dbeaa7eb3352261d6d299/pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:42b54c2c90ad348b5e3a85e03e715d572c1fde357ef104cdfe3b03b697a404ea", size = 2159857, upload-time = "2026-10-11T18:33:17.51Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/65/a0/fb0a3ca10f139dcf765b2d312d10cf0f65c57c59993229d00ad12b14ceff/pydantic_core-2.50.1-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:2df1ff41884de2bc4b307bafd7c40a691094fad2ff8e767e5b45a319257bcf4e", size = 2233954, upload-time = "2026-10-11T18:33:19.591Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8c/6a/e63842252702aa4ec6e6b7178ca85e541a77459076592c23ebe2d9840b33/pydantic_core-2.50.1-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:fe90228920fd8ff2be62622b6bb8a2b11acd65046d50c6b130614b5879605a20", size = 2243876, upload-time = "2026-10-11T18:33:21.393Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/39/25/5991cf8318b37e0dfab47b87541619a1df8501a793cba0d978846cba37a7/pydantic_core-2.50.1-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:844b869f118e22a41a091bdcedda8a71bc1b0f62c38d1a0c3211cece47e1d8fc", size = 2277908, upload-time = "2026-10-11T18:33:23.324Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a7/3e/3ee8baaa6cc25a6961c69168cf9ff0f002d56f4e0d541ad6724c18fb61f3/pydantic_core-2.50.1-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:2eb75304506894a281d346220a4f7481a1b8729577c5ed2a05395991966a8396", size = 2449285, upload-time = "2026-10-11T18:33:24.942Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c0/c7/acbec6deac13fe697a80c275a9b6661db62c4d323bac8a47347b1f39c7cd/pydantic_core-2.50.1-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:6b20a4bffabdad0db2927ac034ae3b8a681b1f7a0182f3e60b479ad2fde21ebb", size = 2479013, upload-time = "2026-10-11T18:33:26.925Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/10/08/21a3f237b264389f6219d053ee78fc1b5c2fd402c1b1cb2b6cb8b85f9834/pydantic_core-2.50.1-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:99ba9bc2b8062ea0c326a990f7f00e6530c23579de66dd246e72c4cafef950a5", size = 1484400, upload-time = "2026-10-11T18:33:28.693Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/09/ce/077a6d262d12ef09108377ac0717f029f420d773ace63cafd6143af75568/pydantic_core-2.50.1-cp314-cp314-win32.whl", hash = "sha256:cf356f70551d40374eaffb1aa63f1eb6d2006681cbd7a9faea173ce0f4dd7cd2", size = 2103222, upload-time = "2026-10-11T18:33:30.326Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/14/4c/350a2415209c43d670eb71d3c040f332c04a30583d39e311b05c7ac15762/pydantic_core-2.50.1-cp314-cp314-win_amd64.whl", hash = "sha256:d32f3acc081cc3923386d88f422cde8892335e95f034e0104bb4cf9310d9915f", size = 2171586, upload-time = "2026-10-11T18:33:32.139Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bf/92/9bea6ca96580a0902fed366f064f0829e404f41889b34543279a1162b888/pydantic_core-2.50.1-cp314-cp314-win_arm64.whl", hash = "sha256:bed5163e03b98bc1fa2eb05d74c63d9c5c95d8ed6254985481640fbf5e237dea", size = 2155773, upload-time = "2026-10-11T18:33:33.896Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/86/8c/f121f073cf32bdd5cba7e6230b1ce0ac845b0cf43e44dd597d95af272db2/pydantic_core-2.50.1-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:9572c1369e9c9da2d64a7b7992c786d90ff295abc93964cfe3125e4290768070", size = 2234017, upload-time = "2026-10-11T18:33:35.588Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a4/69/2bb2bcd6146cffe98d760a46c42ae71efd5151d9b2f9c9bf6619a3b32083/pydantic_core-2.50.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2005207aafe1231315718bf6ed5d064a7300fb4772754af35ee72fc68159492e", size = 2001016, upload-time = "2026-10-11T18:33:37.57Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/20/b3/fbf854c7d07ec114260c26e9e2071a4381740f9ae09641dbfcbdf2a18c45/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:64f6047f62a6c5ae08d0a6afb035667aa2d97c3d20d69762e034c5ea144d92a5", size = 2023015, upload-time = "2026-10-11T18:33:39.433Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/65/20/6de55b2f92cdb614b745c6e9ced639fc4fd7e1e77604825a88bdece6fcbd/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:1ef800dd7d85bcdadf4c3076e4c94e43939493558a3b69a1ea830c706d4617bb", size = 2192543, upload-time = "2026-10-11T18:33:41.381Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0c/d9/19e91c94bd5c405945ce2f15526808aea37e162c253160de8ed7bf70b406/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b0135bcdcaa0f23573f286e4cb5e0fd2962700964ed13df085b85f2b97aeab9e", size = 2388704, upload-time = "2026-10-11T18:33:43.167Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b6/bc/2e24c8415eae1a25ee5a5484946a917123bad2e9d01689a759236928175a/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0b3a6f334c6a2345ca15318ff894502a90012536404b37c844a976c76c846e0b", size = 2464118, upload-time = "2026-10-11T18:33:44.856Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bd/1f/945b8053cb061c64e102bcaf7bfb9ed740c0bd4349f9bb978a7d4ddff4ab/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:06e01fbbfdb9be777b316a71b6c49efaf4a08b615d0a98d678cda3023f79d019", size = 2150142, upload-time = "2026-10-11T18:33:46.661Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2b/78/96a3e50bf0d64aaae781107eb9335b7529d05a85793ed6e7241c4cd1d931/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:a29a061fec0b4e2d714f277e70a3a18125ecff803f2fea6eade2f2e53711d112", size = 2245577, upload-time = "2026-10-11T18:33:48.574Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7a/5d/a6038a0322232758a6ebfa709f4ca14a60bf5b93940cd0b345056a557da4/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f5187624823423e1d1b82b1072ac41dc837389e18d3d0572cc19bbee46cd550a", size = 2263728, upload-time = "2026-10-11T18:33:50.527Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0d/4b/76ded3333a457a9344c4f2d63f2d82d0101654b05178fa4ddfe7d3627674/pydantic_core-2.50.1-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:3e46a9eb0a0901dd6275e6b06ac3a464885ef350ec4121fe486869de8053e4bb", size = 2293630, upload-time = "2026-10-11T18:33:52.362Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a9/00/9eca378335c9c1b72bc779bf6e4c2a82ce784f14ec48a0e87102c9870e05/pydantic_core-2.50.1-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:756d669f04e62ec4148ecfe22be6a4484d9b1181a6ef32e205ebfd200540858b", size = 2468048, upload-time = "2026-10-11T18:33:54.118Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/35/ca/e3832e9cf93651251de43c8c5c029ed680a3c1a0a1b17ee26c81bed08cbd/pydantic_core-2.50.1-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:c516cc5367ca3448995d42cb994bf3f4c9002d2a7c22eac9622551269ad1b807", size = 2512159, upload-time = "2026-10-11T18:33:55.99Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4b/f2/773469b5a10a39116a2cb17edaf6d722f017dd8da07161b371465311c542/pydantic_core-2.50.1-cp314-cp314t-win32.whl", hash = "sha256:9d1bed94af6a63835461f3cf7502058eb166c58c4778e11d0f433cfb1bd69e19", size = 2098406, upload-time = "2026-10-11T18:33:58.043Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ee/42/0bb74f8f25204b259b11ab7c12dc7f180893b6bd706118b385147fb6efd5/pydantic_core-2.50.1-cp314-cp314t-win_amd64.whl", hash = "sha256:c8dce1f1e0e5358b682a6ad3fa5e31b31d4560997b8e61417e9217c8d60f8a0c", size = 2148481, upload-time = "2026-10-11T18:33:59.913Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/47/0d/d801646c9679a4e630e15cf521d4108b93854b42a6e6e02391bd4c6b1095/pydantic_core-2.50.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ceff0acc940be2715bd6ad17b24c0e5304abf44f6efd0f81ee8499e640f9dc86", size = 2174972, upload-time = "2026-10-11T18:34:01.875Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b2/84/23984b763d8862a02a13d27a44b6e8169428fd85ecfed88f54c29108604d/pydantic_core-2.50.1-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:8a6791afa2245e6c6b180122d105941644f5bd410bb18623b408808cc41a3102", size = 2224599, upload-time = "2026-10-11T18:34:04.016Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4d/90/a63cf8586abc1d1a3f6d9b18f0224789ebf003851f092ebda3c7c863fd32/pydantic_core-2.50.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:84f34323a61a365b4e9295de6028474754829aaddd59c7bf1a040e7487ef8f3c", size = 2024191, upload-time = "2026-10-11T18:34:05.901Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a6/6a/f34bff9808ffb4907fbf5f5040457d253cacf2da7fce9efbc99ca1b1a44d/pydantic_core-2.50.1-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:23edad659e8dbd8ca7e4e877fe6c81573abbdf215bd25a68b53e1272f58b80c7", size = 2048252, upload-time = "2026-10-11T18:34:07.757Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b2/54/13f419bf1eb59852003818e25935aaf175687d978f4c4bca70e08fe40a3b/pydantic_core-2.50.1-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3a5fce22f1e87d181e924e12da7d81cfe031fb3881a5ddf26ad28f141756ca43", size = 2173376, upload-time = "2026-10-11T18:34:09.592Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6d/6c/b5a34d24cd0c81669d8f8339d74e6815abcf2f8fb48ab4b49b84c09be1d5/pydantic_core-2.50.1-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c73622ef819328873b53109ee4f77ceb598bffedd02daf916102be3228866b78", size = 2364559, upload-time = "2026-10-11T18:34:11.534Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/eb/8d/d64d6216a8df365082665927ff923f183056f9049fee08e9777c9ac05296/pydantic_core-2.50.1-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ce8c25ca38cc0e3d7753ba180808de2c0c8cb24eae0df64491e40921454e9831", size = 2444697, upload-time = "2026-10-11T18:34:13.535Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b8/0d/1b1149f60a00ea21ba5f70e28acbd40feb4598af414f80f53c921fac07c9/pydantic_core-2.50.1-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7689580e72a642ab5ec64d5f55b2e33636fa43b4ebe63c0c2c965ef307c7d1aa", size = 2159961, upload-time = "2026-10-11T18:34:15.56Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1e/35/f236549299dcc78e71e945495d7ec67e78d20844d0999c60601685003031/pydantic_core-2.50.1-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:d5c0e32fdbce7f1e8ef4d11f655694bf5f4175c757a9f1dc2be09b8864e5bcf5", size = 2234581, upload-time = "2026-10-11T18:34:17.502Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6a/85/26901a490522b7f75ef9bb9a7afb73e5bb550f0e1cb5b99a0069183e2eb9/pydantic_core-2.50.1-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:40f523349960fa30f3ea51404308ff50f9997a90df639590f47a057c1f32b415", size = 2244090, upload-time = "2026-10-11T18:34:19.402Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ca/2c/481bcfc70ceeb77a778ca6e5b705fe592cb64735c108157f81b7dd9c280e/pydantic_core-2.50.1-cp315-cp315-musllinux_1_1_aarch64.whl", hash = "sha256:d4193206b6587047437f6f11d7e776df23e1c1e23af2a54d9347275614791e10", size = 2277948, upload-time = "2026-10-11T18:34:21.317Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/24/eb/f1e09333faa7ba447cde967310f758430cc7c5e987bdab5228816c70030d/pydantic_core-2.50.1-cp315-cp315-musllinux_1_1_armv7l.whl", hash = "sha256:84bc765b282a9d5b7fe0348b8648904f25a6a04b2139da52b1dd30c8ac3a2c8f", size = 2449688, upload-time = "2026-10-11T18:34:23.321Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d1/b3/036bde636db8f76d92996e81aefc75678ab5cec4a07eea1ad0c72a893fc3/pydantic_core-2.50.1-cp315-cp315-musllinux_1_1_x86_64.whl", hash = "sha256:ed1e728b39a383c81035b2459cfcb35d99dfb01f7d6ebe3a913bc1cc5b81e459", size = 2479286, upload-time = "2026-10-11T18:34:25.214Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d0/a3/07f018294ee18d144afeb6df1a47d9e92960f014be45c5ed13519fa5af95/pydantic_core-2.50.1-cp315-cp315-win32.whl", hash = "sha256:bc94f474417604bd383d2cd445d071b07dd55fedceed3ce33407bf1fcc107290", size = 2103683, upload-time = "2026-10-11T18:34:27.42Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5f/98/f9bd7e1f9b6709f155acb9ef826d9c3884fe925f811fd8e55b9b52280bad/pydantic_core-2.50.1-cp315-cp315-win_amd64.whl", hash = "sha256:983a662de2571cb2502fc8ff47b6770b03d025d2eb314c92f77b3f07c74720ed", size = 2171681, upload-time = "2026-10-11T18:34:29.508Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/10/87/4bb3e1e7f385c076ab5af4d6dd0571b22042cd8207eb810d5b9fef15ae31/pydantic_core-2.50.1-cp315-cp315-win_arm64.whl", hash = "sha256:94845ff54dc5193f228cab81b2662a04bfbb892e95bdc15edf7399000ce57d54", size = 2156251, upload-time = "2026-10-11T18:34:31.455Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/47/47/83643225b08f2aef6c8cc4bbe6e3f79c5e139c4364a6e450d0f399d87774/pydantic_core-2.50.1-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:4a53d13cdfbedbfa87f08b83c1a0a5efcc767d785a4b41934fa9cb672670493a", size = 2234363, upload-time = "2026-10-11T18:34:33.65Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5e/66/127ca649ba2f2462039dc1e694c6c01e00a3689f023a617364d3507e6d97/pydantic_core-2.50.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:efbecf43d321f7b9281441f1f213f7c21c66988b0e06c2730ba13ed47a46bb08", size = 2000972, upload-time = "2026-10-11T18:34:36.037Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5e/4f/e421e0a5d653b1203b090b2e48745976988d7338a647940704b5b9c2b399/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bc1f08f68dac9f9e83845a8039880aba2ab553eb9b2259c3243a313182c253fe", size = 2022925, upload-time = "2026-10-11T18:34:37.972Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d5/4e/ea5568e2491e1a71100f15ae8c2d01ef52db42a184a2d4e716bc79e5eb8f/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:5dfe41f232befddb9c4377f6cfc702b51595e2d78ed082672adf8758d2c4619f", size = 2192867, upload-time = "2026-10-11T18:34:39.921Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ae/5e/3b8c3a35acbe219909ada5defad5d7d9fed845fb2b37bd5ec518f453c119/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:adc06d218a1cadfd2ec4628424d7d79ce4eba69c2965e7e7b55106f0da5208c8", size = 2388687, upload-time = "2026-10-11T18:34:42.184Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b6/aa/7889b4e515f91a2e8c0ae6b5081fec0feb30c4398d1434e14793c60f173a/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2cf91809d0721ab81592ba67bea7694821679c10b1a2e3c3460082b286c1918a", size = 2464415, upload-time = "2026-10-11T18:34:44.384Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/08/78/93449e628eb8a6fdcce3eff9043081179d1bc7ce6f1bff32dc5006f41e00/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:23923ab9292c40da026330b1ecf4dc2618c8e86e0422e5d1fbf50d94d64ca4f8", size = 2150823, upload-time = "2026-10-11T18:34:46.392Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f4/f1/72c5bc129fceb0d00f05dc1e67f518c1728de1928c55f81fc13d7690de39/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:f3377c8c2b3ce898423c5e5dd94c7982e30aa7717a7e6ab2470b9de364963709", size = 2245806, upload-time = "2026-10-11T18:34:48.805Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/28/2a/922a0e78f3aa6ab837b59f88190233fb8dad546c17995fde9bb3ed3b9b49/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:455a773617b5913bf5c20d0692e5787b119e52c4d40ea644ca31f5758fd31be2", size = 2264160, upload-time = "2026-10-11T18:34:50.876Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/52/a8/0f1449e3e1b20941c9372faa18e7b6a092e30cdfa841902473f7989532ac/pydantic_core-2.50.1-cp315-cp315t-musllinux_1_1_aarch64.whl", hash = "sha256:1a9006395dece0e32e704c315eff8a00bede494f6108546cfc5539c89fef4f9a", size = 2294031, upload-time = "2026-10-11T18:34:52.876Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d1/d0/1031f492857de70355fb16524bbb03efce5fd34c93ed4a1ec60be07e0d4b/pydantic_core-2.50.1-cp315-cp315t-musllinux_1_1_armv7l.whl", hash = "sha256:d2d82aa62521c55ddfb000ae70f88cdd8de974078f6024e821dfe5addd0c818f", size = 2468423, upload-time = "2026-10-11T18:34:54.995Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/46/52/269ffffa645b8e47906395a39cf9db1151ae9fa4bcd7f47b960bc31baf37/pydantic_core-2.50.1-cp315-cp315t-musllinux_1_1_x86_64.whl", hash = "sha256:009634b83993777ddcd69cad0ffcace43dabde692109528e35f0fde91e386a8b", size = 2512598, upload-time = "2026-10-11T18:34:57.149Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/31/5c/e47e28281f20326ff6f3c31d626f0a83e615d2d94ba41bb0ad6ec237184a/pydantic_core-2.50.1-cp315-cp315t-win32.whl", hash = "sha256:3fde4fdc6487a58d944ca87cf5adc95d5f266e872c19599f5f4c0a8a1b1f9f9f", size = 2098535, upload-time = "2026-10-11T18:34:59.313Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/03/ad/759e181e69c1b472c60b2049e5f61d5da1deefdd5ce1df4bb2ebcf771f25/pydantic_core-2.50.1-cp315-cp315t-win_amd64.whl", hash = "sha256:1c8632d4ac04e6f91128fca584b3a8a507d81604c24eeaaad00d4be42765c32b", size = 2148645, upload-time = "2026-10-11T18:35:01.571Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6d/56/8a702c27e5be9f47e5f19d8669227424290e4c024e7c370279cbaf244b4e/pydantic_core-2.50.1-cp315-cp315t-win_arm64.whl", hash = "sha256:c3ede305158e75510be50869b319550ab072008c13d64d4ab1e094fb286b6f44", size = 2175297, upload-time = "2026-10-11T18:35:04.079Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyyaml"
|
||||
version = "6.0.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/d1/11/0fd08f8192109f7169db964b5707a2f1e8b745d4e239b784a5a1dd80d1db/pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", size = 181669, upload-time = "2025-09-25T21:32:23.673Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", size = 173252, upload-time = "2025-09-25T21:32:25.149Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/50/31/b20f376d3f810b9b2371e72ef5adb33879b25edb7a6d072cb7ca0c486398/pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", size = 767081, upload-time = "2025-09-25T21:32:26.575Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/49/1e/a55ca81e949270d5d4432fbbd19dfea5321eda7c41a849d443dc92fd1ff7/pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", size = 841159, upload-time = "2025-09-25T21:32:27.727Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/74/27/e5b8f34d02d9995b80abcef563ea1f8b56d20134d8f4e5e81733b1feceb2/pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", size = 801626, upload-time = "2025-09-25T21:32:28.878Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f9/11/ba845c23988798f40e52ba45f34849aa8a1f2d4af4b798588010792ebad6/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", size = 753613, upload-time = "2025-09-25T21:32:30.178Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3d/e0/7966e1a7bfc0a45bf0a7fb6b98ea03fc9b8d84fa7f2229e9659680b69ee3/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", size = 794115, upload-time = "2025-09-25T21:32:31.353Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/de/94/980b50a6531b3019e45ddeada0626d45fa85cbe22300844a7983285bed3b/pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", size = 137427, upload-time = "2025-09-25T21:32:32.58Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/97/c9/39d5b874e8b28845e4ec2202b5da735d0199dbe5b8fb85f91398814a9a46/pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", size = 154090, upload-time = "2025-09-25T21:32:33.659Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/73/e8/2bdf3ca2090f68bb3d75b44da7bbc71843b19c9f2b9cb9b0f4ab7a5a4329/pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", size = 140246, upload-time = "2025-09-25T21:32:34.663Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814, upload-time = "2025-09-25T21:32:35.712Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809, upload-time = "2025-09-25T21:32:36.789Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454, upload-time = "2025-09-25T21:32:37.966Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355, upload-time = "2025-09-25T21:32:39.178Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175, upload-time = "2025-09-25T21:32:40.865Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228, upload-time = "2025-09-25T21:32:42.084Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194, upload-time = "2025-09-25T21:32:43.362Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429, upload-time = "2025-09-25T21:32:57.844Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912, upload-time = "2025-09-25T21:32:59.247Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108, upload-time = "2025-09-25T21:32:44.377Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641, upload-time = "2025-09-25T21:32:45.407Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901, upload-time = "2025-09-25T21:32:48.83Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132, upload-time = "2025-09-25T21:32:50.149Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261, upload-time = "2025-09-25T21:32:51.808Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272, upload-time = "2025-09-25T21:32:52.941Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923, upload-time = "2025-09-25T21:32:54.537Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062, upload-time = "2025-09-25T21:32:55.767Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typing-extensions"
|
||||
version = "4.16.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typing-inspection"
|
||||
version = "0.4.4"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a3/26/b09b8010994eccc3c09092e6b34058f36a460eea2d4c3e8b910c695975a0/typing_inspection-0.4.4.tar.gz", hash = "sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47", size = 76928, upload-time = "2026-08-12T12:37:25.997Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" },
|
||||
]
|
||||
Reference in new issue
Block a user