Compare commits

..
4 Commits
54 changed files with 807 additions and 4599 deletions

No files matched your search

+2
View File
@@ -9,6 +9,8 @@ on:
jobs: jobs:
validate: validate:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container:
image: nixery.dev/shell/coreutils/git/nix/nodejs:latest
steps: steps:
- name: Check out repository - name: Check out repository
uses: actions/checkout@v4 uses: actions/checkout@v4
+1 -4
View File
@@ -6,6 +6,7 @@ backup.zip
.envrc .envrc
.direnv .direnv
.venv .venv
.worktrees/
nixos/instance.nix nixos/instance.nix
# SSL / ACME Certificates & Keys # SSL / ACME Certificates & Keys
@@ -41,7 +42,6 @@ config/homepage/custom.js
Thumbs.db Thumbs.db
.vscode/ .vscode/
.idea/ .idea/
.worktrees/
# Python & Testing Caches # Python & Testing Caches
__pycache__/ __pycache__/
@@ -55,6 +55,3 @@ mutants/
scripts/bootstrap_lldap_users.py scripts/bootstrap_lldap_users.py
scripts/bootstrap_*.py scripts/bootstrap_*.py
!scripts/bootstrap_token.py !scripts/bootstrap_token.py
# Worktrees & Slices
.worktrees/
+8 -15
View File
@@ -1,13 +1,13 @@
# Canopy NixOS Core — Agent Guidelines # Homelab Core — Agent Guidelines
## 1. Project Overview & Architectural Boundaries ## 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. **Homelab Core** defines the declarative NixOS host foundation, shared platform infrastructure services, security boundaries, and the `appctl` operational control plane. Independent application workloads live in `~/Sites/<app>` and integrate through declarative `app.yaml` manifests and workload-scoped Docker Compose files.
### Core vs. `~/Workloads` Ownership ### Core vs. `~/Sites` 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`). - **Core owns**: NixOS host configuration, shared platform services (edge ingress, SSO/LDAP, mail, log/update monitors), platform-level ports and security policy, and orchestration/deployment mechanics.
- **`~/Workloads` owns**: Independently deployed application workloads, workload-specific `docker-compose.yml` topologies, workload intent (`app.yaml`), and `deployments.yaml`. - **`~/Sites` owns**: Independently deployed application workloads, workload-specific `docker-compose.yml` topologies, and workload intent (`app.yaml`).
- **Boundary Rule**: Never hardcode *workload-specific* domains, ports, containers, environment variables, or deployment policies in Core (`scripts/appctl*`, GitOps, or Core `docker-compose.yml`), and never move Core platform services into `~/Workloads`. When ownership is ambiguous, consult [`docs/architecture.md`](docs/architecture.md) before changing the boundary. - **Boundary Rule**: Never hardcode *workload-specific* domains, ports, containers, environment variables, or deployment policies in Core (`scripts/appctl*`, GitOps, or Core `docker-compose.yml`), and never move Core platform services into `~/Sites`. When ownership is ambiguous, consult [`docs/architecture.md`](docs/architecture.md) before changing the boundary.
### Context Discovery Hierarchy ### Context Discovery Hierarchy
Before proposing or implementing changes, establish context in this order: Before proposing or implementing changes, establish context in this order:
@@ -27,7 +27,7 @@ Every implementation step must close with the automated verification gate before
```bash ```bash
# Full verification gate: Ruff + Pyright + Pytest (124+ tests) + nix flake check + NixOS drv eval # Full verification gate: Ruff + Pyright + Pytest (124+ tests) + nix flake check + NixOS drv eval
./scripts/run-tests ./scripts/test
# Targeted fast iteration commands (inside direnv / nix develop, or via .venv) # Targeted fast iteration commands (inside direnv / nix develop, or via .venv)
ruff check . ruff check .
@@ -67,7 +67,7 @@ docker compose config -q
1. **Workload Manifests (`app.yaml`)**: Describe declarative workload identity, routing metadata, and deployment intent only. Never introduce arbitrary command execution, host filesystem paths, privileged flags, or Docker control capabilities into `app.yaml`. 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`)**: 2. **GitOps Trust Boundary (`scripts/gitops_dispatcher.py`)**:
- Webhook admission requires cryptographic authentication (HMAC-SHA256). - 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. - Repository identity and filesystem paths must be resolved strictly through trusted Core configuration (`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`). - 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**: 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`). - `socket-proxy` is the **only** service permitted to mount `/var/run/docker.sock` (strictly `:ro`, read-only API capabilities only; `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`).
@@ -89,10 +89,3 @@ docker compose config -q
- Never run destructive Git commands (`reset --hard`, `restore`, `clean -fd`, `push --force`) without explicit user confirmation. - 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. - 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. - 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).
+11 -12
View File
@@ -1,15 +1,15 @@
# Canopy — NixOS Core (`canopy-homelab/nixos-core`) # Homelab Core
**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. **Homelab Core** is the declarative NixOS host foundation, shared platform infrastructure stack, and `appctl` operational control plane for a self-hosted homelab appliance.
It is designed around a strict two-tier boundary: 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. 1. **Homelab Core (this repository)**: Owns NixOS operating system configuration, edge TLS ingress, SSO/LDAP directory identity, mail routing, read-only Docker socket isolation, and orchestration/deployment mechanics.
2. **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. 2. **Workload Repositories (`~/Sites/<app>`)**: Independently deployed application stacks that integrate with Core through self-describing `app.yaml` manifests and workload-scoped `docker-compose.yml` definitions.
All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime. All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime.
> [!NOTE] > [!NOTE]
> **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. > **Milestone P4 Control Plane Architecture**: Under [Milestone P4 in `ROADMAP.md`](ROADMAP.md), `appctl` operates as an operational control plane daemon service (`homelab-appctl.service`) exposing a unified logical API across a local Unix Domain Socket (`/run/homelab/appctl.sock`) and loopback HTTP (`127.0.0.1:9876`). The thin `appctl` CLI delegates commands to this daemon with automatic `SO_PEERCRED` identity inspection and token-based RBAC. See [`docs/appctl.md`](docs/appctl.md) and [`ROADMAP.md`](ROADMAP.md) for details.
--- ---
@@ -35,7 +35,7 @@ All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_
├───────────────────────────────┤ ├───────────────────────────────┤
│ • Core Services (Homepage, │ │ • Core Services (Homepage, │
│ Dozzle, Stalwart, etc.) │ │ Dozzle, Stalwart, etc.) │
│ • Workload Apps (~/Workloads/*) │ │ • Workload Apps (~/Sites/*) │
└───────────────┬───────────────┘ └───────────────┬───────────────┘
│ (Read-Only API via TCP:2375) │ (Read-Only API via TCP:2375)
▼ ▼
@@ -81,8 +81,8 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran
. .
├── flake.nix # NixOS host configuration, devShell (.venv symlink), and CI checks ├── flake.nix # NixOS host configuration, devShell (.venv symlink), and CI checks
├── docker-compose.yml # Core platform service stack ├── docker-compose.yml # Core platform service stack
├── nixos/ # Declarative NixOS modules, systemd units, SOPS secret wiring & instance.example.nix ├── nixos/ # Declarative NixOS modules, systemd units, and SOPS secret wiring
├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml template) ├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml)
├── scripts/ ├── scripts/
│ ├── appctl # Thin operational CLI delegating to control plane daemon │ ├── appctl # Thin operational CLI delegating to control plane daemon
│ ├── appctl_daemon.py # Async HTTP/UDS daemon server (homelab-appctl.service) │ ├── appctl_daemon.py # Async HTTP/UDS daemon server (homelab-appctl.service)
@@ -95,8 +95,7 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran
│ ├── bootstrap_token.py # Operator Bearer token provisioning helper │ ├── bootstrap_token.py # Operator Bearer token provisioning helper
│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for app.yaml │ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for app.yaml
│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST validation │ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST validation
│ ├── workload_grants.py # Fail-closed Pydantic v2 loader for /etc/homelab/grants.json │ └── test # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks)
│ └── run-tests # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks)
├── tests/ # Unit, structural, and security invariant test suites ├── tests/ # Unit, structural, and security invariant test suites
└── docs/ # Architecture references, operational runbooks, and MADR decisions └── docs/ # Architecture references, operational runbooks, and MADR decisions
``` ```
@@ -111,7 +110,7 @@ Entering the directory via `direnv` (`use flake`) or `nix develop` provisions th
```bash ```bash
# Run full automated verification (Ruff + Pyright + Pytest + nix flake check + NixOS drv eval) # Run full automated verification (Ruff + Pyright + Pytest + nix flake check + NixOS drv eval)
./scripts/run-tests ./scripts/test
# Run individual checks directly # Run individual checks directly
ruff check . ruff check .
@@ -167,7 +166,7 @@ systemctl status dynu-monitor.service
| Document | Scope | | Document | Scope |
| :--- | :--- | | :--- | :--- |
| [**`docs/architecture.md`**](docs/architecture.md) | Runtime layers, network segmentation, and Core / `~/Workloads` boundaries. | | [**`docs/architecture.md`**](docs/architecture.md) | Runtime layers, network segmentation, and Core / `~/Sites` boundaries. |
| [**`docs/decisions/README.md`**](docs/decisions/README.md) | Architecture Decision Records (MADR 4.0) governing platform evolution. | | [**`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. | | [**`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/appctl.md`**](docs/appctl.md) | Current `appctl` CLI commands, resolution hierarchy, and `app.yaml` schema v1.0 contract. |
+6 -7
View File
@@ -1,10 +1,10 @@
# 🗺️ Canopy — NixOS Core & Appctl Engineering Roadmap # 🗺️ Homelab 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)). This document serves as the repository-facing projection of the authoritative **Homelab Architecture Consolidation & Control Plane Roadmap (v6)** and the locked Milestone P4 boundary specification ([`docs/plans/p4-readiness-plan.md`](docs/plans/p4-readiness-plan.md)).
It describes the implementation trajectory and phased engineering milestones for evolving the **Canopy** platform (`canopy-homelab/nixos-core`) around a unified `appctl` Operational Control Plane. It describes the implementation trajectory and phased engineering milestones for transitioning Homelab Core into a unified platform driven by the `appctl` Operational Control Plane.
> **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index ([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)). > **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index ([ADR-0001: 3-Tier Provenance Model](docs/decisions/0001-3tier-architecture-and-provenance.md), [ADR-0002: Operational Control Plane Architecture](docs/decisions/0002-appctl-control-plane-architecture.md), and [ADR-0003: Pydantic v2 Runtime Validation](docs/decisions/0003-pydantic-v2-runtime-validation.md)).
--- ---
@@ -29,7 +29,7 @@ It describes the implementation trajectory and phased engineering milestones for
| **`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). | | **`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). | | **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). | | **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`). | | **Deployment Model** | Direct authoring of `app.yaml` and `docker-compose.yml` in `~/Sites/<app>/`. | Authoritative declarative Git state (`app.yaml` + Compose) managed via CLI, GitOps, or client-gated MCP tools (P6). |
| **GitOps Engine** | 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). | | **GitOps Engine** | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | Unified continuous deployment worker driven by Git webhooks delegating to control plane daemon (P4 baseline consolidated). |
| **Secret Distribution** | Age-encrypted `nixos/secrets.yaml` decrypted by `sops-nix` to tmpfs `/run/secrets/`. | Host secrets remain in `sops-nix`; workload secrets referenced by key and projected via `SecretProvider` (planned in P5). | | **Secret Distribution** | Age-encrypted `nixos/secrets.yaml` decrypted by `sops-nix` to tmpfs `/run/secrets/`. | Host secrets remain in `sops-nix`; workload secrets referenced by key and projected via `SecretProvider` (planned in P5). |
| **Dashboard** | `appctl sync` compiles `config/homepage/services.yaml` from `app.yaml` manifests under `_homepage_sync.lock`. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for management (planned in P7). | | **Dashboard** | `appctl sync` compiles `config/homepage/services.yaml` from `app.yaml` manifests under `_homepage_sync.lock`. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for management (planned in P7). |
@@ -45,7 +45,6 @@ It describes the implementation trajectory and phased engineering milestones for
| **P2** | **GitOps Hardening** | Ingress Security | ✅ **Completed** | Authoritative Core repository registry (`deployments.yaml`), Compose AST security validator, systemd sandboxing. | | **P2** | **GitOps Hardening** | Ingress Security | ✅ **Completed** | Authoritative Core repository registry (`deployments.yaml`), Compose AST security validator, systemd sandboxing. |
| **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0 with Pydantic v2 fail-closed models (`core_manifest.py`), two-axis status inspection, unified `appctl_engine.py`. | | **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0 with Pydantic v2 fail-closed models (`core_manifest.py`), two-axis status inspection, unified `appctl_engine.py`. |
| **P4** | **Control Plane Daemon** | API & Dispatch | ✅ **Completed** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. | | **P4** | **Control Plane Daemon** | API & Dispatch | ✅ **Completed** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. |
| **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. | | **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. | | **P6** | **Homelab MCP Gateway** | Protocol Integration | ⏳ **Planned** | Standardized JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`), client-side human-in-the-loop approvals, deprecation of on-server AI proposal compilers. |
| **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. | | **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. |
@@ -149,5 +148,5 @@ It describes the implementation trajectory and phased engineering milestones for
Progress across milestones is governed by explicit verification criteria: 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. * **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). * **Pre-Merge Validation**: Every commit must pass `./scripts/test` (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. * **Zero Production Regressions**: Platform migrations must include verified pre-flight snapshots, state parity proofs, and documented rollback runbooks.
+3 -3
View File
@@ -1,6 +1,6 @@
# 🛡️ Canopy NixOS Core — Security Controls & Hardening # 🛡️ Homelab Core — Security Controls & Hardening
This document outlines the security controls, container isolation rules, and operational boundaries implemented in **Canopy NixOS Core** (`canopy-homelab/nixos-core`). This document outlines the security controls, container isolation rules, and operational boundaries implemented in **Homelab Core**.
--- ---
@@ -63,7 +63,7 @@ This document outlines the security controls, container isolation rules, and ope
- [x] User identities managed in LLDAP (`users.${HOMELAB_DOMAIN}`). - [x] User identities managed in LLDAP (`users.${HOMELAB_DOMAIN}`).
- [x] `socket-proxy` configured with `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`. - [x] `socket-proxy` configured with `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`.
- [x] Webhook HMAC signature verification active on port 9000. - [x] Webhook HMAC signature verification active on port 9000.
- [x] Invariant test runner (`./scripts/run-tests`) passing on changes. - [x] Invariant test runner (`./scripts/test`) passing on changes.
- [x] `config/letsencrypt/acme.json` permissions set to `0600`. - [x] `config/letsencrypt/acme.json` permissions set to `0600`.
- [x] Host firewall ports restricted to declared services in `nixos/modules/homeserver.nix`. - [x] Host firewall ports restricted to declared services in `nixos/modules/homeserver.nix`.
- [x] Control plane daemon (`homelab-appctl.service`) isolated to UDS (`0660`) and loopback HTTP. - [x] Control plane daemon (`homelab-appctl.service`) isolated to UDS (`0660`) and loopback HTTP.
+2 -2
View File
@@ -13,7 +13,7 @@ authentication_backend:
address: 'ldap://lldap:3890' address: 'ldap://lldap:3890'
timeout: 5s timeout: 5s
start_tls: false start_tls: false
base_dn: '{{ env "LLDAP_LDAP_BASE_DN" }}' base_dn: '{{ env "LLDAP_LDAP_BASE_DN" "dc=example,dc=test" }}'
additional_users_dn: 'ou=people' additional_users_dn: 'ou=people'
users_filter: '(&({username_attribute}={input})(objectClass=person))' users_filter: '(&({username_attribute}={input})(objectClass=person))'
additional_groups_dn: 'ou=groups' additional_groups_dn: 'ou=groups'
@@ -24,7 +24,7 @@ authentication_backend:
display_name: 'displayName' display_name: 'displayName'
mail: 'mail' mail: 'mail'
group_name: 'cn' group_name: 'cn'
user: 'uid=admin,ou=people,{{ env "LLDAP_LDAP_BASE_DN" }}' user: 'uid=admin,ou=people,{{ env "LLDAP_LDAP_BASE_DN" "dc=example,dc=test" }}'
access_control: access_control:
default_policy: deny default_policy: deny
+47 -12
View File
@@ -1,18 +1,53 @@
# Example Repository Identity Registry Template # Core Authoritative Repository Identity Registry
# Live production deployments are configured in ~/Workloads/deployments.yaml # Governs admitted continuous deployment targets for GitOps webhook execution.
# (or overridden via the HOMELAB_DEPLOYMENTS_FILE environment variable).
#
# Owns: repository identity, canonical filesystem path, and aliases. # Owns: repository identity, canonical filesystem path, and aliases.
# Enforces: strict path containment within ~/Workloads (WORKLOADS_DIR). # Enforces: strict path containment within ~/Sites.
schemaVersion: "1.0" schemaVersion: "1.0"
repositories: repositories:
example-app: snappymail:
path: "~/Workloads/example-app" path: "~/Sites/snappymail"
aliases: aliases:
- "example" - "homelab-snappymail"
- "homelab-example" - "mail"
example-docs: - "webmail"
path: "~/Workloads/example-docs" gitea:
path: "~/Sites/homelab-gitea"
aliases: aliases:
- "docs" - "homelab-gitea"
- "git"
jellyfin:
path: "~/Sites/homelab-jellyfin"
aliases:
- "homelab-jellyfin"
- "media"
docs:
path: "~/Sites/homelab-doc2site"
aliases:
- "doc2site"
- "homelab-doc2site"
courses:
path: "~/Sites/courses"
aliases:
- "homelab-courses"
bdinvite:
path: "~/Sites/homelab-bdinvite"
aliases:
- "homelab-bdinvite"
- "birthday"
landing:
path: "~/Sites/homelab-landing"
aliases:
- "homelab-landing"
mermaid:
path: "~/Sites/homelab-mermaid"
aliases:
- "homelab-mermaid"
excalidraw:
path: "~/Sites/homelab-excalidraw"
aliases:
- "homelab-excalidraw"
houston:
path: "~/Sites/homelab-houston"
aliases:
- "homelab-houston"
+2 -9
View File
@@ -3,8 +3,6 @@ services:
image: tecnativa/docker-socket-proxy image: tecnativa/docker-socket-proxy
container_name: socket-proxy container_name: socket-proxy
restart: always restart: always
ports:
- "127.0.0.1:2375:2375"
volumes: volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro - /var/run/docker.sock:/var/run/docker.sock:ro
environment: environment:
@@ -44,7 +42,7 @@ services:
- "80:80" - "80:80"
- "443:443" - "443:443"
environment: environment:
- CF_DNS_API_TOKEN=${CF_DNS_API_TOKEN} - DYNU_API_KEY=${DYNU_API_KEY}
- DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40} - DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40}
command: command:
- "--log.level=INFO" - "--log.level=INFO"
@@ -61,7 +59,7 @@ services:
- "--entrypoints.websecure.http.tls.domains[0].sans=*.${DOMAIN}" - "--entrypoints.websecure.http.tls.domains[0].sans=*.${DOMAIN}"
# SSL Setup # SSL Setup
- "--certificatesresolvers.myresolver.acme.dnschallenge=true" - "--certificatesresolvers.myresolver.acme.dnschallenge=true"
- "--certificatesresolvers.myresolver.acme.dnschallenge.provider=cloudflare" - "--certificatesresolvers.myresolver.acme.dnschallenge.provider=dynu"
- "--certificatesresolvers.myresolver.acme.email=${ACME_EMAIL}" - "--certificatesresolvers.myresolver.acme.email=${ACME_EMAIL}"
- "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json" - "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"
volumes: volumes:
@@ -81,11 +79,6 @@ services:
- "traefik.http.middlewares.authelia-auth.forwardauth.trustForwardHeader=true" - "traefik.http.middlewares.authelia-auth.forwardauth.trustForwardHeader=true"
- "traefik.http.middlewares.authelia-auth.forwardauth.authResponseHeaders=Remote-User,Remote-Groups,Remote-Email,Remote-Name" - "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) # Dashboard - Public (HTTPS)
- "traefik.http.routers.traefik-dash.rule=Host(`traefik.${DOMAIN}`)" - "traefik.http.routers.traefik-dash.rule=Host(`traefik.${DOMAIN}`)"
- "traefik.http.routers.traefik-dash.entrypoints=websecure" - "traefik.http.routers.traefik-dash.entrypoints=websecure"
+12 -12
View File
@@ -14,7 +14,7 @@ To understand how the system is organized, three architectural dimensions are di
### A. Ownership Boundary ### A. Ownership Boundary
* **Core (`~/Core`) owns**: NixOS host configuration, shared platform services, edge ingress, identity boundaries, secrets distribution, and deployment orchestration mechanics. * **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>/`). * **Workload Plane (`~/Sites`) owns**: Independent application deployments, workload-specific Docker Compose files, declarative `app.yaml` manifests, and workload-scoped runtime state (`~/var/lib/homelab/<app>/`).
### B. Four Runtime Layers ### B. Four Runtime Layers
The runtime environment consists of four functional layers: The runtime environment consists of four functional layers:
@@ -35,7 +35,7 @@ The runtime environment consists of four functional layers:
│ │
▼ ▼
┌────────────────────────────────────────────────────────────────────────┐ ┌────────────────────────────────────────────────────────────────────────┐
│ 3. WORKLOAD PLANE (~/Workloads) │ │ 3. WORKLOAD PLANE (~/Sites) │
│ Autonomous Workload Repositories (SnappyMail, Docs, Gitea, etc.) │ │ Autonomous Workload Repositories (SnappyMail, Docs, Gitea, etc.) │
│ Declarative app.yaml Manifests & Compose Stacks │ │ Declarative app.yaml Manifests & Compose Stacks │
└───────────────────────────────────┬────────────────────────────────────┘ └───────────────────────────────────┬────────────────────────────────────┘
@@ -51,8 +51,8 @@ The runtime environment consists of four functional layers:
### C. Cross-Cutting Orchestration ### C. Cross-Cutting Orchestration
Orchestration coordinates operations across the runtime layers: 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. * **`appctl` Operational Control Plane Daemon (`homelab-appctl.service`, `scripts/appctl_daemon.py`, `scripts/appctl_router.py`)**: Centralized control plane running under isolated service identity `homelab-appctl:homelab-operators`. Exposes `POST /v1/operations` and `GET /v1/health` over `/run/homelab/appctl.sock` (mode `0660`) and `127.0.0.1:9001`, enforcing SHA-256 Bearer token authentication, 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`), per-target `flock` serialization, fail-closed append-only audit logging (`/var/log/homelab/appctl/audit.jsonl`), Pydantic v2 `app.yaml` validation, Compose AST security checks, and pure-Python `.env` assembly.
* **GitOps Webhook Dispatcher (`scripts/gitops_dispatcher.py`)**: Governed by the `homelab-gitops.service` systemd unit, it receives webhooks on port 9000, verifies HMAC-SHA256 signatures, enforces the `~/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. * **GitOps Webhook Dispatcher (`scripts/gitops_dispatcher.py`)**: Governed by the `homelab-gitops.service` systemd unit, it receives webhooks on port 9000, verifies HMAC-SHA256 signatures, enforces the `config/deployments.yaml` allowlist, and delegates serialized `workload.update` execution to `homelab-appctl.service` over `/run/homelab/appctl.sock` using its `homelab-operator` Bearer token.
--- ---
@@ -70,7 +70,7 @@ Orchestration coordinates operations across the runtime layers:
- Mounted read-only: `/var/run/docker.sock:/var/run/docker.sock:ro`. - 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`. - 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`. - 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`. * **Network**: Attached exclusively to `socket-net`. Application containers in `~/Sites` are never attached to `socket-net`.
### C. Identity & Directory Services (`lldap` & `authelia`) ### 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`. * **`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`.
@@ -84,10 +84,10 @@ Orchestration coordinates operations across the runtime layers:
- WebAdmin & JMAP endpoint accessible at `smtp.${HOMELAB_DOMAIN}` via Traefik. - WebAdmin & JMAP endpoint accessible at `smtp.${HOMELAB_DOMAIN}` via Traefik.
- Authenticates users against the LLDAP directory. - Authenticates users against the LLDAP directory.
- Outbound mail relay configured to route through an external smart host (Brevo SMTP relay via SOPS secrets). - 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/`.)* - *(Note: User-facing webmail, such as SnappyMail, runs as an independent Class B workload in `~/Sites/snappymail` with isolated state under `~/var/lib/homelab/snappymail/`.)*
### E. Portal & Observability (`homepage`, `dozzle`) ### E. Portal & Observability (`homepage`, `dozzle`)
* **`homepage`**: Service dashboard at `dashboard.${HOMELAB_DOMAIN}`. Synchronized from `app.yaml` manifests in `~/Workloads` by `appctl sync`. * **`homepage`**: Service dashboard at `dashboard.${HOMELAB_DOMAIN}`. Synchronized from `app.yaml` manifests in `~/Sites` by `appctl sync`.
* **`dozzle`**: Real-time container log viewer at `logs.${HOMELAB_DOMAIN}`, connecting read-only through `socket-proxy`. * **`dozzle`**: Real-time container log viewer at `logs.${HOMELAB_DOMAIN}`, connecting read-only through `socket-proxy`.
### F. Host Foundation & Daemons ### F. Host Foundation & Daemons
@@ -113,7 +113,7 @@ Homelab Core configures two isolated Docker bridge networks:
│ │ • traefik (router) • authelia (sso) │ │ │ │ • traefik (router) • authelia (sso) │ │
│ │ • lldap (directory) • stalwart (mail) │ │ │ │ • lldap (directory) • stalwart (mail) │ │
│ │ • homepage (dashboard) • dozzle (logs) │ │ │ │ • homepage (dashboard) • dozzle (logs) │ │
│ │ • All User Workloads (~/Workloads/*) │ │ │ │ • All User Workloads (~/Sites/*) │ │
│ └──────────────────────────────┬───────────────────────────────┘ │ │ └──────────────────────────────┬───────────────────────────────┘ │
│ │ │ │ │ │
│ ┌──────────────────────────────┴───────────────────────────────┐ │ │ ┌──────────────────────────────┴───────────────────────────────┐ │
@@ -129,7 +129,7 @@ Homelab Core configures two isolated Docker bridge networks:
└────────────────────────────────────────────────────────────────────────┘ └────────────────────────────────────────────────────────────────────────┘
``` ```
1. **`proxy-net`**: Ingress routing network. Traefik directs traffic to backend service containers on this network. Workload containers in `~/Workloads` join `proxy-net`. 1. **`proxy-net`**: Ingress routing network. Traefik directs traffic to backend service containers on this network. Workload containers in `~/Sites` join `proxy-net`.
2. **`socket-net`**: Isolated Docker socket proxy network. Only Core infrastructure components needing read-only container metadata join this network. 2. **`socket-net`**: Isolated Docker socket proxy network. Only Core infrastructure components needing read-only container metadata join this network.
--- ---
@@ -151,13 +151,13 @@ The host firewall is configured in `nixos/modules/homeserver.nix`:
| **993** | TCP | Stalwart | IMAPS (Secure IMAP) | Public | | **993** | TCP | Stalwart | IMAPS (Secure IMAP) | Public |
| **4190** | TCP | Stalwart | ManageSieve (Mail Filters) | 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`. Application containers in `~/Sites` do not bind host ports directly; they receive traffic routed by Traefik over `proxy-net`.
--- ---
## 5. Workload Integration Model ## 5. Workload Integration Model
Workloads in `~/Workloads/<app>` integrate with Core through three mechanisms: Workloads in `~/Sites/<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. 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`)**: 2. **Compose Configuration (`docker-compose.yml`)**:
@@ -177,4 +177,4 @@ Workloads in `~/Workloads/<app>` integrate with Core through three mechanisms:
# If auth is required: # If auth is required:
- "traefik.http.routers.${CONTAINER_NAME}.middlewares=authelia-auth@docker" - "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>/`. 3. **Execution & State Isolation**: `appctl` and `gitops_dispatcher.py` validate the manifest and Compose AST (blocking privilege escalation and out-of-bounds mounts) before supplying runtime environment variables (`SERVICE_DOMAIN`, `CONTAINER_NAME`, and projected secrets). Persistent mutable workload data resides strictly under `~/var/lib/homelab/<app>/`.
@@ -1,91 +0,0 @@
---
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)
@@ -1,101 +0,0 @@
---
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).
-20
View File
@@ -10,8 +10,6 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
| Decision Record | Status | Date | Scope & One-Line Purpose | | Decision Record | Status | Date | Scope & One-Line Purpose |
| :--- | :--- | :--- | :--- | | :--- | :--- | :--- | :--- |
| [**ADR-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-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-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. | | [**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. |
@@ -20,24 +18,6 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
## 🧭 Summaries of Governing Decisions ## 🧭 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) ### [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md)
* **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md) * **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md)
* **Status**: `accepted` (Active) * **Status**: `accepted` (Active)
+4 -4
View File
@@ -27,7 +27,7 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
▼ ▼
┌───────────────────────────────────────────────┐ ┌───────────────────────────────────────────────┐
│ 3. Authoritative Registry Resolution │ │ 3. Authoritative Registry Resolution │
│ Maps names via ~/Workloads/deployments.yaml│ │ Maps names via Core/config/deployments.yaml│
│ Fails closed; zero dynamic discovery on host│ │ Fails closed; zero dynamic discovery on host│
└───────────────────────┬───────────────────────┘ └───────────────────────┬───────────────────────┘
│ │
@@ -74,7 +74,7 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
### C. Authoritative Repository Registry (`deployments.yaml`) ### C. Authoritative Repository Registry (`deployments.yaml`)
* Webhook payloads identify targets strictly by logical name (e.g. `docs`, `homelab-docs`), never by raw filesystem path. * 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. * `Core/config/deployments.yaml` 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`. * **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. * **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. * **Input Validation**: Names must match `^[a-zA-Z0-9][a-zA-Z0-9._-]*$`. Slashes, backslashes, and path traversal sequences (`..`) are rejected.
@@ -175,11 +175,11 @@ The continuous deployment engine operates strictly **downstream** of CI verifica
``` ```
[Developer / PR] ──► [Gitea Actions CI] ──► [Merge to main] ──► [Gitea Webhook] ──► [homelab-gitops] ──► [Deploy] [Developer / PR] ──► [Gitea Actions CI] ──► [Merge to main] ──► [Gitea Webhook] ──► [homelab-gitops] ──► [Deploy]
(:host act_runner) (Host Daemon) (Ephemeral Container) (Host Daemon)
``` ```
1. **Pre-Merge CI Invariant (`.gitea/workflows/ci.yaml`)**: 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. - Executes inside containerized `act_runner` environments using **pre-baked toolchain images** (`container: nixery.dev/shell/coreutils/git/nix/nodejs:latest`).
- Runs hermetic validation (`nix flake check`, `pytest`, `ruff`) with Git safe directory enforcement. - Runs hermetic validation (`nix flake check`, `pytest`, `ruff`) with Git safe directory enforcement.
- Prevents broken code, misconfigured flakes, or regression bugs from entering `main`. - Prevents broken code, misconfigured flakes, or regression bugs from entering `main`.
2. **Post-Merge CD Execution (`homelab-gitops.service`)**: 2. **Post-Merge CD Execution (`homelab-gitops.service`)**:
+19 -145
View File
@@ -109,7 +109,7 @@ tail -n 20 /var/lib/dynu/ip_history.jsonl
## 3. Workload Lifecycle Operations (`appctl`) ## 3. Workload Lifecycle Operations (`appctl`)
Applications in `~/Workloads` are managed with the `appctl` CLI. Applications in `~/Sites` are managed with the `appctl` CLI.
### Inspection & Status ### Inspection & Status
```bash ```bash
@@ -145,8 +145,9 @@ appctl restart docs
appctl restart traefik appctl restart traefik
appctl restart authelia appctl restart authelia
# Sequential stack update for independent Workloads (clean tree check -> git pull -> compose pull -> up -> sync) # Sequential stack update (clean working tree check -> git pull -> compose pull -> up -> sync)
appctl update docs appctl update docs
appctl update core
# Stream live container logs # Stream live container logs
appctl logs docs appctl logs docs
@@ -156,37 +157,6 @@ appctl logs -f stalwart
appctl config docs appctl config docs
``` ```
### Workload vs. Core Update Policy
Homelab enforces a strict architectural boundary between independent application workloads (`~/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) ## 4. User Identity & Access Management (LLDAP & Authelia)
@@ -467,51 +437,7 @@ Activate the declarative configuration under the `operator` profile:
chmod 600 /home/operator/Core/nixos/instance.nix chmod 600 /home/operator/Core/nixos/instance.nix
``` ```
2. **Bootstrap appctl control plane tokens (CR-SO-08)**: 2. **Rebuild NixOS host configuration**:
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: Execute the rebuild from the new canonical Core path using `--impure` and the `path:` scheme to import the untracked instance profile:
```bash ```bash
cd /home/operator/Core cd /home/operator/Core
@@ -519,10 +445,10 @@ Activate the declarative configuration under the `operator` profile:
``` ```
> [!NOTE] > [!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`. > 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).
4. **Restart platform services**: 3. **Restart platform services**:
Restart the Core Compose stack and control plane services to consume updated paths and secrets: Restart the Core Compose stack and control plane services to consume updated paths:
```bash ```bash
sudo systemctl restart homeserver-core sudo systemctl restart homeserver-core
sudo systemctl restart homelab-appctl sudo systemctl restart homelab-appctl
@@ -541,26 +467,22 @@ Validate system health and operational readiness under the `operator` identity:
sudo -u operator git -C /home/operator/Sites/<any-workload> status sudo -u operator git -C /home/operator/Sites/<any-workload> status
``` ```
2. **Verify SOPS secrets and tokens projection**: 2. **Verify appctl control plane status**:
Ensure `/run/secrets/appctl/tokens.json` is readable by `homelab-appctl` (mode `0400`, owned by `homelab-appctl:homelab-operators`) and contains valid descriptors: Execute CLI inspection using both UDS peercred authentication and token authentication:
```bash
# Peercred UDS inspection
sudo -u operator appctl list --core
# Workload health check
sudo -u operator appctl status
```
3. **Verify SOPS secrets and tokens**:
Ensure `/run/secrets/appctl/tokens.json` is readable by `homelab-appctl` and valid tokens exist for operator administration:
```bash ```bash
sudo ls -l /run/secrets/appctl/tokens.json 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**: 4. **Verify container reachability & proxy routing**:
Check that external endpoints and internal reverse proxies resolve: Check that external endpoints and internal reverse proxies resolve:
```bash ```bash
@@ -587,51 +509,3 @@ If unexpected service degradation occurs during the cutover:
3. **Log rollback reason**: 3. **Log rollback reason**:
Record the diagnostic failure logs in `journalctl -xe` and investigate before attempting another cutover window. 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/*`.
+1 -1
View File
@@ -391,4 +391,4 @@ Before marking Milestone P4 complete, the following automated regression suite m
| **Truthful Error Reporting** | `test_execution_failure_audit`: Failing or timing-out Docker/Git subprocess returns `500 ERR_EXECUTION_FAILED` and records `phase: FAILED` in `audit.jsonl`. | Reject PR | | **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 | | **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 | | **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 | | **Existing Invariant Regression** | Run `./scripts/test`: All 124 existing unit, security, structural, Ruff, Pyright, and Nix flake sandbox checks pass with 0 regressions. | Block Merge |
+1 -29
View File
@@ -113,34 +113,6 @@ docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
2. Authenticate using `admin` and the password configured in `nixos/secrets.yaml` (`lldap/admin_password`). 2. Authenticate using `admin` and the password configured in `nixos/secrets.yaml` (`lldap/admin_password`).
3. Create standard user accounts and assign them to required groups. 3. Create standard user accounts and assign them to required groups.
### 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 ## 3. Onboarding a New Application Workload
@@ -235,7 +207,7 @@ Before committing changes to Homelab Core, run the repository test runner:
```bash ```bash
cd ~/Core cd ~/Core
./scripts/run-tests ./scripts/test
``` ```
This runs: This runs:
* Code formatting and lint checks (`ruff`). * Code formatting and lint checks (`ruff`).
Generated
+7 -7
View File
@@ -2,11 +2,11 @@
"nodes": { "nodes": {
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1795234589, "lastModified": 1792773339,
"narHash": "sha256-pAEASBc6wof0S58XcSEdZoQ2iFQDkCnZwH+wFLrkd1Q=", "narHash": "sha256-17eNBI5Khe4JZaRkL5hRGPWf8MZ6qv+bWAr4V8YeKBw=",
"rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f", "rev": "3ec636362e1816bc2f0888fa0fa2c69f1bc9e504",
"type": "tarball", "type": "tarball",
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1125864.2786a2a72088/nixexprs.tar.zst" "url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1100280.3ec636362e18/nixexprs.tar.zst"
}, },
"original": { "original": {
"type": "tarball", "type": "tarball",
@@ -26,11 +26,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1794866654, "lastModified": 1792056300,
"narHash": "sha256-Y28AMB8lyKjASdJ0BVsR2AqR1cUsVuo8RVVpzHoECho=", "narHash": "sha256-YU1LjDe1o2Ymg5zEiCHbmMXLkDCtxHQRiVqZ3nC5GGk=",
"owner": "Mic92", "owner": "Mic92",
"repo": "sops-nix", "repo": "sops-nix",
"rev": "7c637afdccdf9bcf35c4a2d67b58a77c1fd843a4", "rev": "44931708c62937c2b1bf7953902989fa5bb9ee1b",
"type": "github" "type": "github"
}, },
"original": { "original": {
+5 -34
View File
@@ -10,9 +10,10 @@
./hardware-configuration.nix # Server-specific disk and CPU configuration ./hardware-configuration.nix # Server-specific disk and CPU configuration
./modules/homeserver.nix # Core services: systemd units, Authelia, SOPS secrets ./modules/homeserver.nix # Core services: systemd units, Authelia, SOPS secrets
./modules/traefik-deployments.nix # Traefik deployment secrets and env templates ./modules/traefik-deployments.nix # Traefik deployment secrets and env templates
./modules/dynu.nix # Dynu DDNS smart IP monitor service
./modules/shell.nix # Declarative bash environment for the server ./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 ./instance.nix) ./instance.nix
++ lib.optional (!(builtins.pathExists /etc/nixos/homelab-instance.nix) && builtins.pathExists ./instance.nix) ./instance.nix; ++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix;
# ── Homelab platform settings ──────────────────────────────────────────────── # ── Homelab platform settings ────────────────────────────────────────────────
homelab.operatorUser = "operator"; homelab.operatorUser = "operator";
@@ -22,8 +23,6 @@
enable = true; enable = true;
config.safe.directory = [ config.safe.directory = [
"/home/${config.homelab.operatorUser}/Core" "/home/${config.homelab.operatorUser}/Core"
"/home/${config.homelab.operatorUser}/Workloads"
"/home/${config.homelab.operatorUser}/Workloads/*"
"/home/${config.homelab.operatorUser}/Sites/*" "/home/${config.homelab.operatorUser}/Sites/*"
]; ];
}; };
@@ -67,7 +66,7 @@
networking.hostName = "server"; networking.hostName = "server";
networking.networkmanager.enable = true; networking.networkmanager.enable = true;
# ── User accounts ──────────────────────────────────────────────────────────── # ── User account ─────────────────────────────────────────────────────────────
users.users.${config.homelab.operatorUser} = { users.users.${config.homelab.operatorUser} = {
isNormalUser = true; isNormalUser = true;
description = "Primary server administrator"; description = "Primary server administrator";
@@ -82,39 +81,11 @@
]; ];
}; };
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 ────────────────────────────────────────────────────────────────────── # ── SSH ──────────────────────────────────────────────────────────────────────
services.openssh = let services.openssh = {
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; enable = true;
ports = [ 22 ]; ports = [ 22 ];
settings.PermitRootLogin = "no"; 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 ───────────────────────────────────────────────────────────
-20
View File
@@ -1,20 +0,0 @@
# 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" ];
# };
};
}
+88
View File
@@ -0,0 +1,88 @@
# 🌐 Dynu DDNS IP Monitor & Updater Service
# This NixOS module configures a smart, local-first IP change detector.
# It queries public IP providers, maintains a history log of WAN IP rotations,
# and triggers ddclient only when an actual change is detected to prevent API rate limits.
{ config, lib, pkgs, ... }:
let
# Declaratively read the external Python script into the Nix store at evaluation time
ipMonitorScript = pkgs.writers.writePython3Bin "dynu-ip-monitor" { } (builtins.readFile ../scripts/monitor.py);
in
{
# Define the keys to decrypt
sops.secrets."dynu/user" = { };
sops.secrets."dynu/domain" = { };
sops.secrets."dynu/password" = { };
sops.secrets."system/pdf_decrypt_password" = {
owner = 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" ];
};
}
+15 -105
View File
@@ -23,31 +23,8 @@
}; };
sitesDir = lib.mkOption { sitesDir = lib.mkOption {
type = lib.types.str; type = lib.types.str;
default = "/home/${config.homelab.operatorUser}/Workloads"; default = "/home/${config.homelab.operatorUser}/Sites";
description = "Path to Workloads directory (legacy option name: sitesDir)"; description = "Path to Sites directory";
};
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.";
}; };
}; };
@@ -55,62 +32,9 @@
domainParts = lib.splitString "." config.homelab.domain; domainParts = lib.splitString "." config.homelab.domain;
ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts); ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts);
in { 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 # Define the keys to decrypt from secrets.yaml
sops.secrets = (lib.genAttrs [ sops.secrets = (lib.genAttrs [
"cloudflare/dns_api_token" "dynu/api_key"
"traefik/acme_email" "traefik/acme_email"
"authelia/session_secret" "authelia/session_secret"
"authelia/storage_encryption_key" "authelia/storage_encryption_key"
@@ -139,13 +63,11 @@
# Generate the unified environment file at runtime in /run/secrets/homeserver.env # Generate the unified environment file at runtime in /run/secrets/homeserver.env
sops.templates."homeserver.env" = { sops.templates."homeserver.env" = {
owner = config.homelab.operatorUser; owner = config.homelab.operatorUser;
group = "homelab-operators";
mode = "0440";
content = lib.generators.toKeyValue {} { content = lib.generators.toKeyValue {} {
DOMAIN = config.homelab.domain; DOMAIN = config.homelab.domain;
LLDAP_LDAP_BASE_DN = ldapBaseDn; LLDAP_LDAP_BASE_DN = ldapBaseDn;
DOCKER_API_VERSION = "1.40"; DOCKER_API_VERSION = "1.40";
CF_DNS_API_TOKEN = config.sops.placeholder."cloudflare/dns_api_token"; DYNU_API_KEY = config.sops.placeholder."dynu/api_key";
ACME_EMAIL = config.sops.placeholder."traefik/acme_email"; ACME_EMAIL = config.sops.placeholder."traefik/acme_email";
AUTHELIA_SESSION_SECRET = config.sops.placeholder."authelia/session_secret"; AUTHELIA_SESSION_SECRET = config.sops.placeholder."authelia/session_secret";
AUTHELIA_STORAGE_ENCRYPTION_KEY = config.sops.placeholder."authelia/storage_encryption_key"; AUTHELIA_STORAGE_ENCRYPTION_KEY = config.sops.placeholder."authelia/storage_encryption_key";
@@ -181,8 +103,8 @@
# Declarative Dynamic GitOps Webhook Service (Internal Port 9000) # Declarative Dynamic GitOps Webhook Service (Internal Port 9000)
systemd.services.homelab-gitops = { systemd.services.homelab-gitops = {
description = "Dynamic Homelab GitOps Webhook Dispatcher"; description = "Dynamic Homelab GitOps Webhook Dispatcher";
after = [ "network-online.target" "docker.service" "homelab-appctl.service" ]; after = [ "network-online.target" "docker.service" ];
wants = [ "network-online.target" "homelab-appctl.service" ]; wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
path = with pkgs; [ path = with pkgs; [
@@ -199,11 +121,6 @@
GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path; GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path;
GITOPS_APPCTL_TOKEN_FILE = config.sops.secrets."gitops/appctl_token".path; GITOPS_APPCTL_TOKEN_FILE = config.sops.secrets."gitops/appctl_token".path;
DOCKER_CONFIG = "/home/${config.homelab.operatorUser}/.local/state/homelab/docker"; 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 = { serviceConfig = {
@@ -237,7 +154,7 @@
ReadWritePaths = [ ReadWritePaths = [
config.homelab.sitesDir config.homelab.sitesDir
"/home/${config.homelab.operatorUser}/.local/state/homelab" "/home/${config.homelab.operatorUser}/.local/state/homelab"
"-/run/homelab" "/run/homelab"
]; ];
}; };
}; };
@@ -278,13 +195,10 @@
APPCTL_AUDIT_LOG = "/var/log/homelab/appctl/audit.jsonl"; APPCTL_AUDIT_LOG = "/var/log/homelab/appctl/audit.jsonl";
APPCTL_LOCK_DIR = "/var/lib/homelab/appctl/locks"; APPCTL_LOCK_DIR = "/var/lib/homelab/appctl/locks";
APPCTL_TOKENS_FILE = config.sops.secrets."appctl/tokens_json".path; APPCTL_TOKENS_FILE = config.sops.secrets."appctl/tokens_json".path;
WORKLOADS_DIR = config.homelab.sitesDir;
SITES_DIR = config.homelab.sitesDir; SITES_DIR = config.homelab.sitesDir;
CORE_DIR = config.homelab.coreDir; 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_CONFIG_DIR = "/home/${config.homelab.operatorUser}/.config/homelab";
HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.sitesDir}/deployments.yaml"; HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.coreDir}/config/deployments.yaml";
HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";
}; };
serviceConfig = { serviceConfig = {
@@ -312,11 +226,11 @@
ProtectControlGroups = true; ProtectControlGroups = true;
ReadWritePaths = [ ReadWritePaths = [
config.homelab.sitesDir config.homelab.sitesDir
"-/home/${config.homelab.operatorUser}/var/lib/homelab" "/home/${config.homelab.operatorUser}/var/lib/homelab"
"-${config.homelab.coreDir}/config/homepage" "${config.homelab.coreDir}/config/homepage"
"/var/log/homelab/appctl" "/var/log/homelab/appctl"
"-/var/lib/homelab/appctl" "/var/lib/homelab/appctl"
"-/run/homelab" "/run/homelab"
]; ];
}; };
}; };
@@ -326,15 +240,11 @@
"d ${config.homelab.coreDir}/config/stalwart/data 0777 ${config.homelab.operatorUser} users -" "d ${config.homelab.coreDir}/config/stalwart/data 0777 ${config.homelab.operatorUser} users -"
"d ${config.homelab.coreDir}/config/stalwart/etc 0777 ${config.homelab.operatorUser} users -" "d ${config.homelab.coreDir}/config/stalwart/etc 0777 ${config.homelab.operatorUser} users -"
"d ${config.homelab.sitesDir} 0755 ${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/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}/.local/state/homelab/docker 0755 ${config.homelab.operatorUser} users -"
"d /home/${config.homelab.operatorUser}/var/lib/homelab 0755 ${config.homelab.operatorUser} users -" # POSIX ACLs granting homelab-appctl traverse and access to operator sites & homepage config
# 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"
"a+ /home/${config.homelab.operatorUser} - - - - u:homelab-appctl:x,g:homelab-operators:x,m::rx" "a+ ${config.homelab.coreDir} - - - - u:homelab-appctl:x"
"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+ ${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+ /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" "A+ ${config.homelab.coreDir}/config/homepage - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
+1 -4
View File
@@ -3,12 +3,9 @@
# This replaces the laptop-inherited ~/.bashrc with a clean, server-appropriate profile. # This replaces the laptop-inherited ~/.bashrc with a clean, server-appropriate profile.
# Delivered via /etc/bashrc — no Home Manager required. # Delivered via /etc/bashrc — no Home Manager required.
{ config, pkgs, ... }: { pkgs, ... }:
{ {
sops.secrets."system/pdf_decrypt_password" = {
owner = config.homelab.operatorUser;
};
# ── Shell-integrated programs ───────────────────────────────────────────────── # ── Shell-integrated programs ─────────────────────────────────────────────────
# These handle both installation and bash hook injection automatically # These handle both installation and bash hook injection automatically
programs.zoxide.enable = true; # smart cd with bash init wired into /etc/bashrc programs.zoxide.enable = true; # smart cd with bash init wired into /etc/bashrc
-2
View File
@@ -20,8 +20,6 @@
# Generate the unified environment file at runtime in /run/secrets/traefik-deployments.env # Generate the unified environment file at runtime in /run/secrets/traefik-deployments.env
sops.templates."traefik-deployments.env" = { sops.templates."traefik-deployments.env" = {
owner = config.homelab.operatorUser; owner = config.homelab.operatorUser;
group = "homelab-operators";
mode = "0440";
content = lib.generators.toKeyValue {} { content = lib.generators.toKeyValue {} {
# --- Core / Infrastructure Settings --- # --- Core / Infrastructure Settings ---
PROXY_NETWORK = "proxy-net"; PROXY_NETWORK = "proxy-net";
-92
View File
@@ -1,92 +0,0 @@
#!/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
+12
View File
@@ -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@
+193
View File
@@ -0,0 +1,193 @@
"""
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()
+2 -7
View File
@@ -38,11 +38,6 @@ lldap:
brevo: brevo:
smtp_login: ENC[AES256_GCM,data:zfqKsAtoAOWCrSqx38sknwcJZT2m8W2J,iv:tMwTNDf+2CE3/8rKqWTWLl5Zp4LUVNSFV90QN94VXxo=,tag:XYXz9w3oIa0qkcfjCcgcYg==,type:str] smtp_login: ENC[AES256_GCM,data:zfqKsAtoAOWCrSqx38sknwcJZT2m8W2J,iv:tMwTNDf+2CE3/8rKqWTWLl5Zp4LUVNSFV90QN94VXxo=,tag:XYXz9w3oIa0qkcfjCcgcYg==,type:str]
smtp_key: ENC[AES256_GCM,data:YulXyaVF/sLWE9x12yxdBAj9KMbfP/CK/7FS3XkYO8sCj3GWgPbNoSaUT/9quLWHPtCsBxxdLeLoDNa1jE2WRyHP1W+Ioyyx5sAzdzevzHIBmfP+fdw0rKhe,iv:QT0HfzNPsTqXlN3IC/+bBzJfUzN9YkXYiv/3uqkXHBw=,tag:vBetkZPDYoh0Yy3BpMT9BQ==,type:str] smtp_key: ENC[AES256_GCM,data:YulXyaVF/sLWE9x12yxdBAj9KMbfP/CK/7FS3XkYO8sCj3GWgPbNoSaUT/9quLWHPtCsBxxdLeLoDNa1jE2WRyHP1W+Ioyyx5sAzdzevzHIBmfP+fdw0rKhe,iv:QT0HfzNPsTqXlN3IC/+bBzJfUzN9YkXYiv/3uqkXHBw=,tag:vBetkZPDYoh0Yy3BpMT9BQ==,type:str]
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: 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] tokens_json: ENC[AES256_GCM,data:O2vsiMMcZjsduFSRen1MnnckdRYK45aPH40EhX42h1WUwf62Nm58PV5BQJOgJ97AH3hOH97mzg1tjL0C1oV/epXMaypRWY9AGLS00CfzD2sgdM5Wx7VKbfGggFnGqgd7veaCA+pxUC0uTk/Dq2Cz/uhXhLX1wVjafX0OAqS6fxO+L9Oza3+RBtKgx2xX0AKW+KSZQUM1nvNW8R/Eyvnqvw2OSb2FdKN1CKhlVWhCZiaxTe8617BqGhJDL9pu4lfn0m+tdIwvluI3h8cmKuT6dzd01Jxr0EHBY/+mZZ/WQoNhIy4QulFpKiMudiT+WGzUm+UT4mYBoGwzQCVV8MD7W1r84mkbCkLc/HpWG08TqK4tpAdtLgYK3Zslr1+lmboWyJ6WcinmxkhUexhj+gTyfXYmVSB3fF8PIeyQINGB3rLvmpZ7DDMzYa1ICgFbJ6zmYa54TXRDLGzLD09koeDp9FhXNKPvuwz2x4uwWDDUfU8wwTkGbw==,iv:FJpB+WZiE4PKUhIuwBWIB/TLtifwCzGRMtbMx7x6ly8=,tag:NZQXYFnVBqbOONl+Yh3tuA==,type:str]
sops: sops:
@@ -65,7 +60,7 @@ sops:
yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A== yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A==
-----END AGE ENCRYPTED FILE----- -----END AGE ENCRYPTED FILE-----
recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg
lastmodified: "2026-11-23T20:45:18Z" lastmodified: "2026-10-19T20:40:13Z"
mac: ENC[AES256_GCM,data:3Rm8olJtCErH+KGisvQENqwFhMF3Y9acXjrBHC7ot3ThRzT8Yo3X1RyxKXzyYzB6Yy2G3ua9yUtgQjydXgjQR1b6KY6ERmyu6H2S1IF/Ps4grYVZ6xEhJMDtjNKDvhtjhRM61eFByeYzJeHWD6K8dsxDcWUI2GKRRH7U8iG95Fo=,iv:/IY6iKamEEoi5vVLRGOmmPpyJte3amLfjVhYIDbMdBE=,tag:gT3RSrnwl0TH14LJvbiPlg==,type:str] mac: ENC[AES256_GCM,data:rui8qF/l3ucq8vrZniHtGjlLGPq7ihteKK7rcaz2prRvmo7nHd97Axt7oElo050HFuoaJB1/coVPzYcAUozjZNsNx3TQYABGFWvxF5Y0SxjdLc1rqAjGR/j2Cf5wmvF9H457KBHfij2gQHY/ZZ2Nyd9aEpAKSFtKkn3aYkmTvW4=,iv:RdQWUpkahFEYEhd9kTpPG0GMJaHr7b+wbhf5MBhk6mo=,tag:1E3mcFk/EMnJNNxuZ6AXAw==,type:str]
unencrypted_suffix: _unencrypted unencrypted_suffix: _unencrypted
version: 3.13.3 version: 3.13.3
+3 -7
View File
@@ -28,7 +28,7 @@ DEFAULT_AUDIT_LOG = Path("/var/log/homelab/appctl/audit.jsonl")
DEFAULT_LOCK_DIR = Path("/var/lib/homelab/appctl/locks") DEFAULT_LOCK_DIR = Path("/var/lib/homelab/appctl/locks")
REDACT_KEY_PATTERNS = re.compile( REDACT_KEY_PATTERNS = re.compile(
r"^(?:.*_)?(?:KEY|SECRET|PASSWORD|TOKEN|PASS|HASH)$", re.IGNORECASE r".*(?:_KEY|_SECRET|_PASSWORD|_TOKEN|_PASS|_HASH)$", re.IGNORECASE
) )
@@ -105,9 +105,7 @@ class ConcurrentMutationError(Exception):
def __init__(self, target: str, message: str | None = None) -> None: def __init__(self, target: str, message: str | None = None) -> None:
self.target = target self.target = target
msg = ( msg = message or f"Operation on target '{target}' is locked by a concurrent task."
message or f"Operation on target '{target}' is locked by a concurrent task."
)
super().__init__(msg) super().__init__(msg)
@@ -118,9 +116,7 @@ def redact_sensitive_data(val: Any) -> Any:
""" """
if isinstance(val, dict): if isinstance(val, dict):
return { return {
k: "[REDACTED]" k: "[REDACTED]" if REDACT_KEY_PATTERNS.match(str(k)) else redact_sensitive_data(v)
if REDACT_KEY_PATTERNS.match(str(k))
else redact_sensitive_data(v)
for k, v in val.items() for k, v in val.items()
} }
if isinstance(val, list): if isinstance(val, list):
+20 -58
View File
@@ -6,7 +6,7 @@ Implements the zero-trust authorization pipeline for homelab-appctl.service:
- Unix domain socket SO_PEERCRED fallback to homelab-viewer for zero-friction local reads - 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 - Mandatory Bearer tokens for all network (HTTP) operations and all mutations / sensitive reads
- 3-role RBAC enforcement (homelab-admin, homelab-operator, homelab-viewer) - 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 - Workload scope gating against config/deployments.yaml for homelab-operator
""" """
from __future__ import annotations from __future__ import annotations
@@ -33,17 +33,9 @@ except ImportError:
yaml = None # type: ignore[assignment] yaml = None # type: ignore[assignment]
DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json") DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json")
DEFAULT_DEPLOYMENTS_FILE = ( DEFAULT_DEPLOYMENTS_FILE = Path(__file__).resolve().parent.parent / "config" / "deployments.yaml"
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_TARGETS: frozenset[str] = frozenset({
{
"core", "core",
"traefik", "traefik",
"authelia", "authelia",
@@ -54,36 +46,29 @@ CORE_TARGETS: frozenset[str] = frozenset(
"homepage", "homepage",
"diun", "diun",
"watchtower", "watchtower",
} })
)
SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset( SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset({
{
OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_CONFIG,
OperationType.WORKLOAD_LOGS, OperationType.WORKLOAD_LOGS,
} })
)
MUTATING_OPERATIONS: frozenset[OperationType] = frozenset( MUTATING_OPERATIONS: frozenset[OperationType] = frozenset({
{
OperationType.WORKLOAD_DEPLOY, OperationType.WORKLOAD_DEPLOY,
OperationType.WORKLOAD_STOP, OperationType.WORKLOAD_STOP,
OperationType.WORKLOAD_RESTART, OperationType.WORKLOAD_RESTART,
OperationType.WORKLOAD_UPDATE, OperationType.WORKLOAD_UPDATE,
OperationType.WORKLOAD_PULL, OperationType.WORKLOAD_PULL,
OperationType.PLATFORM_SYNC_HOMEPAGE, OperationType.PLATFORM_SYNC_HOMEPAGE,
} })
)
READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset( READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset({
{
OperationType.WORKLOAD_LIST, OperationType.WORKLOAD_LIST,
OperationType.WORKLOAD_GET, OperationType.WORKLOAD_GET,
OperationType.WORKLOAD_RESOLVE, OperationType.WORKLOAD_RESOLVE,
OperationType.PLATFORM_SSL, OperationType.PLATFORM_SSL,
OperationType.PLATFORM_HEALTH, OperationType.PLATFORM_HEALTH,
} })
)
class Role(StrEnum): class Role(StrEnum):
@@ -134,11 +119,7 @@ class TokenDescriptor(StrictModel):
class AuthenticationError(Exception): class AuthenticationError(Exception):
"""Raised when authentication fails (401 Unauthorized).""" """Raised when authentication fails (401 Unauthorized)."""
def __init__( def __init__(self, message: str = "Authentication required", code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED) -> None:
self,
message: str = "Authentication required",
code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED,
) -> None:
super().__init__(message) super().__init__(message)
self.code = code self.code = code
self.http_status = 401 self.http_status = 401
@@ -147,11 +128,7 @@ class AuthenticationError(Exception):
class AuthorizationError(Exception): class AuthorizationError(Exception):
"""Raised when an authenticated principal lacks required role or scope (403 Forbidden).""" """Raised when an authenticated principal lacks required role or scope (403 Forbidden)."""
def __init__( def __init__(self, message: str = "Permission denied", code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED) -> None:
self,
message: str = "Permission denied",
code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED,
) -> None:
super().__init__(message) super().__init__(message)
self.code = code self.code = code
self.http_status = 403 self.http_status = 403
@@ -204,15 +181,13 @@ class TokenStore:
constant-time hmac.compare_digest. constant-time hmac.compare_digest.
""" """
if not secret: if not secret:
raise AuthenticationError( raise AuthenticationError("Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED)
"Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED
)
secret_hash = hashlib.sha256(secret.encode("utf-8")).hexdigest() secret_hash = hashlib.sha256(secret.encode("utf-8")).hexdigest()
tokens = self.load_tokens() tokens = self.load_tokens()
for token in tokens: for token in tokens:
if hmac.compare_digest(secret_hash, token.sha256.lower()): if hmac.compare_digest(secret_hash, token.sha256):
return Principal( return Principal(
identity=token.identity, identity=token.identity,
role=token.role, role=token.role,
@@ -220,25 +195,18 @@ class TokenStore:
auth_method="bearer_token", auth_method="bearer_token",
) )
raise AuthenticationError( raise AuthenticationError("Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED)
"Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED
)
def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[str]: def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[str]:
""" """
Load admitted repository names and aliases from ~/Workloads/deployments.yaml Load admitted repository names and aliases from config/deployments.yaml.
(or HOMELAB_DEPLOYMENTS_FILE / WORKLOADS_DIR override).
Fails closed (empty set) if registry is missing or malformed. Fails closed (empty set) if registry is missing or malformed.
""" """
if deployments_path is not None: if deployments_path is not None:
reg_file = Path(deployments_path) reg_file = Path(deployments_path)
elif env_deploy := os.environ.get("HOMELAB_DEPLOYMENTS_FILE"): elif "HOMELAB_DEPLOYMENTS_FILE" in os.environ:
reg_file = Path(env_deploy) reg_file = Path(os.environ["HOMELAB_DEPLOYMENTS_FILE"])
elif env_workloads := (
os.environ.get("WORKLOADS_DIR") or os.environ.get("SITES_DIR")
):
reg_file = Path(env_workloads) / "deployments.yaml"
else: else:
reg_file = DEFAULT_DEPLOYMENTS_FILE reg_file = DEFAULT_DEPLOYMENTS_FILE
@@ -267,13 +235,7 @@ def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[s
if isinstance(alias, str) and alias.strip(): if isinstance(alias, str) and alias.strip():
admitted.add(alias.strip()) admitted.add(alias.strip())
return admitted return admitted
except ( except (OSError, UnicodeDecodeError, ValueError, json.JSONDecodeError, *yaml_errors):
OSError,
UnicodeDecodeError,
ValueError,
json.JSONDecodeError,
*yaml_errors,
):
return set() return set()
@@ -348,7 +310,7 @@ def enforce_rbac(
return return
# Target checks for operations targeting infrastructure # Target checks for operations targeting infrastructure
if target is not None and target.strip().lower() in CORE_TARGETS: if target is not None and target in CORE_TARGETS:
raise AuthorizationError( raise AuthorizationError(
f"Role 'homelab-operator' is not permitted to target core service '{target}'", f"Role 'homelab-operator' is not permitted to target core service '{target}'",
code=ErrorCode.ERR_PERMISSION_DENIED, code=ErrorCode.ERR_PERMISSION_DENIED,
+1 -3
View File
@@ -116,12 +116,11 @@ FlexibleWorkloadAction = FlexibleOperationType
class ErrorCode(StrEnum): class ErrorCode(StrEnum):
"""Canonical 7-code error taxonomy for homelab-appctl.service.""" """Canonical 6-code error taxonomy for homelab-appctl.service."""
ERR_VALIDATION_FAILED = "ERR_VALIDATION_FAILED" ERR_VALIDATION_FAILED = "ERR_VALIDATION_FAILED"
ERR_AUTH_REQUIRED = "ERR_AUTH_REQUIRED" ERR_AUTH_REQUIRED = "ERR_AUTH_REQUIRED"
ERR_PERMISSION_DENIED = "ERR_PERMISSION_DENIED" ERR_PERMISSION_DENIED = "ERR_PERMISSION_DENIED"
ERR_CAPABILITY_NOT_GRANTED = "ERR_CAPABILITY_NOT_GRANTED"
ERR_TARGET_NOT_FOUND = "ERR_TARGET_NOT_FOUND" ERR_TARGET_NOT_FOUND = "ERR_TARGET_NOT_FOUND"
ERR_CONCURRENT_MUTATION = "ERR_CONCURRENT_MUTATION" ERR_CONCURRENT_MUTATION = "ERR_CONCURRENT_MUTATION"
ERR_EXECUTION_FAILED = "ERR_EXECUTION_FAILED" ERR_EXECUTION_FAILED = "ERR_EXECUTION_FAILED"
@@ -135,7 +134,6 @@ ERROR_HTTP_STATUS: dict[ErrorCode, int] = {
ErrorCode.ERR_VALIDATION_FAILED: 400, ErrorCode.ERR_VALIDATION_FAILED: 400,
ErrorCode.ERR_AUTH_REQUIRED: 401, ErrorCode.ERR_AUTH_REQUIRED: 401,
ErrorCode.ERR_PERMISSION_DENIED: 403, ErrorCode.ERR_PERMISSION_DENIED: 403,
ErrorCode.ERR_CAPABILITY_NOT_GRANTED: 403,
ErrorCode.ERR_TARGET_NOT_FOUND: 404, ErrorCode.ERR_TARGET_NOT_FOUND: 404,
ErrorCode.ERR_CONCURRENT_MUTATION: 409, ErrorCode.ERR_CONCURRENT_MUTATION: 409,
ErrorCode.ERR_EXECUTION_FAILED: 500, ErrorCode.ERR_EXECUTION_FAILED: 500,
+2 -21
View File
@@ -57,14 +57,9 @@ from pydantic import ValidationError
logger = logging.getLogger("appctl_daemon") logger = logging.getLogger("appctl_daemon")
CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent)) CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent))
WORKLOADS_DIR = Path( SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
os.environ.get("WORKLOADS_DIR")
or os.environ.get("SITES_DIR")
or os.path.expanduser("~/Workloads")
)
SITES_DIR = WORKLOADS_DIR
DEPLOYMENTS_FILE = Path( DEPLOYMENTS_FILE = Path(
os.environ.get("HOMELAB_DEPLOYMENTS_FILE") or (WORKLOADS_DIR / "deployments.yaml") os.environ.get("HOMELAB_DEPLOYMENTS_FILE", CORE_DIR / "config" / "deployments.yaml")
) )
DEFAULT_SOCKET_PATH = Path( DEFAULT_SOCKET_PATH = Path(
@@ -391,7 +386,6 @@ class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
return return
# Dispatch operation to OperationalRouter # Dispatch operation to OperationalRouter
try:
resp = self.appctl_server.router.dispatch( resp = self.appctl_server.router.dispatch(
request=req, request=req,
principal=principal, principal=principal,
@@ -399,19 +393,6 @@ class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
origin=origin, origin=origin,
client=client_header, 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 status_code = resp.error.code.http_status if (not resp.success and resp.error) else 200
self._send_operation_response(status_code, resp) self._send_operation_response(status_code, resp)
+7 -18
View File
@@ -37,19 +37,12 @@ CORE_DIR = os.environ.get(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
) )
def _resolve_default_workloads_dir() -> str: SITES_DIR = os.environ.get(
"""Resolve workloads root honoring WORKLOADS_DIR, SITES_DIR, sibling Workloads, or ~/Workloads.""" "SITES_DIR",
env_dir = os.environ.get("WORKLOADS_DIR") or os.environ.get("SITES_DIR") os.path.join(os.path.dirname(CORE_DIR), "Sites")
if env_dir: if os.path.isdir(os.path.join(os.path.dirname(CORE_DIR), "Sites"))
return env_dir else os.path.expanduser("~/Sites"),
sibling_workloads = os.path.join(os.path.dirname(CORE_DIR), "Workloads") )
if os.path.isdir(sibling_workloads):
return sibling_workloads
return os.path.expanduser("~/Workloads")
WORKLOADS_DIR = _resolve_default_workloads_dir()
SITES_DIR = WORKLOADS_DIR
HOMELAB_DOMAIN = ( HOMELAB_DOMAIN = (
os.environ.get("HOMELAB_DOMAIN") os.environ.get("HOMELAB_DOMAIN")
@@ -749,12 +742,8 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
lines.append("") lines.append("")
content = "\n".join(lines).strip() + "\n" content = "\n".join(lines).strip() + "\n"
tmp_services_path = services_yaml_path + ".tmp" with open(services_yaml_path, "w", encoding="utf-8") as f:
with open(tmp_services_path, "w", encoding="utf-8") as f:
f.write(content) f.write(content)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_services_path, services_yaml_path)
print( print(
f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)" f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)"
+54 -260
View File
@@ -12,16 +12,12 @@ Implements the single command execution pipeline for homelab-appctl.service:
from __future__ import annotations from __future__ import annotations
import logging
import os import os
import subprocess import subprocess
import time import time
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
import yaml
logger = logging.getLogger("appctl_router")
from appctl_audit import ( from appctl_audit import (
AuditLogger, AuditLogger,
AuditPersistenceError, AuditPersistenceError,
@@ -85,16 +81,12 @@ MAX_OUTPUT_BYTES = 256 * 1024 # 256 KiB cap per invocation
class RouterValidationError(Exception): class RouterValidationError(Exception):
"""Raised when request payload or pre-flight validation fails (400 Bad Request or 403 Capability Denied).""" """Raised when request payload or pre-flight validation fails (400 Bad Request)."""
def __init__( def __init__(self, message: str) -> None:
self,
message: str,
code: ErrorCode = ErrorCode.ERR_VALIDATION_FAILED,
) -> None:
super().__init__(message) super().__init__(message)
self.code = code self.code = ErrorCode.ERR_VALIDATION_FAILED
self.http_status = code.http_status self.http_status = 400
class RouterExecutionError(Exception): class RouterExecutionError(Exception):
@@ -216,18 +208,6 @@ def assemble_workload_env(
if local_env.is_file(): if local_env.is_file():
env.update(parse_dotenv(local_env, validate_keys=True)) env.update(parse_dotenv(local_env, validate_keys=True))
# Re-assert immutable platform infrastructure keys (defense-in-depth)
env["HOMELAB_DOMAIN"] = domain
env["DOMAIN_SUFFIX"] = domain
env["DOMAIN"] = domain
env["PROXY_NETWORK"] = os.environ.get("PROXY_NETWORK", "proxy-net")
env["CERT_RESOLVER"] = os.environ.get("CERT_RESOLVER", "myresolver")
env["SERVICE_NAME"] = app_name
env["CONTAINER_NAME"] = app_name
env["SERVICE_DOMAIN"] = f"{app_name}.{domain}"
if "DOCKER_CONFIG" in os.environ:
env["DOCKER_CONFIG"] = os.environ["DOCKER_CONFIG"]
return env return env
@@ -310,38 +290,19 @@ def validate_workload_preflight(
try: try:
manifest = parse_manifest(manifest_file) manifest = parse_manifest(manifest_file)
except ManifestValidationError as err: except ManifestValidationError as err:
raise RouterValidationError( raise RouterValidationError(f"Workload manifest validation failed: {err}") from err
f"Workload manifest validation failed: {err}"
) from err
effective_name = app_name or manifest.name effective_name = app_name or manifest.name
compose_file = _resolve_compose_file(app_dir) compose_file = _resolve_compose_file(app_dir)
if compose_file.exists(): if compose_file.exists():
resolved_env = assemble_workload_env(app_dir, manifest, effective_name)
ok, reason = validate_compose_security( ok, reason = validate_compose_security(
compose_file=compose_file, compose_file=compose_file,
allowed_root=app_dir, allowed_root=app_dir,
app_name=effective_name, app_name=effective_name,
resolved_env=resolved_env,
) )
if not ok: if not ok:
is_cap_denial = bool(
reason
and reason.startswith(
(
"Capability not granted:",
"Capability grants integrity check failed:",
)
)
)
err_code = (
ErrorCode.ERR_CAPABILITY_NOT_GRANTED
if is_cap_denial
else ErrorCode.ERR_VALIDATION_FAILED
)
raise RouterValidationError( raise RouterValidationError(
f"Compose AST security validation failed for '{effective_name}': {reason}", f"Compose AST security validation failed for '{effective_name}': {reason}"
code=err_code,
) )
return manifest, compose_file return manifest, compose_file
@@ -367,9 +328,7 @@ def validate_core_preflight(
if not compose_file.is_file(): if not compose_file.is_file():
raise RouterValidationError(f"Core compose file not found at '{compose_file}'") raise RouterValidationError(f"Core compose file not found at '{compose_file}'")
if compose_file.is_symlink() and not compose_file.resolve().is_relative_to( if compose_file.is_symlink() and not compose_file.resolve().is_relative_to(core_dir_resolved):
core_dir_resolved
):
raise RouterValidationError( raise RouterValidationError(
f"Core compose file symlink escapes Core root: '{compose_file}'" f"Core compose file symlink escapes Core root: '{compose_file}'"
) )
@@ -633,9 +592,7 @@ class OperationalRouter:
elif operation == OperationType.WORKLOAD_PULL: elif operation == OperationType.WORKLOAD_PULL:
result_data = self._op_workload_pull(resolved_app) result_data = self._op_workload_pull(resolved_app)
elif operation == OperationType.WORKLOAD_UPDATE: elif operation == OperationType.WORKLOAD_UPDATE:
result_data, commit_sha = self._op_workload_update( result_data, commit_sha = self._op_workload_update(request, resolved_app)
request, resolved_app
)
elif operation == OperationType.PLATFORM_SYNC_HOMEPAGE: elif operation == OperationType.PLATFORM_SYNC_HOMEPAGE:
result_data = self._op_platform_sync_homepage() result_data = self._op_platform_sync_homepage()
else: else:
@@ -644,12 +601,7 @@ class OperationalRouter:
duration_ms = int((time.perf_counter() - start_time) * 1000) duration_ms = int((time.perf_counter() - start_time) * 1000)
# Audit COMPLETED for mutating ops and sensitive reads # Audit COMPLETED for mutating ops and sensitive reads
# Audit COMPLETED for mutating ops and sensitive reads if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS:
if (
operation in MUTATING_OPERATIONS
or operation in SENSITIVE_READ_OPERATIONS
):
try:
self.audit_logger.log_completed( self.audit_logger.log_completed(
operation_id=op_id, operation_id=op_id,
principal=principal_audit, principal=principal_audit,
@@ -661,12 +613,8 @@ class OperationalRouter:
parameters=request.parameters, parameters=request.parameters,
duration_ms=duration_ms, duration_ms=duration_ms,
commit_sha=commit_sha, commit_sha=commit_sha,
message=result_data.get( message=result_data.get("message", "Operation completed successfully"),
"message", "Operation completed successfully"
),
) )
except AuditPersistenceError as audit_err:
logger.error("Failed to persist COMPLETED audit record: %s", audit_err)
return OperationResponse( return OperationResponse(
version="1.0", version="1.0",
@@ -682,11 +630,7 @@ class OperationalRouter:
except (RouterValidationError, RouterExecutionError) as err: except (RouterValidationError, RouterExecutionError) as err:
duration_ms = int((time.perf_counter() - start_time) * 1000) duration_ms = int((time.perf_counter() - start_time) * 1000)
if ( if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS:
operation in MUTATING_OPERATIONS
or operation in SENSITIVE_READ_OPERATIONS
):
try:
self.audit_logger.log_failed( self.audit_logger.log_failed(
operation_id=op_id, operation_id=op_id,
principal=principal_audit, principal=principal_audit,
@@ -701,8 +645,6 @@ class OperationalRouter:
error_code=err.code.value, error_code=err.code.value,
message=str(err), message=str(err),
) )
except AuditPersistenceError as audit_err:
logger.error("Failed to persist FAILED audit record: %s", audit_err)
return OperationResponse( return OperationResponse(
version="1.0", version="1.0",
success=False, success=False,
@@ -712,42 +654,6 @@ class OperationalRouter:
duration_ms=duration_ms, duration_ms=duration_ms,
error=OperationError(code=err.code, message=str(err)), error=OperationError(code=err.code, message=str(err)),
) )
except Exception as err:
logger.exception("Unexpected execution error in router")
duration_ms = int((time.perf_counter() - start_time) * 1000)
if (
operation in MUTATING_OPERATIONS
or operation in SENSITIVE_READ_OPERATIONS
):
try:
self.audit_logger.log_failed(
operation_id=op_id,
principal=principal_audit,
action=operation.value,
target=target,
transport=transport,
origin=origin,
client=client,
parameters=request.parameters,
duration_ms=duration_ms,
exit_code=1,
error_code=ErrorCode.ERR_EXECUTION_FAILED.value,
message=f"Unexpected execution failure: {err}",
)
except AuditPersistenceError as audit_err:
logger.error("Failed to persist FAILED audit record: %s", audit_err)
return OperationResponse(
version="1.0",
success=False,
operation_id=op_id,
operation=operation,
target=target,
duration_ms=duration_ms,
error=OperationError(
code=ErrorCode.ERR_EXECUTION_FAILED,
message=f"Unexpected execution failure: {err}",
),
)
# ----------------------------------------------------------------------- # -----------------------------------------------------------------------
# Domain Operation Implementations # Domain Operation Implementations
@@ -793,9 +699,7 @@ class OperationalRouter:
dir_path=self.core_dir, dir_path=self.core_dir,
container_name=svc.container_name, container_name=svc.container_name,
) )
svc_dict["deployment_status"] = ( svc_dict["deployment_status"] = core_checkout.status_label if i == 0 else ""
core_checkout.status_label if i == 0 else ""
)
svc_dict["provenance_status"] = "— Core Platform" svc_dict["provenance_status"] = "— Core Platform"
if params.ssl and not svc.is_internal: if params.ssl and not svc.is_internal:
svc_dict["ssl"] = check_ssl_cert(svc.domain) svc_dict["ssl"] = check_ssl_cert(svc.domain)
@@ -822,14 +726,9 @@ class OperationalRouter:
domain = target or resolve_canonical_domain() domain = target or resolve_canonical_domain()
try: try:
cert_info = check_ssl_cert(domain) cert_info = check_ssl_cert(domain)
return { return {"ssl": cert_info, "message": f"SSL certificate inspected for {domain}"}
"ssl": cert_info,
"message": f"SSL certificate inspected for {domain}",
}
except Exception as err: except Exception as err:
raise RouterExecutionError( raise RouterExecutionError(f"SSL inspection failed for '{domain}': {err}") from err
f"SSL inspection failed for '{domain}': {err}"
) from err
def _op_platform_health(self) -> dict[str, Any]: def _op_platform_health(self) -> dict[str, Any]:
return { return {
@@ -843,23 +742,13 @@ class OperationalRouter:
app_dir, _, compose_file, env, _ = self._prepare_target_context(app) app_dir, _, compose_file, env, _ = self._prepare_target_context(app)
cmd = ["docker", "compose", "-f", str(compose_file), "config"] cmd = ["docker", "compose", "-f", str(compose_file), "config"]
code, stdout, stderr = run_bounded_subprocess( code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0)
cmd, cwd=app_dir, env=env, timeout=15.0
)
if code != 0: if code != 0:
raise RouterExecutionError( raise RouterExecutionError(f"docker compose config failed: {stderr}", exit_code=code)
f"docker compose config failed: {stderr}", exit_code=code
)
config_output = stdout config_output = stdout
if principal.role != Role.ADMIN: if principal.role != Role.ADMIN:
# Redact secrets for non-admin callers # Redact secrets for non-admin callers
try:
parsed_yaml = yaml.safe_load(stdout)
if isinstance(parsed_yaml, (dict, list)):
redacted_parsed = redact_sensitive_data(parsed_yaml)
config_output = yaml.safe_dump(redacted_parsed, sort_keys=False)
except (yaml.YAMLError, ValueError):
config_output = redact_sensitive_data(config_output) config_output = redact_sensitive_data(config_output)
return {"output": config_output, "message": "Evaluated compose configuration"} return {"output": config_output, "message": "Evaluated compose configuration"}
@@ -882,23 +771,13 @@ class OperationalRouter:
if container: if container:
cmd.append(container) cmd.append(container)
code, stdout, stderr = run_bounded_subprocess( code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0)
cmd, cwd=app_dir, env=env, timeout=15.0
)
if code != 0: if code != 0:
raise RouterExecutionError( raise RouterExecutionError(f"docker compose logs failed: {stderr}", exit_code=code)
f"docker compose logs failed: {stderr}", exit_code=code
)
return { return {"output": stdout, "tail": params.tail, "message": f"Tail {params.tail} logs"}
"output": stdout,
"tail": params.tail,
"message": f"Tail {params.tail} logs",
}
def _op_workload_deploy( def _op_workload_deploy(self, request: OperationRequest, app: Any) -> dict[str, Any]:
self, request: OperationRequest, app: Any
) -> dict[str, Any]:
params = request.parse_parameters() params = request.parse_parameters()
assert isinstance(params, DeployParams) assert isinstance(params, DeployParams)
app_dir, _, compose_file, env, container = self._prepare_target_context(app) app_dir, _, compose_file, env, container = self._prepare_target_context(app)
@@ -906,25 +785,14 @@ class OperationalRouter:
# Optional build # Optional build
if params.build: if params.build:
build_cmd = [ build_cmd = ["docker", "compose", "-f", str(compose_file), "build", "--pull"]
"docker",
"compose",
"-f",
str(compose_file),
"build",
"--pull",
]
if params.no_cache: if params.no_cache:
build_cmd.append("--no-cache") build_cmd.append("--no-cache")
if container: if container:
build_cmd.append(container) build_cmd.append(container)
code, out, err = run_bounded_subprocess( code, out, err = run_bounded_subprocess(build_cmd, cwd=app_dir, env=env, timeout=300.0)
build_cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError( raise RouterExecutionError(f"docker compose build failed: {err}", exit_code=code)
f"docker compose build failed: {err}", exit_code=code
)
# Deploy up # Deploy up
up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d"] up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d"]
@@ -933,13 +801,9 @@ class OperationalRouter:
if container: if container:
up_cmd.append(container) up_cmd.append(container)
code, out, err = run_bounded_subprocess( code, out, err = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0)
up_cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError( raise RouterExecutionError(f"docker compose up failed: {err}", exit_code=code)
f"docker compose up failed: {err}", exit_code=code
)
# Trigger Homepage sync for Sites workloads # Trigger Homepage sync for Sites workloads
if not is_core: if not is_core:
@@ -960,21 +824,13 @@ class OperationalRouter:
else: else:
cmd = ["docker", "compose", "-f", str(compose_file), "down"] cmd = ["docker", "compose", "-f", str(compose_file), "down"]
code, out, err = run_bounded_subprocess( code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0)
cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError( raise RouterExecutionError(f"docker compose stop/down failed: {err}", exit_code=code)
f"docker compose stop/down failed: {err}", exit_code=code
)
if not is_core: if not is_core:
self._trigger_homepage_sync() self._trigger_homepage_sync()
return { return {"output": out, "action": "stopped", "message": f"Workload '{app.name}' stopped"}
"output": out,
"action": "stopped",
"message": f"Workload '{app.name}' stopped",
}
def _op_workload_restart(self, app: Any) -> dict[str, Any]: def _op_workload_restart(self, app: Any) -> dict[str, Any]:
app_dir, _, compose_file, env, container = self._prepare_target_context(app) app_dir, _, compose_file, env, container = self._prepare_target_context(app)
@@ -984,21 +840,13 @@ class OperationalRouter:
if container: if container:
cmd.append(container) cmd.append(container)
code, out, err = run_bounded_subprocess( code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0)
cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError( raise RouterExecutionError(f"docker compose restart failed: {err}", exit_code=code)
f"docker compose restart failed: {err}", exit_code=code
)
if not is_core: if not is_core:
self._trigger_homepage_sync() self._trigger_homepage_sync()
return { return {"output": out, "action": "restarted", "message": f"Workload '{app.name}' restarted"}
"output": out,
"action": "restarted",
"message": f"Workload '{app.name}' restarted",
}
def _op_workload_pull(self, app: Any) -> dict[str, Any]: def _op_workload_pull(self, app: Any) -> dict[str, Any]:
app_dir, _, compose_file, env, container = self._prepare_target_context(app) app_dir, _, compose_file, env, container = self._prepare_target_context(app)
@@ -1007,49 +855,20 @@ class OperationalRouter:
pull_cmd = ["docker", "compose", "-f", str(compose_file), "pull"] pull_cmd = ["docker", "compose", "-f", str(compose_file), "pull"]
if container: if container:
pull_cmd.append(container) pull_cmd.append(container)
code, _, err = run_bounded_subprocess( code, _, err = run_bounded_subprocess(pull_cmd, cwd=app_dir, env=env, timeout=300.0)
pull_cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError( raise RouterExecutionError(f"docker compose pull failed: {err}", exit_code=code)
f"docker compose pull failed: {err}", exit_code=code
)
up_cmd = [ up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"]
"docker",
"compose",
"-f",
str(compose_file),
"up",
"-d",
"--remove-orphans",
]
if container: if container:
up_cmd.append(container) up_cmd.append(container)
code, out_up, err_up = run_bounded_subprocess( code, out_up, err_up = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0)
up_cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError( raise RouterExecutionError(f"docker compose up failed after pull: {err_up}", exit_code=code)
f"docker compose up failed after pull: {err_up}", exit_code=code
)
if not is_core: if not is_core:
self._trigger_homepage_sync() self._trigger_homepage_sync()
return { return {"output": out_up, "action": "pulled", "message": f"Workload '{app.name}' pulled and updated"}
"output": out_up,
"action": "pulled",
"message": f"Workload '{app.name}' pulled and updated",
}
@staticmethod
def _resolve_git_context(app_dir: Path) -> tuple[Path, str | None]:
"""Resolve (git_root, subpath) supporting standalone <app>/.git and parent monorepo .git."""
if (app_dir / ".git").exists():
return app_dir, None
if (app_dir.parent / ".git").exists():
return app_dir.parent, f"{app_dir.name}/"
return app_dir, None
def _op_workload_update( def _op_workload_update(
self, request: OperationRequest, app: Any self, request: OperationRequest, app: Any
@@ -1067,17 +886,11 @@ class OperationalRouter:
app_dir = Path(app.dir_path) app_dir = Path(app.dir_path)
is_core = self._is_core_target(app) is_core = self._is_core_target(app)
container = self._target_container(app) container = self._target_container(app)
git_root, git_subpath = (
(app_dir, None) if is_core else self._resolve_git_context(app_dir)
)
# 1. Clean working tree check # 1. Clean working tree check
status_cmd = ["git", "-C", str(git_root), "status", "--porcelain"]
if git_subpath is not None:
status_cmd.extend(["--", git_subpath])
code, status_out, _ = run_bounded_subprocess( code, status_out, _ = run_bounded_subprocess(
status_cmd, ["git", "-C", str(app_dir), "status", "--porcelain"],
cwd=git_root, cwd=app_dir,
timeout=5.0, timeout=5.0,
) )
if code != 0 or status_out.strip(): if code != 0 or status_out.strip():
@@ -1086,16 +899,14 @@ class OperationalRouter:
) )
# 2. git pull --ff-only # 2. git pull --ff-only
pull_cmd = ["git", "-C", str(git_root), "pull", "--ff-only"] pull_cmd = ["git", "-C", str(app_dir), "pull", "--ff-only"]
if params.expected_branch: if params.expected_branch:
pull_cmd.extend(["origin", "--", params.expected_branch]) pull_cmd.extend(["origin", params.expected_branch])
code, pull_out, pull_err = run_bounded_subprocess( code, pull_out, pull_err = run_bounded_subprocess(
pull_cmd, cwd=git_root, timeout=60.0 pull_cmd, cwd=app_dir, timeout=60.0
) )
if code != 0: if code != 0:
raise RouterExecutionError( raise RouterExecutionError(f"git pull failed for '{app.name}': {pull_err}", exit_code=code)
f"git pull failed for '{app.name}': {pull_err}", exit_code=code
)
# 3. Post-pull re-validation of manifest and expected_branch # 3. Post-pull re-validation of manifest and expected_branch
if is_core: if is_core:
@@ -1103,17 +914,15 @@ class OperationalRouter:
manifest = None manifest = None
declared_actions = ["compose_pull", "compose_up"] declared_actions = ["compose_pull", "compose_up"]
else: else:
manifest, compose_file = validate_workload_preflight( manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name)
app_dir, self.sites_dir, app.name
)
if ( if (
params.expected_branch params.expected_branch
and manifest.deployment and manifest.source
and manifest.deployment.branch != params.expected_branch and manifest.source.ref != params.expected_branch
): ):
raise RouterValidationError( raise RouterValidationError(
f"Post-pull branch mismatch for '{app.name}': expected '{params.expected_branch}', " f"Post-pull branch mismatch for '{app.name}': expected '{params.expected_branch}', "
f"manifest declared '{manifest.deployment.branch}'" f"manifest declared '{manifest.source.ref}'"
) )
declared_actions = manifest.deployment.actions or ["compose_up"] declared_actions = manifest.deployment.actions or ["compose_up"]
@@ -1139,15 +948,7 @@ class OperationalRouter:
if params.no_cache: if params.no_cache:
cmd.append("--no-cache") cmd.append("--no-cache")
elif action == "compose_up": elif action == "compose_up":
cmd = [ cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"]
"docker",
"compose",
"-f",
str(compose_file),
"up",
"-d",
"--remove-orphans",
]
elif action == "compose_restart": elif action == "compose_restart":
cmd = ["docker", "compose", "-f", str(compose_file), "restart"] cmd = ["docker", "compose", "-f", str(compose_file), "restart"]
else: else:
@@ -1156,9 +957,7 @@ class OperationalRouter:
if container: if container:
cmd.append(container) cmd.append(container)
code, act_out, act_err = run_bounded_subprocess( code, act_out, act_err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0)
cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError( raise RouterExecutionError(
f"Action '{action}' failed during workload.update for '{app.name}': {act_err}", f"Action '{action}' failed during workload.update for '{app.name}': {act_err}",
@@ -1168,8 +967,8 @@ class OperationalRouter:
# 5. Extract current commit SHA # 5. Extract current commit SHA
_, sha_out, _ = run_bounded_subprocess( _, sha_out, _ = run_bounded_subprocess(
["git", "-C", str(git_root), "rev-parse", "--short", "HEAD"], ["git", "-C", str(app_dir), "rev-parse", "--short", "HEAD"],
cwd=git_root, cwd=app_dir,
timeout=5.0, timeout=5.0,
) )
commit_sha = sha_out.strip() or None commit_sha = sha_out.strip() or None
@@ -1186,18 +985,13 @@ class OperationalRouter:
}, commit_sha }, commit_sha
def _op_platform_sync_homepage(self) -> dict[str, Any]: def _op_platform_sync_homepage(self) -> dict[str, Any]:
cmd_sync_homepage() self._trigger_homepage_sync()
return { return {"action": "sync_homepage", "message": "Homepage dashboard synchronized successfully"}
"action": "sync_homepage",
"message": "Homepage dashboard synchronized successfully",
}
def _trigger_homepage_sync(self) -> None: def _trigger_homepage_sync(self) -> None:
"""Atomic compile of Homepage dashboard services.yaml under _homepage_sync.lock.""" """Atomic compile of Homepage dashboard services.yaml under _homepage_sync.lock."""
try: try:
with self.lock_manager.homepage_sync_lock():
cmd_sync_homepage() cmd_sync_homepage()
except (OSError, ValueError, RuntimeError, ConcurrentMutationError) as exc: except (OSError, ValueError, RuntimeError) as exc:
import sys import sys
print(f"Warning: Homepage sync non-fatal error: {exc}", file=sys.stderr) print(f"Warning: Homepage sync non-fatal error: {exc}", file=sys.stderr)
+6 -17
View File
@@ -72,26 +72,10 @@ RESERVED_ENV_KEYS = {
"SITES_DIR", "SITES_DIR",
"ENV_FILE", "ENV_FILE",
"HOMESERVER_ENV", "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_STRATEGIES = {"compose"}
ALLOWED_ACTIONS = { ALLOWED_ACTIONS = {"git_pull", "compose_pull", "compose_up", "compose_build", "compose_restart"}
"git_pull",
"compose_pull",
"compose_up",
"compose_build",
"compose_restart",
}
def validate_transport(url: str) -> tuple[TransportScheme, str]: def validate_transport(url: str) -> tuple[TransportScheme, str]:
@@ -184,11 +168,13 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]:
return RefType.BRANCH, ref return RefType.BRANCH, ref
class SourceConfig(BaseModel): class SourceConfig(BaseModel):
"""Upstream source provenance descriptor.""" """Upstream source provenance descriptor."""
model_config = ConfigDict(extra="forbid", ignored_types=(dict,)) model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
url: str url: str
ref: str = "main" ref: str = "main"
type: str = "git" type: str = "git"
@@ -237,6 +223,7 @@ class DeploymentConfig(BaseModel):
model_config = ConfigDict(extra="forbid", ignored_types=(dict,)) model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
strategy: str = "compose" strategy: str = "compose"
branch: str = "main" branch: str = "main"
actions: list[str] = Field(default_factory=lambda: ["git_pull", "compose_up"]) actions: list[str] = Field(default_factory=lambda: ["git_pull", "compose_up"])
@@ -277,6 +264,7 @@ class HomepageConfig(BaseModel):
model_config = ConfigDict(extra="forbid", ignored_types=(dict,)) model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
title: str title: str
group: str = "Applications" group: str = "Applications"
icon: str = "default.png" icon: str = "default.png"
@@ -307,6 +295,7 @@ class Manifest(BaseModel):
ignored_types=(dict,), ignored_types=(dict,),
) )
name: str name: str
schema_version: str = Field(default="1.0", alias="schemaVersion") schema_version: str = Field(default="1.0", alias="schemaVersion")
domain: str = "" domain: str = ""
File diff suppressed because it is too large. Load diff
+7 -17
View File
@@ -92,17 +92,10 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
""" """
Inspect local git repository checkout state. Inspect local git repository checkout state.
Reports clean/dirty status, active branch/ref, and current commit SHA. 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) path = Path(dir_path)
subpath: str | None = None git_dir = path / ".git"
if (path / ".git").exists(): if not git_dir.exists():
git_root = path
elif (path.parent / ".git").exists():
git_root = path.parent
subpath = f"{path.name}/"
else:
return CheckoutStatus( return CheckoutStatus(
is_git=False, is_git=False,
is_dirty=False, is_dirty=False,
@@ -114,15 +107,12 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
# Clean git environment so calls are not polluted by outer hooks # 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_")} 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) # 1. Check cleanliness
is_dirty = False is_dirty = False
git_error: str | None = None git_error: str | None = None
status_cmd = ["git", "-C", str(git_root), "status", "--porcelain"]
if subpath is not None:
status_cmd.extend(["--", subpath])
try: try:
status_res = subprocess.run( status_res = subprocess.run(
status_cmd, ["git", "-C", str(path), "status", "--porcelain"],
capture_output=True, capture_output=True,
text=True, text=True,
check=False, check=False,
@@ -142,7 +132,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
branch = "" branch = ""
try: try:
branch_res = subprocess.run( branch_res = subprocess.run(
["git", "-C", str(git_root), "rev-parse", "--abbrev-ref", "HEAD"], ["git", "-C", str(path), "rev-parse", "--abbrev-ref", "HEAD"],
capture_output=True, capture_output=True,
text=True, text=True,
check=False, check=False,
@@ -154,7 +144,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
if branch == "HEAD": if branch == "HEAD":
# Detached HEAD, check describe # Detached HEAD, check describe
desc_res = subprocess.run( desc_res = subprocess.run(
["git", "-C", str(git_root), "describe", "--tags", "--exact-match"], ["git", "-C", str(path), "describe", "--tags", "--exact-match"],
capture_output=True, capture_output=True,
text=True, text=True,
check=False, check=False,
@@ -170,7 +160,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
commit_sha = "" commit_sha = ""
try: try:
sha_res = subprocess.run( sha_res = subprocess.run(
["git", "-C", str(git_root), "rev-parse", "--short", "HEAD"], ["git", "-C", str(path), "rev-parse", "--short", "HEAD"],
capture_output=True, capture_output=True,
text=True, text=True,
check=False, check=False,
+1 -1
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# scripts/run-tests - Automated test & invariant verification runner for Homelab Core # scripts/test - Automated test & invariant verification runner for Homelab Core
set -euo pipefail set -euo pipefail
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
-149
View File
@@ -1,149 +0,0 @@
"""
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
-53
View File
@@ -1,53 +0,0 @@
"""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
-338
View File
@@ -1,338 +0,0 @@
"""
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}"
)
-784
View File
@@ -228,34 +228,6 @@ def test_missing_or_corrupt_registry_fails_closed(tmp_path: Path, monkeypatch):
# Missing registry must fail closed: empty mapping, no resolution # Missing registry must fail closed: empty mapping, no resolution
assert gitops_dispatcher.get_trusted_repository_mapping() == {} assert gitops_dispatcher.get_trusted_repository_mapping() == {}
def test_registry_resolves_workloads_and_sites_tilde_prefixes(
tmp_path: Path, monkeypatch
):
"""Ensure ~/Workloads/<app> and legacy ~/Sites/<app> paths resolve cleanly inside SITES_DIR."""
workloads_dir = tmp_path / "Workloads"
app_a = workloads_dir / "snappymail"
app_b = workloads_dir / "legacy-app"
app_a.mkdir(parents=True)
app_b.mkdir(parents=True)
registry = tmp_path / "deployments.yaml"
registry.write_text(
'schemaVersion: "1.0"\n'
"repositories:\n"
" snappymail:\n"
' path: "~/Workloads/snappymail"\n'
" legacy:\n"
' path: "~/Sites/legacy-app"\n',
encoding="utf-8",
)
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", workloads_dir)
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
assert gitops_dispatcher.resolve_repository("snappymail") == app_a.resolve()
assert gitops_dispatcher.resolve_repository("legacy") == app_b.resolve()
assert gitops_dispatcher.resolve_repository("valid") is None assert gitops_dispatcher.resolve_repository("valid") is None
# Corrupt YAML registry must also fail closed # Corrupt YAML registry must also fail closed
@@ -269,48 +241,6 @@ def test_registry_resolves_workloads_and_sites_tilde_prefixes(
assert gitops_dispatcher.resolve_repository("valid") is None assert gitops_dispatcher.resolve_repository("valid") is None
def test_deployments_file_defaults_to_workloads(
tmp_path: Path, run_isolated_script_expr
):
"""Ensure DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml."""
resolved_default = run_isolated_script_expr(
"import gitops_dispatcher; print(gitops_dispatcher.DEPLOYMENTS_FILE)"
)
assert Path(resolved_default) == tmp_path / "Workloads" / "deployments.yaml"
def test_deployments_file_fails_closed_without_config_dir_fallback(
tmp_path: Path, monkeypatch
):
"""Ensure missing DEPLOYMENTS_FILE fails closed even when CONFIG_DIR/deployments.yaml exists."""
config_dir = tmp_path / "config-fallback"
config_dir.mkdir()
(config_dir / "deployments.yaml").write_text(
'schemaVersion: "1.0"\n'
"repositories:\n"
" docs:\n"
' path: "~/Workloads/docs"\n',
encoding="utf-8",
)
monkeypatch.setattr(
gitops_dispatcher, "DEPLOYMENTS_FILE", tmp_path / "Workloads" / "deployments.yaml"
)
monkeypatch.setattr(gitops_dispatcher, "CONFIG_DIR", config_dir)
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
def test_deployments_file_honors_workloads_dir_override(
tmp_path: Path, run_isolated_script_expr
):
"""Ensure DEPLOYMENTS_FILE honors WORKLOADS_DIR override when HOMELAB_DEPLOYMENTS_FILE is unset."""
custom_workloads = tmp_path / "CustomWorkloads"
resolved_override = run_isolated_script_expr(
"import gitops_dispatcher; print(gitops_dispatcher.DEPLOYMENTS_FILE)",
extra_env={"WORKLOADS_DIR": str(custom_workloads)},
)
assert Path(resolved_override) == custom_workloads / "deployments.yaml"
def test_webhook_verification_valid_signature(): def test_webhook_verification_valid_signature():
"""Ensure valid HMAC-SHA256 signature passes verification.""" """Ensure valid HMAC-SHA256 signature passes verification."""
import hashlib import hashlib
@@ -1138,717 +1068,3 @@ services:
) )
assert valid is False assert valid is False
assert err is not None and "security_opt" in err.lower() assert err is not None and "security_opt" in err.lower()
def test_validate_compose_security_rejects_dict_volume_without_type_bind(
tmp_path: Path,
):
"""Ensure dictionary volume declarations without explicit type: bind enforce host containment (CR-DI-01)."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
volumes:
- source: /etc/shadow
target: /app/shadow
""",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is False
assert err is not None and "prohibited host bind mount" in err.lower()
def test_validate_compose_security_rejects_variable_interpolation_in_volume_host_path(
tmp_path: Path,
):
"""Ensure volume host paths containing variable interpolation (${...}) fail closed (CR-DI-02)."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
volumes:
- "${HOST_DIR}/data:/data"
""",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is False
assert err is not None and "variable interpolation" in err.lower()
def test_validate_compose_security_rejects_variable_interpolation_in_dict_volume_source(
tmp_path: Path,
):
"""Ensure dictionary volume source containing variable interpolation (${...}) fails closed (CR-DI-02)."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
volumes:
- source: "${HOST_DIR}/data"
target: /data
""",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is False
assert err is not None and "variable interpolation" in err.lower()
def test_validate_compose_security_allows_valid_dict_volume_within_workload(
tmp_path: Path,
):
"""Ensure valid dictionary volume within workload root is accepted even without type: bind."""
(tmp_path / "data").mkdir()
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
volumes:
- source: ./data
target: /data
""",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is True
assert err is None
def test_validate_compose_security_allows_remote_git_build_urls(tmp_path: Path):
"""Ensure validate_compose_security permits remote Git/HTTP build URLs (#33)."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
https_app:
build: https://git.example.com/operator/app.git#main
ssh_dict_app:
build:
context: ssh://git@git.example.com:2223/operator/app.git
dockerfile: Dockerfile
scp_git_app:
build: git@git.example.com:operator/app.git
local_app:
build:
context: ./docker
""",
encoding="utf-8",
)
(tmp_path / "docker").mkdir()
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is True
assert err is None
@pytest.mark.parametrize(
"build_yaml,expected_substr",
[
("build: /etc", "escaping workload root"),
("build:\n context: ../../outside", "escaping workload root"),
('build: "${BUILD_CTX}/app"', "variable interpolation"),
('build:\n context: "${BUILD_CTX}/app"', "variable interpolation"),
],
)
def test_validate_compose_security_rejects_unsafe_build_contexts(
tmp_path: Path, build_yaml: str, expected_substr: str
):
"""Ensure validate_compose_security blocks local build host-path escapes and ${...} interpolation (#33)."""
app_dir = tmp_path / "Workloads" / "my-app"
app_dir.mkdir(parents=True)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"services:\n app:\n {build_yaml}\n",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="my-app"
)
assert valid is False
assert err is not None and expected_substr in err.lower()
def test_monorepo_webhook_dispatch_pulls_once_and_deploys_only_admitted_changed_subdirs(
tmp_path: Path, monkeypatch
):
"""Ensure canopy-workloads push pulls ~/Workloads once and dispatches only admitted changed subdirs (#33)."""
workloads_dir = tmp_path / "Workloads"
(workloads_dir / ".git").mkdir(parents=True)
snappymail_dir = workloads_dir / "snappymail"
gitea_dir = workloads_dir / "homelab-gitea"
rogue_dir = workloads_dir / "rogue-app"
for d in (snappymail_dir, gitea_dir, rogue_dir):
d.mkdir(parents=True)
(d / "app.yaml").write_text(f"name: {d.name}\n", encoding="utf-8")
registry = tmp_path / "deployments.yaml"
registry.write_text(
'schemaVersion: "1.0"\n'
"repositories:\n"
" snappymail:\n"
' path: "~/Workloads/snappymail"\n'
" gitea:\n"
' path: "~/Workloads/homelab-gitea"\n',
encoding="utf-8",
)
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", workloads_dir)
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
monkeypatch.setattr(gitops_dispatcher, "STATE_DIR", tmp_path / "state")
payload = {
"ref": "refs/heads/main",
"after": "deadbeef1234",
"repository": {"name": "canopy-workloads"},
"commits": [
{
"added": ["rogue-app/app.yaml", "README.md"],
"modified": ["snappymail/docker-compose.yml"],
"removed": ["../Core/scripts/appctl"],
}
],
}
git_calls: list[list[str]] = []
enqueued: list[Path] = []
spawned: list[str] = []
def mock_run(cmd, *args, **kwargs):
git_calls.append(cmd)
return MagicMock(returncode=0, stdout="", stderr="")
monkeypatch.setattr(gitops_dispatcher.subprocess, "run", mock_run)
monkeypatch.setattr(
gitops_dispatcher,
"enqueue_deployment",
lambda target_dir, cfg, branch, commit_sha="": enqueued.append(target_dir),
)
monkeypatch.setattr(
gitops_dispatcher,
"spawn_worker_async",
lambda target_name: spawned.append(target_name),
)
assert gitops_dispatcher.is_monorepo_push(payload) is True
ok, dispatched, _ = gitops_dispatcher.dispatch_monorepo_push(payload, "push")
assert ok is True
assert dispatched == [snappymail_dir.resolve()]
assert enqueued == [snappymail_dir.resolve()]
assert spawned == ["snappymail"]
# Pulled ~/Workloads exactly once
pull_calls = [c for c in git_calls if "pull" in c]
assert len(pull_calls) == 1
assert str(workloads_dir) in pull_calls[0]
# ---------------------------------------------------------------------------
# ADR-0005 Host-Granted Workload Capabilities ("Compose Requests, Nix Grants")
# ---------------------------------------------------------------------------
def _write_grants(path: Path, workloads: dict) -> Path:
import json
path.write_text(
json.dumps({"schemaVersion": "1.0", "workloads": workloads}),
encoding="utf-8",
)
return path
def _fake_group_lookup(key: str | int) -> tuple[str, int]:
table = {
"render": ("render", 303),
303: ("render", 303),
"video": ("video", 44),
44: ("video", 44),
"docker": ("docker", 998),
998: ("docker", 998),
"wheel": ("wheel", 10),
10: ("wheel", 10),
"root": ("root", 0),
0: ("root", 0),
}
lookup_key = int(key) if isinstance(key, str) and key.isdigit() else key
if lookup_key in table:
return table[lookup_key]
raise KeyError(key)
def test_validate_compose_security_permits_granted_stack(tmp_path: Path):
"""Positive ADR-0005 grants: render<->303, existing device, short & long :ro readOnlyPaths."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
dev_dir = tmp_path / "dev" / "dri"
dev_dir.mkdir(parents=True)
render_node = dev_dir / "renderD128"
render_node.write_text("", encoding="utf-8")
media_dir = tmp_path / "mnt" / "media"
media_sub = media_dir / "movies"
media_sub.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{
"media": {
"devices": [str(render_node)],
"groups": ["render"],
"readOnlyPaths": [str(media_dir)],
}
},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
jellyfin:
image: jellyfin/jellyfin:latest
user: "1000:303"
group_add:
- "303"
devices:
- "{render_node}:/dev/dri/renderD128:rw"
volumes:
- "{media_sub}:/media/movies:ro"
- type: bind
source: "{media_dir}"
target: /media/all
read_only: true
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="media",
grants_file=grants_file,
group_lookup=_fake_group_lookup,
)
assert ok is True, f"Expected granted capabilities to pass, got: {err}"
assert err is None
def test_capability_grants_evaluates_resolved_env_interpolation(tmp_path: Path):
"""Post-interpolation values from resolved_env are evaluated and permitted when granted."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"groups": ["303"], "readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
user: "${PUID:-1000}:${PGID:-1000}"
group_add:
- "${RENDER_GID}"
volumes:
- "${MEDIA_PATH}:/media:ro"
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="media",
resolved_env={
"PUID": "1000",
"PGID": "1000",
"RENDER_GID": "render",
"MEDIA_PATH": str(media_dir),
},
grants_file=grants_file,
group_lookup=_fake_group_lookup,
)
assert ok is True, f"Expected resolved env capabilities to pass, got: {err}"
@pytest.mark.parametrize(
"compose_body,expected_substr",
[
(" user: '0:131'", "user"),
(" user: '00:1000'", "root"),
(" user: '1000:0'", "user"),
(" user: '1000:docker'", "docker"),
(" user: '1000:44'", "44"),
(" user: '1000:999'", "999"),
(" group_add:\n - '303'", "group_add"),
(" network_mode: 'container:traefik'", "container:traefik"),
(" network_mode: 'service:web'", "service:web"),
(" device_cgroup_rules:\n - 'c 226:* rmw'", "device_cgroup_rules"),
(" user: '${PUID}:1000'", "interpolation"),
],
)
def test_validate_compose_security_rejects_ungranted_capabilities(
tmp_path: Path, compose_body: str, expected_substr: str
):
"""Ensure bypass vectors and ungranted capabilities fail closed."""
app_dir = tmp_path / "Workloads" / "ungranted"
app_dir.mkdir(parents=True)
grants_file = _write_grants(tmp_path / "grants.json", {})
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"services:\n app:\n image: alpine\n{compose_body}\n",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="ungranted",
grants_file=grants_file,
group_lookup=_fake_group_lookup,
)
assert ok is False
assert err is not None
assert expected_substr.lower() in err.lower()
def test_validate_compose_security_fails_closed_when_pyyaml_missing(
tmp_path: Path, monkeypatch
):
"""Ensure validate_compose_security fails closed when PyYAML is unavailable."""
app_dir = tmp_path / "Workloads" / "app"
app_dir.mkdir(parents=True)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text("services:\n app:\n image: alpine\n", encoding="utf-8")
monkeypatch.setattr(gitops_dispatcher, "yaml", None)
ok, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir)
assert ok is False
assert err is not None and "pyyaml" in err.lower()
def test_capability_grants_device_mknod_rejected(tmp_path: Path):
"""Ensure :rwm (mknod) is rejected even when the device node exists and is granted."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
dev_dir = tmp_path / "dev" / "dri"
dev_dir.mkdir(parents=True)
render_node = dev_dir / "renderD128"
render_node.write_text("", encoding="utf-8")
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"devices": [str(render_node)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
devices:
- "{render_node}:/dev/dri/renderD128:rwm"
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
assert err is not None and "mknod" in err.lower()
def test_capability_grants_missing_device_node_rejected(tmp_path: Path):
"""Ensure a granted device path that does not exist on the host fails closed."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
missing_node = tmp_path / "dev" / "dri" / "renderD999"
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"devices": [str(missing_node)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
devices:
- "{missing_node}:/dev/dri/renderD999:rw"
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
assert err is not None and "does not exist" in err.lower()
def test_capability_grants_volumes_reject_rw_long_syntax(tmp_path: Path):
"""Ensure readOnlyPaths rejects long-syntax bind mounts without read_only: true."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
volumes:
- type: bind
source: "{media_dir}"
target: /media
read_only: false
""",
encoding="utf-8",
)
ok, _ = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
def test_capability_grants_volumes_reject_unsafe_propagation(tmp_path: Path):
"""Ensure readOnlyPaths rejects long-syntax bind mounts with unsafe propagation (rshared)."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
volumes:
- type: bind
source: "{media_dir}"
target: /media
read_only: true
bind:
propagation: rshared
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
assert err is not None and "propagation" in err.lower()
def test_capability_grants_volumes_reject_symlink_escape(tmp_path: Path):
"""Ensure readOnlyPaths rejects symlinks resolving outside the granted directory."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
outside_dir = tmp_path / "etc"
outside_dir.mkdir(parents=True)
escaped_link = media_dir / "escape"
escaped_link.symlink_to(outside_dir)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
volumes:
- "{escaped_link}:/media:ro"
""",
encoding="utf-8",
)
ok, _ = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
def test_capability_grants_app_name_none_receives_zero_grants(tmp_path: Path):
"""Ensure app_name=None receives zero grants even when grants.json defines workloads."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
volumes:
- "{media_dir}:/media:ro"
""",
encoding="utf-8",
)
ok, _ = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name=None, grants_file=grants_file
)
assert ok is False
def test_capability_grants_malformed_grants_fail_closed(tmp_path: Path):
"""Ensure malformed grants.json fails closed even on a plain compose file."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
plain_compose = app_dir / "plain.yml"
plain_compose.write_text("services:\n app:\n image: alpine\n", encoding="utf-8")
bad_grants = tmp_path / "bad_grants.json"
bad_grants.write_text("{corrupt", encoding="utf-8")
ok, err = gitops_dispatcher.validate_compose_security(
plain_compose, app_dir, app_name="media", grants_file=bad_grants
)
assert ok is False
assert err is not None and "grants" in err.lower()
def test_validate_compose_security_allows_ungranted_gid_1000(tmp_path: Path):
"""Ensure unprivileged numeric GID >= 1000 (1000:1000) is allowed without a grant."""
app_dir = tmp_path / "Workloads" / "ungranted"
app_dir.mkdir(parents=True)
grants_file = _write_grants(tmp_path / "grants.json", {})
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
"services:\n app:\n image: alpine\n user: '1000:1000'\n",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="ungranted",
grants_file=grants_file,
group_lookup=_fake_group_lookup,
)
assert ok is True
assert err is None
def test_validate_compose_security_rejects_high_numeric_gid_for_privileged_group(
tmp_path: Path,
):
"""Ensure numeric GID >= 1000 that resolves to a privileged group (docker) fails closed."""
app_dir = tmp_path / "Workloads" / "ungranted"
app_dir.mkdir(parents=True)
grants_file = _write_grants(tmp_path / "grants.json", {})
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
"services:\n app:\n image: alpine\n user: '1000:1998'\n",
encoding="utf-8",
)
def lookup_with_high_docker(key: str | int) -> tuple[str, int]:
if key in (1998, "1998"):
return ("docker", 1998)
return _fake_group_lookup(key)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="ungranted",
grants_file=grants_file,
group_lookup=lookup_with_high_docker,
)
assert ok is False
assert err is not None and "docker" in err.lower()
def test_validate_compose_security_rejects_sibling_prefix_paths(tmp_path: Path):
"""Ensure sibling directory prefixes (/dev/dri2, /mnt/media2) cannot bypass containment."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
granted_dev = tmp_path / "dev" / "dri"
granted_dev.mkdir(parents=True)
sibling_dev_dir = tmp_path / "dev" / "dri2"
sibling_dev_dir.mkdir(parents=True)
sibling_node = sibling_dev_dir / "renderD128"
sibling_node.write_text("", encoding="utf-8")
granted_media = tmp_path / "mnt" / "media"
granted_media.mkdir(parents=True)
sibling_media = tmp_path / "mnt" / "media2"
sibling_media.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{
"media": {
"devices": [str(granted_dev)],
"readOnlyPaths": [str(granted_media)],
}
},
)
dev_compose = app_dir / "dev-compose.yml"
dev_compose.write_text(
f"services:\n app:\n image: alpine\n devices:\n - '{sibling_node}:/dev/dri/renderD128:rw'\n",
encoding="utf-8",
)
ok_dev, _ = gitops_dispatcher.validate_compose_security(
dev_compose, app_dir, app_name="media", grants_file=grants_file
)
assert ok_dev is False
vol_compose = app_dir / "vol-compose.yml"
vol_compose.write_text(
f"services:\n app:\n image: alpine\n volumes:\n - '{sibling_media}:/media:ro'\n",
encoding="utf-8",
)
ok_vol, _ = gitops_dispatcher.validate_compose_security(
vol_compose, app_dir, app_name="media", grants_file=grants_file
)
assert ok_vol is False
+1 -101
View File
@@ -2,7 +2,6 @@
Security invariant tests for Docker Compose and container isolation. Security invariant tests for Docker Compose and container isolation.
""" """
import json
import os import os
import shutil import shutil
import subprocess import subprocess
@@ -210,7 +209,6 @@ def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests(
CORE_ROOT / "flake.nix", CORE_ROOT / "flake.nix",
CORE_ROOT / "docker-compose.yml", CORE_ROOT / "docker-compose.yml",
CORE_ROOT / "nixos" / "configuration.nix", CORE_ROOT / "nixos" / "configuration.nix",
CORE_ROOT / "nixos" / "instance.example.nix",
] ]
violations = [] violations = []
@@ -293,61 +291,6 @@ def test_nixos_tmpfiles_rules_use_recursive_acls():
) )
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(): def test_default_homelab_domain_evaluates_to_example_test():
"""Assert default homelab.domain in NixOS config evaluates to 'example.test'.""" """Assert default homelab.domain in NixOS config evaluates to 'example.test'."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix" homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
@@ -486,18 +429,12 @@ def test_nixos_switch_alias_uses_path_and_impure():
def test_nixos_safe_directory_includes_core_and_sites(): 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.""" """Ensure programs.git.config.safe.directory includes Core and Sites to prevent dubious ownership errors."""
config_nix = CORE_ROOT / "nixos" / "configuration.nix" config_nix = CORE_ROOT / "nixos" / "configuration.nix"
content = config_nix.read_text(encoding="utf-8") content = config_nix.read_text(encoding="utf-8")
assert '"/home/${config.homelab.operatorUser}/Core"' in content, ( assert '"/home/${config.homelab.operatorUser}/Core"' in content, (
"nixos/configuration.nix must include Core in git safe.directory" "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, ( assert '"/home/${config.homelab.operatorUser}/Sites/*"' in content, (
"nixos/configuration.nix must include Sites/* in git safe.directory" "nixos/configuration.nix must include Sites/* in git safe.directory"
) )
@@ -528,46 +465,9 @@ def test_nixos_safe_directory_includes_core_and_sites():
assert "/home/operator/Core" in safe_dirs, ( assert "/home/operator/Core" in safe_dirs, (
f"Expected '/home/operator/Core' in git safe.directory, got {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, ( assert "/home/operator/Sites/*" in safe_dirs, (
f"Expected '/home/operator/Sites/*' in git safe.directory, got {safe_dirs}" f"Expected '/home/operator/Sites/*' in git safe.directory, got {safe_dirs}"
) )
def test_nixos_homeserver_defaults_to_workloads_dir():
"""Ensure homeserver.nix defaults sitesDir to ~/Workloads and exports WORKLOADS_DIR + SITES_DIR (#33)."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert 'default = "/home/${config.homelab.operatorUser}/Workloads";' in content, (
"homelab.sitesDir must default to /home/${config.homelab.operatorUser}/Workloads"
)
assert "WORKLOADS_DIR = config.homelab.sitesDir;" in content, (
"homeserver.nix must export WORKLOADS_DIR"
)
assert "SITES_DIR = config.homelab.sitesDir;" in content, (
"homeserver.nix must export SITES_DIR for backward compatibility"
)
def test_nixos_workload_grants_option_and_projection():
"""Ensure homeserver.nix defines homelab.workloadGrants, /etc/homelab/grants.json, and HOMELAB_GRANTS_FILE."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert "workloadGrants = lib.mkOption" in content
assert 'environment.etc."homelab/grants.json"' in content
assert 'user = "root";' in content
assert 'group = "homelab-operators";' in content
assert 'mode = "0640";' in content
assert content.count('HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";') >= 2
assert "PrivateUsers" not in content
@@ -20,7 +20,6 @@ def test_required_architectural_paths_exist():
"SECURITY.md", "SECURITY.md",
"nixos", "nixos",
"nixos/configuration.nix", "nixos/configuration.nix",
"nixos/instance.example.nix",
"nixos/modules/homeserver.nix", "nixos/modules/homeserver.nix",
"nixos/secrets.yaml", "nixos/secrets.yaml",
"scripts/gitops_dispatcher.py", "scripts/gitops_dispatcher.py",
+14 -30
View File
@@ -8,6 +8,7 @@ test_<subject>_<accepts|rejects|enforces>_<condition>
from __future__ import annotations from __future__ import annotations
import json import json
import os
import stat import stat
from pathlib import Path from pathlib import Path
@@ -231,31 +232,6 @@ def test_redact_sensitive_data_masks_secret_keys():
assert redacted["nested"]["list_items"][1] == "safe_string" 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( def test_audit_logger_automatically_redacts_sensitive_parameters(
temp_audit_file: Path, sample_principal: PrincipalAudit temp_audit_file: Path, sample_principal: PrincipalAudit
): ):
@@ -284,12 +260,17 @@ def test_audit_logger_automatically_redacts_sensitive_parameters(
def test_audit_logger_fails_closed_when_audit_log_unwritable( def test_audit_logger_fails_closed_when_audit_log_unwritable(
tmp_path: Path, sample_principal: PrincipalAudit tmp_path: Path, sample_principal: PrincipalAudit
): ):
# Using a directory as the audit path causes os.open with O_WRONLY to fail with read_only_dir = tmp_path / "readonly_audit"
# EISDIR / OSError across all platforms and environments (including root containers). read_only_dir.mkdir(parents=True, exist_ok=True)
unwritable_target = tmp_path / "unwritable_audit_dir" unwritable_file = read_only_dir / "audit.jsonl"
unwritable_target.mkdir(parents=True, exist_ok=True) unwritable_file.touch(mode=0o400)
os.chmod(unwritable_file, 0o400)
logger = AuditLogger(unwritable_target) # In addition, make directory read-only
os.chmod(read_only_dir, 0o500)
try:
logger = AuditLogger(unwritable_file)
with pytest.raises(AuditPersistenceError) as exc_info: with pytest.raises(AuditPersistenceError) as exc_info:
logger.log_dispatched( logger.log_dispatched(
operation_id="op_105", operation_id="op_105",
@@ -302,6 +283,9 @@ def test_audit_logger_fails_closed_when_audit_log_unwritable(
parameters={"recreate": True}, parameters={"recreate": True},
) )
assert "Failed to persist audit event" in str(exc_info.value) assert "Failed to persist audit event" in str(exc_info.value)
finally:
os.chmod(read_only_dir, 0o700)
os.chmod(unwritable_file, 0o600)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
+34 -187
View File
@@ -37,12 +37,8 @@ def secret_tokens() -> dict[str, str]:
@pytest.fixture @pytest.fixture
def temp_tokens_file(tmp_path: Path, secret_tokens: dict[str, str]) -> Path: def temp_tokens_file(tmp_path: Path, secret_tokens: dict[str, str]) -> Path:
tokens_path = tmp_path / "tokens.json" tokens_path = tmp_path / "tokens.json"
admin_hash = hashlib.sha256( admin_hash = hashlib.sha256(secret_tokens["admin_secret"].encode("utf-8")).hexdigest()
secret_tokens["admin_secret"].encode("utf-8") op_hash = hashlib.sha256(secret_tokens["operator_secret"].encode("utf-8")).hexdigest()
).hexdigest()
op_hash = hashlib.sha256(
secret_tokens["operator_secret"].encode("utf-8")
).hexdigest()
data = [ data = [
{ {
@@ -125,31 +121,6 @@ def test_token_store_authenticates_valid_bearer_secrets(
assert p_op.token_id == "tok_gitops_01" 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): def test_token_store_rejects_invalid_bearer_secret(temp_tokens_file: Path):
store = TokenStore(temp_tokens_file) store = TokenStore(temp_tokens_file)
@@ -207,9 +178,7 @@ def test_authenticate_request_over_uds_falls_back_to_viewer(
# Explicit Bearer token over UDS confers full privileges # Explicit Bearer token over UDS confers full privileges
auth_header = f"Bearer {secret_tokens['admin_secret']}" auth_header = f"Bearer {secret_tokens['admin_secret']}"
p_admin = authenticate_request( p_admin = authenticate_request("unix_socket", auth_header, peer_uid=1000, token_store=store)
"unix_socket", auth_header, peer_uid=1000, token_store=store
)
assert p_admin.role == Role.ADMIN assert p_admin.role == Role.ADMIN
assert p_admin.auth_method == "bearer_token" assert p_admin.auth_method == "bearer_token"
@@ -227,8 +196,7 @@ def test_authenticate_request_over_uds_rejects_missing_peer_uid():
def test_load_admitted_workloads_parses_names_and_aliases(tmp_path: Path): def test_load_admitted_workloads_parses_names_and_aliases(tmp_path: Path):
deploy_file = tmp_path / "deployments.yaml" deploy_file = tmp_path / "deployments.yaml"
deploy_file.write_text( deploy_file.write_text("""
"""
schemaVersion: "1.0" schemaVersion: "1.0"
repositories: repositories:
snappymail: snappymail:
@@ -240,9 +208,7 @@ repositories:
path: "/home/operator/Sites/homelab-jellyfin" path: "/home/operator/Sites/homelab-jellyfin"
aliases: aliases:
- "media" - "media"
""", """, encoding="utf-8")
encoding="utf-8",
)
admitted = load_admitted_workloads(deploy_file) admitted = load_admitted_workloads(deploy_file)
assert "snappymail" in admitted assert "snappymail" in admitted
@@ -255,19 +221,14 @@ repositories:
def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: Path): def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: Path):
deploy_file = tmp_path / "deployments.json" deploy_file = tmp_path / "deployments.json"
deploy_file.write_text( deploy_file.write_text(json.dumps({
json.dumps(
{
"repositories": { "repositories": {
"app1": { "app1": {
"path": "/home/operator/Sites/app1", "path": "/home/operator/Sites/app1",
"aliases": [123, None, " ", "valid_alias"], "aliases": [123, None, " ", "valid_alias"]
} }
} }
} }), encoding="utf-8")
),
encoding="utf-8",
)
admitted = load_admitted_workloads(deploy_file) admitted = load_admitted_workloads(deploy_file)
assert "app1" in admitted assert "app1" in admitted
@@ -277,17 +238,13 @@ def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: P
assert "" not in admitted assert "" not in admitted
def test_load_admitted_workloads_fails_closed_on_missing_file( def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
admitted = load_admitted_workloads(tmp_path / "missing.yaml") admitted = load_admitted_workloads(tmp_path / "missing.yaml")
assert admitted == set() assert admitted == set()
# Test HOMELAB_DEPLOYMENTS_FILE fallback # Test HOMELAB_DEPLOYMENTS_FILE fallback
deploy_file = tmp_path / "env_deploy.yaml" deploy_file = tmp_path / "env_deploy.yaml"
deploy_file.write_text( deploy_file.write_text("repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8")
"repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8"
)
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deploy_file)) monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deploy_file))
admitted_env = load_admitted_workloads(None) admitted_env = load_admitted_workloads(None)
assert "env_app" in admitted_env assert "env_app" in admitted_env
@@ -301,16 +258,12 @@ def test_load_admitted_workloads_fails_closed_on_missing_file(
def test_rbac_admin_permitted_across_all_operations_and_targets( def test_rbac_admin_permitted_across_all_operations_and_targets(
admitted_workloads: set[str], admitted_workloads: set[str],
): ):
admin = Principal( admin = Principal(identity="admin_user", role=Role.ADMIN, auth_method="bearer_token")
identity="admin_user", role=Role.ADMIN, auth_method="bearer_token"
)
# Mutations across Core and Sites # Mutations across Core and Sites
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads) enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads)
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "traefik", admitted_workloads) enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "traefik", admitted_workloads)
enforce_rbac( enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads)
admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads
)
enforce_rbac(admin, OperationType.WORKLOAD_CONFIG, "core", admitted_workloads) enforce_rbac(admin, OperationType.WORKLOAD_CONFIG, "core", admitted_workloads)
enforce_rbac(admin, OperationType.WORKLOAD_LOGS, "traefik", 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.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads)
@@ -320,139 +273,79 @@ def test_rbac_admin_permitted_across_all_operations_and_targets(
def test_rbac_operator_permitted_on_admitted_workloads( def test_rbac_operator_permitted_on_admitted_workloads(
admitted_workloads: set[str], admitted_workloads: set[str],
): ):
operator = Principal( operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
# Permitted on admitted workload # Permitted on admitted workload
enforce_rbac( enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads)
operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads
)
enforce_rbac(operator, OperationType.WORKLOAD_UPDATE, "mail", admitted_workloads) enforce_rbac(operator, OperationType.WORKLOAD_UPDATE, "mail", admitted_workloads)
enforce_rbac( enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads)
operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads
)
enforce_rbac(operator, OperationType.WORKLOAD_LOGS, "docs", admitted_workloads) enforce_rbac(operator, OperationType.WORKLOAD_LOGS, "docs", admitted_workloads)
enforce_rbac( enforce_rbac(operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads)
operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads
)
enforce_rbac(operator, OperationType.WORKLOAD_LIST, None, admitted_workloads) enforce_rbac(operator, OperationType.WORKLOAD_LIST, None, admitted_workloads)
def test_rbac_operator_denied_on_core_targets( def test_rbac_operator_denied_on_core_targets(
admitted_workloads: set[str], admitted_workloads: set[str],
): ):
operator = Principal( operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
# Targeting "core" stack # Targeting "core" stack
with pytest.raises(AuthorizationError) as exc_info: with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac( enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads)
operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads
)
assert "not permitted to target core service 'core'" in str(exc_info.value) assert "not permitted to target core service 'core'" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
# Targeting core services (traefik, stalwart, etc.) # Targeting core services (traefik, stalwart, etc.)
for core_svc in ["traefik", "authelia", "stalwart", "socket-proxy"]: for core_svc in ["traefik", "authelia", "stalwart", "socket-proxy"]:
with pytest.raises(AuthorizationError) as exc_info: with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac( enforce_rbac(operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads)
operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads assert f"not permitted to target core service '{core_svc}'" in str(exc_info.value)
)
assert f"not permitted to target core service '{core_svc}'" in str(
exc_info.value
)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED 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( def test_rbac_operator_denied_without_target_on_mutating_or_sensitive_ops(
admitted_workloads: set[str], admitted_workloads: set[str],
): ):
operator = Principal( operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
for op in [ for op in [OperationType.WORKLOAD_DEPLOY, OperationType.WORKLOAD_UPDATE, OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]:
OperationType.WORKLOAD_DEPLOY,
OperationType.WORKLOAD_UPDATE,
OperationType.WORKLOAD_CONFIG,
OperationType.WORKLOAD_LOGS,
]:
with pytest.raises(AuthorizationError) as exc_info: with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, op, None, admitted_workloads) enforce_rbac(operator, op, None, admitted_workloads)
assert f"Operation '{op.value}' requires an explicit workload target" in str( assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value)
exc_info.value
)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
with pytest.raises(AuthorizationError) as exc_info: with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, op, "", admitted_workloads) enforce_rbac(operator, op, "", admitted_workloads)
assert f"Operation '{op.value}' requires an explicit workload target" in str( assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value)
exc_info.value
)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_operator_with_default_admitted_workloads( def test_rbac_operator_with_default_admitted_workloads(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
):
deployments_file = tmp_path / "deployments.yaml" deployments_file = tmp_path / "deployments.yaml"
deployments_file.write_text( deployments_file.write_text("repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8")
"repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8"
)
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file)) monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file))
operator = Principal( operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token" enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "customapp", admitted_workloads=None)
)
enforce_rbac(
operator, OperationType.WORKLOAD_DEPLOY, "customapp", admitted_workloads=None
)
with pytest.raises(AuthorizationError) as exc_info: with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac( enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unknownapp", admitted_workloads=None)
operator,
OperationType.WORKLOAD_DEPLOY,
"unknownapp",
admitted_workloads=None,
)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_operator_denied_on_unregistered_workload( def test_rbac_operator_denied_on_unregistered_workload(
admitted_workloads: set[str], admitted_workloads: set[str],
): ):
operator = Principal( operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
with pytest.raises(AuthorizationError) as exc_info: with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac( enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unregistered_app", admitted_workloads)
operator,
OperationType.WORKLOAD_DEPLOY,
"unregistered_app",
admitted_workloads,
)
assert "not registered in deployments.yaml" in str(exc_info.value) assert "not registered in deployments.yaml" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_viewer_permitted_only_on_non_sensitive_reads(): def test_rbac_viewer_permitted_only_on_non_sensitive_reads():
viewer = Principal( viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
)
# Permitted reads # Permitted reads
enforce_rbac(viewer, OperationType.WORKLOAD_LIST, None) enforce_rbac(viewer, OperationType.WORKLOAD_LIST, None)
@@ -463,9 +356,7 @@ def test_rbac_viewer_permitted_only_on_non_sensitive_reads():
def test_rbac_viewer_denied_on_mutations(): def test_rbac_viewer_denied_on_mutations():
viewer = Principal( viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
)
mutations = [ mutations = [
OperationType.WORKLOAD_DEPLOY, OperationType.WORKLOAD_DEPLOY,
@@ -483,54 +374,10 @@ def test_rbac_viewer_denied_on_mutations():
def test_rbac_viewer_denied_on_sensitive_reads(): def test_rbac_viewer_denied_on_sensitive_reads():
viewer = Principal( viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
)
for sens_op in [OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]: for sens_op in [OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]:
with pytest.raises(AuthorizationError) as exc_info: with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(viewer, sens_op, "snappymail") enforce_rbac(viewer, sens_op, "snappymail")
assert "not permitted to access sensitive operation" in str(exc_info.value) assert "not permitted to access sensitive operation" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED 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"}
+1 -4
View File
@@ -473,11 +473,9 @@ def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path,
import socket as std_socket import socket as std_socket
import subprocess import subprocess
import sys import sys
import tempfile
bash_bin = shutil.which("bash") or "bash" bash_bin = shutil.which("bash") or "bash"
sock_dir = tempfile.TemporaryDirectory(prefix="appctl_sock_", dir="/tmp") sock_path = tmp_path / "appctl.sock"
sock_path = Path(sock_dir.name) / "appctl.sock"
srv = std_socket.socket(std_socket.AF_UNIX, std_socket.SOCK_STREAM) srv = std_socket.socket(std_socket.AF_UNIX, std_socket.SOCK_STREAM)
srv.bind(str(sock_path)) srv.bind(str(sock_path))
try: try:
@@ -514,7 +512,6 @@ def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path,
assert "core" in res_words.stdout assert "core" in res_words.stdout
finally: finally:
srv.close() srv.close()
sock_dir.cleanup()
def test_appctl_wrapper_fails_closed_when_socket_is_missing(tmp_path: Path): def test_appctl_wrapper_fails_closed_when_socket_is_missing(tmp_path: Path):
+2 -4
View File
@@ -445,13 +445,12 @@ def test_operation_request_backward_compatibility_aliases():
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def test_error_code_taxonomy_contains_exactly_7_canonical_codes(): def test_error_code_taxonomy_contains_exactly_6_canonical_codes():
assert len(ErrorCode) == 7 assert len(ErrorCode) == 6
expected_codes = { expected_codes = {
"ERR_VALIDATION_FAILED", "ERR_VALIDATION_FAILED",
"ERR_AUTH_REQUIRED", "ERR_AUTH_REQUIRED",
"ERR_PERMISSION_DENIED", "ERR_PERMISSION_DENIED",
"ERR_CAPABILITY_NOT_GRANTED",
"ERR_TARGET_NOT_FOUND", "ERR_TARGET_NOT_FOUND",
"ERR_CONCURRENT_MUTATION", "ERR_CONCURRENT_MUTATION",
"ERR_EXECUTION_FAILED", "ERR_EXECUTION_FAILED",
@@ -463,7 +462,6 @@ def test_error_code_http_status_mapping():
assert ErrorCode.ERR_VALIDATION_FAILED.http_status == 400 assert ErrorCode.ERR_VALIDATION_FAILED.http_status == 400
assert ErrorCode.ERR_AUTH_REQUIRED.http_status == 401 assert ErrorCode.ERR_AUTH_REQUIRED.http_status == 401
assert ErrorCode.ERR_PERMISSION_DENIED.http_status == 403 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_TARGET_NOT_FOUND.http_status == 404
assert ErrorCode.ERR_CONCURRENT_MUTATION.http_status == 409 assert ErrorCode.ERR_CONCURRENT_MUTATION.http_status == 409
assert ErrorCode.ERR_EXECUTION_FAILED.http_status == 500 assert ErrorCode.ERR_EXECUTION_FAILED.http_status == 500
+7 -66
View File
@@ -22,7 +22,6 @@ import concurrent.futures
import hashlib import hashlib
import json import json
import socket import socket
import tempfile
import threading import threading
import time import time
from pathlib import Path from pathlib import Path
@@ -30,7 +29,7 @@ from unittest.mock import patch
import gitops_dispatcher import gitops_dispatcher
import pytest import pytest
from appctl_audit import AuditLogger, AuditPersistenceError, TargetLockManager from appctl_audit import AuditLogger, TargetLockManager
from appctl_auth import Role, TokenDescriptor, TokenStore from appctl_auth import Role, TokenDescriptor, TokenStore
from appctl_contracts import ErrorCode, OperationRequest, OperationType from appctl_contracts import ErrorCode, OperationRequest, OperationType
from appctl_daemon import ( from appctl_daemon import (
@@ -65,8 +64,7 @@ def daemon_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
- Valid 0600 audit log file - Valid 0600 audit log file
""" """
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test") monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
sock_dir = tempfile.TemporaryDirectory(prefix="appctl_sock_", dir="/tmp") socket_path = tmp_path / "appctl.sock"
socket_path = Path(sock_dir.name) / "appctl.sock"
http_port = get_free_port() http_port = get_free_port()
http_host = "127.0.0.1" http_host = "127.0.0.1"
@@ -153,7 +151,6 @@ def daemon_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
f' path: "{docs_dir}"\n', f' path: "{docs_dir}"\n',
encoding="utf-8", encoding="utf-8",
) )
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file))
router = OperationalRouter( router = OperationalRouter(
audit_logger=audit_logger, audit_logger=audit_logger,
@@ -194,7 +191,6 @@ def daemon_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
yield ctx yield ctx
finally: finally:
daemon.stop() daemon.stop()
sock_dir.cleanup()
def test_health_endpoint(daemon_env): def test_health_endpoint(daemon_env):
@@ -523,16 +519,10 @@ def test_audit_failure_blocks_mutation(daemon_env):
Unwritable audit.jsonl aborts mutating command with 500 ERR_EXECUTION_FAILED Unwritable audit.jsonl aborts mutating command with 500 ERR_EXECUTION_FAILED
and zero Docker invocations. and zero Docker invocations.
""" """
daemon_env.audit_file.chmod(0o400)
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs") deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
with ( with patch("appctl_router.run_bounded_subprocess") as mock_subproc:
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( resp = send_daemon_request(
endpoint=daemon_env.socket_path, endpoint=daemon_env.socket_path,
operation_request=deploy_req, operation_request=deploy_req,
@@ -544,6 +534,9 @@ def test_audit_failure_blocks_mutation(daemon_env):
assert resp.error.code.http_status == 500 assert resp.error.code.http_status == 500
assert mock_subproc.call_count == 0 assert mock_subproc.call_count == 0
# Restore write permission for teardown
daemon_env.audit_file.chmod(0o600)
def test_daemon_restart_preserves_state(daemon_env): def test_daemon_restart_preserves_state(daemon_env):
""" """
@@ -591,55 +584,3 @@ def test_gitops_dispatcher_delegates_to_daemon(daemon_env, monkeypatch):
) )
assert success is True assert success is True
assert mock_sub.call_count >= 1 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
-53
View File
@@ -554,56 +554,3 @@ def test_cmd_list_flags_manifest_error(
engine.cmd_list([]) engine.cmd_list([])
captured = capsys.readouterr() captured = capsys.readouterr()
assert "Manifest Error" in captured.out 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
+4 -31
View File
@@ -66,9 +66,7 @@ def test_validate_transport_rejects_http(insecure_url: str):
], ],
) )
def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url): def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url):
with pytest.raises( with pytest.raises(ManifestValidationError, match=r"^Source URL cannot be empty\.$"):
ManifestValidationError, match=r"^Source URL cannot be empty\.$"
):
validate_transport(empty_or_invalid_url) # type: ignore[arg-type] validate_transport(empty_or_invalid_url) # type: ignore[arg-type]
@@ -79,9 +77,7 @@ def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url):
("ssh://git.example.com/", "SSH"), ("ssh://git.example.com/", "SSH"),
], ],
) )
def test_validate_transport_rejects_root_repository_path( def test_validate_transport_rejects_root_repository_path(root_path_url: str, scheme: str):
root_path_url: str, scheme: str
):
with pytest.raises( with pytest.raises(
ManifestValidationError, ManifestValidationError,
match=rf"^Malformed {scheme} source URL \(missing repository path\)", match=rf"^Malformed {scheme} source URL \(missing repository path\)",
@@ -136,10 +132,8 @@ def test_classify_ref_branches():
"feat/manifest-engine", "feat/manifest-engine",
) )
assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0") assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0")
assert classify_ref("custom-adhoc-branch") == ( assert classify_ref("custom-adhoc-branch") == (RefType.BRANCH, "custom-adhoc-branch")
RefType.BRANCH,
"custom-adhoc-branch",
)
def test_classify_ref_tags(): def test_classify_ref_tags():
@@ -277,15 +271,6 @@ def test_parse_manifest_from_path(tmp_path: Path):
"IFS", "IFS",
"CORE_DIR", "CORE_DIR",
"SITES_DIR", "SITES_DIR",
"HOMELAB_DOMAIN",
"DOMAIN_SUFFIX",
"DOMAIN",
"PROXY_NETWORK",
"CERT_RESOLVER",
"DOCKER_CONFIG",
"SERVICE_NAME",
"CONTAINER_NAME",
"SERVICE_DOMAIN",
], ],
) )
def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str): def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str):
@@ -355,15 +340,3 @@ description: "Pydantic serialization test"
assert dumped["name"] == "serialized-app" assert dumped["name"] == "serialized-app"
assert dumped["schemaVersion"] == "1.0" assert dumped["schemaVersion"] == "1.0"
assert manifest.to_dict()["name"] == "serialized-app" assert manifest.to_dict()["name"] == "serialized-app"
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)
-97
View File
@@ -266,100 +266,3 @@ def test_get_local_checkout_status_git_error(tmp_path: Path):
assert status.is_dirty is False assert status.is_dirty is False
assert status.status_label == "⚠️ Git Error (exit 128)" 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"
-164
View File
@@ -1,164 +0,0 @@
"""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) == {}