From 92333b017c0c77cb93137c18fd7da77306cc09fe Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 20 Nov 2026 13:43:14 -0500 Subject: [PATCH 01/10] docs(adr): add ADR-0005 for host-granted workload capabilities - Record ADR-0005 ('Compose Requests, Nix Grants') amending ADR-0002 - Define homelab.workloadGrants -> /etc/homelab/grants.json and nixos/instance.example.nix contract - Register ADR-0005 in docs/decisions/README.md --- .../0005-workload-capability-grants.md | 84 +++++++++++++++++++ docs/decisions/README.md | 10 +++ 2 files changed, 94 insertions(+) create mode 100644 docs/decisions/0005-workload-capability-grants.md diff --git a/docs/decisions/0005-workload-capability-grants.md b/docs/decisions/0005-workload-capability-grants.md new file mode 100644 index 0000000..2a77965 --- /dev/null +++ b/docs/decisions/0005-workload-capability-grants.md @@ -0,0 +1,84 @@ +--- +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-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`) and [ADR-0004](0004-unified-workloads-monorepo.md), `validate_compose_security()` in `scripts/gitops_dispatcher.py` enforces a uniform deny-all pre-flight policy on Tier 2 workload `docker-compose.yml` files: + +* All `devices:` mounts are unconditionally blocked. +* All host bind mounts outside `~/Workloads/` and `~/var/lib/homelab/` are blocked. +* All host namespace sharing (`network_mode: host`, etc.) is blocked. + +While this prevents a Tier 2 `git push` from escalating privileges on the host, it creates real friction for legitimate single-operator workloads: + +1. **Hardware Acceleration (`jellyfin`)**: Using an integrated GPU (`/dev/dri`) for VAAPI transcoding and reading a dedicated media partition (`/media:ro`) are blocked unless the validator is relaxed globally or fragile host-level bind-mount workarounds are maintained. +2. **LAN Broadcast / Peer Services (e.g., `lg-smtv-mcp`)**: Workloads that send Wake-on-LAN broadcasts or discover LAN peers may require `network_mode: host` when bridged Docker networks cannot forward subnet broadcasts. +3. **Host-Agnostic Core Boundary**: Hardcoding `/dev/dri`, `/media`, or specific workload names inside `nixos-core` violates platform genericism and couples Core to one machine's hardware and app catalog. + +The central architectural question is: **How should Canopy NixOS Core permit hardware devices, external read-only paths, and host networking 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 be able to 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 the requested `devices`, `volumes`, `group_add`, and `network_mode`. +* **Documented Instance Schema**: Provide a tracked `nixos/instance.example.nix` template so new hosts (or a future setup wizard) can configure `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants` cleanly in `/etc/nixos/homelab-instance.nix` (or gitignored `nixos/instance.nix`). +* **Fail-Closed Validation**: Absent, unreadable, or malformed grant configuration must default to zero grants (identical to today's strict baseline), and `privileged: true` and `/var/run/docker.sock` mounts remain permanently prohibited for all workloads. + +## 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 checked by `validate_compose_security()`. + +## Decision Outcome + +Chosen option: **Option 3: "Compose Requests, Nix Grants" via `homelab.workloadGrants`**, because it keeps `nixos-core` 100% 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 four explicit grant fields: + * `devices` (list of exact device paths, e.g. `"/dev/dri"` or `"/dev/dri/renderD128"`). + * `groups` (list of supplementary group names/GIDs permitted in `group_add`). + * `readOnlyPaths` (list of host directories permitted for `:ro` bind mounts only). + * `hostNetwork` (boolean permitting `network_mode: host`). + * `privileged: true`, `/var/run/docker.sock`, `cap_add`, and `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, readable by `homelab-appctl` and `homelab-gitops`, configurable via `HOMELAB_GRANTS_FILE` for testing). + * If the grants file is absent, `validate_compose_security()` defaults to zero grants. If present but malformed, validation fails closed. + +3. **Exact-Match Pre-Flight Enforcement**: + * Every capability requested in `/docker-compose.yml` must match an explicit grant for `` in `/etc/homelab/grants.json`: + * `devices` entries must resolve canonically within the granted device path(s) (with no `..` traversal or container-side privilege escalation). + * `readOnlyPaths` grants permit mounts **only** when `:ro` is specified and `Path.resolve()` remains contained within the granted directory. + * `network_mode: host` is permitted **only** when `hostNetwork = true` for that workload. + +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 their concrete configuration in `/etc/nixos/homelab-instance.nix` (or gitignored `nixos/instance.nix`) without build-time file translation between the two. + +## 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 cannot safely express `network_mode: host`. + +### 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` stays clean, and privilege elevation requires explicit host-level `nixos-rebuild switch`. +* Bad, because adding a new privileged capability for a workload requires editing `/etc/nixos/homelab-instance.nix` and rebuilding NixOS before `appctl up`. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index a3b57b8..4496572 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -10,6 +10,7 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using | Decision Record | Status | Date | Scope & One-Line Purpose | | :--- | :--- | :--- | :--- | +| [**ADR-0005: Host-Granted Workload Capabilities**](0005-workload-capability-grants.md) | `accepted` | 2026-11-20 | Amends ADR-0002 to introduce `homelab.workloadGrants` (`/etc/homelab/grants.json`) and `nixos/instance.example.nix` so NixOS hosts explicitly authorize `devices`, `groups`, `readOnlyPaths`, and `hostNetwork` per workload. | | [**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//` state isolation. | | [**ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. | | [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and deterministic Git-backed declarative deployment state. | @@ -19,6 +20,15 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using ## 🧭 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`, `readOnlyPaths`, and `hostNetwork` grants while keeping `privileged: true`, `docker.sock`, and `cap_add` 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) From 8f3b98344aa864b05fe66c33f387cab5c1d411cb Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 20 Nov 2026 22:58:16 -0500 Subject: [PATCH 02/10] docs(adr): refine ADR-0005 addressing Zoom Out and Catalyst review findings - Drop hostNetwork grant from workloadGrants to protect 127.0.0.1:9001 appctl boundary - Explicitly motivate groups grant by detailing jellyfin GID 303 (render) requirement - Elevate enforcement specifications to architectural invariants - Acknowledge host-path coupling trade-off --- .../0005-workload-capability-grants.md | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/decisions/0005-workload-capability-grants.md b/docs/decisions/0005-workload-capability-grants.md index 2a77965..a57ee33 100644 --- a/docs/decisions/0005-workload-capability-grants.md +++ b/docs/decisions/0005-workload-capability-grants.md @@ -19,11 +19,11 @@ Under [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`) While this prevents a Tier 2 `git push` from escalating privileges on the host, it creates real friction for legitimate single-operator workloads: -1. **Hardware Acceleration (`jellyfin`)**: Using an integrated GPU (`/dev/dri`) for VAAPI transcoding and reading a dedicated media partition (`/media:ro`) are blocked unless the validator is relaxed globally or fragile host-level bind-mount workarounds are maintained. -2. **LAN Broadcast / Peer Services (e.g., `lg-smtv-mcp`)**: Workloads that send Wake-on-LAN broadcasts or discover LAN peers may require `network_mode: host` when bridged Docker networks cannot forward subnet broadcasts. +1. **Hardware Acceleration & Media Access (`jellyfin`)**: Using an integrated GPU (`/dev/dri`) for VAAPI transcoding requires mounting host device nodes, passing supplementary groups (`group_add: ["303"]` / `render`), and reading a dedicated media partition (`/media:ro`). Currently, `devices:` and arbitrary bind mounts are completely blocked, while `group_add:` is unconstrained (risking arbitrary host GID elevation to groups like `docker` or `wheel` unless strictly governed). +2. **LAN Broadcast / Peer Services (e.g., `lg-smtv-mcp`)**: Workloads that send Wake-on-LAN broadcasts or discover LAN peers may struggle across Docker bridge boundaries, prompting requests for `network_mode: host`. However, blanket host networking collapses network namespace isolation, exposing loopback control services (such as `homelab-appctl.service` on `127.0.0.1:9001`) and bypassing proxy network segmentation. 3. **Host-Agnostic Core Boundary**: Hardcoding `/dev/dri`, `/media`, or specific workload names inside `nixos-core` violates platform genericism and couples Core to one machine's hardware and app catalog. -The central architectural question is: **How should Canopy NixOS Core permit hardware devices, external read-only paths, and host networking for specific workloads without hardcoding personal infrastructure into `nixos-core` or weakening the Tier 2 -> Tier 3 trust boundary?** +The central architectural question is: **How should Canopy NixOS Core permit hardware devices, supplementary groups, 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 @@ -48,12 +48,12 @@ Chosen option: **Option 3: "Compose Requests, Nix Grants" via `homelab.workloadG 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 four explicit grant fields: + * `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, e.g. `"/dev/dri"` or `"/dev/dri/renderD128"`). - * `groups` (list of supplementary group names/GIDs permitted in `group_add`). + * `groups` (list of supplementary group names/GIDs permitted in `group_add`, such as `"303"` or `"render"`). * `readOnlyPaths` (list of host directories permitted for `:ro` bind mounts only). - * `hostNetwork` (boolean permitting `network_mode: host`). - * `privileged: true`, `/var/run/docker.sock`, `cap_add`, and `pid`/`ipc`/`uts`/`userns_mode: host` remain permanently prohibited and are not grantable. + * Note on `network_mode: host`: To preserve the `127.0.0.1:9001` daemon boundary and Traefik reverse-proxy segmentation, host networking is rejected and excluded from `workloadGrants`. Workloads requiring L2 broadcast/discovery should be provisioned on dedicated isolated Docker networks (`macvlan`/`ipvlan`) or host-side intermediaries. + * `privileged: true`, `/var/run/docker.sock`, `cap_add`, and host namespaces (`pid`, `ipc`, `uts`, `userns_mode`, `network_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, readable by `homelab-appctl` and `homelab-gitops`, configurable via `HOMELAB_GRANTS_FILE` for testing). @@ -61,9 +61,10 @@ This ADR formally amends [ADR-0002](0002-appctl-control-plane-architecture.md) ( 3. **Exact-Match Pre-Flight Enforcement**: * Every capability requested in `/docker-compose.yml` must match an explicit grant for `` in `/etc/homelab/grants.json`: - * `devices` entries must resolve canonically within the granted device path(s) (with no `..` traversal or container-side privilege escalation). - * `readOnlyPaths` grants permit mounts **only** when `:ro` is specified and `Path.resolve()` remains contained within the granted directory. - * `network_mode: host` is permitted **only** when `hostNetwork = true` for that workload. + * `devices` entries must have their host path resolve canonically strictly within the granted device node or directory, strictly disallowing directory traversal (`..`) or symlink escapes. + * `groups` entries must match allowlisted GIDs or group names granted to that specific workload. + * `readOnlyPaths` grants permit mounts **only** when `:ro` mode is specified and the canonical host path resolves strictly within the granted directory. + * *Trade-off (Host Path Coupling)*: Workload Compose definitions declare physical host paths matching host grants; logical capability aliasing via environment variable injection remains an optional future refinement. 4. **Tracked Instance Template (`nixos/instance.example.nix`)**: * `nixos-core` tracks `nixos/instance.example.nix` documenting `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants`. From f326b1198643395c16ba66f64fda230501f48ebc Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 21 Nov 2026 00:06:43 -0500 Subject: [PATCH 03/10] docs(adr): generalize ADR-0005 examples and clarify grants permissions/GIDs - Replace specific workload names (jellyfin, lg-smtv-mcp) with capability classes - Clarify /etc/homelab/grants.json ownership (root:homelab-operators 0640) - Specify bidirectional name <-> GID resolution for group_add validation - Link ADR-0001 for Tier 2/3 taxonomy and note --impure flake evaluation --- docs/decisions/0005-workload-capability-grants.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/decisions/0005-workload-capability-grants.md b/docs/decisions/0005-workload-capability-grants.md index a57ee33..9b8ae37 100644 --- a/docs/decisions/0005-workload-capability-grants.md +++ b/docs/decisions/0005-workload-capability-grants.md @@ -11,16 +11,16 @@ amends: 0002-appctl-control-plane-architecture.md ## Context and Problem Statement -Under [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`) and [ADR-0004](0004-unified-workloads-monorepo.md), `validate_compose_security()` in `scripts/gitops_dispatcher.py` enforces a uniform deny-all pre-flight policy on Tier 2 workload `docker-compose.yml` files: +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()` in `scripts/gitops_dispatcher.py` enforces a uniform deny-all pre-flight policy on Tier 2 workload `docker-compose.yml` files: * All `devices:` mounts are unconditionally blocked. * All host bind mounts outside `~/Workloads/` and `~/var/lib/homelab/` are blocked. * All host namespace sharing (`network_mode: host`, etc.) is blocked. -While this prevents a Tier 2 `git push` from escalating privileges on the host, it creates real friction for legitimate single-operator workloads: +While this prevents a Tier 2 `git push` from escalating privileges on the host, it creates real friction for legitimate single-operator capability classes: -1. **Hardware Acceleration & Media Access (`jellyfin`)**: Using an integrated GPU (`/dev/dri`) for VAAPI transcoding requires mounting host device nodes, passing supplementary groups (`group_add: ["303"]` / `render`), and reading a dedicated media partition (`/media:ro`). Currently, `devices:` and arbitrary bind mounts are completely blocked, while `group_add:` is unconstrained (risking arbitrary host GID elevation to groups like `docker` or `wheel` unless strictly governed). -2. **LAN Broadcast / Peer Services (e.g., `lg-smtv-mcp`)**: Workloads that send Wake-on-LAN broadcasts or discover LAN peers may struggle across Docker bridge boundaries, prompting requests for `network_mode: host`. However, blanket host networking collapses network namespace isolation, exposing loopback control services (such as `homelab-appctl.service` on `127.0.0.1:9001`) and bypassing proxy network segmentation. +1. **Hardware-Accelerated & External-Storage Workloads**: Media transcoding or compute workloads requiring an integrated GPU (`/dev/dri`) 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 completely blocked, while `group_add:` is unconstrained (risking arbitrary host GID elevation to groups like `docker` or `wheel` unless strictly governed). +2. **LAN Broadcast / Peer-Discovery Services**: Workloads that send Wake-on-LAN magic packets or discover LAN peers struggle across Docker bridge boundaries, prompting requests for `network_mode: host`. However, blanket host networking collapses network namespace isolation, exposing loopback control services (such as `homelab-appctl.service` on `127.0.0.1:9001`) and bypassing proxy network segmentation. 3. **Host-Agnostic Core Boundary**: Hardcoding `/dev/dri`, `/media`, or specific workload names inside `nixos-core` violates platform genericism 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 groups, 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?** @@ -56,19 +56,19 @@ This ADR formally amends [ADR-0002](0002-appctl-control-plane-architecture.md) ( * `privileged: true`, `/var/run/docker.sock`, `cap_add`, and host namespaces (`pid`, `ipc`, `uts`, `userns_mode`, `network_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, readable by `homelab-appctl` and `homelab-gitops`, configurable via `HOMELAB_GRANTS_FILE` for testing). + * 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; configurable via `HOMELAB_GRANTS_FILE` for testing). * If the grants file is absent, `validate_compose_security()` defaults to zero grants. If present but malformed, validation fails closed. 3. **Exact-Match Pre-Flight Enforcement**: * Every capability requested in `/docker-compose.yml` must match an explicit grant for `` in `/etc/homelab/grants.json`: * `devices` entries must have their host path resolve canonically strictly within the granted device node or directory, strictly disallowing directory traversal (`..`) or symlink escapes. - * `groups` entries must match allowlisted GIDs or group names granted to that specific workload. + * `groups` entries are canonicalized bidirectionally between group names and integer GIDs via the host group database (so a grant of `"render"` or `"303"` accepts either representation in `group_add`, while unknown or ungranted groups fail closed). * `readOnlyPaths` grants permit mounts **only** when `:ro` mode is specified and the canonical host path resolves strictly within the granted directory. * *Trade-off (Host Path Coupling)*: Workload Compose definitions declare physical host paths matching host grants; logical capability aliasing via environment variable injection remains an optional future refinement. 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 their concrete configuration in `/etc/nixos/homelab-instance.nix` (or gitignored `nixos/instance.nix`) without build-time file translation between the two. + * Live hosts keep their concrete configuration in `/etc/nixos/homelab-instance.nix` (loaded via `--impure` flake evaluation) or gitignored `nixos/instance.nix` without build-time file translation between the two. ## Pros and Cons of the Options From 37d529848aa70e9ca9dddf5b133faee208a4d77f Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 21 Nov 2026 00:26:44 -0500 Subject: [PATCH 04/10] docs(adr): resolve Stage 7 critic findings in ADR-0005 and README - Close user: primary GID, device_cgroup_rules:, and network_mode: container:* bypasses - Specify post-interpolation validation, long/short volume syntax, :ro, and :rwm mknod ban - Reconcile absent vs unreadable/malformed grants.json behavior and permissions checks - Add Consequences and More Information sections; sync docs/decisions/README.md --- .../0005-workload-capability-grants.md | 78 +++++++++++-------- docs/decisions/README.md | 4 +- 2 files changed, 49 insertions(+), 33 deletions(-) diff --git a/docs/decisions/0005-workload-capability-grants.md b/docs/decisions/0005-workload-capability-grants.md index 9b8ae37..e7d0e6e 100644 --- a/docs/decisions/0005-workload-capability-grants.md +++ b/docs/decisions/0005-workload-capability-grants.md @@ -11,37 +11,37 @@ amends: 0002-appctl-control-plane-architecture.md ## 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()` in `scripts/gitops_dispatcher.py` enforces a uniform deny-all pre-flight policy on Tier 2 workload `docker-compose.yml` files: +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: -* All `devices:` mounts are unconditionally blocked. -* All host bind mounts outside `~/Workloads/` and `~/var/lib/homelab/` are blocked. -* All host namespace sharing (`network_mode: host`, etc.) is blocked. +* `devices:` mounts are blocked. +* Host bind mounts outside `~/Workloads/` and `~/var/lib/homelab/` 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 creates real friction for legitimate single-operator capability classes: +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`) 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 completely blocked, while `group_add:` is unconstrained (risking arbitrary host GID elevation to groups like `docker` or `wheel` unless strictly governed). -2. **LAN Broadcast / Peer-Discovery Services**: Workloads that send Wake-on-LAN magic packets or discover LAN peers struggle across Docker bridge boundaries, prompting requests for `network_mode: host`. However, blanket host networking collapses network namespace isolation, exposing loopback control services (such as `homelab-appctl.service` on `127.0.0.1:9001`) and bypassing proxy network segmentation. -3. **Host-Agnostic Core Boundary**: Hardcoding `/dev/dri`, `/media`, or specific workload names inside `nixos-core` violates platform genericism and couples Core to one machine's hardware and app catalog. +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 groups, 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?** +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 be able to grant itself root-equivalent host access; capability grants must originate from root-level Tier 3 NixOS host configuration (`nixos-rebuild switch`). +* **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 the requested `devices`, `volumes`, `group_add`, and `network_mode`. -* **Documented Instance Schema**: Provide a tracked `nixos/instance.example.nix` template so new hosts (or a future setup wizard) can configure `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants` cleanly in `/etc/nixos/homelab-instance.nix` (or gitignored `nixos/instance.nix`). -* **Fail-Closed Validation**: Absent, unreadable, or malformed grant configuration must default to zero grants (identical to today's strict baseline), and `privileged: true` and `/var/run/docker.sock` mounts remain permanently prohibited for all workloads. +* **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 checked by `validate_compose_security()`. +* **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` 100% hardware- and workload-agnostic while preserving the security boundary between Tier 2 Git pushes and Tier 3 `sudo nixos-rebuild switch`. +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 @@ -49,37 +49,53 @@ This ADR formally amends [ADR-0002](0002-appctl-control-plane-architecture.md) ( 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, e.g. `"/dev/dri"` or `"/dev/dri/renderD128"`). - * `groups` (list of supplementary group names/GIDs permitted in `group_add`, such as `"303"` or `"render"`). - * `readOnlyPaths` (list of host directories permitted for `:ro` bind mounts only). - * Note on `network_mode: host`: To preserve the `127.0.0.1:9001` daemon boundary and Traefik reverse-proxy segmentation, host networking is rejected and excluded from `workloadGrants`. Workloads requiring L2 broadcast/discovery should be provisioned on dedicated isolated Docker networks (`macvlan`/`ipvlan`) or host-side intermediaries. - * `privileged: true`, `/var/run/docker.sock`, `cap_add`, and host namespaces (`pid`, `ipc`, `uts`, `userns_mode`, `network_mode: host`) remain permanently prohibited and are not grantable. + * `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; configurable via `HOMELAB_GRANTS_FILE` for testing). - * If the grants file is absent, `validate_compose_security()` defaults to zero grants. If present but malformed, validation fails closed. + * 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**: - * Every capability requested in `/docker-compose.yml` must match an explicit grant for `` in `/etc/homelab/grants.json`: - * `devices` entries must have their host path resolve canonically strictly within the granted device node or directory, strictly disallowing directory traversal (`..`) or symlink escapes. - * `groups` entries are canonicalized bidirectionally between group names and integer GIDs via the host group database (so a grant of `"render"` or `"303"` accepts either representation in `group_add`, while unknown or ungranted groups fail closed). - * `readOnlyPaths` grants permit mounts **only** when `:ro` mode is specified and the canonical host path resolves strictly within the granted directory. - * *Trade-off (Host Path Coupling)*: Workload Compose definitions declare physical host paths matching host grants; logical capability aliasing via environment variable injection remains an optional future refinement. + * `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 `/docker-compose.yml` must match an explicit grant for ``: + * `devices` entries support `host:container[:perms]`, forbid `m` (`mknod`) in permissions, and require canonical host path resolution (`strict=True` existence check) 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 (requiring `homelab-appctl.service` to retain `/etc/group` access without `PrivateUsers=true`, and supporting test injection). `user:` primary GIDs must also fall within granted `groups` (or standard unprivileged non-host-group UID/GID policy). + * `readOnlyPaths` validates both short (`host:container:ro[,opts]`) and long (`type: bind`, `read_only: true`) volume syntax, rejects unsafe bind propagation, and requires canonical host path containment (`strict=True`) 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 their concrete configuration in `/etc/nixos/homelab-instance.nix` (loaded via `--impure` flake evaluation) or gitignored `nixos/instance.nix` without build-time file translation between the two. + * 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 cannot safely express `network_mode: host`. +* 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` stays clean, and privilege elevation requires explicit host-level `nixos-rebuild switch`. -* Bad, because adding a new privileged capability for a workload requires editing `/etc/nixos/homelab-instance.nix` and rebuilding NixOS before `appctl up`. +* 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). diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 4496572..023f92c 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -10,7 +10,7 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using | Decision Record | Status | Date | Scope & One-Line Purpose | | :--- | :--- | :--- | :--- | -| [**ADR-0005: Host-Granted Workload Capabilities**](0005-workload-capability-grants.md) | `accepted` | 2026-11-20 | Amends ADR-0002 to introduce `homelab.workloadGrants` (`/etc/homelab/grants.json`) and `nixos/instance.example.nix` so NixOS hosts explicitly authorize `devices`, `groups`, `readOnlyPaths`, and `hostNetwork` per workload. | +| [**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//` state isolation. | | [**ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. | | [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and deterministic Git-backed declarative deployment state. | @@ -24,7 +24,7 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using * **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`, `readOnlyPaths`, and `hostNetwork` grants while keeping `privileged: true`, `docker.sock`, and `cap_add` permanently forbidden. + 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`. From e807a900175594a15ff93c14c8d323dea789acd0 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 21 Nov 2026 03:25:16 -0500 Subject: [PATCH 05/10] docs(adr): polish Stage 8 zoom-out nits in ADR-0005 - Replace strict=True and PrivateUsers=true implementation details with architectural invariants - State unprivileged primary UID/GID rule directly --- docs/decisions/0005-workload-capability-grants.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/decisions/0005-workload-capability-grants.md b/docs/decisions/0005-workload-capability-grants.md index e7d0e6e..ea97f83 100644 --- a/docs/decisions/0005-workload-capability-grants.md +++ b/docs/decisions/0005-workload-capability-grants.md @@ -62,9 +62,9 @@ This ADR formally amends [ADR-0002](0002-appctl-control-plane-architecture.md) ( 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 `/docker-compose.yml` must match an explicit grant for ``: - * `devices` entries support `host:container[:perms]`, forbid `m` (`mknod`) in permissions, and require canonical host path resolution (`strict=True` existence check) 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 (requiring `homelab-appctl.service` to retain `/etc/group` access without `PrivateUsers=true`, and supporting test injection). `user:` primary GIDs must also fall within granted `groups` (or standard unprivileged non-host-group UID/GID policy). - * `readOnlyPaths` validates both short (`host:container:ro[,opts]`) and long (`type: bind`, `read_only: true`) volume syntax, rejects unsafe bind propagation, and requires canonical host path containment (`strict=True`) within the granted directory. + * `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`. From ce969f467854faff144b7e3c526715ef65df92b4 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 21 Nov 2026 03:54:02 -0500 Subject: [PATCH 06/10] feat(nixos): add homelab.workloadGrants option, grants.json projection, and instance.example.nix - Define homelab.workloadGrants attrsOf submodule in nixos/modules/homeserver.nix with devices, groups, and readOnlyPaths - Add Nix assertions rejecting privileged groups (0, root, wheel, docker) and relative/traversal paths - Generate /etc/homelab/grants.json (root:homelab-operators 0640) and wire HOMELAB_GRANTS_FILE into homelab-appctl and homelab-gitops - Add tracked nixos/instance.example.nix and prioritize /etc/nixos/homelab-instance.nix over nixos/instance.nix - Add structural and security invariant tests for workloadGrants and instance.example.nix --- nixos/configuration.nix | 4 +- nixos/instance.example.nix | 20 +++++++ nixos/modules/homeserver.nix | 59 +++++++++++++++++++ tests/security/test_security_invariants.py | 16 +++++ tests/structural/test_repository_structure.py | 1 + 5 files changed, 98 insertions(+), 2 deletions(-) create mode 100644 nixos/instance.example.nix diff --git a/nixos/configuration.nix b/nixos/configuration.nix index d9cefec..46b916e 100644 --- a/nixos/configuration.nix +++ b/nixos/configuration.nix @@ -12,8 +12,8 @@ ./modules/traefik-deployments.nix # Traefik deployment secrets and env templates ./modules/dynu.nix # Dynu DDNS smart IP monitor service ./modules/shell.nix # Declarative bash environment for the server - ] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix - ++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix; + ] ++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix + ++ lib.optional (!(builtins.pathExists /etc/nixos/homelab-instance.nix) && builtins.pathExists ./instance.nix) ./instance.nix; # ── Homelab platform settings ──────────────────────────────────────────────── homelab.operatorUser = "operator"; diff --git a/nixos/instance.example.nix b/nixos/instance.example.nix new file mode 100644 index 0000000..732d21b --- /dev/null +++ b/nixos/instance.example.nix @@ -0,0 +1,20 @@ +# Example host-local instance configuration for Canopy NixOS Core. +# Copy to /etc/nixos/homelab-instance.nix (recommended, loaded with --impure) +# or gitignored nixos/instance.nix, and customize for your host. +{ ... }: + +{ + homelab.domain = "example.com"; + homelab.operatorUser = "operator"; + + # Host-granted workload capabilities ("Compose Requests, Nix Grants" β€” ADR-0005). + # Keyed by workload name matching ~/Workloads/. + homelab.workloadGrants = { + # Example hardware-accelerated media workload: + # media-server = { + # devices = [ "/dev/dri/renderD128" ]; + # groups = [ "render" ]; + # readOnlyPaths = [ "/mnt/media" ]; + # }; + }; +} diff --git a/nixos/modules/homeserver.nix b/nixos/modules/homeserver.nix index decb377..9ae8d3b 100644 --- a/nixos/modules/homeserver.nix +++ b/nixos/modules/homeserver.nix @@ -26,12 +26,69 @@ default = "/home/${config.homelab.operatorUser}/Workloads"; description = "Path to Workloads directory (legacy option name: sitesDir)"; }; + workloadGrants = lib.mkOption { + type = lib.types.attrsOf (lib.types.submodule { + options = { + devices = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = []; + description = "Host device paths permitted for this workload (prefer specific nodes such as /dev/dri/renderD128)."; + }; + groups = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = []; + description = "Host group names or numeric GIDs permitted in group_add and user: primary GID."; + }; + readOnlyPaths = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = []; + description = "Host directories permitted for read-only (:ro) bind mounts."; + }; + }; + }); + default = {}; + description = "Host-granted hardware devices, groups, and read-only storage paths keyed by workload name."; + }; }; config = let domainParts = lib.splitString "." config.homelab.domain; ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts); in { + # ── Workload Capability Grant Invariants (ADR-0005) ───────────────────────── + assertions = let + grantsList = lib.mapAttrsToList (app: grant: { inherit app grant; }) config.homelab.workloadGrants; + privilegedGroups = [ "0" "root" "wheel" "docker" ]; + hasInvalidPath = p: + !(lib.hasPrefix "/" p) + || (lib.hasInfix "/../" p) + || (lib.hasSuffix "/.." p) + || (p == ".."); + in + (map ({ app, grant }: { + assertion = lib.all (g: !(lib.elem (lib.toLower (lib.strings.trim g)) privilegedGroups)) grant.groups; + message = "homelab.workloadGrants.${app}.groups must not contain privileged groups (0, root, wheel, docker)."; + }) grantsList) + ++ (map ({ app, grant }: { + assertion = lib.all (p: !(hasInvalidPath p)) grant.devices; + message = "homelab.workloadGrants.${app}.devices must contain absolute paths without '..' traversal."; + }) grantsList) + ++ (map ({ app, grant }: { + assertion = lib.all (p: !(hasInvalidPath p)) grant.readOnlyPaths; + message = "homelab.workloadGrants.${app}.readOnlyPaths must contain absolute paths without '..' traversal."; + }) grantsList); + + # ── Host Capability Grants Projection (/etc/homelab/grants.json) ───────────── + environment.etc."homelab/grants.json" = { + user = "root"; + group = "homelab-operators"; + mode = "0640"; + text = builtins.toJSON { + schemaVersion = "1.0"; + workloads = config.homelab.workloadGrants; + }; + }; + # ── Host Activation Guard ──────────────────────────────────────────────────── # Prevents activating on a live host if homelab.domain defaulted to example.test (e.g. forgot --impure) system.activationScripts.checkHomelabDomain = { @@ -146,6 +203,7 @@ 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 = { @@ -226,6 +284,7 @@ HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab"; HOMELAB_CONFIG_DIR = "/home/${config.homelab.operatorUser}/.config/homelab"; HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.sitesDir}/deployments.yaml"; + HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json"; }; serviceConfig = { diff --git a/tests/security/test_security_invariants.py b/tests/security/test_security_invariants.py index 393f89f..9146e05 100644 --- a/tests/security/test_security_invariants.py +++ b/tests/security/test_security_invariants.py @@ -210,6 +210,7 @@ def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests( CORE_ROOT / "flake.nix", CORE_ROOT / "docker-compose.yml", CORE_ROOT / "nixos" / "configuration.nix", + CORE_ROOT / "nixos" / "instance.example.nix", ] violations = [] @@ -554,4 +555,19 @@ def test_nixos_homeserver_defaults_to_workloads_dir(): ) +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 + + + diff --git a/tests/structural/test_repository_structure.py b/tests/structural/test_repository_structure.py index f0a6656..aa40145 100644 --- a/tests/structural/test_repository_structure.py +++ b/tests/structural/test_repository_structure.py @@ -20,6 +20,7 @@ def test_required_architectural_paths_exist(): "SECURITY.md", "nixos", "nixos/configuration.nix", + "nixos/instance.example.nix", "nixos/modules/homeserver.nix", "nixos/secrets.yaml", "scripts/gitops_dispatcher.py", From 4f406685362c4fa223305e0e14b2b74a0cb06463 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 21 Nov 2026 03:58:21 -0500 Subject: [PATCH 07/10] feat(security): add Pydantic workload grants loader, RESERVED_ENV_KEYS, and error code - Add HOMELAB_GRANTS_FILE to RESERVED_ENV_KEYS in scripts/core_manifest.py - Add ERR_CAPABILITY_NOT_GRANTED (HTTP 403) to ErrorCode in scripts/appctl_contracts.py - Implement WorkloadGrant, GrantsRegistry, and load_workload_grants in scripts/workload_grants.py with strict Pydantic v2 and fail-closed permission/integrity checks - Add unit tests for workload_grants, RESERVED_ENV_KEYS, and ErrorCode taxonomy --- scripts/appctl_contracts.py | 4 +- scripts/core_manifest.py | 1 + scripts/workload_grants.py | 149 ++++++++++++++++++++++++++++ tests/unit/test_appctl_contracts.py | 6 +- tests/unit/test_core_manifest.py | 12 +++ tests/unit/test_workload_grants.py | 148 +++++++++++++++++++++++++++ 6 files changed, 317 insertions(+), 3 deletions(-) create mode 100644 scripts/workload_grants.py create mode 100644 tests/unit/test_workload_grants.py diff --git a/scripts/appctl_contracts.py b/scripts/appctl_contracts.py index d85dbe3..96cf190 100644 --- a/scripts/appctl_contracts.py +++ b/scripts/appctl_contracts.py @@ -116,11 +116,12 @@ FlexibleWorkloadAction = FlexibleOperationType class ErrorCode(StrEnum): - """Canonical 6-code error taxonomy for homelab-appctl.service.""" + """Canonical 7-code error taxonomy for homelab-appctl.service.""" ERR_VALIDATION_FAILED = "ERR_VALIDATION_FAILED" ERR_AUTH_REQUIRED = "ERR_AUTH_REQUIRED" ERR_PERMISSION_DENIED = "ERR_PERMISSION_DENIED" + ERR_CAPABILITY_NOT_GRANTED = "ERR_CAPABILITY_NOT_GRANTED" ERR_TARGET_NOT_FOUND = "ERR_TARGET_NOT_FOUND" ERR_CONCURRENT_MUTATION = "ERR_CONCURRENT_MUTATION" ERR_EXECUTION_FAILED = "ERR_EXECUTION_FAILED" @@ -134,6 +135,7 @@ ERROR_HTTP_STATUS: dict[ErrorCode, int] = { ErrorCode.ERR_VALIDATION_FAILED: 400, ErrorCode.ERR_AUTH_REQUIRED: 401, ErrorCode.ERR_PERMISSION_DENIED: 403, + ErrorCode.ERR_CAPABILITY_NOT_GRANTED: 403, ErrorCode.ERR_TARGET_NOT_FOUND: 404, ErrorCode.ERR_CONCURRENT_MUTATION: 409, ErrorCode.ERR_EXECUTION_FAILED: 500, diff --git a/scripts/core_manifest.py b/scripts/core_manifest.py index efb4735..a194c9b 100644 --- a/scripts/core_manifest.py +++ b/scripts/core_manifest.py @@ -81,6 +81,7 @@ RESERVED_ENV_KEYS = { "SERVICE_NAME", "CONTAINER_NAME", "SERVICE_DOMAIN", + "HOMELAB_GRANTS_FILE", } ALLOWED_STRATEGIES = {"compose"} diff --git a/scripts/workload_grants.py b/scripts/workload_grants.py new file mode 100644 index 0000000..7856fb4 --- /dev/null +++ b/scripts/workload_grants.py @@ -0,0 +1,149 @@ +""" +workload_grants.py β€” Host-Granted Workload Capability Loader & Schema (ADR-0005) + +Loads and validates /etc/homelab/grants.json (or HOMELAB_GRANTS_FILE) using strict +Pydantic v2 models (ConfigDict(extra="forbid")). +""" + +from __future__ import annotations + +import json +import os +import stat +from pathlib import Path, PurePosixPath +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator + +DEFAULT_GRANTS_FILE = Path("/etc/homelab/grants.json") +PRIVILEGED_GROUPS: frozenset[str] = frozenset({"0", "root", "wheel", "docker"}) + + +class WorkloadGrantsError(Exception): + """Raised when the host capability grants file fails integrity or schema checks.""" + + +class WorkloadGrant(BaseModel): + """Explicit host-granted capabilities for a single workload.""" + + model_config = ConfigDict(extra="forbid") + + devices: list[str] = Field(default_factory=list) + groups: list[str] = Field(default_factory=list) + readOnlyPaths: list[str] = Field(default_factory=list) + + @field_validator("groups") + @classmethod + def _validate_groups(cls, values: list[str]) -> list[str]: + cleaned: list[str] = [] + for raw in values: + group = raw.strip() + if not group: + raise ValueError("Granted group entry cannot be empty.") + if group.lower() in PRIVILEGED_GROUPS: + raise ValueError( + f"Privileged group '{group}' cannot be granted to workloads." + ) + cleaned.append(group) + return cleaned + + @field_validator("devices", "readOnlyPaths") + @classmethod + def _validate_absolute_paths(cls, values: list[str]) -> list[str]: + cleaned: list[str] = [] + for raw in values: + path_str = raw.strip() + if not path_str: + raise ValueError("Granted path entry cannot be empty.") + posix = PurePosixPath(path_str) + if not posix.is_absolute(): + raise ValueError( + f"Granted path '{path_str}' must be an absolute path." + ) + if ".." in posix.parts: + raise ValueError( + f"Granted path '{path_str}' must not contain '..' traversal." + ) + cleaned.append(path_str) + return cleaned + + +class GrantsRegistry(BaseModel): + """Root schema for /etc/homelab/grants.json.""" + + model_config = ConfigDict(extra="forbid") + + schemaVersion: Literal["1.0"] = "1.0" + workloads: dict[str, WorkloadGrant] = Field(default_factory=dict) + + +def load_workload_grants( + grants_file: Path | None = None, + *, + verify_permissions: bool | None = None, +) -> dict[str, WorkloadGrant]: + """ + Load host-granted workload capabilities from grants_file or HOMELAB_GRANTS_FILE. + + - If the target file does not exist (and is not a symlink), returns {} (zero grants). + - If the file is present (or is a symlink) and fails permission/integrity checks, + is unreadable, or fails JSON/Pydantic validation, raises WorkloadGrantsError. + """ + if grants_file is None: + env_path = os.environ.get("HOMELAB_GRANTS_FILE", "").strip() + target_path = Path(env_path) if env_path else DEFAULT_GRANTS_FILE + else: + target_path = grants_file + + should_verify = ( + (target_path == DEFAULT_GRANTS_FILE) + if verify_permissions is None + else verify_permissions + ) + + if not target_path.exists() and not target_path.is_symlink(): + return {} + + if should_verify: + try: + st = os.lstat(target_path) + except OSError as exc: + raise WorkloadGrantsError( + f"Failed to stat grants file '{target_path}': {exc}" + ) from exc + + if stat.S_ISLNK(st.st_mode) or not stat.S_ISREG(st.st_mode): + raise WorkloadGrantsError( + f"Grants file '{target_path}' must be a regular non-symlink file." + ) + if st.st_uid != 0: + raise WorkloadGrantsError( + f"Grants file '{target_path}' must be owned by root (uid 0)." + ) + if (st.st_mode & 0o022) != 0: + raise WorkloadGrantsError( + f"Grants file '{target_path}' must not be group- or world-writable." + ) + + try: + raw_text = target_path.read_text(encoding="utf-8") + except OSError as exc: + raise WorkloadGrantsError( + f"Failed to read grants file '{target_path}': {exc}" + ) from exc + + try: + payload = json.loads(raw_text) + except json.JSONDecodeError as exc: + raise WorkloadGrantsError( + f"Malformed JSON in grants file '{target_path}': {exc}" + ) from exc + + try: + registry = GrantsRegistry.model_validate(payload) + except ValidationError as exc: + raise WorkloadGrantsError( + f"Invalid schema in grants file '{target_path}': {exc}" + ) from exc + + return registry.workloads diff --git a/tests/unit/test_appctl_contracts.py b/tests/unit/test_appctl_contracts.py index 678cca9..f38c791 100644 --- a/tests/unit/test_appctl_contracts.py +++ b/tests/unit/test_appctl_contracts.py @@ -445,12 +445,13 @@ def test_operation_request_backward_compatibility_aliases(): # --------------------------------------------------------------------------- -def test_error_code_taxonomy_contains_exactly_6_canonical_codes(): - assert len(ErrorCode) == 6 +def test_error_code_taxonomy_contains_exactly_7_canonical_codes(): + assert len(ErrorCode) == 7 expected_codes = { "ERR_VALIDATION_FAILED", "ERR_AUTH_REQUIRED", "ERR_PERMISSION_DENIED", + "ERR_CAPABILITY_NOT_GRANTED", "ERR_TARGET_NOT_FOUND", "ERR_CONCURRENT_MUTATION", "ERR_EXECUTION_FAILED", @@ -462,6 +463,7 @@ def test_error_code_http_status_mapping(): assert ErrorCode.ERR_VALIDATION_FAILED.http_status == 400 assert ErrorCode.ERR_AUTH_REQUIRED.http_status == 401 assert ErrorCode.ERR_PERMISSION_DENIED.http_status == 403 + assert ErrorCode.ERR_CAPABILITY_NOT_GRANTED.http_status == 403 assert ErrorCode.ERR_TARGET_NOT_FOUND.http_status == 404 assert ErrorCode.ERR_CONCURRENT_MUTATION.http_status == 409 assert ErrorCode.ERR_EXECUTION_FAILED.http_status == 500 diff --git a/tests/unit/test_core_manifest.py b/tests/unit/test_core_manifest.py index af9905a..943c9fe 100644 --- a/tests/unit/test_core_manifest.py +++ b/tests/unit/test_core_manifest.py @@ -355,3 +355,15 @@ description: "Pydantic serialization test" assert dumped["name"] == "serialized-app" assert dumped["schemaVersion"] == "1.0" assert manifest.to_dict()["name"] == "serialized-app" + + +def test_parse_manifest_rejects_homelab_grants_file_in_env(): + """Ensure HOMELAB_GRANTS_FILE is in RESERVED_ENV_KEYS and cannot be overridden by app.yaml.""" + raw_yaml = """ +name: "grants-override-app" +env: + HOMELAB_GRANTS_FILE: "/tmp/evil-grants.json" +""" + with pytest.raises(ManifestValidationError): + parse_manifest(raw_yaml) + diff --git a/tests/unit/test_workload_grants.py b/tests/unit/test_workload_grants.py new file mode 100644 index 0000000..3665c0b --- /dev/null +++ b/tests/unit/test_workload_grants.py @@ -0,0 +1,148 @@ +"""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_and_bad_schema_version() -> None: + with pytest.raises(ValidationError): + GrantsRegistry.model_validate( + { + "schemaVersion": "1.0", + "workloads": {"app": {"devices": [], "extra_field": True}}, + } + ) + 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_and_writable( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + grants_path = tmp_path / "grants.json" + grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8") + + # Non-root owner + 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) + + # Group/world writable even if root-owned + monkeypatch.setattr( + os, + "lstat", + lambda _p: SimpleNamespace(st_mode=0o100664, st_uid=0), + ) + with pytest.raises(WorkloadGrantsError, match="writable"): + load_workload_grants(grants_path, verify_permissions=True) + + # Valid root-owned 0640 regular file + monkeypatch.setattr( + os, + "lstat", + lambda _p: SimpleNamespace(st_mode=0o100640, st_uid=0), + ) + assert load_workload_grants(grants_path, verify_permissions=True) == {} From c9f31088054d24bd4b1d22d06c6507a084885e85 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 21 Nov 2026 04:05:42 -0500 Subject: [PATCH 08/10] feat(security): enforce host-granted workload capabilities in validate_compose_security - Update validate_compose_security() in scripts/gitops_dispatcher.py to enforce fail-closed workloadGrants for devices, group_add, user primary GIDs, and readOnlyPaths - Permanently block device_cgroup_rules and container:*/service:* namespace sharing, and reject uninterpolated ${...} after resolved_env interpolation - Pass assembled 6-layer env into validate_compose_security() in scripts/appctl_router.py and map capability denials to ERR_CAPABILITY_NOT_GRANTED - Add comprehensive Red->Green security and router tests for positive grants and bypass vectors --- scripts/appctl_router.py | 31 +- scripts/gitops_dispatcher.py | 436 ++++++++++++++++++++++++- tests/security/test_gitops_security.py | 327 +++++++++++++++++++ tests/unit/test_appctl_router.py | 64 ++++ 4 files changed, 836 insertions(+), 22 deletions(-) diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py index e22da0f..7ae07b8 100644 --- a/scripts/appctl_router.py +++ b/scripts/appctl_router.py @@ -85,12 +85,16 @@ MAX_OUTPUT_BYTES = 256 * 1024 # 256 KiB cap per invocation class RouterValidationError(Exception): - """Raised when request payload or pre-flight validation fails (400 Bad Request).""" + """Raised when request payload or pre-flight validation fails (400 Bad Request or 403 Capability Denied).""" - def __init__(self, message: str) -> None: + def __init__( + self, + message: str, + code: ErrorCode = ErrorCode.ERR_VALIDATION_FAILED, + ) -> None: super().__init__(message) - self.code = ErrorCode.ERR_VALIDATION_FAILED - self.http_status = 400 + self.code = code + self.http_status = code.http_status class RouterExecutionError(Exception): @@ -313,14 +317,31 @@ def validate_workload_preflight( effective_name = app_name or manifest.name compose_file = _resolve_compose_file(app_dir) if compose_file.exists(): + resolved_env = assemble_workload_env(app_dir, manifest, effective_name) ok, reason = validate_compose_security( compose_file=compose_file, allowed_root=app_dir, app_name=effective_name, + resolved_env=resolved_env, ) 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( - 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 diff --git a/scripts/gitops_dispatcher.py b/scripts/gitops_dispatcher.py index cdb8336..2ffa641 100755 --- a/scripts/gitops_dispatcher.py +++ b/scripts/gitops_dispatcher.py @@ -10,6 +10,7 @@ deployment actions with zero Core restarts. import contextlib import datetime import fcntl +import grp import hashlib import hmac import http.client @@ -19,7 +20,8 @@ import os import re import subprocess import sys -from pathlib import Path +from collections.abc import Callable +from pathlib import Path, PurePosixPath from typing import Any from appctl_contracts import OperationRequest, OperationType @@ -30,6 +32,12 @@ from core_manifest import ( parse_manifest, ) from pydantic import ValidationError +from workload_grants import ( + PRIVILEGED_GROUPS, + WorkloadGrant, + WorkloadGrantsError, + load_workload_grants, +) try: import yaml @@ -415,12 +423,295 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]: PROHIBITED_HOST_NAMESPACES = {"host"} DANGEROUS_SECURITY_OPTS = {"unconfined", "apparmor:unconfined", "seccomp:unconfined"} +UNSAFE_BIND_PROPAGATIONS = {"shared", "rshared", "slave", "rslave"} +_COMPOSE_VAR_RE = re.compile( + r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?:(:-|-)([^}]*))?\}" +) + + +def _interpolate_compose_value( + value: str, resolved_env: dict[str, str] | None +) -> str: + """Resolve ${VAR}, ${VAR:-default}, and ${VAR-default} using resolved_env without shell evaluation.""" + if resolved_env is None or "${" not in value: + return value + + def _replace(match: re.Match[str]) -> str: + var_name = match.group(1) + op = match.group(2) + default = match.group(3) + if op == ":-": + val = resolved_env.get(var_name) + return val if val else (default or "") + if op == "-": + return resolved_env.get(var_name, default or "") + return resolved_env.get(var_name, match.group(0)) + + return _COMPOSE_VAR_RE.sub(_replace, value) + + +def _default_group_lookup(key: str | int) -> tuple[str, int]: + """Resolve a group name or numeric GID against the host group database.""" + if isinstance(key, int) or (isinstance(key, str) and key.isdigit()): + entry = grp.getgrgid(int(key)) + else: + entry = grp.getgrnam(str(key)) + return entry.gr_name, entry.gr_gid + + +def _resolve_granted_groups( + grant_groups: list[str], + lookup_fn: Callable[[str | int], tuple[str, int]], +) -> tuple[set[str], set[int]]: + """Canonicalize granted groups bidirectionally between group names and integer GIDs.""" + granted_names: set[str] = set() + granted_gids: set[int] = set() + for raw in grant_groups: + key: str | int = int(raw) if raw.isdigit() else raw + try: + res = lookup_fn(key) + except KeyError as exc: + raise WorkloadGrantsError( + f"Granted group '{raw}' does not exist in host group database." + ) from exc + if res is None: + raise WorkloadGrantsError( + f"Granted group '{raw}' does not exist in host group database." + ) + gr_name, gr_gid = res + if gr_name.lower() in PRIVILEGED_GROUPS or str(gr_gid) in PRIVILEGED_GROUPS: + raise WorkloadGrantsError( + f"Granted group '{raw}' resolves to privileged group '{gr_name}:{gr_gid}'." + ) + granted_names.add(gr_name) + granted_gids.add(gr_gid) + return granted_names, granted_gids + + +def _validate_service_group_add( + svc_name: str, + svc: dict[str, Any], + grant: WorkloadGrant, + resolved_env: dict[str, str] | None, + lookup_fn: Callable[[str | int], tuple[str, int]], + granted_names: set[str], + granted_gids: set[int], +) -> tuple[bool, str | None]: + group_add = svc.get("group_add") + if not group_add: + return True, None + if not isinstance(group_add, list): + return ( + False, + f"Service '{svc_name}' specifies invalid 'group_add' configuration.", + ) + if not grant.groups: + return ( + False, + f"Capability not granted: Service '{svc_name}' requests 'group_add' without any granted groups.", + ) + + for item in group_add: + val = _interpolate_compose_value(str(item).strip(), resolved_env) + if "${" in val or "}" in val: + return ( + False, + f"Service '{svc_name}' specifies prohibited variable interpolation in group_add: '{val}'.", + ) + key: str | int = int(val) if val.isdigit() else val + try: + res = lookup_fn(key) + except KeyError: + res = None + if res is None: + return ( + False, + f"Capability not granted: Service '{svc_name}' requests unknown group_add '{val}'.", + ) + req_name, req_gid = res + if req_name.lower() in PRIVILEGED_GROUPS or str(req_gid) in PRIVILEGED_GROUPS: + return ( + False, + f"Capability not granted: Service '{svc_name}' requests privileged group_add '{val}'.", + ) + if req_name not in granted_names and req_gid not in granted_gids: + return ( + False, + f"Capability not granted: Service '{svc_name}' requests ungranted group_add '{val}' ({req_name}:{req_gid}).", + ) + return True, None + + +def _validate_service_user( + svc_name: str, + svc: dict[str, Any], + resolved_env: dict[str, str] | None, + lookup_fn: Callable[[str | int], tuple[str, int]], + granted_names: set[str], + granted_gids: set[int], +) -> tuple[bool, str | None]: + raw_user = svc.get("user") + if raw_user is None: + return True, None + user_val = _interpolate_compose_value(str(raw_user).strip(), resolved_env) + if "${" in user_val or "}" in user_val: + return ( + False, + f"Service '{svc_name}' specifies prohibited variable interpolation in user: '{user_val}'.", + ) + if not user_val: + return True, None + + if ":" in user_val: + uid_part, gid_part = user_val.split(":", 1) + else: + uid_part, gid_part = user_val, None + + uid_clean = uid_part.strip() + if uid_clean.lower() in ("0", "root"): + return ( + False, + f"Capability not granted: Service '{svc_name}' requests root user '{user_val}'.", + ) + + if gid_part is not None: + gid_clean = gid_part.strip() + if gid_clean.lower() in PRIVILEGED_GROUPS: + return ( + False, + f"Capability not granted: Service '{svc_name}' requests privileged primary group '{gid_clean}' in user '{user_val}'.", + ) + if gid_clean.isdigit(): + gid_num = int(gid_clean) + if gid_num == 0: + return ( + False, + f"Capability not granted: Service '{svc_name}' requests root GID 0 in user '{user_val}'.", + ) + if gid_num in granted_gids: + return True, None + if gid_num < 1000: + return ( + False, + f"Capability not granted: Service '{svc_name}' requests ungranted system GID '{gid_clean}' in user '{user_val}'.", + ) + try: + res = lookup_fn(gid_num) + except KeyError: + res = None + if res is not None and res[0].lower() in PRIVILEGED_GROUPS: + return ( + False, + f"Capability not granted: Service '{svc_name}' requests privileged GID '{gid_clean}' ({res[0]}).", + ) + else: + try: + res = lookup_fn(gid_clean) + except KeyError: + res = None + if res is None: + return ( + False, + f"Capability not granted: Service '{svc_name}' requests unknown primary group '{gid_clean}' in user '{user_val}'.", + ) + req_name, req_gid = res + if req_name.lower() in PRIVILEGED_GROUPS or req_gid == 0: + return ( + False, + f"Capability not granted: Service '{svc_name}' requests privileged primary group '{gid_clean}' in user '{user_val}'.", + ) + if req_name not in granted_names and req_gid not in granted_gids: + return ( + False, + f"Capability not granted: Service '{svc_name}' requests ungranted primary group '{gid_clean}' in user '{user_val}'.", + ) + return True, None + + +def _validate_service_devices( + svc_name: str, + svc: dict[str, Any], + grant: WorkloadGrant, + resolved_env: dict[str, str] | None, +) -> tuple[bool, str | None]: + devices = svc.get("devices") + if not devices: + return True, None + if not isinstance(devices, list): + return ( + False, + f"Service '{svc_name}' specifies invalid 'devices' configuration.", + ) + if not grant.devices: + return ( + False, + f"Capability not granted: Service '{svc_name}' specifies prohibited host device mount: {devices}.", + ) + + granted_resolved: list[Path] = [] + for g_dev in grant.devices: + try: + granted_resolved.append(Path(g_dev).resolve(strict=True)) + except OSError: + continue + + for dev_entry in devices: + dev_str = _interpolate_compose_value(str(dev_entry).strip(), resolved_env) + if "${" in dev_str or "}" in dev_str: + return ( + False, + f"Service '{svc_name}' specifies prohibited variable interpolation in devices: '{dev_str}'.", + ) + parts = dev_str.split(":") + if len(parts) in (1, 2): + host_dev, perms = parts[0].strip(), "" + elif len(parts) == 3: + host_dev, perms = parts[0].strip(), parts[2].strip() + else: + return ( + False, + f"Service '{svc_name}' specifies malformed device entry '{dev_str}'.", + ) + + if "m" in perms.lower(): + return ( + False, + f"Capability not granted: Service '{svc_name}' requests prohibited 'm' (mknod) device permission in '{dev_str}'.", + ) + + posix = PurePosixPath(host_dev) + if not posix.is_absolute() or ".." in posix.parts: + return ( + False, + f"Capability not granted: Service '{svc_name}' device path '{host_dev}' must be absolute without '..'.", + ) + + try: + resolved_dev = Path(host_dev).resolve(strict=True) + except OSError: + return ( + False, + f"Capability not granted: Service '{svc_name}' device '{host_dev}' does not exist on host.", + ) + + if not any( + resolved_dev == g_res or resolved_dev.is_relative_to(g_res) + for g_res in granted_resolved + ): + return ( + False, + f"Capability not granted: Service '{svc_name}' requests ungranted device '{host_dev}'.", + ) + return True, None def validate_compose_security( compose_file: Path, allowed_root: Path, app_name: str | None = None, + resolved_env: dict[str, str] | None = None, + grants_file: Path | None = None, + group_lookup: Callable[[str | int], tuple[str, int]] | None = None, ) -> tuple[bool, str | None]: """ Pre-flight AST inspection of workload docker-compose.yml enforcing Core platform security invariants: @@ -510,6 +801,18 @@ def validate_compose_security( if not isinstance(services, dict): return True, None + try: + grants = load_workload_grants(grants_file) + except WorkloadGrantsError as exc: + return False, f"Capability grants integrity check failed: {exc}" + + grant = grants.get(app_name, WorkloadGrant()) if app_name else WorkloadGrant() + lookup_fn = group_lookup or _default_group_lookup + try: + granted_names, granted_gids = _resolve_granted_groups(grant.groups, lookup_fn) + except WorkloadGrantsError as exc: + return False, f"Capability grants integrity check failed: {exc}" + state_root = Path( os.environ.get("HOMELAB_STATE_ROOT", Path.home() / "var/lib/homelab") ).resolve() @@ -539,13 +842,28 @@ def validate_compose_security( f"Service '{svc_name}' specifies prohibited 'cap_add' capabilities: {cap_add}.", ) - devices = svc.get("devices") - if devices: + if svc.get("device_cgroup_rules"): return ( False, - f"Service '{svc_name}' specifies prohibited host device mount: {devices}.", + f"Service '{svc_name}' specifies prohibited 'device_cgroup_rules'.", ) + ok_dev, dev_err = _validate_service_devices(svc_name, svc, grant, resolved_env) + if not ok_dev: + return False, dev_err + + ok_grp, grp_err = _validate_service_group_add( + svc_name, svc, grant, resolved_env, lookup_fn, granted_names, granted_gids + ) + if not ok_grp: + return False, grp_err + + ok_usr, usr_err = _validate_service_user( + svc_name, svc, resolved_env, lookup_fn, granted_names, granted_gids + ) + if not ok_usr: + return False, usr_err + sec_opts = svc.get("security_opt", []) if isinstance(sec_opts, str): sec_opts = [sec_opts] @@ -616,15 +934,15 @@ def validate_compose_security( if not clean_env: continue if clean_env.startswith("~"): - resolved_env = Path(clean_env).expanduser().resolve() + env_file_resolved = Path(clean_env).expanduser().resolve() elif Path(clean_env).is_absolute(): - resolved_env = Path(clean_env).resolve() + env_file_resolved = Path(clean_env).resolve() else: - resolved_env = (allowed_root / clean_env).resolve() + env_file_resolved = (allowed_root / clean_env).resolve() if not ( allowed_root.is_dir() - and resolved_env.is_relative_to(canonical_allowed_root) + and env_file_resolved.is_relative_to(canonical_allowed_root) ): return ( False, @@ -633,7 +951,9 @@ def validate_compose_security( for ns_key in ("network_mode", "pid", "ipc", "uts", "userns_mode"): val = str(svc.get(ns_key, "")).strip().lower() - if val in PROHIBITED_HOST_NAMESPACES: + if val in PROHIBITED_HOST_NAMESPACES or val.startswith( + ("container:", "service:") + ): return ( False, f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'.", @@ -641,20 +961,47 @@ def validate_compose_security( volumes = svc.get("volumes", []) if isinstance(volumes, list): + granted_ro_resolved: list[Path] = [] + for g_ro in grant.readOnlyPaths: + try: + granted_ro_resolved.append(Path(g_ro).resolve(strict=True)) + except OSError: + continue + for vol in volumes: host_path = "" + is_short_ro = False + is_long_bind_ro = False + is_long_syntax = False + unsafe_prop: str | None = None + if isinstance(vol, str): - if "/var/run/docker.sock" in vol: + vol_resolved = _interpolate_compose_value(vol, resolved_env) + if "/var/run/docker.sock" in vol_resolved: return ( False, - f"Service '{svc_name}' directly mounts Docker socket: {vol}.", + f"Service '{svc_name}' directly mounts Docker socket: {vol_resolved}.", ) - if ":" in vol: - host_path = vol.split(":")[0].strip() + if ":" in vol_resolved: + parts = vol_resolved.split(":") + host_path = parts[0].strip() + if len(parts) >= 3: + opts = [ + o.strip().lower() + for o in parts[2].split(",") + if o.strip() + ] + for opt in opts: + if opt in UNSAFE_BIND_PROPAGATIONS: + unsafe_prop = opt + is_short_ro = ("ro" in opts) and ("rw" not in opts) else: - host_path = vol.strip() + host_path = vol_resolved.strip() elif isinstance(vol, dict): - src = str(vol.get("source", "")) + is_long_syntax = True + src = _interpolate_compose_value( + str(vol.get("source", "")), resolved_env + ) if "/var/run/docker.sock" in src: return ( False, @@ -663,6 +1010,23 @@ def validate_compose_security( vol_type = vol.get("type") if vol_type in ("bind", "volume") or (vol_type is None and src): host_path = src + bind_cfg = vol.get("bind") + if isinstance(bind_cfg, dict): + prop = _interpolate_compose_value( + str(bind_cfg.get("propagation", "")).strip().lower(), + resolved_env, + ) + if prop in UNSAFE_BIND_PROPAGATIONS: + unsafe_prop = prop + is_long_bind_ro = (vol_type == "bind") and ( + vol.get("read_only") is True + ) + + if unsafe_prop is not None: + return ( + False, + f"Capability not granted: Service '{svc_name}' specifies unsafe bind propagation '{unsafe_prop}'.", + ) if not host_path: continue @@ -707,10 +1071,48 @@ def validate_compose_security( ) is_in_own_state = expanded.is_relative_to(target_state_root) - if not (is_in_workload or is_in_own_state): + if is_in_workload or is_in_own_state: + continue + + if not grant.readOnlyPaths: return ( False, - f"Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'.", + f"Capability not granted: Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'.", + ) + + if is_long_syntax and not is_long_bind_ro: + return ( + False, + f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must specify type=bind and read_only=true.", + ) + if not is_long_syntax and not is_short_ro: + return ( + False, + f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must be read-only (:ro).", + ) + + posix_host = PurePosixPath(host_path) + if not posix_host.is_absolute() or ".." in posix_host.parts: + return ( + False, + f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must be absolute without '..'.", + ) + + try: + strict_host = Path(host_path).resolve(strict=True) + except OSError: + return ( + False, + f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' does not exist on host.", + ) + + if not any( + strict_host == g_res or strict_host.is_relative_to(g_res) + for g_res in granted_ro_resolved + ): + return ( + False, + f"Capability not granted: Service '{svc_name}' requests ungranted host bind mount '{host_path}'.", ) return True, None diff --git a/tests/security/test_gitops_security.py b/tests/security/test_gitops_security.py index 5ebe9b8..7f06470 100644 --- a/tests/security/test_gitops_security.py +++ b/tests/security/test_gitops_security.py @@ -1358,3 +1358,330 @@ def test_monorepo_webhook_dispatch_pulls_once_and_deploys_only_admitted_changed_ 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_capability_grants_positive_device_group_and_ro_volumes(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: '1000:0'", "user"), + (" user: '1000:docker'", "docker"), + (" user: '1000:44'", "44"), + (" 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_capability_grants_negative_and_bypass_cases( + 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_capability_grants_device_mknod_and_missing_node_rejected(tmp_path: Path): + """Ensure :rwm (mknod) and non-existent device nodes are rejected even with a device grant.""" + 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_volumes_reject_rw_long_syntax_unsafe_propagation_and_symlink_escape( + tmp_path: Path, +): + """Ensure readOnlyPaths rejects long-syntax rw, unsafe bind propagation, and symlink escapes.""" + 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" + + # 1. Long syntax without read_only: true + 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 + + # 2. Long syntax with unsafe bind propagation (rshared) + 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() + + # 3. Symlink escape outside granted readOnlyPaths + 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_and_malformed_grants_fail_closed( + tmp_path: Path, +): + """Ensure app_name=None gets zero grants and malformed grants.json fails closed.""" + 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", + ) + + # app_name=None -> zero grants + ok, _ = gitops_dispatcher.validate_compose_security( + compose_file, app_dir, app_name=None, grants_file=grants_file + ) + assert ok is False + + # Malformed grants.json -> fails closed even on plain compose file + 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() + diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 9b45cef..8c68d66 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -1682,3 +1682,67 @@ def test_operational_router_workload_update_pulls_monorepo_when_parent_git_exist # Compose commands still run in app_dir compose_cwds = [cwd for c, cwd in executed if c[0] == "docker"] assert compose_cwds and all(cwd == mock_workload_dir for cwd in compose_cwds) + + +def test_operational_router_returns_err_capability_not_granted_and_passes_resolved_env( + tmp_path: Path, admin_principal: Principal, monkeypatch +): + """Ensure appctl_router passes assembled env to validate_compose_security and maps denials to ERR_CAPABILITY_NOT_GRANTED.""" + sites_dir = tmp_path / "Workloads" + app_dir = sites_dir / "media" + app_dir.mkdir(parents=True) + media_dir = tmp_path / "mnt" / "media" + media_dir.mkdir(parents=True) + + (app_dir / "app.yaml").write_text( + f"name: media\ndomain: media.example.test\nenv:\n MEDIA_PATH: '{media_dir}'\n", + encoding="utf-8", + ) + (app_dir / "docker-compose.yml").write_text( + "services:\n app:\n image: alpine\n volumes:\n - \"${MEDIA_PATH}:/media:ro\"\n", + encoding="utf-8", + ) + + grants_file = tmp_path / "grants.json" + grants_file.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8") + monkeypatch.setenv("HOMELAB_GRANTS_FILE", str(grants_file)) + monkeypatch.setenv("HOMELAB_DOMAIN", "example.test") + + mock_app = MagicMock() + mock_app.name = "media" + mock_app.dir_path = str(app_dir) + + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=sites_dir, + ) + req = OperationRequest.model_validate( + {"operation": "workload.deploy", "target": "media"} + ) + + # 1. Without grant -> ERR_CAPABILITY_NOT_GRANTED + with patch("appctl_router.resolve_app", return_value=mock_app): + resp = router.dispatch(req, admin_principal) + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_CAPABILITY_NOT_GRANTED + + # 2. With grant -> resolved_env interpolates ${MEDIA_PATH} and deploy succeeds + grants_file.write_text( + json.dumps( + { + "schemaVersion": "1.0", + "workloads": {"media": {"readOnlyPaths": [str(media_dir)]}}, + } + ), + encoding="utf-8", + ) + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", return_value=(0, "ok", "")), + patch("appctl_router.cmd_sync_homepage"), + ): + resp_ok = router.dispatch(req, admin_principal) + assert resp_ok.success is True + From 1a8e3b5eae9b63dff388fedadd97c76508288b99 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 21 Nov 2026 04:13:59 -0500 Subject: [PATCH 09/10] fix(security,tests): harden compose fallback, root UID check, and split grant tests - Fail closed in validate_compose_security() when PyYAML is unavailable instead of regex fallback (CR-01) - Reject zero-padded root UIDs (e.g. 00:1000) in _validate_service_user() via int() parsing (CR-02) - Extract _resolve_contained_host_path() and _validate_service_volumes() and add docstrings across capability helpers (CR-03, CR-04) - Fix missing-device-node test and split multi-behavior grant tests into focused single-behavior tests (Axis 3 CR-01, CR-02) --- scripts/gitops_dispatcher.py | 435 ++++++++++++------------- tests/security/test_gitops_security.py | 106 ++++-- tests/unit/test_appctl_router.py | 43 ++- tests/unit/test_workload_grants.py | 24 +- 4 files changed, 358 insertions(+), 250 deletions(-) diff --git a/scripts/gitops_dispatcher.py b/scripts/gitops_dispatcher.py index 2ffa641..c9e88f6 100755 --- a/scripts/gitops_dispatcher.py +++ b/scripts/gitops_dispatcher.py @@ -497,6 +497,7 @@ def _validate_service_group_add( granted_names: set[str], granted_gids: set[int], ) -> tuple[bool, str | None]: + """Enforce default-deny and host-granted group_add membership.""" group_add = svc.get("group_add") if not group_add: return True, None @@ -550,6 +551,7 @@ def _validate_service_user( granted_names: set[str], granted_gids: set[int], ) -> tuple[bool, str | None]: + """Enforce non-root UID and granted/unprivileged primary GID containment for service user.""" raw_user = svc.get("user") if raw_user is None: return True, None @@ -568,7 +570,11 @@ def _validate_service_user( uid_part, gid_part = user_val, None uid_clean = uid_part.strip() - if uid_clean.lower() in ("0", "root"): + try: + is_zero_uid = int(uid_clean) == 0 + except ValueError: + is_zero_uid = False + if uid_clean.lower() == "root" or is_zero_uid: return ( False, f"Capability not granted: Service '{svc_name}' requests root user '{user_val}'.", @@ -628,12 +634,46 @@ def _validate_service_user( return True, None +def _resolve_contained_host_path( + svc_name: str, + kind: str, + host_path: str, + granted_roots: list[Path], +) -> tuple[bool, str | None]: + """Verify an absolute host path exists canonically without '..' and falls within a granted root.""" + posix = PurePosixPath(host_path) + if not posix.is_absolute() or ".." in posix.parts: + return ( + False, + f"Capability not granted: Service '{svc_name}' {kind} '{host_path}' must be absolute without '..'.", + ) + + try: + strict_host = Path(host_path).resolve(strict=True) + except OSError: + return ( + False, + f"Capability not granted: Service '{svc_name}' {kind} '{host_path}' does not exist on host.", + ) + + if not any( + strict_host == g_res or strict_host.is_relative_to(g_res) + for g_res in granted_roots + ): + return ( + False, + f"Capability not granted: Service '{svc_name}' requests ungranted {kind} '{host_path}'.", + ) + return True, None + + def _validate_service_devices( svc_name: str, svc: dict[str, Any], grant: WorkloadGrant, resolved_env: dict[str, str] | None, ) -> tuple[bool, str | None]: + """Validate host device mounts against granted device paths and forbid mknod ('m') permissions.""" devices = svc.get("devices") if not devices: return True, None @@ -679,29 +719,160 @@ def _validate_service_devices( f"Capability not granted: Service '{svc_name}' requests prohibited 'm' (mknod) device permission in '{dev_str}'.", ) - posix = PurePosixPath(host_dev) - if not posix.is_absolute() or ".." in posix.parts: - return ( - False, - f"Capability not granted: Service '{svc_name}' device path '{host_dev}' must be absolute without '..'.", - ) + ok_path, path_err = _resolve_contained_host_path( + svc_name, "device", host_dev, granted_resolved + ) + if not ok_path: + return False, path_err + return True, None + +def _validate_service_volumes( + svc_name: str, + svc: dict[str, Any], + allowed_root: Path, + canonical_allowed_root: Path, + target_state_root: Path, + top_volumes: set[str], + grant: WorkloadGrant, + resolved_env: dict[str, str] | None, +) -> tuple[bool, str | None]: + """Validate service volume mounts against workload/state roots and granted readOnlyPaths.""" + volumes = svc.get("volumes", []) + if not isinstance(volumes, list): + return True, None + + granted_ro_resolved: list[Path] = [] + for g_ro in grant.readOnlyPaths: try: - resolved_dev = Path(host_dev).resolve(strict=True) + granted_ro_resolved.append(Path(g_ro).resolve(strict=True)) except OSError: - return ( - False, - f"Capability not granted: Service '{svc_name}' device '{host_dev}' does not exist on host.", + continue + + for vol in volumes: + host_path = "" + is_short_ro = False + is_long_bind_ro = False + is_long_syntax = False + unsafe_prop: str | None = None + + if isinstance(vol, str): + vol_resolved = _interpolate_compose_value(vol, resolved_env) + if "/var/run/docker.sock" in vol_resolved: + return ( + False, + f"Service '{svc_name}' directly mounts Docker socket: {vol_resolved}.", + ) + if ":" in vol_resolved: + parts = vol_resolved.split(":") + host_path = parts[0].strip() + if len(parts) >= 3: + opts = [ + o.strip().lower() + for o in parts[2].split(",") + if o.strip() + ] + for opt in opts: + if opt in UNSAFE_BIND_PROPAGATIONS: + unsafe_prop = opt + is_short_ro = ("ro" in opts) and ("rw" not in opts) + else: + host_path = vol_resolved.strip() + elif isinstance(vol, dict): + is_long_syntax = True + src = _interpolate_compose_value( + str(vol.get("source", "")), resolved_env + ) + if "/var/run/docker.sock" in src: + return ( + False, + f"Service '{svc_name}' directly mounts Docker socket: {src}.", + ) + vol_type = vol.get("type") + if vol_type in ("bind", "volume") or (vol_type is None and src): + host_path = src + bind_cfg = vol.get("bind") + if isinstance(bind_cfg, dict): + prop = _interpolate_compose_value( + str(bind_cfg.get("propagation", "")).strip().lower(), + resolved_env, + ) + if prop in UNSAFE_BIND_PROPAGATIONS: + unsafe_prop = prop + is_long_bind_ro = (vol_type == "bind") and ( + vol.get("read_only") is True ) - if not any( - resolved_dev == g_res or resolved_dev.is_relative_to(g_res) - for g_res in granted_resolved + if unsafe_prop is not None: + return ( + False, + f"Capability not granted: Service '{svc_name}' specifies unsafe bind propagation '{unsafe_prop}'.", + ) + + if not host_path: + continue + + if "${" in host_path or "}" in host_path: + return ( + False, + f"Service '{svc_name}' specifies prohibited variable interpolation in volume host path: '{host_path}'.", + ) + + if host_path in top_volumes and not ( + host_path.startswith((".", "/", "~")) + or "/" in host_path + or "\\" in host_path + ): + continue + + if not ( + host_path.startswith((".", "/", "~")) + or "/" in host_path + or "\\" in host_path ): return ( False, - f"Capability not granted: Service '{svc_name}' requests ungranted device '{host_dev}'.", + f"Service '{svc_name}' specifies undeclared named volume or ambiguous path: '{host_path}'.", ) + + if host_path.startswith("~"): + expanded = Path(host_path).expanduser().resolve() + elif Path(host_path).is_absolute(): + expanded = Path(host_path).resolve() + else: + expanded = (allowed_root / host_path).resolve() + + is_in_workload = allowed_root.is_dir() and expanded.is_relative_to( + canonical_allowed_root + ) + is_in_own_state = expanded.is_relative_to(target_state_root) + + if is_in_workload or is_in_own_state: + continue + + if not grant.readOnlyPaths: + return ( + False, + f"Capability not granted: Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'.", + ) + + if is_long_syntax and not is_long_bind_ro: + return ( + False, + f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must specify type=bind and read_only=true.", + ) + if not is_long_syntax and not is_short_ro: + return ( + False, + f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must be read-only (:ro).", + ) + + ok_path, path_err = _resolve_contained_host_path( + svc_name, "external bind mount", host_path, granted_ro_resolved + ) + if not ok_path: + return False, path_err + return True, None @@ -714,15 +885,15 @@ def validate_compose_security( group_lookup: Callable[[str | int], tuple[str, int]] | None = None, ) -> tuple[bool, str | None]: """ - Pre-flight AST inspection of workload docker-compose.yml enforcing Core platform security invariants: - 1. File Integrity: regular file, non-symlink (or strictly contained symlink). - 2. Privilege Containment: blocks 'privileged: true', 'cap_add', 'devices', and 'security_opt: unconfined'. - 3. Host Namespace Isolation: blocks 'pid: host', 'ipc: host', 'uts: host', 'userns_mode: host', 'network_mode: host'. - 4. Docker Socket Ban: blocks direct mounts of /var/run/docker.sock. - 5. Top-Level Inclusion Ban: blocks top-level 'include' directives. - 6. Bind-Mount & Tenant State Isolation: resolves all relative and absolute host paths. Requires containment - strictly within either the workload root (allowed_root) OR the workload's dedicated state root - (~/var/lib/homelab//). Cross-tenant state mounts are rejected fail-closed. + Pre-flight AST inspection of workload docker-compose.yml enforcing Core platform security invariants + and host-granted workload capabilities (ADR-0005): + 1. File Integrity & Parser: regular file, non-symlink (or strictly contained symlink); fails closed if PyYAML is unavailable. + 2. Privilege Containment: blocks 'privileged: true', 'cap_add', 'device_cgroup_rules', and 'security_opt: unconfined'. + 3. Host Namespace Isolation: blocks 'host', 'container:*', and 'service:*' across 'network_mode', 'pid', 'ipc', 'uts', 'userns_mode'. + 4. Docker Socket & Include Bans: blocks direct mounts of /var/run/docker.sock and top-level 'include' directives. + 5. Host-Granted Capabilities: enforces fail-closed workloadGrants for 'devices' (forbidding mknod 'm'), 'group_add', + 'user' primary GIDs, and external ':ro' 'volumes' ('readOnlyPaths', rejecting unsafe bind propagation). + 6. Bind-Mount & Tenant State Isolation: resolves all relative and absolute host paths within allowed_root or ~/var/lib/homelab//. """ if not compose_file.exists(): return True, None @@ -745,48 +916,13 @@ def validate_compose_security( except OSError as e: return False, f"Failed to read compose file {compose_file}: {e}" - yaml_errors = (yaml.YAMLError,) if yaml is not None else () - if yaml is not None: - try: - data = yaml.safe_load(content) or {} - except yaml_errors as e: - return False, f"Failed to parse compose YAML {compose_file}: {e}" - else: - # Fallback regex inspection if yaml module is not present - if re.search( - r"^\s*privileged:\s*true\b", content, re.MULTILINE | re.IGNORECASE - ): - return False, "Privileged mode is prohibited in workload compose files." - if "/var/run/docker.sock" in content: - return ( - False, - "Docker socket mounts are prohibited in workload compose files.", - ) - if re.search( - r"^\s*network_mode:\s*[\"']?host[\"']?", - content, - re.MULTILINE | re.IGNORECASE, - ): - return ( - False, - "Host networking (network_mode: host) is prohibited in workload compose files.", - ) - if re.search(r"^\s*cap_add:\s*", content, re.MULTILINE | re.IGNORECASE): - return ( - False, - "Linux capabilities (cap_add) are prohibited in workload compose files.", - ) - if re.search(r"^\s*devices:\s*", content, re.MULTILINE | re.IGNORECASE): - return ( - False, - "Host device mounts (devices) are prohibited in workload compose files.", - ) - if re.search(r"^\s*include:\s*", content, re.MULTILINE | re.IGNORECASE): - return ( - False, - "Top-level include directives are prohibited in workload compose files.", - ) - return True, None + if yaml is None: + return False, "PyYAML is required for Compose security validation." + + try: + data = yaml.safe_load(content) or {} + except yaml.YAMLError as e: + return False, f"Failed to parse compose YAML {compose_file}: {e}" if not isinstance(data, dict): return False, f"Invalid compose root in {compose_file}: expected mapping" @@ -959,161 +1095,18 @@ def validate_compose_security( f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'.", ) - volumes = svc.get("volumes", []) - if isinstance(volumes, list): - granted_ro_resolved: list[Path] = [] - for g_ro in grant.readOnlyPaths: - try: - granted_ro_resolved.append(Path(g_ro).resolve(strict=True)) - except OSError: - continue - - for vol in volumes: - host_path = "" - is_short_ro = False - is_long_bind_ro = False - is_long_syntax = False - unsafe_prop: str | None = None - - if isinstance(vol, str): - vol_resolved = _interpolate_compose_value(vol, resolved_env) - if "/var/run/docker.sock" in vol_resolved: - return ( - False, - f"Service '{svc_name}' directly mounts Docker socket: {vol_resolved}.", - ) - if ":" in vol_resolved: - parts = vol_resolved.split(":") - host_path = parts[0].strip() - if len(parts) >= 3: - opts = [ - o.strip().lower() - for o in parts[2].split(",") - if o.strip() - ] - for opt in opts: - if opt in UNSAFE_BIND_PROPAGATIONS: - unsafe_prop = opt - is_short_ro = ("ro" in opts) and ("rw" not in opts) - else: - host_path = vol_resolved.strip() - elif isinstance(vol, dict): - is_long_syntax = True - src = _interpolate_compose_value( - str(vol.get("source", "")), resolved_env - ) - if "/var/run/docker.sock" in src: - return ( - False, - f"Service '{svc_name}' directly mounts Docker socket: {src}.", - ) - vol_type = vol.get("type") - if vol_type in ("bind", "volume") or (vol_type is None and src): - host_path = src - bind_cfg = vol.get("bind") - if isinstance(bind_cfg, dict): - prop = _interpolate_compose_value( - str(bind_cfg.get("propagation", "")).strip().lower(), - resolved_env, - ) - if prop in UNSAFE_BIND_PROPAGATIONS: - unsafe_prop = prop - is_long_bind_ro = (vol_type == "bind") and ( - vol.get("read_only") is True - ) - - if unsafe_prop is not None: - return ( - False, - f"Capability not granted: Service '{svc_name}' specifies unsafe bind propagation '{unsafe_prop}'.", - ) - - if not host_path: - continue - - if "${" in host_path or "}" in host_path: - return ( - False, - f"Service '{svc_name}' specifies prohibited variable interpolation in volume host path: '{host_path}'.", - ) - - # Declared top-level named volume without path separators - if host_path in top_volumes and not ( - host_path.startswith((".", "/", "~")) - or "/" in host_path - or "\\" in host_path - ): - continue - - # Undeclared named volumes or bare identifiers not starting with ., /, ~ or containing / are prohibited - if not ( - host_path.startswith((".", "/", "~")) - or "/" in host_path - or "\\" in host_path - ): - return ( - False, - f"Service '{svc_name}' specifies undeclared named volume or ambiguous path: '{host_path}'.", - ) - - # Host bind mount evaluation - if host_path.startswith("~"): - expanded = Path(host_path).expanduser().resolve() - elif Path(host_path).is_absolute(): - expanded = Path(host_path).resolve() - else: - # Relative path resolved against workload root - expanded = (allowed_root / host_path).resolve() - - # Containment check: strictly within workload directory or dedicated state root - is_in_workload = allowed_root.is_dir() and expanded.is_relative_to( - canonical_allowed_root - ) - is_in_own_state = expanded.is_relative_to(target_state_root) - - if is_in_workload or is_in_own_state: - continue - - if not grant.readOnlyPaths: - return ( - False, - f"Capability not granted: Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'.", - ) - - if is_long_syntax and not is_long_bind_ro: - return ( - False, - f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must specify type=bind and read_only=true.", - ) - if not is_long_syntax and not is_short_ro: - return ( - False, - f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must be read-only (:ro).", - ) - - posix_host = PurePosixPath(host_path) - if not posix_host.is_absolute() or ".." in posix_host.parts: - return ( - False, - f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must be absolute without '..'.", - ) - - try: - strict_host = Path(host_path).resolve(strict=True) - except OSError: - return ( - False, - f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' does not exist on host.", - ) - - if not any( - strict_host == g_res or strict_host.is_relative_to(g_res) - for g_res in granted_ro_resolved - ): - return ( - False, - f"Capability not granted: Service '{svc_name}' requests ungranted host bind mount '{host_path}'.", - ) + ok_vol, vol_err = _validate_service_volumes( + svc_name, + svc, + allowed_root, + canonical_allowed_root, + target_state_root, + top_volumes, + grant, + resolved_env, + ) + if not ok_vol: + return False, vol_err return True, None diff --git a/tests/security/test_gitops_security.py b/tests/security/test_gitops_security.py index 7f06470..f027fa7 100644 --- a/tests/security/test_gitops_security.py +++ b/tests/security/test_gitops_security.py @@ -1498,6 +1498,7 @@ services: "compose_body,expected_substr", [ (" user: '0:131'", "user"), + (" user: '00:1000'", "root"), (" user: '1000:0'", "user"), (" user: '1000:docker'", "docker"), (" user: '1000:44'", "44"), @@ -1534,8 +1535,23 @@ def test_capability_grants_negative_and_bypass_cases( assert expected_substr.lower() in err.lower() -def test_capability_grants_device_mknod_and_missing_node_rejected(tmp_path: Path): - """Ensure :rwm (mknod) and non-existent device nodes are rejected even with a device grant.""" +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" @@ -1566,26 +1582,47 @@ services: assert err is not None and "mknod" in err.lower() -def test_capability_grants_volumes_reject_rw_long_syntax_unsafe_propagation_and_symlink_escape( - tmp_path: Path, -): - """Ensure readOnlyPaths rejects long-syntax rw, unsafe bind propagation, and symlink escapes.""" +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) - 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" - - # 1. Long syntax without read_only: true compose_file.write_text( f""" services: @@ -1604,7 +1641,19 @@ services: ) assert ok is False - # 2. Long syntax with unsafe bind propagation (rshared) + +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: @@ -1626,7 +1675,23 @@ services: assert ok is False assert err is not None and "propagation" in err.lower() - # 3. Symlink escape outside granted readOnlyPaths + +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: @@ -1643,10 +1708,8 @@ services: assert ok is False -def test_capability_grants_app_name_none_and_malformed_grants_fail_closed( - tmp_path: Path, -): - """Ensure app_name=None gets zero grants and malformed grants.json fails closed.""" +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" @@ -1668,13 +1731,16 @@ services: encoding="utf-8", ) - # app_name=None -> zero grants ok, _ = gitops_dispatcher.validate_compose_security( compose_file, app_dir, app_name=None, grants_file=grants_file ) assert ok is False - # Malformed grants.json -> fails closed even on plain compose file + +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" diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 8c68d66..a68eee2 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -1684,10 +1684,10 @@ def test_operational_router_workload_update_pulls_monorepo_when_parent_git_exist assert compose_cwds and all(cwd == mock_workload_dir for cwd in compose_cwds) -def test_operational_router_returns_err_capability_not_granted_and_passes_resolved_env( +def test_operational_router_returns_err_capability_not_granted( tmp_path: Path, admin_principal: Principal, monkeypatch ): - """Ensure appctl_router passes assembled env to validate_compose_security and maps denials to ERR_CAPABILITY_NOT_GRANTED.""" + """Ensure appctl_router maps capability-grant denials to ERR_CAPABILITY_NOT_GRANTED.""" sites_dir = tmp_path / "Workloads" app_dir = sites_dir / "media" app_dir.mkdir(parents=True) @@ -1721,14 +1721,33 @@ def test_operational_router_returns_err_capability_not_granted_and_passes_resolv {"operation": "workload.deploy", "target": "media"} ) - # 1. Without grant -> ERR_CAPABILITY_NOT_GRANTED with patch("appctl_router.resolve_app", return_value=mock_app): resp = router.dispatch(req, admin_principal) assert resp.success is False assert resp.error is not None assert resp.error.code == ErrorCode.ERR_CAPABILITY_NOT_GRANTED - # 2. With grant -> resolved_env interpolates ${MEDIA_PATH} and deploy succeeds + +def test_operational_router_passes_resolved_env_to_capability_validation( + tmp_path: Path, admin_principal: Principal, monkeypatch +): + """Ensure appctl_router passes assembled 6-layer env into validate_compose_security().""" + sites_dir = tmp_path / "Workloads" + app_dir = sites_dir / "media" + app_dir.mkdir(parents=True) + media_dir = tmp_path / "mnt" / "media" + media_dir.mkdir(parents=True) + + (app_dir / "app.yaml").write_text( + f"name: media\ndomain: media.example.test\nenv:\n MEDIA_PATH: '{media_dir}'\n", + encoding="utf-8", + ) + (app_dir / "docker-compose.yml").write_text( + "services:\n app:\n image: alpine\n volumes:\n - \"${MEDIA_PATH}:/media:ro\"\n", + encoding="utf-8", + ) + + grants_file = tmp_path / "grants.json" grants_file.write_text( json.dumps( { @@ -1738,6 +1757,22 @@ def test_operational_router_returns_err_capability_not_granted_and_passes_resolv ), encoding="utf-8", ) + monkeypatch.setenv("HOMELAB_GRANTS_FILE", str(grants_file)) + monkeypatch.setenv("HOMELAB_DOMAIN", "example.test") + + mock_app = MagicMock() + mock_app.name = "media" + mock_app.dir_path = str(app_dir) + + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=sites_dir, + ) + req = OperationRequest.model_validate( + {"operation": "workload.deploy", "target": "media"} + ) + with ( patch("appctl_router.resolve_app", return_value=mock_app), patch("appctl_router.run_bounded_subprocess", return_value=(0, "ok", "")), diff --git a/tests/unit/test_workload_grants.py b/tests/unit/test_workload_grants.py index 3665c0b..425f17f 100644 --- a/tests/unit/test_workload_grants.py +++ b/tests/unit/test_workload_grants.py @@ -72,7 +72,7 @@ def test_workload_grant_rejects_relative_and_traversal_paths(bad_path: str) -> N WorkloadGrant(readOnlyPaths=[bad_path]) -def test_grants_registry_rejects_extra_fields_and_bad_schema_version() -> None: +def test_grants_registry_rejects_extra_fields() -> None: with pytest.raises(ValidationError): GrantsRegistry.model_validate( { @@ -80,6 +80,9 @@ def test_grants_registry_rejects_extra_fields_and_bad_schema_version() -> None: "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": {}}) @@ -115,13 +118,12 @@ def test_load_workload_grants_verify_permissions_rejects_symlink(tmp_path: Path) load_workload_grants(link_file, verify_permissions=True) -def test_load_workload_grants_verify_permissions_rejects_non_root_and_writable( +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") - # Non-root owner monkeypatch.setattr( os, "lstat", @@ -130,7 +132,13 @@ def test_load_workload_grants_verify_permissions_rejects_non_root_and_writable( with pytest.raises(WorkloadGrantsError, match="root"): load_workload_grants(grants_path, verify_permissions=True) - # Group/world writable even if root-owned + +def test_load_workload_grants_verify_permissions_rejects_writable_mode( + 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", @@ -139,7 +147,13 @@ def test_load_workload_grants_verify_permissions_rejects_non_root_and_writable( with pytest.raises(WorkloadGrantsError, match="writable"): load_workload_grants(grants_path, verify_permissions=True) - # Valid root-owned 0640 regular file + +def test_load_workload_grants_verify_permissions_accepts_root_0640( + 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", From 1eed45c301c76f4d07dd286ad911303efbfc5615 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 21 Nov 2026 04:48:13 -0500 Subject: [PATCH 10/10] test(security,grants): harden capability grant boundaries and test names - Parametrize writable and non-writable permission mode tests in tests/unit/test_workload_grants.py across 0o020/0o002 bits (CR-02) - Add GID 999 vs 1000 boundary, high numeric GID 1998 resolving to docker, and sibling path prefix (/dev/dri2, /mnt/media2) tests in tests/security/test_gitops_security.py (CR-01) - Rename grant stack/ungranted capability tests to match validate_compose_security() behavior (CR-03, CR-04) --- tests/security/test_gitops_security.py | 105 ++++++++++++++++++++++++- tests/unit/test_workload_grants.py | 12 +-- 2 files changed, 110 insertions(+), 7 deletions(-) diff --git a/tests/security/test_gitops_security.py b/tests/security/test_gitops_security.py index f027fa7..6eab9bc 100644 --- a/tests/security/test_gitops_security.py +++ b/tests/security/test_gitops_security.py @@ -1394,7 +1394,7 @@ def _fake_group_lookup(key: str | int) -> tuple[str, int]: raise KeyError(key) -def test_capability_grants_positive_device_group_and_ro_volumes(tmp_path: Path): +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) @@ -1502,6 +1502,7 @@ services: (" 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"), @@ -1509,7 +1510,7 @@ services: (" user: '${PUID}:1000'", "interpolation"), ], ) -def test_capability_grants_negative_and_bypass_cases( +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.""" @@ -1751,3 +1752,103 @@ def test_capability_grants_malformed_grants_fail_closed(tmp_path: Path): 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 + + diff --git a/tests/unit/test_workload_grants.py b/tests/unit/test_workload_grants.py index 425f17f..a9c2191 100644 --- a/tests/unit/test_workload_grants.py +++ b/tests/unit/test_workload_grants.py @@ -133,8 +133,9 @@ def test_load_workload_grants_verify_permissions_rejects_non_root_owner( 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 + 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") @@ -142,14 +143,15 @@ def test_load_workload_grants_verify_permissions_rejects_writable_mode( monkeypatch.setattr( os, "lstat", - lambda _p: SimpleNamespace(st_mode=0o100664, st_uid=0), + lambda _p: SimpleNamespace(st_mode=bad_mode, st_uid=0), ) with pytest.raises(WorkloadGrantsError, match="writable"): load_workload_grants(grants_path, verify_permissions=True) -def test_load_workload_grants_verify_permissions_accepts_root_0640( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch +@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") @@ -157,6 +159,6 @@ def test_load_workload_grants_verify_permissions_accepts_root_0640( monkeypatch.setattr( os, "lstat", - lambda _p: SimpleNamespace(st_mode=0o100640, st_uid=0), + lambda _p: SimpleNamespace(st_mode=good_mode, st_uid=0), ) assert load_workload_grants(grants_path, verify_permissions=True) == {}