Compare commits

..
Author SHA1 Message Date
kiskaadee 49cded6122 chore(secrets): add sops-encrypted cloudflare/dns_api_token for Traefik ACME
Core Architecture & Invariant CI / validate (push) Successful in 23s
2026-11-23 15:46:59 -05:00
kiskaadee 90f3ca930c fix(core): grant authelia u:1000 ACLs, switch ACME to cloudflare, and add ratelimit middleware
- nixos/modules/homeserver.nix: grant u:1000 rwX POSIX ACLs on config/authelia and db.sqlite3 so Authelia can write SQLite state under operator ownership

- docker-compose.yml & homeserver.nix: switch Traefik DNS-01 ACME provider from dynu to cloudflare (CF_DNS_API_TOKEN via cloudflare/dns_api_token)

- docker-compose.yml: add public-ratelimit Traefik middleware (average=20, burst=40, period=1s) for public workload routes
2026-11-23 15:26:33 -05:00
kiskaadee 47d059ee8d chore(flake): bump nixpkgs and sops-nix inputs
Core Architecture & Invariant CI / validate (push) Successful in 1m16s
- nixpkgs: roll nixos-unstable channel 3ec63636 -> 2786a2a7 (2026-10-23 to 2026-11-21)
- sops-nix: update 44931708 -> 7c637afd (sops 3.12.2 -> 3.13.3, systemd shutdown loop fix, native ssh-to-age support)
- test: verified nix flake check and ./scripts/run-tests pass cleanly (523 tests)
2026-11-22 12:13:31 -05:00
kiskaadee a966244f08 docs: reconcile ~/Workloads, ADR-0005 grants, and P4.5 completion
Core Architecture & Invariant CI / validate (push) Successful in 23s
- Replace stale ~/Sites references with ~/Workloads across README.md, AGENTS.md, docs/architecture.md, docs/operations.md, and ROADMAP.md (ADR-0004)

- Document homelab.workloadGrants, /etc/homelab/grants.json, scripts/workload_grants.py, and nixos/instance.example.nix (ADR-0005)

- Link ADR-0004 and ADR-0005 in ROADMAP.md and record Milestone P4.5 completion in nixos-core
2026-11-21 13:22:07 -05:00
kiskaadee ef42bfc801 fix(ci): remove container image from ci.yaml for :host act_runner (#46)
Core Architecture & Invariant CI / validate (push) Successful in 4s
Co-authored-by: kiskaadee <fcortesbio@gmail.com>
2026-11-21 18:13:01 +00:00
kiskaadee 6ba45961ae Merge pull request 'feat(nixos,security): implement homelab.workloadGrants and nixos/instance.example.nix (ADR-0005)' (#44) from feat/workload-capability-grants into main
Core Architecture & Invariant CI / validate (push) Failing after 0s
2026-11-21 17:52:43 +00:00
kiskaadee 1eed45c301 test(security,grants): harden capability grant boundaries and test names
Core Architecture & Invariant CI / validate (pull_request) Failing after 0s
- 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)
2026-11-21 04:48:13 -05:00
kiskaadee 1a8e3b5eae fix(security,tests): harden compose fallback, root UID check, and split grant tests
Core Architecture & Invariant CI / validate (pull_request) Failing after 0s
- 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)
2026-11-21 04:13:59 -05:00
kiskaadee c9f3108805 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
2026-11-21 04:05:42 -05:00
kiskaadee 4f40668536 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
2026-11-21 03:58:21 -05:00
kiskaadee ce969f4678 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
2026-11-21 03:54:02 -05:00
kiskaadee e807a90017 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
2026-11-21 03:25:16 -05:00
kiskaadee 37d529848a 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
2026-11-21 00:26:44 -05:00
kiskaadee f326b11986 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
2026-11-21 00:06:43 -05:00
kiskaadee 8f3b98344a 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
2026-11-20 22:58:16 -05:00
kiskaadee 92333b017c 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
2026-11-20 13:43:14 -05:00
kiskaadee 131e5d75a1 Merge pull request 'feat(nixos): provision read-only agents SSH user for inspection' (#42) from feat/agents-ssh-user into main
Core Architecture & Invariant CI / validate (push) Successful in 1m14s
2026-11-19 09:11:43 -05:00
kiskaadee 158bbb0eed test(security): harden agents SSH access and ForceCommand tests
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m13s
- CR-01: Test post-subcommand Docker connection/context/config override flags across ps, logs, and inspect
- CR-02: Assert exact extraGroups allowlist ({'homelab-operators', 'systemd-journal'}) for users.users.agents
- CR-03: Assert all socket-proxy published ports are non-empty loopback-only strings starting with 127.0.0.1:
- CR-04: Assert Match User agents ForceCommand targets agents-force-command
- CR-05: Add carriage-return (\r) control-character rejection test case
2026-11-18 23:10:44 -05:00
kiskaadee c104c69fbc docs(nixos): document agents SSH key setup and read-only inspection
- docs/setup_guide.md: add Step 8 covering Ed25519 key generation, NixOS authorizedKeys wiring, workstation ~/.ssh/config, and verification commands
- docs/operations.md: add Section 8 covering workstation setup, safe read-only inspection examples, and ForceCommand/group security boundaries
2026-11-18 22:51:04 -05:00
kiskaadee 11aaf6038b feat(nixos,security): provision read-only agents SSH user and ForceCommand allowlist
- Provision users.users.agents in nixos/configuration.nix with homelab-operators and systemd-journal groups (excluding wheel and docker) and canopy-agents SSH key
- Add Match User agents ForceCommand wrapper and SSH hardening (AllowTcpForwarding, X11Forwarding, AllowAgentForwarding, PermitTTY, PasswordAuthentication disabled)
- Implement nixos/scripts/agents-force-command.sh allowlisting read-only docker ps/logs/inspect, journalctl, and appctl read subcommands while rejecting metacharacters and mutating commands/flags
- Bind socket-proxy to 127.0.0.1:2375:2375 in docker-compose.yml for loopback-only read-only Docker API access
- Add TDD security and structural tests in tests/security/test_agents_access.py
2026-11-18 22:46:39 -05:00
kiskaadee 648dd49c82 fix(nixos): preserve operator home traverse ACL after users activation
Core Architecture & Invariant CI / validate (push) Successful in 27m51s
- Add system.activationScripts.homelabHomeAcl ordered after users activation
- Re-applies u:homelab-appctl:x,g:homelab-operators:x,m::rx on /home/<operatorUser>
- Prevents nixos-rebuild switch from resetting POSIX ACL mask::--- via chmod 0700 and causing homelab-appctl 200/CHDIR failures
2026-11-18 21:32:09 -05:00
kiskaadee 365801a169 Merge pull request 'feat(gitops): decouple deployments.yaml into ~/Workloads/deployments.yaml' (#41) from feat/decouple-deployments-yaml into main
Core Architecture & Invariant CI / validate (push) Successful in 21m16s
2026-11-18 21:14:17 -05:00
kiskaadee 7d4cfe1c04 test(gitops,appctl): split deployments.yaml path tests into single-behavior cases
Core Architecture & Invariant CI / validate (pull_request) Successful in 5m8s
- Split test_deployments_file_defaults_to_workloads_and_does_not_fallback in tests/security/test_gitops_security.py into 3 single-behavior tests
- Split test_default_deployments_file_resolves_to_workloads_dir in tests/unit/test_appctl_auth.py into 3 single-behavior tests
- Split test_daemon_deployments_file_defaults_to_workloads_and_honors_override in tests/unit/test_appctl_daemon.py into 2 single-behavior tests
2026-11-18 19:56:45 -05:00
kiskaadee 9306dae56b test(gitops,appctl): extract isolated env subprocess fixture and split daemon test
- Add tests/conftest.py with run_isolated_script_expr fixture stripping HOMELAB_DEPLOYMENTS_FILE, WORKLOADS_DIR, and SITES_DIR and setting HOME/PYTHONPATH
- Refactor gitops_security, appctl_auth, and appctl_daemon tests to use run_isolated_script_expr instead of duplicated subprocess env-isolation boilerplate
- Split test_daemon_deployments_file_defaults_to_workloads_and_fails_closed into a pure default/override test and a daemon_env 403 fail-closed test
2026-11-18 19:45:42 -05:00
kiskaadee c337914fb3 docs(auth,gitops): update deployments.yaml docstrings to reflect ~/Workloads registry
- Update scripts/appctl_auth.py module and load_admitted_workloads docstrings to reference ~/Workloads/deployments.yaml and HOMELAB_DEPLOYMENTS_FILE / WORKLOADS_DIR overrides instead of config/deployments.yaml
- Update scripts/gitops_dispatcher.py get_trusted_repository_mapping docstring to reference the ~/Workloads/deployments.yaml admission registry (templated by config/deployments.yaml)
2026-11-18 19:41:34 -05:00
kiskaadee df7c1f5292 chore(nixos): point deployments registry to ~/Workloads/deployments.yaml
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m14s
- Point HOMELAB_DEPLOYMENTS_FILE in nixos/modules/homeserver.nix to ${config.homelab.sitesDir}/deployments.yaml for both homelab-appctl and homelab-gitops
- Replace config/deployments.yaml with an infrastructure-agnostic schemaVersion 1.0 example template (example-app, example-docs) and remove all personal workload entries
- Sync AGENTS.md, README.md, docs/architecture.md, docs/gitops.md, docs/operations.md, and docs/decisions/README.md to reference ~/Workloads/deployments.yaml as the live registry and config/deployments.yaml as the template
2026-11-18 14:52:12 -05:00
kiskaadee 33fda26dc1 feat(gitops): default deployments.yaml to ~/Workloads/deployments.yaml
- scripts/appctl_auth.py: default DEFAULT_DEPLOYMENTS_FILE to WORKLOADS_DIR/SITES_DIR or ~/Workloads/deployments.yaml and honor WORKLOADS_DIR in load_admitted_workloads()
- scripts/appctl_daemon.py: default DEPLOYMENTS_FILE to WORKLOADS_DIR/deployments.yaml (~/Workloads/deployments.yaml) instead of CORE_DIR/config/deployments.yaml
- scripts/gitops_dispatcher.py: default DEPLOYMENTS_FILE to WORKLOADS_DIR/deployments.yaml and remove CONFIG_DIR/deployments.yaml fallback in get_trusted_repository_mapping() so missing registry fails closed
- tests: add regression tests for default ~/Workloads/deployments.yaml resolution and fail-closed behavior; isolate test_operational_router_workload_update_propagates_non_zero_exit_and_stderr from host registry
2026-11-18 14:47:51 -05:00
36 changed files with 2517 additions and 249 deletions

No files matched your search

-2
View File
@@ -9,8 +9,6 @@ on:
jobs: jobs:
validate: validate:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container:
image: nixery.dev/shell/coreutils/git/nix/nodejs:latest
steps: steps:
- name: Check out repository - name: Check out repository
uses: actions/checkout@v4 uses: actions/checkout@v4
+6 -6
View File
@@ -2,12 +2,12 @@
## 1. Project Overview & Architectural Boundaries ## 1. Project Overview & Architectural Boundaries
**Canopy NixOS Core** (`canopy-homelab/nixos-core`) defines the declarative NixOS host foundation, shared platform infrastructure services, security boundaries, and the `appctl` operational control plane for the **Canopy** ecosystem. Independent application workloads live in `~/Sites/<app>` and integrate through declarative `app.yaml` manifests and workload-scoped Docker Compose files. **Canopy NixOS Core** (`canopy-homelab/nixos-core`) defines the declarative NixOS host foundation, shared platform infrastructure services, security boundaries, and the `appctl` operational control plane for the **Canopy** ecosystem. Independent application workloads live in `~/Workloads/<app>` and integrate through declarative `app.yaml` manifests and workload-scoped Docker Compose files.
### Core vs. `~/Sites` Ownership ### Core vs. `~/Workloads` Ownership
- **Core owns**: NixOS host configuration, shared platform services (edge ingress, SSO/LDAP, mail, log/update monitors), platform-level ports and security policy, and orchestration/deployment mechanics. - **Core owns**: NixOS host configuration (`nixos/instance.example.nix` template for `/etc/nixos/homelab-instance.nix`), shared platform services (edge ingress, SSO/LDAP, mail, log/update monitors), platform-level ports and security policy (including `homelab.workloadGrants` -> `/etc/homelab/grants.json`), and orchestration/deployment mechanics (`appctl`, `gitops_dispatcher.py`, `workload_grants.py`).
- **`~/Sites` owns**: Independently deployed application workloads, workload-specific `docker-compose.yml` topologies, and workload intent (`app.yaml`). - **`~/Workloads` owns**: Independently deployed application workloads, workload-specific `docker-compose.yml` topologies, workload intent (`app.yaml`), and `deployments.yaml`.
- **Boundary Rule**: Never hardcode *workload-specific* domains, ports, containers, environment variables, or deployment policies in Core (`scripts/appctl*`, GitOps, or Core `docker-compose.yml`), and never move Core platform services into `~/Sites`. When ownership is ambiguous, consult [`docs/architecture.md`](docs/architecture.md) before changing the boundary. - **Boundary Rule**: Never hardcode *workload-specific* domains, ports, containers, environment variables, or deployment policies in Core (`scripts/appctl*`, GitOps, or Core `docker-compose.yml`), and never move Core platform services into `~/Workloads`. When ownership is ambiguous, consult [`docs/architecture.md`](docs/architecture.md) before changing the boundary.
### Context Discovery Hierarchy ### Context Discovery Hierarchy
Before proposing or implementing changes, establish context in this order: Before proposing or implementing changes, establish context in this order:
@@ -67,7 +67,7 @@ docker compose config -q
1. **Workload Manifests (`app.yaml`)**: Describe declarative workload identity, routing metadata, and deployment intent only. Never introduce arbitrary command execution, host filesystem paths, privileged flags, or Docker control capabilities into `app.yaml`. 1. **Workload Manifests (`app.yaml`)**: Describe declarative workload identity, routing metadata, and deployment intent only. Never introduce arbitrary command execution, host filesystem paths, privileged flags, or Docker control capabilities into `app.yaml`.
2. **GitOps Trust Boundary (`scripts/gitops_dispatcher.py`)**: 2. **GitOps Trust Boundary (`scripts/gitops_dispatcher.py`)**:
- Webhook admission requires cryptographic authentication (HMAC-SHA256). - Webhook admission requires cryptographic authentication (HMAC-SHA256).
- Repository identity and filesystem paths must be resolved strictly through trusted Core configuration (`config/deployments.yaml`)—never directly from webhook payloads. - Repository identity and filesystem paths must be resolved strictly through the trusted workloads registry (`~/Workloads/deployments.yaml` or `HOMELAB_DEPLOYMENTS_FILE`, templated by `config/deployments.yaml`)—never directly from webhook payloads.
- Execution must remain allowlisted, serialized (`flock`), pre-validated by the Compose AST security checker, and free of shell interpolation (`shell=False`, no `eval`). - Execution must remain allowlisted, serialized (`flock`), pre-validated by the Compose AST security checker, and free of shell interpolation (`shell=False`, no `eval`).
3. **Docker & Privilege Isolation**: 3. **Docker & Privilege Isolation**:
- `socket-proxy` is the **only** service permitted to mount `/var/run/docker.sock` (strictly `:ro`, read-only API capabilities only; `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`). - `socket-proxy` is the **only** service permitted to mount `/var/run/docker.sock` (strictly `:ro`, read-only API capabilities only; `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`).
+6 -5
View File
@@ -4,7 +4,7 @@
It is designed around a strict two-tier boundary: It is designed around a strict two-tier boundary:
1. **Canopy NixOS Core (`canopy-homelab/nixos-core`, this repository)**: Owns NixOS operating system configuration, edge TLS ingress, SSO/LDAP directory identity, mail routing, read-only Docker socket isolation, and orchestration/deployment mechanics. 1. **Canopy NixOS Core (`canopy-homelab/nixos-core`, this repository)**: Owns NixOS operating system configuration, edge TLS ingress, SSO/LDAP directory identity, mail routing, read-only Docker socket isolation, and orchestration/deployment mechanics.
2. **Canopy Workloads (`~/Sites/<app>`, e.g. `<user>/canopy-workloads`)**: Independently deployed application stacks that integrate with Core through self-describing `app.yaml` manifests and workload-scoped `docker-compose.yml` definitions. 2. **Canopy Workloads (`~/Workloads/<app>`, e.g. `<user>/canopy-workloads`)**: Independently deployed application stacks that integrate with Core through self-describing `app.yaml` manifests and workload-scoped `docker-compose.yml` definitions.
All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime. All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime.
@@ -35,7 +35,7 @@ All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_
├───────────────────────────────┤ ├───────────────────────────────┤
│ • Core Services (Homepage, │ │ • Core Services (Homepage, │
│ Dozzle, Stalwart, etc.) │ │ Dozzle, Stalwart, etc.) │
│ • Workload Apps (~/Sites/*) │ │ • Workload Apps (~/Workloads/*) │
└───────────────┬───────────────┘ └───────────────┬───────────────┘
│ (Read-Only API via TCP:2375) │ (Read-Only API via TCP:2375)
▼ ▼
@@ -81,8 +81,8 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran
. .
├── flake.nix # NixOS host configuration, devShell (.venv symlink), and CI checks ├── flake.nix # NixOS host configuration, devShell (.venv symlink), and CI checks
├── docker-compose.yml # Core platform service stack ├── docker-compose.yml # Core platform service stack
├── nixos/ # Declarative NixOS modules, systemd units, and SOPS secret wiring ├── nixos/ # Declarative NixOS modules, systemd units, SOPS secret wiring & instance.example.nix
├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml) ├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml template)
├── scripts/ ├── scripts/
│ ├── appctl # Thin operational CLI delegating to control plane daemon │ ├── appctl # Thin operational CLI delegating to control plane daemon
│ ├── appctl_daemon.py # Async HTTP/UDS daemon server (homelab-appctl.service) │ ├── appctl_daemon.py # Async HTTP/UDS daemon server (homelab-appctl.service)
@@ -95,6 +95,7 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran
│ ├── bootstrap_token.py # Operator Bearer token provisioning helper │ ├── bootstrap_token.py # Operator Bearer token provisioning helper
│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for app.yaml │ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for app.yaml
│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST validation │ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST validation
│ ├── workload_grants.py # Fail-closed Pydantic v2 loader for /etc/homelab/grants.json
│ └── run-tests # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks) │ └── run-tests # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks)
├── tests/ # Unit, structural, and security invariant test suites ├── tests/ # Unit, structural, and security invariant test suites
└── docs/ # Architecture references, operational runbooks, and MADR decisions └── docs/ # Architecture references, operational runbooks, and MADR decisions
@@ -166,7 +167,7 @@ systemctl status dynu-monitor.service
| Document | Scope | | Document | Scope |
| :--- | :--- | | :--- | :--- |
| [**`docs/architecture.md`**](docs/architecture.md) | Runtime layers, network segmentation, and Core / `~/Sites` boundaries. | | [**`docs/architecture.md`**](docs/architecture.md) | Runtime layers, network segmentation, and Core / `~/Workloads` boundaries. |
| [**`docs/decisions/README.md`**](docs/decisions/README.md) | Architecture Decision Records (MADR 4.0) governing platform evolution. | | [**`docs/decisions/README.md`**](docs/decisions/README.md) | Architecture Decision Records (MADR 4.0) governing platform evolution. |
| [**`ROADMAP.md`**](ROADMAP.md) | Phased engineering milestones (P0–P7) and baseline-to-target architecture matrix. | | [**`ROADMAP.md`**](ROADMAP.md) | Phased engineering milestones (P0–P7) and baseline-to-target architecture matrix. |
| [**`docs/appctl.md`**](docs/appctl.md) | Current `appctl` CLI commands, resolution hierarchy, and `app.yaml` schema v1.0 contract. | | [**`docs/appctl.md`**](docs/appctl.md) | Current `appctl` CLI commands, resolution hierarchy, and `app.yaml` schema v1.0 contract. |
+3 -2
View File
@@ -4,7 +4,7 @@ This document serves as the repository-facing projection of the authoritative **
It describes the implementation trajectory and phased engineering milestones for evolving the **Canopy** platform (`canopy-homelab/nixos-core`) around a unified `appctl` Operational Control Plane. It describes the implementation trajectory and phased engineering milestones for evolving the **Canopy** platform (`canopy-homelab/nixos-core`) around a unified `appctl` Operational Control Plane.
> **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index ([ADR-0001: 3-Tier Provenance Model](docs/decisions/0001-3tier-architecture-and-provenance.md), [ADR-0002: Operational Control Plane Architecture](docs/decisions/0002-appctl-control-plane-architecture.md), and [ADR-0003: Pydantic v2 Runtime Validation](docs/decisions/0003-pydantic-v2-runtime-validation.md)). > **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index ([ADR-0001: 3-Tier Provenance Model](docs/decisions/0001-3tier-architecture-and-provenance.md), [ADR-0002: Operational Control Plane Architecture](docs/decisions/0002-appctl-control-plane-architecture.md), [ADR-0003: Pydantic v2 Runtime Validation](docs/decisions/0003-pydantic-v2-runtime-validation.md), [ADR-0004: Unified ~/Workloads Monorepo](docs/decisions/0004-unified-workloads-monorepo.md), and [ADR-0005: Host-Granted Workload Capabilities](docs/decisions/0005-workload-capability-grants.md)).
--- ---
@@ -29,7 +29,7 @@ It describes the implementation trajectory and phased engineering milestones for
| **`appctl` Architecture** | Dedicated daemon service (`homelab-appctl.service`, user `homelab-appctl`) exposing `POST /v1/operations` over Unix socket and loopback HTTP, with thin-client CLI (`scripts/appctl_cli.py`). | Expand with Operations UI and external ForwardAuth integration (P5–P7). | | **`appctl` Architecture** | Dedicated daemon service (`homelab-appctl.service`, user `homelab-appctl`) exposing `POST /v1/operations` over Unix socket and loopback HTTP, with thin-client CLI (`scripts/appctl_cli.py`). | Expand with Operations UI and external ForwardAuth integration (P5–P7). |
| **Operational Auth** | Mandatory SHA-256 Bearer token + 3-role RBAC + UDS `SO_PEERCRED` viewer fallback (`/run/secrets/appctl/tokens.json`). | LLDAP directory RBAC & Authelia ForwardAuth (P5). | | **Operational Auth** | Mandatory SHA-256 Bearer token + 3-role RBAC + UDS `SO_PEERCRED` viewer fallback (`/run/secrets/appctl/tokens.json`). | LLDAP directory RBAC & Authelia ForwardAuth (P5). |
| **Metadata & Schema Engine** | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | Standardized JSON-RPC Model Context Protocol tools over Pydantic v2 schemas (P6). | | **Metadata & Schema Engine** | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | Standardized JSON-RPC Model Context Protocol tools over Pydantic v2 schemas (P6). |
| **Deployment Model** | Direct authoring of `app.yaml` and `docker-compose.yml` in `~/Sites/<app>/`. | Authoritative declarative Git state (`app.yaml` + Compose) managed via CLI, GitOps, or client-gated MCP tools (P6). | | **Deployment Model** | Authoritative declarative Git state (`app.yaml`, `docker-compose.yml`, `deployments.yaml`) in `~/Workloads/<app>/`, bounded by `homelab.workloadGrants` (`/etc/homelab/grants.json`). | Standardized JSON-RPC MCP tools (`P6`) and Operations UI (`P7`). |
| **GitOps Engine** | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | Unified continuous deployment worker driven by Git webhooks delegating to control plane daemon (P4 baseline consolidated). | | **GitOps Engine** | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | Unified continuous deployment worker driven by Git webhooks delegating to control plane daemon (P4 baseline consolidated). |
| **Secret Distribution** | Age-encrypted `nixos/secrets.yaml` decrypted by `sops-nix` to tmpfs `/run/secrets/`. | Host secrets remain in `sops-nix`; workload secrets referenced by key and projected via `SecretProvider` (planned in P5). | | **Secret Distribution** | Age-encrypted `nixos/secrets.yaml` decrypted by `sops-nix` to tmpfs `/run/secrets/`. | Host secrets remain in `sops-nix`; workload secrets referenced by key and projected via `SecretProvider` (planned in P5). |
| **Dashboard** | `appctl sync` compiles `config/homepage/services.yaml` from `app.yaml` manifests under `_homepage_sync.lock`. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for management (planned in P7). | | **Dashboard** | `appctl sync` compiles `config/homepage/services.yaml` from `app.yaml` manifests under `_homepage_sync.lock`. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for management (planned in P7). |
@@ -45,6 +45,7 @@ It describes the implementation trajectory and phased engineering milestones for
| **P2** | **GitOps Hardening** | Ingress Security | ✅ **Completed** | Authoritative Core repository registry (`deployments.yaml`), Compose AST security validator, systemd sandboxing. | | **P2** | **GitOps Hardening** | Ingress Security | ✅ **Completed** | Authoritative Core repository registry (`deployments.yaml`), Compose AST security validator, systemd sandboxing. |
| **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0 with Pydantic v2 fail-closed models (`core_manifest.py`), two-axis status inspection, unified `appctl_engine.py`. | | **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0 with Pydantic v2 fail-closed models (`core_manifest.py`), two-axis status inspection, unified `appctl_engine.py`. |
| **P4** | **Control Plane Daemon** | API & Dispatch | ✅ **Completed** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. | | **P4** | **Control Plane Daemon** | API & Dispatch | ✅ **Completed** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. |
| **P4.5** | **Workloads Contract & Agent Readiness** | Monorepo & Grants | ✅ **Completed** *(in `nixos-core`)* | `~/Workloads/deployments.yaml` decoupling, read-only `agents` SSH user, `homelab.workloadGrants` (`ADR-0005`), `nixos/instance.example.nix`, and `:host` CI runner workflow. |
| **P5** | **Identity & Secrets** | Auth & Providers | 🎯 **Current / Up Next** | LLDAP RBAC group mapping, Authelia ForwardAuth header integration, user-scoped token lifecycle, `SecretProvider` reference resolution. | | **P5** | **Identity & Secrets** | Auth & Providers | 🎯 **Current / Up Next** | LLDAP RBAC group mapping, Authelia ForwardAuth header integration, user-scoped token lifecycle, `SecretProvider` reference resolution. |
| **P6** | **Homelab MCP Gateway** | Protocol Integration | ⏳ **Planned** | Standardized JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`), client-side human-in-the-loop approvals, deprecation of on-server AI proposal compilers. | | **P6** | **Homelab MCP Gateway** | Protocol Integration | ⏳ **Planned** | Standardized JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`), client-side human-in-the-loop approvals, deprecation of on-server AI proposal compilers. |
| **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. | | **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. |
+12 -42
View File
@@ -1,48 +1,18 @@
# Core Authoritative Repository Identity Registry # Example Repository Identity Registry Template
# Governs admitted continuous deployment targets for GitOps webhook execution. # Live production deployments are configured in ~/Workloads/deployments.yaml
# (or overridden via the HOMELAB_DEPLOYMENTS_FILE environment variable).
#
# Owns: repository identity, canonical filesystem path, and aliases. # Owns: repository identity, canonical filesystem path, and aliases.
# Enforces: strict path containment within ~/Workloads. # Enforces: strict path containment within ~/Workloads (WORKLOADS_DIR).
schemaVersion: "1.0" schemaVersion: "1.0"
repositories: repositories:
snappymail: example-app:
path: "~/Workloads/snappymail" path: "~/Workloads/example-app"
aliases: aliases:
- "homelab-snappymail" - "example"
- "mail" - "homelab-example"
- "webmail" example-docs:
gitea: path: "~/Workloads/example-docs"
path: "~/Workloads/homelab-gitea"
aliases: aliases:
- "homelab-gitea" - "docs"
- "git"
jellyfin:
path: "~/Workloads/homelab-jellyfin"
aliases:
- "homelab-jellyfin"
- "media"
courses:
path: "~/Workloads/courses"
aliases:
- "homelab-courses"
bdinvite:
path: "~/Workloads/homelab-bdinvite"
aliases:
- "homelab-bdinvite"
- "birthday"
landing:
path: "~/Workloads/homelab-landing"
aliases:
- "homelab-landing"
mermaid:
path: "~/Workloads/homelab-mermaid"
aliases:
- "homelab-mermaid"
excalidraw:
path: "~/Workloads/homelab-excalidraw"
aliases:
- "homelab-excalidraw"
houston:
path: "~/Workloads/homelab-houston"
aliases:
- "homelab-houston"
+9 -2
View File
@@ -3,6 +3,8 @@ services:
image: tecnativa/docker-socket-proxy image: tecnativa/docker-socket-proxy
container_name: socket-proxy container_name: socket-proxy
restart: always restart: always
ports:
- "127.0.0.1:2375:2375"
volumes: volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro - /var/run/docker.sock:/var/run/docker.sock:ro
environment: environment:
@@ -42,7 +44,7 @@ services:
- "80:80" - "80:80"
- "443:443" - "443:443"
environment: environment:
- DYNU_API_KEY=${DYNU_API_KEY} - CF_DNS_API_TOKEN=${CF_DNS_API_TOKEN}
- DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40} - DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40}
command: command:
- "--log.level=INFO" - "--log.level=INFO"
@@ -59,7 +61,7 @@ services:
- "--entrypoints.websecure.http.tls.domains[0].sans=*.${DOMAIN}" - "--entrypoints.websecure.http.tls.domains[0].sans=*.${DOMAIN}"
# SSL Setup # SSL Setup
- "--certificatesresolvers.myresolver.acme.dnschallenge=true" - "--certificatesresolvers.myresolver.acme.dnschallenge=true"
- "--certificatesresolvers.myresolver.acme.dnschallenge.provider=dynu" - "--certificatesresolvers.myresolver.acme.dnschallenge.provider=cloudflare"
- "--certificatesresolvers.myresolver.acme.email=${ACME_EMAIL}" - "--certificatesresolvers.myresolver.acme.email=${ACME_EMAIL}"
- "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json" - "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"
volumes: volumes:
@@ -79,6 +81,11 @@ services:
- "traefik.http.middlewares.authelia-auth.forwardauth.trustForwardHeader=true" - "traefik.http.middlewares.authelia-auth.forwardauth.trustForwardHeader=true"
- "traefik.http.middlewares.authelia-auth.forwardauth.authResponseHeaders=Remote-User,Remote-Groups,Remote-Email,Remote-Name" - "traefik.http.middlewares.authelia-auth.forwardauth.authResponseHeaders=Remote-User,Remote-Groups,Remote-Email,Remote-Name"
# Middleware: Public Rate Limit (mitigates scraper/crawler bursts on public routes)
- "traefik.http.middlewares.public-ratelimit.ratelimit.average=20"
- "traefik.http.middlewares.public-ratelimit.ratelimit.burst=40"
- "traefik.http.middlewares.public-ratelimit.ratelimit.period=1s"
# Dashboard - Public (HTTPS) # Dashboard - Public (HTTPS)
- "traefik.http.routers.traefik-dash.rule=Host(`traefik.${DOMAIN}`)" - "traefik.http.routers.traefik-dash.rule=Host(`traefik.${DOMAIN}`)"
- "traefik.http.routers.traefik-dash.entrypoints=websecure" - "traefik.http.routers.traefik-dash.entrypoints=websecure"
+12 -12
View File
@@ -14,7 +14,7 @@ To understand how the system is organized, three architectural dimensions are di
### A. Ownership Boundary ### A. Ownership Boundary
* **Core (`~/Core`) owns**: NixOS host configuration, shared platform services, edge ingress, identity boundaries, secrets distribution, and deployment orchestration mechanics. * **Core (`~/Core`) owns**: NixOS host configuration, shared platform services, edge ingress, identity boundaries, secrets distribution, and deployment orchestration mechanics.
* **Workload Plane (`~/Sites`) owns**: Independent application deployments, workload-specific Docker Compose files, declarative `app.yaml` manifests, and workload-scoped runtime state (`~/var/lib/homelab/<app>/`). * **Workload Plane (`~/Workloads`) owns**: Independent application deployments, workload-specific Docker Compose files, declarative `app.yaml` manifests, `~/Workloads/deployments.yaml`, and workload-scoped runtime state (`~/var/lib/homelab/<app>/`).
### B. Four Runtime Layers ### B. Four Runtime Layers
The runtime environment consists of four functional layers: The runtime environment consists of four functional layers:
@@ -35,7 +35,7 @@ The runtime environment consists of four functional layers:
│ │
▼ ▼
┌────────────────────────────────────────────────────────────────────────┐ ┌────────────────────────────────────────────────────────────────────────┐
│ 3. WORKLOAD PLANE (~/Sites) │ │ 3. WORKLOAD PLANE (~/Workloads) │
│ Autonomous Workload Repositories (SnappyMail, Docs, Gitea, etc.) │ │ Autonomous Workload Repositories (SnappyMail, Docs, Gitea, etc.) │
│ Declarative app.yaml Manifests & Compose Stacks │ │ Declarative app.yaml Manifests & Compose Stacks │
└───────────────────────────────────┬────────────────────────────────────┘ └───────────────────────────────────┬────────────────────────────────────┘
@@ -51,8 +51,8 @@ The runtime environment consists of four functional layers:
### C. Cross-Cutting Orchestration ### C. Cross-Cutting Orchestration
Orchestration coordinates operations across the runtime layers: Orchestration coordinates operations across the runtime layers:
* **`appctl` Operational Control Plane Daemon (`homelab-appctl.service`, `scripts/appctl_daemon.py`, `scripts/appctl_router.py`)**: Centralized control plane running under isolated service identity `homelab-appctl:homelab-operators`. Exposes `POST /v1/operations` and `GET /v1/health` over `/run/homelab/appctl.sock` (mode `0660`) and `127.0.0.1:9001`, enforcing SHA-256 Bearer token authentication, 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`), per-target `flock` serialization, fail-closed append-only audit logging (`/var/log/homelab/appctl/audit.jsonl`), Pydantic v2 `app.yaml` validation, Compose AST security checks, and pure-Python `.env` assembly. * **`appctl` Operational Control Plane Daemon (`homelab-appctl.service`, `scripts/appctl_daemon.py`, `scripts/appctl_router.py`)**: Centralized control plane running under isolated service identity `homelab-appctl:homelab-operators`. Exposes `POST /v1/operations` and `GET /v1/health` over `/run/homelab/appctl.sock` (mode `0660`) and `127.0.0.1:9001`, enforcing SHA-256 Bearer token authentication, 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`), per-target `flock` serialization, fail-closed append-only audit logging (`/var/log/homelab/appctl/audit.jsonl`), Pydantic v2 `app.yaml` validation, Compose AST security checks (enforcing host-granted `homelab.workloadGrants` from `/etc/homelab/grants.json` via `scripts/workload_grants.py`), and pure-Python `.env` assembly.
* **GitOps Webhook Dispatcher (`scripts/gitops_dispatcher.py`)**: Governed by the `homelab-gitops.service` systemd unit, it receives webhooks on port 9000, verifies HMAC-SHA256 signatures, enforces the `config/deployments.yaml` allowlist, and delegates serialized `workload.update` execution to `homelab-appctl.service` over `/run/homelab/appctl.sock` using its `homelab-operator` Bearer token. * **GitOps Webhook Dispatcher (`scripts/gitops_dispatcher.py`)**: Governed by the `homelab-gitops.service` systemd unit, it receives webhooks on port 9000, verifies HMAC-SHA256 signatures, enforces the `~/Workloads/deployments.yaml` allowlist (configured via `HOMELAB_DEPLOYMENTS_FILE`, with `config/deployments.yaml` as the example template), and delegates serialized `workload.update` execution to `homelab-appctl.service` over `/run/homelab/appctl.sock` using its `homelab-operator` Bearer token.
--- ---
@@ -70,7 +70,7 @@ Orchestration coordinates operations across the runtime layers:
- Mounted read-only: `/var/run/docker.sock:/var/run/docker.sock:ro`. - Mounted read-only: `/var/run/docker.sock:/var/run/docker.sock:ro`.
- State-modifying and execution endpoints disabled: `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`, `COMMIT=0`, `CONFIGS=0`, `DISTRIBUTION=0`, `NODES=0`, `PLUGINS=0`, `SECRETS=0`, `SWARM=0`, `SYSTEM=0`. - State-modifying and execution endpoints disabled: `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`, `COMMIT=0`, `CONFIGS=0`, `DISTRIBUTION=0`, `NODES=0`, `PLUGINS=0`, `SECRETS=0`, `SWARM=0`, `SYSTEM=0`.
- Read-only inspection endpoints enabled: `CONTAINERS=1`, `NETWORKS=1`, `SERVICES=1`, `TASKS=1`, `IMAGES=1`, `VOLUMES=1`, `INFO=1`, `EVENTS=1`, `PING=1`, `VERSION=1`. - Read-only inspection endpoints enabled: `CONTAINERS=1`, `NETWORKS=1`, `SERVICES=1`, `TASKS=1`, `IMAGES=1`, `VOLUMES=1`, `INFO=1`, `EVENTS=1`, `PING=1`, `VERSION=1`.
* **Network**: Attached exclusively to `socket-net`. Application containers in `~/Sites` are never attached to `socket-net`. * **Network**: Attached exclusively to `socket-net`. Application containers in `~/Workloads` are never attached to `socket-net`.
### C. Identity & Directory Services (`lldap` & `authelia`) ### C. Identity & Directory Services (`lldap` & `authelia`)
* **`lldap`**: Lightweight LDAP directory service storing user accounts, password hashes, and groups. Web UI exposed at `users.${HOMELAB_DOMAIN}` (protected by Authelia). SQLite database stored in `config/lldap/data/users.db`. * **`lldap`**: Lightweight LDAP directory service storing user accounts, password hashes, and groups. Web UI exposed at `users.${HOMELAB_DOMAIN}` (protected by Authelia). SQLite database stored in `config/lldap/data/users.db`.
@@ -84,10 +84,10 @@ Orchestration coordinates operations across the runtime layers:
- WebAdmin & JMAP endpoint accessible at `smtp.${HOMELAB_DOMAIN}` via Traefik. - WebAdmin & JMAP endpoint accessible at `smtp.${HOMELAB_DOMAIN}` via Traefik.
- Authenticates users against the LLDAP directory. - Authenticates users against the LLDAP directory.
- Outbound mail relay configured to route through an external smart host (Brevo SMTP relay via SOPS secrets). - Outbound mail relay configured to route through an external smart host (Brevo SMTP relay via SOPS secrets).
- *(Note: User-facing webmail, such as SnappyMail, runs as an independent Class B workload in `~/Sites/snappymail` with isolated state under `~/var/lib/homelab/snappymail/`.)* - *(Note: User-facing webmail, such as SnappyMail, runs as an independent Class B workload in `~/Workloads/snappymail` with isolated state under `~/var/lib/homelab/snappymail/`.)*
### E. Portal & Observability (`homepage`, `dozzle`) ### E. Portal & Observability (`homepage`, `dozzle`)
* **`homepage`**: Service dashboard at `dashboard.${HOMELAB_DOMAIN}`. Synchronized from `app.yaml` manifests in `~/Sites` by `appctl sync`. * **`homepage`**: Service dashboard at `dashboard.${HOMELAB_DOMAIN}`. Synchronized from `app.yaml` manifests in `~/Workloads` by `appctl sync`.
* **`dozzle`**: Real-time container log viewer at `logs.${HOMELAB_DOMAIN}`, connecting read-only through `socket-proxy`. * **`dozzle`**: Real-time container log viewer at `logs.${HOMELAB_DOMAIN}`, connecting read-only through `socket-proxy`.
### F. Host Foundation & Daemons ### F. Host Foundation & Daemons
@@ -113,7 +113,7 @@ Homelab Core configures two isolated Docker bridge networks:
│ │ • traefik (router) • authelia (sso) │ │ │ │ • traefik (router) • authelia (sso) │ │
│ │ • lldap (directory) • stalwart (mail) │ │ │ │ • lldap (directory) • stalwart (mail) │ │
│ │ • homepage (dashboard) • dozzle (logs) │ │ │ │ • homepage (dashboard) • dozzle (logs) │ │
│ │ • All User Workloads (~/Sites/*) │ │ │ │ • All User Workloads (~/Workloads/*) │ │
│ └──────────────────────────────┬───────────────────────────────┘ │ │ └──────────────────────────────┬───────────────────────────────┘ │
│ │ │ │ │ │
│ ┌──────────────────────────────┴───────────────────────────────┐ │ │ ┌──────────────────────────────┴───────────────────────────────┐ │
@@ -129,7 +129,7 @@ Homelab Core configures two isolated Docker bridge networks:
└────────────────────────────────────────────────────────────────────────┘ └────────────────────────────────────────────────────────────────────────┘
``` ```
1. **`proxy-net`**: Ingress routing network. Traefik directs traffic to backend service containers on this network. Workload containers in `~/Sites` join `proxy-net`. 1. **`proxy-net`**: Ingress routing network. Traefik directs traffic to backend service containers on this network. Workload containers in `~/Workloads` join `proxy-net`.
2. **`socket-net`**: Isolated Docker socket proxy network. Only Core infrastructure components needing read-only container metadata join this network. 2. **`socket-net`**: Isolated Docker socket proxy network. Only Core infrastructure components needing read-only container metadata join this network.
--- ---
@@ -151,13 +151,13 @@ The host firewall is configured in `nixos/modules/homeserver.nix`:
| **993** | TCP | Stalwart | IMAPS (Secure IMAP) | Public | | **993** | TCP | Stalwart | IMAPS (Secure IMAP) | Public |
| **4190** | TCP | Stalwart | ManageSieve (Mail Filters) | Public | | **4190** | TCP | Stalwart | ManageSieve (Mail Filters) | Public |
Application containers in `~/Sites` do not bind host ports directly; they receive traffic routed by Traefik over `proxy-net`. Application containers in `~/Workloads` do not bind host ports directly; they receive traffic routed by Traefik over `proxy-net`.
--- ---
## 5. Workload Integration Model ## 5. Workload Integration Model
Workloads in `~/Sites/<app>` integrate with Core through three mechanisms: Workloads in `~/Workloads/<app>` integrate with Core through three mechanisms:
1. **Manifest Metadata (`app.yaml`)**: Validated by `scripts/core_manifest.py` (Schema v1.0). Declares canonical identity, routed domain, upstream source provenance (`source.url`, `source.ref`), environment defaults, Homepage card layout, and allowlisted GitOps deployment policy. 1. **Manifest Metadata (`app.yaml`)**: Validated by `scripts/core_manifest.py` (Schema v1.0). Declares canonical identity, routed domain, upstream source provenance (`source.url`, `source.ref`), environment defaults, Homepage card layout, and allowlisted GitOps deployment policy.
2. **Compose Configuration (`docker-compose.yml`)**: 2. **Compose Configuration (`docker-compose.yml`)**:
@@ -177,4 +177,4 @@ Workloads in `~/Sites/<app>` integrate with Core through three mechanisms:
# If auth is required: # If auth is required:
- "traefik.http.routers.${CONTAINER_NAME}.middlewares=authelia-auth@docker" - "traefik.http.routers.${CONTAINER_NAME}.middlewares=authelia-auth@docker"
``` ```
3. **Execution & State Isolation**: `appctl` and `gitops_dispatcher.py` validate the manifest and Compose AST (blocking privilege escalation and out-of-bounds mounts) before supplying runtime environment variables (`SERVICE_DOMAIN`, `CONTAINER_NAME`, and projected secrets). Persistent mutable workload data resides strictly under `~/var/lib/homelab/<app>/`. 3. **Execution & State Isolation**: `appctl` and `gitops_dispatcher.py` validate the manifest and Compose AST (blocking privilege escalation and out-of-bounds mounts unless explicitly authorized per workload in `homelab.workloadGrants`, projected to `/etc/homelab/grants.json` and read via `HOMELAB_GRANTS_FILE` per ADR-0005) before supplying runtime environment variables (`SERVICE_DOMAIN`, `CONTAINER_NAME`, and projected secrets). Persistent mutable workload data resides strictly under `~/var/lib/homelab/<app>/`.
@@ -0,0 +1,101 @@
---
type: decision
status: accepted
project: homelab-core
date: 2026-11-20
tags: [architecture, security, nixos, workloads, appctl, gitops]
amends: 0002-appctl-control-plane-architecture.md
---
# ADR 0005: Host-Granted Workload Capabilities ("Compose Requests, Nix Grants")
## Context and Problem Statement
Under [ADR-0001](0001-3tier-architecture-and-provenance.md), [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`), and [ADR-0004](0004-unified-workloads-monorepo.md), `validate_compose_security()` (shared pre-flight validator invoked authoritatively by `homelab-appctl.service` in `scripts/appctl_router.py` across CLI and GitOps paths) enforces a uniform deny-all policy on Tier 2 workload `docker-compose.yml` files:
* `devices:` mounts are blocked.
* Host bind mounts outside `~/Workloads/<app>` and `~/var/lib/homelab/<app>` are blocked.
* Host namespace sharing (`network_mode: host`, etc.) is blocked.
While this prevents a Tier 2 `git push` from escalating privileges on the host, it blocks required single-operator capability classes:
1. **Hardware-Accelerated & External-Storage Workloads**: Media transcoding or compute workloads requiring an integrated GPU (`/dev/dri/renderD128`) must mount host device nodes, pass a supplementary device group (such as `render` / GID `303`), and read an external read-only storage partition (`/media:ro`). Currently, `devices:` and external bind mounts are blocked, while `group_add:` and `user:` primary GIDs are unconstrained (risking arbitrary host GID elevation to groups such as `docker` or `wheel` unless constrained).
2. **LAN Broadcast / Peer-Discovery Services (Out of Scope for Host Networking)**: Workloads that send Wake-on-LAN magic packets or discover LAN peers cannot traverse Docker bridge L2 isolation, prompting requests for `network_mode: host`. Because blanket host networking collapses network namespace isolation—exposing loopback control services such as `homelab-appctl.service` on `127.0.0.1:9001`—host networking remains out of scope for workload grants and must be handled via isolated L2 Docker networks (`macvlan`/`ipvlan`) or host-side intermediaries.
3. **Host-Agnostic Core Boundary**: Hardcoding `/dev/dri`, `/media`, or specific workload names inside `nixos-core` violates platform portability and couples Core to one machine's hardware and app catalog.
The central architectural question is: **How should Canopy NixOS Core permit hardware devices, supplementary/primary GIDs, and external read-only storage paths for specific workloads without hardcoding personal infrastructure into `nixos-core` or weakening the Tier 2 -> Tier 3 trust boundary?**
## Decision Drivers
* **Preserve the Trust Split**: A push to Tier 2 (`canopy-workloads`) must never grant itself root-equivalent host access; capability grants must originate from root-level Tier 3 NixOS host configuration (`nixos-rebuild switch`).
* **Keep `nixos-core` Generic**: Core defines the capability schema and enforcement logic only, with zero hardcoded personal app names, device nodes, or media paths.
* **Keep `app.yaml` Free of Host Paths**: Workload manifests remain declarative routing/provenance metadata; `docker-compose.yml` already declares requested `devices`, `volumes`, `group_add`, and `user`.
* **Documented Instance Schema**: Provide a tracked `nixos/instance.example.nix` template so new hosts can configure `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants` in `/etc/nixos/homelab-instance.nix` (or gitignored `nixos/instance.nix`).
* **Fail-Closed Validation**: An absent grants file defaults to zero grants (current baseline); a present but unreadable, tampered, or malformed grants file fails closed across all workloads. `privileged: true`, `/var/run/docker.sock`, `cap_add`, `device_cgroup_rules:`, and host/container namespace sharing remain permanently prohibited.
## Considered Options
* **Option 1: Relax `validate_compose_security()` Globally**: Allow `/dev/dri` and arbitrary `:ro` paths for all workloads.
* **Option 2: Store Grants in `~/Workloads/grants.yaml`**: Allow `canopy-workloads` to declare its own exceptions alongside `deployments.yaml`.
* **Option 3: "Compose Requests, Nix Grants" via `homelab.workloadGrants` (Adopted)**: Define a typed `homelab.workloadGrants` option in `nixos-core` rendered to root-owned `/etc/homelab/grants.json`, validated with Pydantic v2 (`extra="forbid"`), and enforced by `validate_compose_security()`.
## Decision Outcome
Chosen option: **Option 3: "Compose Requests, Nix Grants" via `homelab.workloadGrants`**, because it keeps `nixos-core` hardware- and workload-agnostic while preserving the security boundary between Tier 2 Git pushes and Tier 3 `sudo nixos-rebuild switch`.
### Summary of Architectural Commitments
This ADR formally amends [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`) with the following commitments:
1. **Typed Host Grant Schema (`homelab.workloadGrants`)**:
* `nixos/modules/homeserver.nix` defines `homelab.workloadGrants` as an attribute set keyed by workload name, supporting three explicit grant fields:
* `devices` (list of exact device paths; prefer specific nodes such as `"/dev/dri/renderD128"` over whole directories unless display control is required).
* `groups` (list of supplementary/primary group names or GIDs permitted in `group_add` and `user:`, such as `"render"` or `"303"`; privileged host groups `0`/`root`, `wheel`, and `docker` are permanently rejected).
* `readOnlyPaths` (list of host directories permitted for read-only bind mounts only).
* `privileged: true`, `/var/run/docker.sock`, `cap_add`, `device_cgroup_rules:`, and namespace sharing (`network_mode: host`, `network_mode: container:*`, `network_mode: service:*`, `pid`, `ipc`, `uts`, `userns_mode: host`) remain permanently prohibited and are not grantable.
2. **Immutable Host Projection (`/etc/homelab/grants.json`)**:
* NixOS generates `/etc/homelab/grants.json` (`root`-owned, group-owned by `homelab-operators` with mode `0640`, granting read access to both `homelab-appctl` and `operator` without POSIX ACLs; overridable via `HOMELAB_GRANTS_FILE`, which is reserved in `RESERVED_ENV_KEYS` so workload `.env` / `app.yaml` cannot override it).
* In production, the loader verifies regular-file (non-symlink), root-owned, non-world/group-writable permissions before parsing.
* If `/etc/homelab/grants.json` is **absent**, `validate_compose_security()` defaults to zero grants. If it is **present** but unreadable, fails permission checks, or fails Pydantic v2 (`extra="forbid"`) validation, pre-flight fails closed for all workloads.
3. **Exact-Match Pre-Flight Enforcement**:
* `validate_compose_security()` evaluates resolved values (post-6-layer env assembly, or rejects uninterpolated `${...}` in `devices`, `volumes`, `group_add`, and `user`). When `app_name` is `None` or unknown, zero grants apply.
* Every capability requested in `<app>/docker-compose.yml` must match an explicit grant for `<app>`:
* `devices` entries support `host:container[:perms]`, forbid `m` (`mknod`) in permissions, and require the host path to exist and resolve canonically within the granted device node or directory, disallowing `..` traversal or symlink escapes.
* `group_add` transitions from unconstrained to **default-deny** when no `groups` grant exists; `groups` entries canonicalize bidirectionally between group names and integer GIDs via the host group database. `user:` primary GIDs must either fall within granted `groups` or be unprivileged numeric IDs that do not map to privileged or host-sensitive groups.
* `readOnlyPaths` validates both short (`host:container:ro[,opts]`) and long (`type: bind`, `read_only: true`) volume syntax, rejects unsafe bind propagation, and requires the host path to exist and resolve canonically within the granted directory.
4. **Tracked Instance Template (`nixos/instance.example.nix`)**:
* `nixos-core` tracks `nixos/instance.example.nix` documenting `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants`.
* Live hosts keep concrete values in `/etc/nixos/homelab-instance.nix` (loaded via `--impure` flake evaluation, taking precedence over gitignored `nixos/instance.nix` if both exist). Both paths remain optional so pure `nix flake check` CI passes with defaults.
## Pros and Cons of the Options
### Option 1: Relax `validate_compose_security()` Globally
* Good, because it requires minimal code.
* Bad, because it hardcodes host hardware assumptions into `nixos-core` and weakens tenant isolation for all workloads.
### Option 2: Store Grants in `~/Workloads/grants.yaml`
* Good, because grants live next to `deployments.yaml`.
* Bad, because Tier 2 would self-authorize Tier 3 host privileges on a single `git push`.
### Option 3: "Compose Requests, Nix Grants" via `homelab.workloadGrants` (Adopted)
* Good, because `nixos-core` stays generic, `canopy-workloads` remains free of host-privilege grants, and privilege elevation requires explicit host-level `nixos-rebuild switch`.
* Bad, because adding a new privileged capability requires editing `/etc/nixos/homelab-instance.nix` and rebuilding NixOS before `appctl up`.
## Consequences
### Positive Consequences
* **Hardware & Media Operability**: Workloads can use GPU acceleration and external `:ro` storage cleanly via standard `docker-compose.yml` syntax once authorized by the host.
* **Closed GID & Namespace Loopholes**: Transitions `group_add:`, `user:` primary GIDs, `device_cgroup_rules:`, and `network_mode: container:*` to fail-closed enforcement.
* **CI Compatibility**: Pure `nix flake check` evaluates cleanly with empty default grants.
### Negative Consequences & Accepted Trade-offs
* **Tier 2 / Tier 3 Deployment Ordering**: Pushing a Compose file requesting a new capability before running `nixos-rebuild switch` fails closed at pre-flight (surfaced clearly via a distinct capability-denial error/audit signal such as `ERR_CAPABILITY_NOT_GRANTED`).
* **Host Path Coupling**: Workload Compose files declare physical host paths matching host grants; logical capability aliasing via environment-variable injection remains an optional future refinement.
## More Information
* Amends [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`).
* Related specifications: [docs/architecture.md](../architecture.md), [docs/appctl.md](../appctl.md), [docs/secrets-and-state.md](../secrets-and-state.md).
+11 -1
View File
@@ -10,6 +10,7 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
| Decision Record | Status | Date | Scope & One-Line Purpose | | Decision Record | Status | Date | Scope & One-Line Purpose |
| :--- | :--- | :--- | :--- | | :--- | :--- | :--- | :--- |
| [**ADR-0005: Host-Granted Workload Capabilities**](0005-workload-capability-grants.md) | `accepted` | 2026-11-20 | Amends ADR-0002 to introduce `homelab.workloadGrants` (`/etc/homelab/grants.json`) and `nixos/instance.example.nix` so NixOS hosts explicitly authorize `devices`, `groups`, and `readOnlyPaths` per workload while keeping host/container networking prohibited. |
| [**ADR-0004: Unified ~/Workloads Monorepo & State Isolation**](0004-unified-workloads-monorepo.md) | `accepted` | 2026-11-16 | Amends ADR-0001 to adopt the unified `~/Workloads` Tier 2 monorepo (`canopy-workloads`), rename `~/Sites` to `~/Workloads` with `WORKLOADS_DIR` fallback, and enforce `~/var/lib/homelab/<app>/` state isolation. | | [**ADR-0004: Unified ~/Workloads Monorepo & State Isolation**](0004-unified-workloads-monorepo.md) | `accepted` | 2026-11-16 | Amends ADR-0001 to adopt the unified `~/Workloads` Tier 2 monorepo (`canopy-workloads`), rename `~/Sites` to `~/Workloads` with `WORKLOADS_DIR` fallback, and enforce `~/var/lib/homelab/<app>/` state isolation. |
| [**ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. | | [**ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. |
| [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and deterministic Git-backed declarative deployment state. | | [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and deterministic Git-backed declarative deployment state. |
@@ -19,6 +20,15 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
## 🧭 Summaries of Governing Decisions ## 🧭 Summaries of Governing Decisions
### [ADR-0005: Host-Granted Workload Capabilities ("Compose Requests, Nix Grants")](0005-workload-capability-grants.md)
* **Canonical Document**: [`0005-workload-capability-grants.md`](0005-workload-capability-grants.md)
* **Status**: `accepted` (Active — Amends ADR-0002)
* **Core Commitments**:
1. **Typed Host Grant Schema (`homelab.workloadGrants`)**: NixOS exposes per-workload `devices`, `groups`, and `readOnlyPaths` grants while keeping `privileged: true`, `docker.sock`, `cap_add`, `device_cgroup_rules`, and host/container namespace sharing permanently forbidden.
2. **Immutable Host Projection (`/etc/homelab/grants.json`)**: Projected root-owned at rebuild time; absent file defaults to zero grants, malformed file fails closed.
3. **Exact-Match Pre-Flight Enforcement**: `validate_compose_security()` allows requested capabilities only when canonically matched against the workload's Nix grant (and `:ro` for `readOnlyPaths`).
4. **Tracked Instance Template (`nixos/instance.example.nix`)**: Documents `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants` for `/etc/nixos/homelab-instance.nix`.
### [ADR-0004: Unified ~/Workloads Monorepo & State Isolation](0004-unified-workloads-monorepo.md) ### [ADR-0004: Unified ~/Workloads Monorepo & State Isolation](0004-unified-workloads-monorepo.md)
* **Canonical Document**: [`0004-unified-workloads-monorepo.md`](0004-unified-workloads-monorepo.md) * **Canonical Document**: [`0004-unified-workloads-monorepo.md`](0004-unified-workloads-monorepo.md)
* **Status**: `accepted` (Active — Amends ADR-0001) * **Status**: `accepted` (Active — Amends ADR-0001)
@@ -26,7 +36,7 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
1. **Tier 2 Rename (`~/Sites` -> `~/Workloads`)**: Canonical Tier 2 deployment root is `~/Workloads`, with `WORKLOADS_DIR` -> `SITES_DIR` environment fallback. 1. **Tier 2 Rename (`~/Sites` -> `~/Workloads`)**: Canonical Tier 2 deployment root is `~/Workloads`, with `WORKLOADS_DIR` -> `SITES_DIR` environment fallback.
2. **Unified `canopy-workloads` Monorepo**: Tier 2 workload manifests (`app.yaml`, `docker-compose.yml`) consolidate under `~/Workloads/<app>/`, supporting hybrid per-app `.git` checkouts during migration. 2. **Unified `canopy-workloads` Monorepo**: Tier 2 workload manifests (`app.yaml`, `docker-compose.yml`) consolidate under `~/Workloads/<app>/`, supporting hybrid per-app `.git` checkouts during migration.
3. **Mandatory State Isolation**: All mutable application data resides strictly under `~/var/lib/homelab/<app>/` (or named Docker volumes), never inside `~/Workloads`. 3. **Mandatory State Isolation**: All mutable application data resides strictly under `~/var/lib/homelab/<app>/` (or named Docker volumes), never inside `~/Workloads`.
4. **Core Registry & Safe Directory Containment**: `config/deployments.yaml` resolves admitted workloads within `WORKLOADS_DIR`; NixOS `safe.directory` includes `~/Workloads` and `~/Workloads/*`. 4. **Workloads Registry & Safe Directory Containment**: `~/Workloads/deployments.yaml` (templated by `config/deployments.yaml`) resolves admitted workloads within `WORKLOADS_DIR`; NixOS `safe.directory` includes `~/Workloads` and `~/Workloads/*`.
### [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md) ### [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md)
* **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md) * **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md)
+4 -4
View File
@@ -27,7 +27,7 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
▼ ▼
┌───────────────────────────────────────────────┐ ┌───────────────────────────────────────────────┐
│ 3. Authoritative Registry Resolution │ │ 3. Authoritative Registry Resolution │
│ Maps names via Core/config/deployments.yaml│ │ Maps names via ~/Workloads/deployments.yaml│
│ Fails closed; zero dynamic discovery on host│ │ Fails closed; zero dynamic discovery on host│
└───────────────────────┬───────────────────────┘ └───────────────────────┬───────────────────────┘
│ │
@@ -74,7 +74,7 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
### C. Authoritative Repository Registry (`deployments.yaml`) ### C. Authoritative Repository Registry (`deployments.yaml`)
* Webhook payloads identify targets strictly by logical name (e.g. `docs`, `homelab-docs`), never by raw filesystem path. * Webhook payloads identify targets strictly by logical name (e.g. `docs`, `homelab-docs`), never by raw filesystem path.
* `Core/config/deployments.yaml` is the **sole admission authority** for GitOps workloads. * `~/Workloads/deployments.yaml` (configured via `HOMELAB_DEPLOYMENTS_FILE`, with `Core/config/deployments.yaml` serving as the example template) is the **sole admission authority** for GitOps workloads.
* **No Dynamic Discovery**: Scanning `~/Sites` dynamically is strictly prohibited. An unapproved directory created on disk cannot receive webhook deployment rights merely by providing an `app.yaml`. * **No Dynamic Discovery**: Scanning `~/Sites` dynamically is strictly prohibited. An unapproved directory created on disk cannot receive webhook deployment rights merely by providing an `app.yaml`.
* **Fail-Closed Guarantee**: If `deployments.yaml` is missing, unreadable, or malformed, the dispatcher fails closed and admits zero repositories. * **Fail-Closed Guarantee**: If `deployments.yaml` is missing, unreadable, or malformed, the dispatcher fails closed and admits zero repositories.
* **Input Validation**: Names must match `^[a-zA-Z0-9][a-zA-Z0-9._-]*$`. Slashes, backslashes, and path traversal sequences (`..`) are rejected. * **Input Validation**: Names must match `^[a-zA-Z0-9][a-zA-Z0-9._-]*$`. Slashes, backslashes, and path traversal sequences (`..`) are rejected.
@@ -175,11 +175,11 @@ The continuous deployment engine operates strictly **downstream** of CI verifica
``` ```
[Developer / PR] ──► [Gitea Actions CI] ──► [Merge to main] ──► [Gitea Webhook] ──► [homelab-gitops] ──► [Deploy] [Developer / PR] ──► [Gitea Actions CI] ──► [Merge to main] ──► [Gitea Webhook] ──► [homelab-gitops] ──► [Deploy]
(Ephemeral Container) (Host Daemon) (:host act_runner) (Host Daemon)
``` ```
1. **Pre-Merge CI Invariant (`.gitea/workflows/ci.yaml`)**: 1. **Pre-Merge CI Invariant (`.gitea/workflows/ci.yaml`)**:
- Executes inside containerized `act_runner` environments using **pre-baked toolchain images** (`container: nixery.dev/shell/coreutils/git/nix/nodejs:latest`). - Executes directly on `:host` `act_runner` instances (`ubuntu-latest:host` / `nix:host`) with a **pre-baked host toolchain** (`nix`, `node`, `git`, `coreutils`), without spawning nested `container:` jobs.
- Runs hermetic validation (`nix flake check`, `pytest`, `ruff`) with Git safe directory enforcement. - Runs hermetic validation (`nix flake check`, `pytest`, `ruff`) with Git safe directory enforcement.
- Prevents broken code, misconfigured flakes, or regression bugs from entering `main`. - Prevents broken code, misconfigured flakes, or regression bugs from entering `main`.
2. **Post-Merge CD Execution (`homelab-gitops.service`)**: 2. **Post-Merge CD Execution (`homelab-gitops.service`)**:
+55 -7
View File
@@ -109,7 +109,7 @@ tail -n 20 /var/lib/dynu/ip_history.jsonl
## 3. Workload Lifecycle Operations (`appctl`) ## 3. Workload Lifecycle Operations (`appctl`)
Applications in `~/Sites` are managed with the `appctl` CLI. Applications in `~/Workloads` are managed with the `appctl` CLI.
### Inspection & Status ### Inspection & Status
```bash ```bash
@@ -145,7 +145,7 @@ appctl restart docs
appctl restart traefik appctl restart traefik
appctl restart authelia appctl restart authelia
# Sequential stack update for independent Sites workloads (clean tree check -> git pull -> compose pull -> up -> sync) # Sequential stack update for independent Workloads (clean tree check -> git pull -> compose pull -> up -> sync)
appctl update docs appctl update docs
# Stream live container logs # Stream live container logs
@@ -158,17 +158,17 @@ appctl config docs
### Workload vs. Core Update Policy ### Workload vs. Core Update Policy
Homelab enforces a strict architectural boundary between independent application workloads (`~/Sites/<app>`) and Homelab Core (`~/Core`): Homelab enforces a strict architectural boundary between independent application workloads (`~/Workloads/<app>`) and Homelab Core (`~/Core`):
#### 1. Independent Sites Workloads (`~/Sites/<app>`) #### 1. Independent Workloads (`~/Workloads/<app>`)
- **Automated Lifecycle**: Workloads declare their lifecycle via `app.yaml` manifests and Compose definitions. - **Automated Lifecycle**: Workloads declare their lifecycle via `app.yaml` manifests and Compose definitions.
- **Update Command**: `appctl update <workload>` performs pre-flight verification, branch matching, `git pull --ff-only`, container image pull, stack reload, and dashboard synchronization. - **Update Command**: `appctl update <workload>` performs pre-flight verification, branch matching, `git pull --ff-only`, container image pull, stack reload, and dashboard synchronization.
- **GitOps Webhook Dispatch**: Workloads registered in `config/deployments.yaml` can be triggered automatically via authenticated GitOps webhooks on Gitea push events. - **GitOps Webhook Dispatch**: Workloads registered in `~/Workloads/deployments.yaml` (with `config/deployments.yaml` as the example template) can be triggered automatically via authenticated GitOps webhooks on Gitea push events.
- **Daemon Permissions**: `homelab-appctl.service` holds read-write permissions over `~/Sites` to manage files, compose configurations, and workload state. - **Daemon Permissions**: `homelab-appctl.service` holds read-write permissions over `~/Workloads` to manage files, compose configurations, and workload state.
#### 2. Homelab Core Platform Stack (`~/Core`) #### 2. Homelab Core Platform Stack (`~/Core`)
- **Host Foundation & Invariant Boundary**: Core defines NixOS host definitions, platform secrets, edge ingress, and security sandboxes. - **Host Foundation & Invariant Boundary**: Core defines NixOS host definitions, platform secrets, edge ingress, and security sandboxes.
- **No Untrusted Webhooks**: Core does **not** register for webhook dispatch in `config/deployments.yaml`. External push events can never trigger an automated deployment or rebuild of Core. - **No Untrusted Webhooks**: Core does **not** register for webhook dispatch in `~/Workloads/deployments.yaml`. External push events can never trigger an automated deployment or rebuild of Core.
- **Read-Only Sandbox**: Under NixOS systemd sandboxing (`ProtectHome = "read-only"`), `homelab-appctl.service` has strictly read-only access to `/home/operator/Core`. The daemon cannot mutate the Core Git repository or run `git pull` on Core. - **Read-Only Sandbox**: Under NixOS systemd sandboxing (`ProtectHome = "read-only"`), `homelab-appctl.service` has strictly read-only access to `/home/operator/Core`. The daemon cannot mutate the Core Git repository or run `git pull` on Core.
- **Operator-Driven Update Workflow**: Core updates must be executed explicitly by the operator: - **Operator-Driven Update Workflow**: Core updates must be executed explicitly by the operator:
1. Review and pull repository changes: 1. Review and pull repository changes:
@@ -587,3 +587,51 @@ If unexpected service degradation occurs during the cutover:
3. **Log rollback reason**: 3. **Log rollback reason**:
Record the diagnostic failure logs in `journalctl -xe` and investigate before attempting another cutover window. Record the diagnostic failure logs in `journalctl -xe` and investigate before attempting another cutover window.
---
## 8. Read-Only Agent Inspection (`agents` SSH Identity)
For automated troubleshooting and agentic workflows, use the dedicated `agents` SSH user instead of the `operator` account.
### Workstation Setup
1. Generate a dedicated Ed25519 keypair on the workstation (if not already provisioned during setup):
```bash
ssh-keygen -t ed25519 -f ~/.ssh/canopy_agents -C "canopy-agents"
```
2. Register the `.pub` key in `users.users.agents.openssh.authorizedKeys.keys` (`nixos/configuration.nix`) and rebuild NixOS.
3. Add a host entry to `~/.ssh/config` (using your server hostname or `server.example.test`):
```sshconfig
Host server-agents
HostName <server-host>
User agents
IdentityFile ~/.ssh/canopy_agents
IdentitiesOnly yes
```
### Safe Read-Only Usage Examples
Commands are passed non-interactively over SSH and validated by the `ForceCommand` wrapper:
```bash
# Container status and logs (via read-only socket-proxy)
ssh server-agents "docker ps"
ssh server-agents "docker logs --tail 50 <container>"
ssh server-agents "docker inspect <container>"
# Platform & workload status
ssh server-agents "appctl list --core"
ssh server-agents "appctl status"
ssh server-agents "appctl info <app>"
# Systemd service logs
ssh server-agents "journalctl -u homelab-appctl -n 5"
```
### Security Boundaries & Allowlist
The `agents` account is constrained at both the OS and OpenSSH layers (`nixos/configuration.nix` and `nixos/scripts/agents-force-command.sh`):
- **Allowlisted commands only (`Match User agents` `ForceCommand`)**:
- `docker`: `ps`, `logs`, `inspect` only (routed to `DOCKER_HOST=tcp://127.0.0.1:2375`; `-H`, `--host`, `--context`, `-c`, and `--config` overrides are rejected).
- `appctl`: `list`, `status`, `info`, `logs`, `ssl`, `health`, `resolve` only.
- `journalctl`: read-only queries only (mutating flags such as `--flush`, `--rotate`, `--vacuum-*`, `--relinquish-var`, `--sync`, `--setup-keys`, and `--update-catalog` are rejected).
- Empty commands, control characters, and shell metacharacters (`;`, `&`, `|`, `` ` ``, `$`, `(`, `)`, `<`, `>`, `\`, `'`, `"`) are rejected.
- **No privilege escalation or interactive shell**: `agents` is not in `wheel` or `docker`, has no `sudo` access, and OpenSSH enforces `PermitTTY no`, `PasswordAuthentication no`, `AllowTcpForwarding no`, `X11Forwarding no`, and `AllowAgentForwarding no`.
- **No host state write access**: `agents` has no write permissions to `~/Core`, `~/Workloads`, or `~/var/lib/homelab/*`.
+28
View File
@@ -113,6 +113,34 @@ docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
2. Authenticate using `admin` and the password configured in `nixos/secrets.yaml` (`lldap/admin_password`). 2. Authenticate using `admin` and the password configured in `nixos/secrets.yaml` (`lldap/admin_password`).
3. Create standard user accounts and assign them to required groups. 3. Create standard user accounts and assign them to required groups.
### Step 8: Provision Read-Only Agent SSH Access (`agents`)
The `agents` user provides a restricted, read-only SSH identity for automated or agentic diagnostics without granting `sudo`, `docker` group membership, or write access to host state.
1. **Generate a dedicated Ed25519 SSH keypair** on your workstation:
```bash
ssh-keygen -t ed25519 -f ~/.ssh/canopy_agents -C "canopy-agents"
```
2. **Wire the public key into NixOS**:
Add the contents of `~/.ssh/canopy_agents.pub` to `users.users.agents.openssh.authorizedKeys.keys` in `nixos/configuration.nix` and apply the configuration on the server:
```bash
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
```
`nixos/configuration.nix` assigns `agents` only to `homelab-operators` (for read-only `appctl` socket queries) and `systemd-journal` (for `journalctl`), and enforces `Match User agents` with `ForceCommand` (`nixos/scripts/agents-force-command.sh`), `PermitTTY no`, `PasswordAuthentication no`, and forwarding disabled.
3. **Configure workstation `~/.ssh/config`** (replace `<server-host>` with your host or `server.example.test`):
```sshconfig
Host server-agents
HostName <server-host>
User agents
IdentityFile ~/.ssh/canopy_agents
IdentitiesOnly yes
```
4. **Verify read-only inspection** from the workstation:
```bash
ssh server-agents "docker ps"
ssh server-agents "appctl list --core"
ssh server-agents "journalctl -u homelab-appctl -n 5"
```
--- ---
## 3. Onboarding a New Application Workload ## 3. Onboarding a New Application Workload
Generated
+7 -7
View File
@@ -2,11 +2,11 @@
"nodes": { "nodes": {
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1792773339, "lastModified": 1795234589,
"narHash": "sha256-17eNBI5Khe4JZaRkL5hRGPWf8MZ6qv+bWAr4V8YeKBw=", "narHash": "sha256-pAEASBc6wof0S58XcSEdZoQ2iFQDkCnZwH+wFLrkd1Q=",
"rev": "3ec636362e1816bc2f0888fa0fa2c69f1bc9e504", "rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f",
"type": "tarball", "type": "tarball",
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1100280.3ec636362e18/nixexprs.tar.zst" "url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1125864.2786a2a72088/nixexprs.tar.zst"
}, },
"original": { "original": {
"type": "tarball", "type": "tarball",
@@ -26,11 +26,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1792056300, "lastModified": 1794866654,
"narHash": "sha256-YU1LjDe1o2Ymg5zEiCHbmMXLkDCtxHQRiVqZ3nC5GGk=", "narHash": "sha256-Y28AMB8lyKjASdJ0BVsR2AqR1cUsVuo8RVVpzHoECho=",
"owner": "Mic92", "owner": "Mic92",
"repo": "sops-nix", "repo": "sops-nix",
"rev": "44931708c62937c2b1bf7953902989fa5bb9ee1b", "rev": "7c637afdccdf9bcf35c4a2d67b58a77c1fd843a4",
"type": "github" "type": "github"
}, },
"original": { "original": {
+32 -4
View File
@@ -12,8 +12,8 @@
./modules/traefik-deployments.nix # Traefik deployment secrets and env templates ./modules/traefik-deployments.nix # Traefik deployment secrets and env templates
./modules/dynu.nix # Dynu DDNS smart IP monitor service ./modules/dynu.nix # Dynu DDNS smart IP monitor service
./modules/shell.nix # Declarative bash environment for the server ./modules/shell.nix # Declarative bash environment for the server
] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix ] ++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix
++ 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 platform settings ────────────────────────────────────────────────
homelab.operatorUser = "operator"; homelab.operatorUser = "operator";
@@ -68,7 +68,7 @@
networking.hostName = "server"; networking.hostName = "server";
networking.networkmanager.enable = true; networking.networkmanager.enable = true;
# ── User account ───────────────────────────────────────────────────────────── # ── User accounts ────────────────────────────────────────────────────────────
users.users.${config.homelab.operatorUser} = { users.users.${config.homelab.operatorUser} = {
isNormalUser = true; isNormalUser = true;
description = "Primary server administrator"; description = "Primary server administrator";
@@ -83,11 +83,39 @@
]; ];
}; };
users.users.agents = {
isNormalUser = true;
description = "Read-only agent inspection user";
openssh.authorizedKeys.keys = [
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIE1pxTdygG5696q0jT7clfJZWtx48ugfUjpzvkHzovVd canopy-agents"
];
extraGroups = [
"homelab-operators" # read-only access via /run/homelab/appctl.sock
"systemd-journal" # read-only access to journalctl
];
};
# ── SSH ────────────────────────────────────────────────────────────────────── # ── SSH ──────────────────────────────────────────────────────────────────────
services.openssh = { services.openssh = let
agentsForceCommand = pkgs.writeShellScriptBin "agents-force-command" ''
export CORE_DIR="''${CORE_DIR:-/home/${config.homelab.operatorUser}/Core}"
export WORKLOADS_DIR="''${WORKLOADS_DIR:-/home/${config.homelab.operatorUser}/Workloads}"
export DOCKER_HOST="''${DOCKER_HOST:-tcp://127.0.0.1:2375}"
exec ${pkgs.bash}/bin/bash ${./scripts/agents-force-command.sh} "$@"
'';
in {
enable = true; enable = true;
ports = [ 22 ]; ports = [ 22 ];
settings.PermitRootLogin = "no"; settings.PermitRootLogin = "no";
extraConfig = ''
Match User agents
ForceCommand ${agentsForceCommand}/bin/agents-force-command
AllowTcpForwarding no
X11Forwarding no
AllowAgentForwarding no
PermitTTY no
PasswordAuthentication no
'';
}; };
# ── Virtualisation ─────────────────────────────────────────────────────────── # ── Virtualisation ───────────────────────────────────────────────────────────
+20
View File
@@ -0,0 +1,20 @@
# Example host-local instance configuration for Canopy NixOS Core.
# Copy to /etc/nixos/homelab-instance.nix (recommended, loaded with --impure)
# or gitignored nixos/instance.nix, and customize for your host.
{ ... }:
{
homelab.domain = "example.com";
homelab.operatorUser = "operator";
# Host-granted workload capabilities ("Compose Requests, Nix Grants" — ADR-0005).
# Keyed by workload name matching ~/Workloads/<app>.
homelab.workloadGrants = {
# Example hardware-accelerated media workload:
# media-server = {
# devices = [ "/dev/dri/renderD128" ];
# groups = [ "render" ];
# readOnlyPaths = [ "/mnt/media" ];
# };
};
}
+72 -3
View File
@@ -26,12 +26,69 @@
default = "/home/${config.homelab.operatorUser}/Workloads"; default = "/home/${config.homelab.operatorUser}/Workloads";
description = "Path to Workloads directory (legacy option name: sitesDir)"; 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 config = let
domainParts = lib.splitString "." config.homelab.domain; domainParts = lib.splitString "." config.homelab.domain;
ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts); ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts);
in { in {
# ── Workload Capability Grant Invariants (ADR-0005) ─────────────────────────
assertions = let
grantsList = lib.mapAttrsToList (app: grant: { inherit app grant; }) config.homelab.workloadGrants;
privilegedGroups = [ "0" "root" "wheel" "docker" ];
hasInvalidPath = p:
!(lib.hasPrefix "/" p)
|| (lib.hasInfix "/../" p)
|| (lib.hasSuffix "/.." p)
|| (p == "..");
in
(map ({ app, grant }: {
assertion = lib.all (g: !(lib.elem (lib.toLower (lib.strings.trim g)) privilegedGroups)) grant.groups;
message = "homelab.workloadGrants.${app}.groups must not contain privileged groups (0, root, wheel, docker).";
}) grantsList)
++ (map ({ app, grant }: {
assertion = lib.all (p: !(hasInvalidPath p)) grant.devices;
message = "homelab.workloadGrants.${app}.devices must contain absolute paths without '..' traversal.";
}) grantsList)
++ (map ({ app, grant }: {
assertion = lib.all (p: !(hasInvalidPath p)) grant.readOnlyPaths;
message = "homelab.workloadGrants.${app}.readOnlyPaths must contain absolute paths without '..' traversal.";
}) grantsList);
# ── Host Capability Grants Projection (/etc/homelab/grants.json) ─────────────
environment.etc."homelab/grants.json" = {
user = "root";
group = "homelab-operators";
mode = "0640";
text = builtins.toJSON {
schemaVersion = "1.0";
workloads = config.homelab.workloadGrants;
};
};
# ── Host Activation Guard ──────────────────────────────────────────────────── # ── Host Activation Guard ────────────────────────────────────────────────────
# Prevents activating on a live host if homelab.domain defaulted to example.test (e.g. forgot --impure) # Prevents activating on a live host if homelab.domain defaulted to example.test (e.g. forgot --impure)
system.activationScripts.checkHomelabDomain = { system.activationScripts.checkHomelabDomain = {
@@ -44,9 +101,16 @@
fi fi
''; '';
}; };
# Re-apply home-dir traverse ACL after `users` activation (chmod 0700 resets POSIX ACL mask::---)
system.activationScripts.homelabHomeAcl = lib.stringAfter [ "users" ] ''
if [ -d "/home/${config.homelab.operatorUser}" ]; then
${pkgs.acl}/bin/setfacl -m u:homelab-appctl:x,g:homelab-operators:x,m::rx "/home/${config.homelab.operatorUser}"
fi
'';
# Define the keys to decrypt from secrets.yaml # Define the keys to decrypt from secrets.yaml
sops.secrets = (lib.genAttrs [ sops.secrets = (lib.genAttrs [
"dynu/api_key" "cloudflare/dns_api_token"
"traefik/acme_email" "traefik/acme_email"
"authelia/session_secret" "authelia/session_secret"
"authelia/storage_encryption_key" "authelia/storage_encryption_key"
@@ -81,7 +145,7 @@
DOMAIN = config.homelab.domain; DOMAIN = config.homelab.domain;
LLDAP_LDAP_BASE_DN = ldapBaseDn; LLDAP_LDAP_BASE_DN = ldapBaseDn;
DOCKER_API_VERSION = "1.40"; DOCKER_API_VERSION = "1.40";
DYNU_API_KEY = config.sops.placeholder."dynu/api_key"; CF_DNS_API_TOKEN = config.sops.placeholder."cloudflare/dns_api_token";
ACME_EMAIL = config.sops.placeholder."traefik/acme_email"; ACME_EMAIL = config.sops.placeholder."traefik/acme_email";
AUTHELIA_SESSION_SECRET = config.sops.placeholder."authelia/session_secret"; AUTHELIA_SESSION_SECRET = config.sops.placeholder."authelia/session_secret";
AUTHELIA_STORAGE_ENCRYPTION_KEY = config.sops.placeholder."authelia/storage_encryption_key"; AUTHELIA_STORAGE_ENCRYPTION_KEY = config.sops.placeholder."authelia/storage_encryption_key";
@@ -138,6 +202,8 @@
HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab"; HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab";
WORKLOADS_DIR = config.homelab.sitesDir; WORKLOADS_DIR = config.homelab.sitesDir;
SITES_DIR = config.homelab.sitesDir; SITES_DIR = config.homelab.sitesDir;
HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.sitesDir}/deployments.yaml";
HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";
}; };
serviceConfig = { serviceConfig = {
@@ -217,7 +283,8 @@
CORE_DIR = config.homelab.coreDir; CORE_DIR = config.homelab.coreDir;
HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab"; HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab";
HOMELAB_CONFIG_DIR = "/home/${config.homelab.operatorUser}/.config/homelab"; HOMELAB_CONFIG_DIR = "/home/${config.homelab.operatorUser}/.config/homelab";
HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.coreDir}/config/deployments.yaml"; HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.sitesDir}/deployments.yaml";
HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";
}; };
serviceConfig = { serviceConfig = {
@@ -259,6 +326,8 @@
"d ${config.homelab.coreDir}/config/stalwart/data 0777 ${config.homelab.operatorUser} users -" "d ${config.homelab.coreDir}/config/stalwart/data 0777 ${config.homelab.operatorUser} users -"
"d ${config.homelab.coreDir}/config/stalwart/etc 0777 ${config.homelab.operatorUser} users -" "d ${config.homelab.coreDir}/config/stalwart/etc 0777 ${config.homelab.operatorUser} users -"
"d ${config.homelab.sitesDir} 0755 ${config.homelab.operatorUser} users -" "d ${config.homelab.sitesDir} 0755 ${config.homelab.operatorUser} users -"
"a+ ${config.homelab.coreDir}/config/authelia - - - - d:u:1000:rwX,u:1000:rwx,m::rwx"
"a+ ${config.homelab.coreDir}/config/authelia/db.sqlite3 - - - - u:1000:rw,m::rw"
"a+ ${config.homelab.coreDir}/config/authelia/emails.txt - - - - u:1000:rw,m::rw" "a+ ${config.homelab.coreDir}/config/authelia/emails.txt - - - - u:1000:rw,m::rw"
"d /home/${config.homelab.operatorUser}/.local/state/homelab/gitops 0755 ${config.homelab.operatorUser} users -" "d /home/${config.homelab.operatorUser}/.local/state/homelab/gitops 0755 ${config.homelab.operatorUser} users -"
"d /home/${config.homelab.operatorUser}/.local/state/homelab/docker 0755 ${config.homelab.operatorUser} users -" "d /home/${config.homelab.operatorUser}/.local/state/homelab/docker 0755 ${config.homelab.operatorUser} users -"
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env bash
# Read-only ForceCommand allowlist wrapper for the `agents` SSH user.
set -euo pipefail
export CORE_DIR="${CORE_DIR:-/home/operator/Core}"
export WORKLOADS_DIR="${WORKLOADS_DIR:-/home/operator/Workloads}"
export DOCKER_HOST="${DOCKER_HOST:-tcp://127.0.0.1:2375}"
raw_cmd="${SSH_ORIGINAL_COMMAND:-}"
if [[ -z "${raw_cmd// }" ]]; then
echo "Error: empty SSH_ORIGINAL_COMMAND is not permitted" >&2
exit 1
fi
if [[ "$raw_cmd" == *$'\n'* || "$raw_cmd" == *$'\r'* ]]; then
echo "Error: control characters are not permitted" >&2
exit 1
fi
if [[ "$raw_cmd" == *[';&|`$()<>\\'\''"']* ]]; then
echo "Error: shell metacharacters are not permitted" >&2
exit 1
fi
# Word-split without globbing or shell evaluation
set -f
read -r -a args <<< "$raw_cmd"
set +f
if [[ ${#args[@]} -eq 0 ]]; then
echo "Error: empty SSH_ORIGINAL_COMMAND is not permitted" >&2
exit 1
fi
cmd="${args[0]}"
case "$cmd" in
docker)
if [[ ${#args[@]} -lt 2 ]]; then
echo "Error: docker subcommand is required" >&2
exit 1
fi
subcmd="${args[1]}"
case "$subcmd" in
ps|logs|inspect) ;;
*)
echo "Error: docker subcommand '$subcmd' is not permitted" >&2
exit 1
;;
esac
for arg in "${args[@]:2}"; do
case "$arg" in
-H|-H=*|--host|--host=*|--context|--context=*|-c|-c=*|--config|--config=*)
echo "Error: docker connection override flag '$arg' is not permitted" >&2
exit 1
;;
esac
done
exec docker "${args[@]:1}"
;;
journalctl)
for arg in "${args[@]:1}"; do
case "$arg" in
--flush|--rotate|--vacuum-*|--relinquish-var|--sync|--setup-keys|--update-catalog)
echo "Error: mutating journalctl flag '$arg' is not permitted" >&2
exit 1
;;
esac
done
exec journalctl "${args[@]:1}"
;;
appctl)
if [[ ${#args[@]} -lt 2 ]]; then
echo "Error: appctl subcommand is required" >&2
exit 1
fi
subcmd="${args[1]}"
case "$subcmd" in
list|status|info|logs|ssl|health|resolve) ;;
*)
echo "Error: appctl subcommand '$subcmd' is not permitted" >&2
exit 1
;;
esac
exec appctl "${args[@]:1}"
;;
*)
echo "Error: command '$cmd' is not permitted" >&2
exit 1
;;
esac
+7 -2
View File
@@ -38,6 +38,11 @@ lldap:
brevo: brevo:
smtp_login: ENC[AES256_GCM,data:zfqKsAtoAOWCrSqx38sknwcJZT2m8W2J,iv:tMwTNDf+2CE3/8rKqWTWLl5Zp4LUVNSFV90QN94VXxo=,tag:XYXz9w3oIa0qkcfjCcgcYg==,type:str] smtp_login: ENC[AES256_GCM,data:zfqKsAtoAOWCrSqx38sknwcJZT2m8W2J,iv:tMwTNDf+2CE3/8rKqWTWLl5Zp4LUVNSFV90QN94VXxo=,tag:XYXz9w3oIa0qkcfjCcgcYg==,type:str]
smtp_key: ENC[AES256_GCM,data:YulXyaVF/sLWE9x12yxdBAj9KMbfP/CK/7FS3XkYO8sCj3GWgPbNoSaUT/9quLWHPtCsBxxdLeLoDNa1jE2WRyHP1W+Ioyyx5sAzdzevzHIBmfP+fdw0rKhe,iv:QT0HfzNPsTqXlN3IC/+bBzJfUzN9YkXYiv/3uqkXHBw=,tag:vBetkZPDYoh0Yy3BpMT9BQ==,type:str] smtp_key: ENC[AES256_GCM,data:YulXyaVF/sLWE9x12yxdBAj9KMbfP/CK/7FS3XkYO8sCj3GWgPbNoSaUT/9quLWHPtCsBxxdLeLoDNa1jE2WRyHP1W+Ioyyx5sAzdzevzHIBmfP+fdw0rKhe,iv:QT0HfzNPsTqXlN3IC/+bBzJfUzN9YkXYiv/3uqkXHBw=,tag:vBetkZPDYoh0Yy3BpMT9BQ==,type:str]
cloudflare:
account_name: ENC[AES256_GCM,data:fIuzvJbLoz/w,iv:tT3rCldA9hqHzKjJa4gENTk/XprzS5X6Wm/rqkb6jow=,tag:p0aEezfUFlJn25PdW/DAOA==,type:str]
global_api_key: ENC[AES256_GCM,data:IDFHetxM2LE1/cytHo2Jn16piLeIvM27ui3Qld4Z5hwWauDRaY05nZH6+V6ic9dYFfagvA==,iv:9q3cosnJ+eC1BLmQ1Hx1y3Dksyc5k4UMQPZ6Or9vWFE=,tag:k/RilX02EJzMWZcfzBtu4A==,type:str]
account_id: ENC[AES256_GCM,data:/IyUXySFGQSGs16Kv6yZajMiGTxwOuxILvcFZ/6YROo=,iv:TdMwtzs/LMnbhpsEbqunj4n+P+JxcscYGKaM42fYQ20=,tag:HHmIq03Jc4g8fBvuaWevAA==,type:str]
dns_api_token: ENC[AES256_GCM,data:lTByYg0BM+mloaHDb2WkN7LY9twnVzKn6NO8W1rTH5FXyWaNlEovLxCPT2sG+JuRfqGJ52w=,iv:nBX3rUSdf1wFSTz0sY/ApNKVaYkCPJAJPhmMu+abzhE=,tag:LK8qyYap/T1HZb+jWnHyuA==,type:str]
appctl: appctl:
tokens_json: ENC[AES256_GCM,data:O2vsiMMcZjsduFSRen1MnnckdRYK45aPH40EhX42h1WUwf62Nm58PV5BQJOgJ97AH3hOH97mzg1tjL0C1oV/epXMaypRWY9AGLS00CfzD2sgdM5Wx7VKbfGggFnGqgd7veaCA+pxUC0uTk/Dq2Cz/uhXhLX1wVjafX0OAqS6fxO+L9Oza3+RBtKgx2xX0AKW+KSZQUM1nvNW8R/Eyvnqvw2OSb2FdKN1CKhlVWhCZiaxTe8617BqGhJDL9pu4lfn0m+tdIwvluI3h8cmKuT6dzd01Jxr0EHBY/+mZZ/WQoNhIy4QulFpKiMudiT+WGzUm+UT4mYBoGwzQCVV8MD7W1r84mkbCkLc/HpWG08TqK4tpAdtLgYK3Zslr1+lmboWyJ6WcinmxkhUexhj+gTyfXYmVSB3fF8PIeyQINGB3rLvmpZ7DDMzYa1ICgFbJ6zmYa54TXRDLGzLD09koeDp9FhXNKPvuwz2x4uwWDDUfU8wwTkGbw==,iv:FJpB+WZiE4PKUhIuwBWIB/TLtifwCzGRMtbMx7x6ly8=,tag:NZQXYFnVBqbOONl+Yh3tuA==,type:str] tokens_json: ENC[AES256_GCM,data:O2vsiMMcZjsduFSRen1MnnckdRYK45aPH40EhX42h1WUwf62Nm58PV5BQJOgJ97AH3hOH97mzg1tjL0C1oV/epXMaypRWY9AGLS00CfzD2sgdM5Wx7VKbfGggFnGqgd7veaCA+pxUC0uTk/Dq2Cz/uhXhLX1wVjafX0OAqS6fxO+L9Oza3+RBtKgx2xX0AKW+KSZQUM1nvNW8R/Eyvnqvw2OSb2FdKN1CKhlVWhCZiaxTe8617BqGhJDL9pu4lfn0m+tdIwvluI3h8cmKuT6dzd01Jxr0EHBY/+mZZ/WQoNhIy4QulFpKiMudiT+WGzUm+UT4mYBoGwzQCVV8MD7W1r84mkbCkLc/HpWG08TqK4tpAdtLgYK3Zslr1+lmboWyJ6WcinmxkhUexhj+gTyfXYmVSB3fF8PIeyQINGB3rLvmpZ7DDMzYa1ICgFbJ6zmYa54TXRDLGzLD09koeDp9FhXNKPvuwz2x4uwWDDUfU8wwTkGbw==,iv:FJpB+WZiE4PKUhIuwBWIB/TLtifwCzGRMtbMx7x6ly8=,tag:NZQXYFnVBqbOONl+Yh3tuA==,type:str]
sops: sops:
@@ -60,7 +65,7 @@ sops:
yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A== yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A==
-----END AGE ENCRYPTED FILE----- -----END AGE ENCRYPTED FILE-----
recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg
lastmodified: "2026-10-19T20:40:13Z" lastmodified: "2026-11-23T20:45:18Z"
mac: ENC[AES256_GCM,data:rui8qF/l3ucq8vrZniHtGjlLGPq7ihteKK7rcaz2prRvmo7nHd97Axt7oElo050HFuoaJB1/coVPzYcAUozjZNsNx3TQYABGFWvxF5Y0SxjdLc1rqAjGR/j2Cf5wmvF9H457KBHfij2gQHY/ZZ2Nyd9aEpAKSFtKkn3aYkmTvW4=,iv:RdQWUpkahFEYEhd9kTpPG0GMJaHr7b+wbhf5MBhk6mo=,tag:1E3mcFk/EMnJNNxuZ6AXAw==,type:str] mac: ENC[AES256_GCM,data:3Rm8olJtCErH+KGisvQENqwFhMF3Y9acXjrBHC7ot3ThRzT8Yo3X1RyxKXzyYzB6Yy2G3ua9yUtgQjydXgjQR1b6KY6ERmyu6H2S1IF/Ps4grYVZ6xEhJMDtjNKDvhtjhRM61eFByeYzJeHWD6K8dsxDcWUI2GKRRH7U8iG95Fo=,iv:/IY6iKamEEoi5vVLRGOmmPpyJte3amLfjVhYIDbMdBE=,tag:gT3RSrnwl0TH14LJvbiPlg==,type:str]
unencrypted_suffix: _unencrypted unencrypted_suffix: _unencrypted
version: 3.13.3 version: 3.13.3
+15 -5
View File
@@ -6,7 +6,7 @@ Implements the zero-trust authorization pipeline for homelab-appctl.service:
- Unix domain socket SO_PEERCRED fallback to homelab-viewer for zero-friction local reads - Unix domain socket SO_PEERCRED fallback to homelab-viewer for zero-friction local reads
- Mandatory Bearer tokens for all network (HTTP) operations and all mutations / sensitive reads - Mandatory Bearer tokens for all network (HTTP) operations and all mutations / sensitive reads
- 3-role RBAC enforcement (homelab-admin, homelab-operator, homelab-viewer) - 3-role RBAC enforcement (homelab-admin, homelab-operator, homelab-viewer)
- Workload scope gating against config/deployments.yaml for homelab-operator - Workload scope gating against ~/Workloads/deployments.yaml (or HOMELAB_DEPLOYMENTS_FILE / WORKLOADS_DIR override) for homelab-operator
""" """
from __future__ import annotations from __future__ import annotations
@@ -34,7 +34,12 @@ except ImportError:
DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json") DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json")
DEFAULT_DEPLOYMENTS_FILE = ( DEFAULT_DEPLOYMENTS_FILE = (
Path(__file__).resolve().parent.parent / "config" / "deployments.yaml" Path(
os.environ.get("WORKLOADS_DIR")
or os.environ.get("SITES_DIR")
or os.path.expanduser("~/Workloads")
)
/ "deployments.yaml"
) )
CORE_TARGETS: frozenset[str] = frozenset( CORE_TARGETS: frozenset[str] = frozenset(
@@ -222,13 +227,18 @@ class TokenStore:
def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[str]: def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[str]:
""" """
Load admitted repository names and aliases from config/deployments.yaml. Load admitted repository names and aliases from ~/Workloads/deployments.yaml
(or HOMELAB_DEPLOYMENTS_FILE / WORKLOADS_DIR override).
Fails closed (empty set) if registry is missing or malformed. Fails closed (empty set) if registry is missing or malformed.
""" """
if deployments_path is not None: if deployments_path is not None:
reg_file = Path(deployments_path) reg_file = Path(deployments_path)
elif "HOMELAB_DEPLOYMENTS_FILE" in os.environ: elif env_deploy := os.environ.get("HOMELAB_DEPLOYMENTS_FILE"):
reg_file = Path(os.environ["HOMELAB_DEPLOYMENTS_FILE"]) reg_file = Path(env_deploy)
elif env_workloads := (
os.environ.get("WORKLOADS_DIR") or os.environ.get("SITES_DIR")
):
reg_file = Path(env_workloads) / "deployments.yaml"
else: else:
reg_file = DEFAULT_DEPLOYMENTS_FILE reg_file = DEFAULT_DEPLOYMENTS_FILE
+3 -1
View File
@@ -116,11 +116,12 @@ FlexibleWorkloadAction = FlexibleOperationType
class ErrorCode(StrEnum): 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_VALIDATION_FAILED = "ERR_VALIDATION_FAILED"
ERR_AUTH_REQUIRED = "ERR_AUTH_REQUIRED" ERR_AUTH_REQUIRED = "ERR_AUTH_REQUIRED"
ERR_PERMISSION_DENIED = "ERR_PERMISSION_DENIED" ERR_PERMISSION_DENIED = "ERR_PERMISSION_DENIED"
ERR_CAPABILITY_NOT_GRANTED = "ERR_CAPABILITY_NOT_GRANTED"
ERR_TARGET_NOT_FOUND = "ERR_TARGET_NOT_FOUND" ERR_TARGET_NOT_FOUND = "ERR_TARGET_NOT_FOUND"
ERR_CONCURRENT_MUTATION = "ERR_CONCURRENT_MUTATION" ERR_CONCURRENT_MUTATION = "ERR_CONCURRENT_MUTATION"
ERR_EXECUTION_FAILED = "ERR_EXECUTION_FAILED" ERR_EXECUTION_FAILED = "ERR_EXECUTION_FAILED"
@@ -134,6 +135,7 @@ ERROR_HTTP_STATUS: dict[ErrorCode, int] = {
ErrorCode.ERR_VALIDATION_FAILED: 400, ErrorCode.ERR_VALIDATION_FAILED: 400,
ErrorCode.ERR_AUTH_REQUIRED: 401, ErrorCode.ERR_AUTH_REQUIRED: 401,
ErrorCode.ERR_PERMISSION_DENIED: 403, ErrorCode.ERR_PERMISSION_DENIED: 403,
ErrorCode.ERR_CAPABILITY_NOT_GRANTED: 403,
ErrorCode.ERR_TARGET_NOT_FOUND: 404, ErrorCode.ERR_TARGET_NOT_FOUND: 404,
ErrorCode.ERR_CONCURRENT_MUTATION: 409, ErrorCode.ERR_CONCURRENT_MUTATION: 409,
ErrorCode.ERR_EXECUTION_FAILED: 500, ErrorCode.ERR_EXECUTION_FAILED: 500,
+1 -1
View File
@@ -64,7 +64,7 @@ WORKLOADS_DIR = Path(
) )
SITES_DIR = WORKLOADS_DIR SITES_DIR = WORKLOADS_DIR
DEPLOYMENTS_FILE = Path( DEPLOYMENTS_FILE = Path(
os.environ.get("HOMELAB_DEPLOYMENTS_FILE", CORE_DIR / "config" / "deployments.yaml") os.environ.get("HOMELAB_DEPLOYMENTS_FILE") or (WORKLOADS_DIR / "deployments.yaml")
) )
DEFAULT_SOCKET_PATH = Path( DEFAULT_SOCKET_PATH = Path(
+26 -5
View File
@@ -85,12 +85,16 @@ MAX_OUTPUT_BYTES = 256 * 1024 # 256 KiB cap per invocation
class RouterValidationError(Exception): class RouterValidationError(Exception):
"""Raised when request payload or pre-flight validation fails (400 Bad Request).""" """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) super().__init__(message)
self.code = ErrorCode.ERR_VALIDATION_FAILED self.code = code
self.http_status = 400 self.http_status = code.http_status
class RouterExecutionError(Exception): class RouterExecutionError(Exception):
@@ -313,14 +317,31 @@ def validate_workload_preflight(
effective_name = app_name or manifest.name effective_name = app_name or manifest.name
compose_file = _resolve_compose_file(app_dir) compose_file = _resolve_compose_file(app_dir)
if compose_file.exists(): if compose_file.exists():
resolved_env = assemble_workload_env(app_dir, manifest, effective_name)
ok, reason = validate_compose_security( ok, reason = validate_compose_security(
compose_file=compose_file, compose_file=compose_file,
allowed_root=app_dir, allowed_root=app_dir,
app_name=effective_name, app_name=effective_name,
resolved_env=resolved_env,
) )
if not ok: if not ok:
is_cap_denial = bool(
reason
and reason.startswith(
(
"Capability not granted:",
"Capability grants integrity check failed:",
)
)
)
err_code = (
ErrorCode.ERR_CAPABILITY_NOT_GRANTED
if is_cap_denial
else ErrorCode.ERR_VALIDATION_FAILED
)
raise RouterValidationError( raise RouterValidationError(
f"Compose AST security validation failed for '{effective_name}': {reason}" f"Compose AST security validation failed for '{effective_name}': {reason}",
code=err_code,
) )
return manifest, compose_file return manifest, compose_file
+1
View File
@@ -81,6 +81,7 @@ RESERVED_ENV_KEYS = {
"SERVICE_NAME", "SERVICE_NAME",
"CONTAINER_NAME", "CONTAINER_NAME",
"SERVICE_DOMAIN", "SERVICE_DOMAIN",
"HOMELAB_GRANTS_FILE",
} }
ALLOWED_STRATEGIES = {"compose"} ALLOWED_STRATEGIES = {"compose"}
+527 -136
View File
@@ -10,6 +10,7 @@ deployment actions with zero Core restarts.
import contextlib import contextlib
import datetime import datetime
import fcntl import fcntl
import grp
import hashlib import hashlib
import hmac import hmac
import http.client import http.client
@@ -19,7 +20,8 @@ import os
import re import re
import subprocess import subprocess
import sys import sys
from pathlib import Path from collections.abc import Callable
from pathlib import Path, PurePosixPath
from typing import Any from typing import Any
from appctl_contracts import OperationRequest, OperationType from appctl_contracts import OperationRequest, OperationType
@@ -30,6 +32,12 @@ from core_manifest import (
parse_manifest, parse_manifest,
) )
from pydantic import ValidationError from pydantic import ValidationError
from workload_grants import (
PRIVILEGED_GROUPS,
WorkloadGrant,
WorkloadGrantsError,
load_workload_grants,
)
try: try:
import yaml import yaml
@@ -47,7 +55,7 @@ CONFIG_DIR = Path(
os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab")) os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab"))
) )
DEPLOYMENTS_FILE = Path( DEPLOYMENTS_FILE = Path(
os.environ.get("HOMELAB_DEPLOYMENTS_FILE", CORE_DIR / "config" / "deployments.yaml") os.environ.get("HOMELAB_DEPLOYMENTS_FILE") or (WORKLOADS_DIR / "deployments.yaml")
) )
DEFAULT_SECRET_PATH = Path( DEFAULT_SECRET_PATH = Path(
os.environ.get("GITOPS_SECRET_FILE", "/run/secrets/gitops/webhook_secret") os.environ.get("GITOPS_SECRET_FILE", "/run/secrets/gitops/webhook_secret")
@@ -260,16 +268,12 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
""" """
Build authoritative mapping of logical repository identities to local paths. Build authoritative mapping of logical repository identities to local paths.
Webhook payloads can only select repositories defined in this mapping. Webhook payloads can only select repositories defined in this mapping.
Core Authoritative Registry (deployments.yaml) is the sole admission authority. Workloads admission registry (~/Workloads/deployments.yaml, templated by config/deployments.yaml) is the sole admission authority.
Fails closed if the registry is missing, unreadable, or malformed. Fails closed if the registry is missing, unreadable, or malformed.
""" """
mapping: dict[str, Path] = {} mapping: dict[str, Path] = {}
registry_file = ( registry_file = DEPLOYMENTS_FILE
DEPLOYMENTS_FILE
if DEPLOYMENTS_FILE.is_file()
else (CONFIG_DIR / "deployments.yaml")
)
if not registry_file.is_file(): if not registry_file.is_file():
logger.error( logger.error(
f"Authoritative registry {registry_file} not found. Failing closed with zero admitted repositories." f"Authoritative registry {registry_file} not found. Failing closed with zero admitted repositories."
@@ -419,23 +423,477 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
PROHIBITED_HOST_NAMESPACES = {"host"} PROHIBITED_HOST_NAMESPACES = {"host"}
DANGEROUS_SECURITY_OPTS = {"unconfined", "apparmor:unconfined", "seccomp:unconfined"} 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]:
"""Enforce default-deny and host-granted group_add membership."""
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]:
"""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
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()
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}'.",
)
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 _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
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}'.",
)
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:
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}'.",
)
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"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
def validate_compose_security( def validate_compose_security(
compose_file: Path, compose_file: Path,
allowed_root: Path, allowed_root: Path,
app_name: str | None = None, 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]: ) -> tuple[bool, str | None]:
""" """
Pre-flight AST inspection of workload docker-compose.yml enforcing Core platform security invariants: 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). and host-granted workload capabilities (ADR-0005):
2. Privilege Containment: blocks 'privileged: true', 'cap_add', 'devices', and 'security_opt: unconfined'. 1. File Integrity & Parser: regular file, non-symlink (or strictly contained symlink); fails closed if PyYAML is unavailable.
3. Host Namespace Isolation: blocks 'pid: host', 'ipc: host', 'uts: host', 'userns_mode: host', 'network_mode: host'. 2. Privilege Containment: blocks 'privileged: true', 'cap_add', 'device_cgroup_rules', and 'security_opt: unconfined'.
4. Docker Socket Ban: blocks direct mounts of /var/run/docker.sock. 3. Host Namespace Isolation: blocks 'host', 'container:*', and 'service:*' across 'network_mode', 'pid', 'ipc', 'uts', 'userns_mode'.
5. Top-Level Inclusion Ban: blocks top-level 'include' directives. 4. Docker Socket & Include Bans: blocks direct mounts of /var/run/docker.sock and top-level 'include' directives.
6. Bind-Mount & Tenant State Isolation: resolves all relative and absolute host paths. Requires containment 5. Host-Granted Capabilities: enforces fail-closed workloadGrants for 'devices' (forbidding mknod 'm'), 'group_add',
strictly within either the workload root (allowed_root) OR the workload's dedicated state root 'user' primary GIDs, and external ':ro' 'volumes' ('readOnlyPaths', rejecting unsafe bind propagation).
(~/var/lib/homelab/<app_name>/). Cross-tenant state mounts are rejected fail-closed. 6. Bind-Mount & Tenant State Isolation: resolves all relative and absolute host paths within allowed_root or ~/var/lib/homelab/<app_name>/.
""" """
if not compose_file.exists(): if not compose_file.exists():
return True, None return True, None
@@ -458,48 +916,13 @@ def validate_compose_security(
except OSError as e: except OSError as e:
return False, f"Failed to read compose file {compose_file}: {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 None:
if yaml is not None: return False, "PyYAML is required for Compose security validation."
try: try:
data = yaml.safe_load(content) or {} data = yaml.safe_load(content) or {}
except yaml_errors as e: except yaml.YAMLError as e:
return False, f"Failed to parse compose YAML {compose_file}: {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 not isinstance(data, dict): if not isinstance(data, dict):
return False, f"Invalid compose root in {compose_file}: expected mapping" return False, f"Invalid compose root in {compose_file}: expected mapping"
@@ -514,6 +937,18 @@ def validate_compose_security(
if not isinstance(services, dict): if not isinstance(services, dict):
return True, None 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( state_root = Path(
os.environ.get("HOMELAB_STATE_ROOT", Path.home() / "var/lib/homelab") os.environ.get("HOMELAB_STATE_ROOT", Path.home() / "var/lib/homelab")
).resolve() ).resolve()
@@ -543,13 +978,28 @@ def validate_compose_security(
f"Service '{svc_name}' specifies prohibited 'cap_add' capabilities: {cap_add}.", f"Service '{svc_name}' specifies prohibited 'cap_add' capabilities: {cap_add}.",
) )
devices = svc.get("devices") if svc.get("device_cgroup_rules"):
if devices:
return ( return (
False, 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", []) sec_opts = svc.get("security_opt", [])
if isinstance(sec_opts, str): if isinstance(sec_opts, str):
sec_opts = [sec_opts] sec_opts = [sec_opts]
@@ -620,15 +1070,15 @@ def validate_compose_security(
if not clean_env: if not clean_env:
continue continue
if clean_env.startswith("~"): 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(): elif Path(clean_env).is_absolute():
resolved_env = Path(clean_env).resolve() env_file_resolved = Path(clean_env).resolve()
else: else:
resolved_env = (allowed_root / clean_env).resolve() env_file_resolved = (allowed_root / clean_env).resolve()
if not ( if not (
allowed_root.is_dir() allowed_root.is_dir()
and resolved_env.is_relative_to(canonical_allowed_root) and env_file_resolved.is_relative_to(canonical_allowed_root)
): ):
return ( return (
False, False,
@@ -637,85 +1087,26 @@ def validate_compose_security(
for ns_key in ("network_mode", "pid", "ipc", "uts", "userns_mode"): for ns_key in ("network_mode", "pid", "ipc", "uts", "userns_mode"):
val = str(svc.get(ns_key, "")).strip().lower() 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 ( return (
False, False,
f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'.", f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'.",
) )
volumes = svc.get("volumes", []) ok_vol, vol_err = _validate_service_volumes(
if isinstance(volumes, list): svc_name,
for vol in volumes: svc,
host_path = "" allowed_root,
if isinstance(vol, str): canonical_allowed_root,
if "/var/run/docker.sock" in vol: target_state_root,
return ( top_volumes,
False, grant,
f"Service '{svc_name}' directly mounts Docker socket: {vol}.", resolved_env,
)
if ":" in vol:
host_path = vol.split(":")[0].strip()
else:
host_path = vol.strip()
elif isinstance(vol, dict):
src = str(vol.get("source", ""))
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
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 not (is_in_workload or is_in_own_state):
return (
False,
f"Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'.",
) )
if not ok_vol:
return False, vol_err
return True, None return True, None
+149
View File
@@ -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
+53
View File
@@ -0,0 +1,53 @@
"""Shared pytest fixtures for Canopy NixOS Core test suites."""
from __future__ import annotations
import os
import subprocess
import sys
from pathlib import Path
from typing import Protocol
import pytest
_STRIPPED_WORKLOAD_ENV_VARS = frozenset(
{"HOMELAB_DEPLOYMENTS_FILE", "WORKLOADS_DIR", "SITES_DIR"}
)
_SCRIPTS_DIR = Path(__file__).resolve().parent.parent / "scripts"
class IsolatedScriptRunner(Protocol):
"""Callable protocol for executing a Python expression in an isolated env."""
def __call__(
self, expr: str, extra_env: dict[str, str] | None = None
) -> str: ...
@pytest.fixture
def run_isolated_script_expr(tmp_path: Path) -> IsolatedScriptRunner:
"""
Execute a Python expression in a clean subprocess with workload env vars stripped.
Strips ``HOMELAB_DEPLOYMENTS_FILE``, ``WORKLOADS_DIR``, and ``SITES_DIR``,
sets ``HOME`` to ``tmp_path`` and ``PYTHONPATH`` to ``scripts/``, and
merges any optional ``extra_env`` overrides.
"""
def _run(expr: str, extra_env: dict[str, str] | None = None) -> str:
env = {
k: v
for k, v in os.environ.items()
if k not in _STRIPPED_WORKLOAD_ENV_VARS
}
env["HOME"] = str(tmp_path)
env["PYTHONPATH"] = str(_SCRIPTS_DIR)
if extra_env:
env.update(extra_env)
return subprocess.check_output(
[sys.executable, "-c", expr],
env=env,
text=True,
).strip()
return _run
+338
View File
@@ -0,0 +1,338 @@
"""
Security and structural tests for the read-only `agents` SSH user,
`ForceCommand` allowlist wrapper, and loopback-only `socket-proxy` binding.
"""
import os
import re
import shutil
import subprocess
from pathlib import Path
import pytest
import yaml
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
NIXOS_CONFIG = CORE_ROOT / "nixos" / "configuration.nix"
COMPOSE_FILE = CORE_ROOT / "docker-compose.yml"
FORCE_COMMAND_SCRIPT = CORE_ROOT / "nixos" / "scripts" / "agents-force-command.sh"
EXPECTED_AGENT_PUBKEY = (
"ssh-ed25519 "
"AAAAC3NzaC1lZDI1NTE5AAAAIE1pxTdygG5696q0jT7clfJZWtx48ugfUjpzvkHzovVd "
"canopy-agents"
)
def _extract_nix_block(content: str, header_pattern: str) -> str:
"""Extract a brace-delimited Nix attribute block starting at header_pattern."""
match = re.search(header_pattern, content)
assert match is not None, f"Missing Nix block matching: {header_pattern}"
pos = match.end()
# Skip `let ... in` bindings if present before the attribute set `{ ... }`
tail = content[pos:]
if re.match(r"\s*let\b", tail):
in_match = re.search(r"\bin\s*\{", tail)
assert in_match is not None, f"Missing 'in {{' for let-block: {header_pattern}"
start = pos + in_match.end() - 1
else:
start = content.find("{", pos)
assert start != -1, f"Opening brace not found for: {header_pattern}"
depth = 0
for idx in range(start, len(content)):
ch = content[idx]
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return content[start : idx + 1]
raise AssertionError(f"Unclosed Nix block for: {header_pattern}")
def _setup_mock_bin(tmp_path: Path) -> tuple[Path, Path]:
"""Create mock docker, journalctl, and appctl binaries that log invocations."""
mock_bin = tmp_path / "mock_bin"
mock_bin.mkdir()
invocations_log = tmp_path / "invocations.log"
bash_bin = shutil.which("bash") or "/bin/bash"
for cmd in ("docker", "journalctl", "appctl"):
stub = mock_bin / cmd
stub.write_text(
f"#!{bash_bin}\n"
f'printf "%s|%s|%s|%s|%s\\n" '
f'"{cmd}" "$*" "${{CORE_DIR:-}}" "${{WORKLOADS_DIR:-}}" "${{DOCKER_HOST:-}}" '
f'>> "{invocations_log}"\n',
encoding="utf-8",
)
stub.chmod(0o755)
return mock_bin, invocations_log
def _run_force_command(
ssh_original_command: str | None,
tmp_path: Path,
) -> tuple[subprocess.CompletedProcess[str], Path]:
"""Execute agents-force-command.sh with isolated mock PATH and SSH_ORIGINAL_COMMAND."""
assert FORCE_COMMAND_SCRIPT.exists(), (
f"ForceCommand script not found at {FORCE_COMMAND_SCRIPT}"
)
mock_bin, invocations_log = _setup_mock_bin(tmp_path)
env = {
"PATH": f"{mock_bin}:{os.environ.get('PATH', '/usr/bin:/bin')}",
"HOME": str(tmp_path),
}
if ssh_original_command is not None:
env["SSH_ORIGINAL_COMMAND"] = ssh_original_command
bash_bin = shutil.which("bash") or "/bin/bash"
proc = subprocess.run(
[bash_bin, str(FORCE_COMMAND_SCRIPT)],
env=env,
capture_output=True,
text=True,
check=False,
)
return proc, invocations_log
def test_socket_proxy_binds_loopback_only():
"""Ensure socket-proxy publishes port 2375 strictly on 127.0.0.1."""
compose = yaml.safe_load(COMPOSE_FILE.read_text(encoding="utf-8"))
services = compose.get("services", {})
assert "socket-proxy" in services, "socket-proxy service must exist"
ports = services["socket-proxy"].get("ports", [])
assert isinstance(ports, list) and len(ports) > 0, (
"socket-proxy must declare non-empty ports list"
)
assert all(isinstance(p, str) and p.startswith("127.0.0.1:") for p in ports), (
f"Every socket-proxy port must bind strictly to 127.0.0.1, got: {ports!r}"
)
assert "127.0.0.1:2375:2375" in ports, (
"socket-proxy must bind 127.0.0.1:2375:2375"
)
def test_nixos_agents_user_least_privilege():
"""Verify users.users.agents has read-only groups and excludes wheel/docker."""
content = NIXOS_CONFIG.read_text(encoding="utf-8")
agents_block = _extract_nix_block(content, r"users\.users\.agents\s*=")
assert re.search(r"isNormalUser\s*=\s*true\s*;", agents_block), (
"users.users.agents must set isNormalUser = true"
)
assert EXPECTED_AGENT_PUBKEY in agents_block, (
"users.users.agents must configure the canopy-agents SSH public key"
)
groups_match = re.search(r"extraGroups\s*=\s*\[(.*?)\]\s*;", agents_block, re.DOTALL)
assert groups_match is not None, "users.users.agents must declare extraGroups"
groups_text = groups_match.group(1)
actual_groups = set(re.findall(r'"([^"]+)"', groups_text))
assert actual_groups == {"homelab-operators", "systemd-journal"}, (
f"agents extraGroups must be strictly {{'homelab-operators', 'systemd-journal'}}, got: {actual_groups!r}"
)
def test_nixos_openssh_match_user_agents_hardening():
"""Verify services.openssh configures Match User agents with ForceCommand and hardening."""
content = NIXOS_CONFIG.read_text(encoding="utf-8")
ssh_block = _extract_nix_block(content, r"services\.openssh\s*=")
assert "Match User agents" in ssh_block, (
"services.openssh must configure Match User agents"
)
match_section = ssh_block[ssh_block.index("Match User agents") :]
required_directives = [
r"ForceCommand\s+\S*agents-force-command\b",
r"AllowTcpForwarding\s+no",
r"X11Forwarding\s+no",
r"AllowAgentForwarding\s+no",
r"PermitTTY\s+no",
r"PasswordAuthentication\s+no",
]
for pattern in required_directives:
assert re.search(pattern, match_section), (
f"Match User agents must include directive matching: {pattern}"
)
def test_force_command_script_has_no_eval_or_sh_c():
"""Ensure agents-force-command.sh never uses eval or subshell invocation."""
assert FORCE_COMMAND_SCRIPT.exists(), (
f"ForceCommand script not found at {FORCE_COMMAND_SCRIPT}"
)
content = FORCE_COMMAND_SCRIPT.read_text(encoding="utf-8")
assert "eval " not in content, "Dangerous 'eval' detected in ForceCommand script"
assert "sh -c" not in content, "Dangerous 'sh -c' detected in ForceCommand script"
assert "bash -c" not in content, "Dangerous 'bash -c' detected in ForceCommand script"
def test_force_command_exports_expected_environment(tmp_path: Path):
"""Verify ForceCommand exports CORE_DIR, WORKLOADS_DIR, and loopback DOCKER_HOST."""
proc, invocations_log = _run_force_command("docker ps", tmp_path)
assert proc.returncode == 0, f"Unexpected failure: {proc.stderr}"
lines = invocations_log.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 1
cmd, args, core_dir, workloads_dir, docker_host = lines[0].split("|")
assert cmd == "docker"
assert args == "ps"
assert core_dir == "/home/operator/Core"
assert workloads_dir == "/home/operator/Workloads"
assert docker_host == "tcp://127.0.0.1:2375"
@pytest.mark.parametrize(
("command", "expected_bin", "expected_args"),
[
("docker ps", "docker", "ps"),
("docker ps -a --format {{.Names}}", "docker", "ps -a --format {{.Names}}"),
("docker logs --tail 50 traefik", "docker", "logs --tail 50 traefik"),
("docker inspect traefik", "docker", "inspect traefik"),
(
"journalctl -u homelab-appctl -n 50 --no-pager",
"journalctl",
"-u homelab-appctl -n 50 --no-pager",
),
("appctl list --core", "appctl", "list --core"),
("appctl status", "appctl", "status"),
("appctl info traefik", "appctl", "info traefik"),
("appctl logs traefik", "appctl", "logs traefik"),
("appctl ssl --all", "appctl", "ssl --all"),
("appctl health", "appctl", "health"),
("appctl resolve traefik", "appctl", "resolve traefik"),
],
)
def test_force_command_allows_read_only_commands(
tmp_path: Path, command: str, expected_bin: str, expected_args: str
):
"""Verify allowlisted read-only commands execute cleanly with exact arguments."""
proc, invocations_log = _run_force_command(command, tmp_path)
assert proc.returncode == 0, f"Allowed command '{command}' failed: {proc.stderr}"
lines = invocations_log.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 1
cmd, args, *_ = lines[0].split("|")
assert cmd == expected_bin
assert args == expected_args
@pytest.mark.parametrize(
"bad_command",
[
None,
"",
" ",
"docker ps; id",
"docker ps && id",
"docker ps || id",
"docker ps | cat",
"docker ps `id`",
"docker ps $(id)",
"docker ps > /tmp/pwn",
"docker ps < /etc/passwd",
"docker ps\nid",
"docker ps\rid",
"docker ps 'traefik'",
'docker ps "traefik"',
"docker ps \\ id",
],
)
def test_force_command_rejects_empty_and_metacharacters(
tmp_path: Path, bad_command: str | None
):
"""Verify empty commands and shell metacharacters are rejected without execution."""
proc, invocations_log = _run_force_command(bad_command, tmp_path)
assert proc.returncode != 0, f"Dangerous input was unexpectedly allowed: {bad_command!r}"
assert not invocations_log.exists(), (
f"Command stub should not have been executed for: {bad_command!r}"
)
@pytest.mark.parametrize(
"disallowed_command",
[
"sudo id",
"su root",
"sh",
"bash",
"cat /etc/shadow",
"rm -rf /tmp/foo",
"systemctl restart docker",
"docker",
"docker run alpine",
"docker exec -it traefik sh",
"docker rm traefik",
"docker build .",
"docker stop traefik",
"docker start traefik",
"docker restart traefik",
"docker kill traefik",
"docker compose up -d",
"docker -H unix:///var/run/docker.sock ps",
"journalctl --flush",
"journalctl --rotate",
"journalctl --vacuum-size=1M",
"journalctl --vacuum-time=1d",
"journalctl --vacuum-files=1",
"journalctl --relinquish-var",
"journalctl --sync",
"journalctl --setup-keys",
"journalctl --update-catalog",
"appctl",
"appctl up traefik",
"appctl down traefik",
"appctl restart traefik",
"appctl update traefik",
"appctl pull traefik",
"appctl sync",
"appctl config",
"appctl deploy traefik",
"appctl complete services",
],
)
def test_force_command_rejects_disallowed_commands_and_subcommands(
tmp_path: Path, disallowed_command: str
):
"""Verify disallowed binaries, mutating subcommands, and mutating flags are rejected."""
proc, invocations_log = _run_force_command(disallowed_command, tmp_path)
assert proc.returncode != 0, (
f"Disallowed command was unexpectedly allowed: {disallowed_command!r}"
)
assert not invocations_log.exists(), (
f"Command stub should not have been executed for: {disallowed_command!r}"
)
@pytest.mark.parametrize("subcmd", ["ps", "logs", "inspect"])
@pytest.mark.parametrize(
"override_flag",
[
"-H unix:///var/run/docker.sock",
"-H=unix:///var/run/docker.sock",
"--host unix:///var/run/docker.sock",
"--host=unix:///var/run/docker.sock",
"--context default",
"--context=default",
"-c default",
"-c=default",
"--config /tmp",
"--config=/tmp",
],
)
def test_force_command_rejects_post_subcommand_docker_override_flags(
tmp_path: Path, subcmd: str, override_flag: str
):
"""Verify Docker connection/context/config override flags are rejected after valid subcommands."""
command = f"docker {subcmd} {override_flag}"
proc, invocations_log = _run_force_command(command, tmp_path)
assert proc.returncode != 0, (
f"Docker override flag was unexpectedly allowed: {command!r}"
)
assert not invocations_log.exists(), (
f"Command stub should not have been executed for: {command!r}"
)
+536
View File
@@ -269,6 +269,48 @@ def test_registry_resolves_workloads_and_sites_tilde_prefixes(
assert gitops_dispatcher.resolve_repository("valid") is None assert gitops_dispatcher.resolve_repository("valid") is None
def test_deployments_file_defaults_to_workloads(
tmp_path: Path, run_isolated_script_expr
):
"""Ensure DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml."""
resolved_default = run_isolated_script_expr(
"import gitops_dispatcher; print(gitops_dispatcher.DEPLOYMENTS_FILE)"
)
assert Path(resolved_default) == tmp_path / "Workloads" / "deployments.yaml"
def test_deployments_file_fails_closed_without_config_dir_fallback(
tmp_path: Path, monkeypatch
):
"""Ensure missing DEPLOYMENTS_FILE fails closed even when CONFIG_DIR/deployments.yaml exists."""
config_dir = tmp_path / "config-fallback"
config_dir.mkdir()
(config_dir / "deployments.yaml").write_text(
'schemaVersion: "1.0"\n'
"repositories:\n"
" docs:\n"
' path: "~/Workloads/docs"\n',
encoding="utf-8",
)
monkeypatch.setattr(
gitops_dispatcher, "DEPLOYMENTS_FILE", tmp_path / "Workloads" / "deployments.yaml"
)
monkeypatch.setattr(gitops_dispatcher, "CONFIG_DIR", config_dir)
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
def test_deployments_file_honors_workloads_dir_override(
tmp_path: Path, run_isolated_script_expr
):
"""Ensure DEPLOYMENTS_FILE honors WORKLOADS_DIR override when HOMELAB_DEPLOYMENTS_FILE is unset."""
custom_workloads = tmp_path / "CustomWorkloads"
resolved_override = run_isolated_script_expr(
"import gitops_dispatcher; print(gitops_dispatcher.DEPLOYMENTS_FILE)",
extra_env={"WORKLOADS_DIR": str(custom_workloads)},
)
assert Path(resolved_override) == custom_workloads / "deployments.yaml"
def test_webhook_verification_valid_signature(): def test_webhook_verification_valid_signature():
"""Ensure valid HMAC-SHA256 signature passes verification.""" """Ensure valid HMAC-SHA256 signature passes verification."""
import hashlib import hashlib
@@ -1316,3 +1358,497 @@ def test_monorepo_webhook_dispatch_pulls_once_and_deploys_only_admitted_changed_
pull_calls = [c for c in git_calls if "pull" in c] pull_calls = [c for c in git_calls if "pull" in c]
assert len(pull_calls) == 1 assert len(pull_calls) == 1
assert str(workloads_dir) in pull_calls[0] assert str(workloads_dir) in pull_calls[0]
# ---------------------------------------------------------------------------
# ADR-0005 Host-Granted Workload Capabilities ("Compose Requests, Nix Grants")
# ---------------------------------------------------------------------------
def _write_grants(path: Path, workloads: dict) -> Path:
import json
path.write_text(
json.dumps({"schemaVersion": "1.0", "workloads": workloads}),
encoding="utf-8",
)
return path
def _fake_group_lookup(key: str | int) -> tuple[str, int]:
table = {
"render": ("render", 303),
303: ("render", 303),
"video": ("video", 44),
44: ("video", 44),
"docker": ("docker", 998),
998: ("docker", 998),
"wheel": ("wheel", 10),
10: ("wheel", 10),
"root": ("root", 0),
0: ("root", 0),
}
lookup_key = int(key) if isinstance(key, str) and key.isdigit() else key
if lookup_key in table:
return table[lookup_key]
raise KeyError(key)
def test_validate_compose_security_permits_granted_stack(tmp_path: Path):
"""Positive ADR-0005 grants: render<->303, existing device, short & long :ro readOnlyPaths."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
dev_dir = tmp_path / "dev" / "dri"
dev_dir.mkdir(parents=True)
render_node = dev_dir / "renderD128"
render_node.write_text("", encoding="utf-8")
media_dir = tmp_path / "mnt" / "media"
media_sub = media_dir / "movies"
media_sub.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{
"media": {
"devices": [str(render_node)],
"groups": ["render"],
"readOnlyPaths": [str(media_dir)],
}
},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
jellyfin:
image: jellyfin/jellyfin:latest
user: "1000:303"
group_add:
- "303"
devices:
- "{render_node}:/dev/dri/renderD128:rw"
volumes:
- "{media_sub}:/media/movies:ro"
- type: bind
source: "{media_dir}"
target: /media/all
read_only: true
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="media",
grants_file=grants_file,
group_lookup=_fake_group_lookup,
)
assert ok is True, f"Expected granted capabilities to pass, got: {err}"
assert err is None
def test_capability_grants_evaluates_resolved_env_interpolation(tmp_path: Path):
"""Post-interpolation values from resolved_env are evaluated and permitted when granted."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"groups": ["303"], "readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
user: "${PUID:-1000}:${PGID:-1000}"
group_add:
- "${RENDER_GID}"
volumes:
- "${MEDIA_PATH}:/media:ro"
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="media",
resolved_env={
"PUID": "1000",
"PGID": "1000",
"RENDER_GID": "render",
"MEDIA_PATH": str(media_dir),
},
grants_file=grants_file,
group_lookup=_fake_group_lookup,
)
assert ok is True, f"Expected resolved env capabilities to pass, got: {err}"
@pytest.mark.parametrize(
"compose_body,expected_substr",
[
(" user: '0:131'", "user"),
(" user: '00:1000'", "root"),
(" user: '1000:0'", "user"),
(" user: '1000:docker'", "docker"),
(" user: '1000:44'", "44"),
(" user: '1000:999'", "999"),
(" group_add:\n - '303'", "group_add"),
(" network_mode: 'container:traefik'", "container:traefik"),
(" network_mode: 'service:web'", "service:web"),
(" device_cgroup_rules:\n - 'c 226:* rmw'", "device_cgroup_rules"),
(" user: '${PUID}:1000'", "interpolation"),
],
)
def test_validate_compose_security_rejects_ungranted_capabilities(
tmp_path: Path, compose_body: str, expected_substr: str
):
"""Ensure bypass vectors and ungranted capabilities fail closed."""
app_dir = tmp_path / "Workloads" / "ungranted"
app_dir.mkdir(parents=True)
grants_file = _write_grants(tmp_path / "grants.json", {})
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"services:\n app:\n image: alpine\n{compose_body}\n",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="ungranted",
grants_file=grants_file,
group_lookup=_fake_group_lookup,
)
assert ok is False
assert err is not None
assert expected_substr.lower() in err.lower()
def test_validate_compose_security_fails_closed_when_pyyaml_missing(
tmp_path: Path, monkeypatch
):
"""Ensure validate_compose_security fails closed when PyYAML is unavailable."""
app_dir = tmp_path / "Workloads" / "app"
app_dir.mkdir(parents=True)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text("services:\n app:\n image: alpine\n", encoding="utf-8")
monkeypatch.setattr(gitops_dispatcher, "yaml", None)
ok, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir)
assert ok is False
assert err is not None and "pyyaml" in err.lower()
def test_capability_grants_device_mknod_rejected(tmp_path: Path):
"""Ensure :rwm (mknod) is rejected even when the device node exists and is granted."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
dev_dir = tmp_path / "dev" / "dri"
dev_dir.mkdir(parents=True)
render_node = dev_dir / "renderD128"
render_node.write_text("", encoding="utf-8")
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"devices": [str(render_node)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
devices:
- "{render_node}:/dev/dri/renderD128:rwm"
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
assert err is not None and "mknod" in err.lower()
def test_capability_grants_missing_device_node_rejected(tmp_path: Path):
"""Ensure a granted device path that does not exist on the host fails closed."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
missing_node = tmp_path / "dev" / "dri" / "renderD999"
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"devices": [str(missing_node)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
devices:
- "{missing_node}:/dev/dri/renderD999:rw"
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
assert err is not None and "does not exist" in err.lower()
def test_capability_grants_volumes_reject_rw_long_syntax(tmp_path: Path):
"""Ensure readOnlyPaths rejects long-syntax bind mounts without read_only: true."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
volumes:
- type: bind
source: "{media_dir}"
target: /media
read_only: false
""",
encoding="utf-8",
)
ok, _ = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
def test_capability_grants_volumes_reject_unsafe_propagation(tmp_path: Path):
"""Ensure readOnlyPaths rejects long-syntax bind mounts with unsafe propagation (rshared)."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
volumes:
- type: bind
source: "{media_dir}"
target: /media
read_only: true
bind:
propagation: rshared
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
assert err is not None and "propagation" in err.lower()
def test_capability_grants_volumes_reject_symlink_escape(tmp_path: Path):
"""Ensure readOnlyPaths rejects symlinks resolving outside the granted directory."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
outside_dir = tmp_path / "etc"
outside_dir.mkdir(parents=True)
escaped_link = media_dir / "escape"
escaped_link.symlink_to(outside_dir)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
volumes:
- "{escaped_link}:/media:ro"
""",
encoding="utf-8",
)
ok, _ = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
def test_capability_grants_app_name_none_receives_zero_grants(tmp_path: Path):
"""Ensure app_name=None receives zero grants even when grants.json defines workloads."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
volumes:
- "{media_dir}:/media:ro"
""",
encoding="utf-8",
)
ok, _ = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name=None, grants_file=grants_file
)
assert ok is False
def test_capability_grants_malformed_grants_fail_closed(tmp_path: Path):
"""Ensure malformed grants.json fails closed even on a plain compose file."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
plain_compose = app_dir / "plain.yml"
plain_compose.write_text("services:\n app:\n image: alpine\n", encoding="utf-8")
bad_grants = tmp_path / "bad_grants.json"
bad_grants.write_text("{corrupt", encoding="utf-8")
ok, err = gitops_dispatcher.validate_compose_security(
plain_compose, app_dir, app_name="media", grants_file=bad_grants
)
assert ok is False
assert err is not None and "grants" in err.lower()
def test_validate_compose_security_allows_ungranted_gid_1000(tmp_path: Path):
"""Ensure unprivileged numeric GID >= 1000 (1000:1000) is allowed without a grant."""
app_dir = tmp_path / "Workloads" / "ungranted"
app_dir.mkdir(parents=True)
grants_file = _write_grants(tmp_path / "grants.json", {})
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
"services:\n app:\n image: alpine\n user: '1000:1000'\n",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="ungranted",
grants_file=grants_file,
group_lookup=_fake_group_lookup,
)
assert ok is True
assert err is None
def test_validate_compose_security_rejects_high_numeric_gid_for_privileged_group(
tmp_path: Path,
):
"""Ensure numeric GID >= 1000 that resolves to a privileged group (docker) fails closed."""
app_dir = tmp_path / "Workloads" / "ungranted"
app_dir.mkdir(parents=True)
grants_file = _write_grants(tmp_path / "grants.json", {})
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
"services:\n app:\n image: alpine\n user: '1000:1998'\n",
encoding="utf-8",
)
def lookup_with_high_docker(key: str | int) -> tuple[str, int]:
if key in (1998, "1998"):
return ("docker", 1998)
return _fake_group_lookup(key)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="ungranted",
grants_file=grants_file,
group_lookup=lookup_with_high_docker,
)
assert ok is False
assert err is not None and "docker" in err.lower()
def test_validate_compose_security_rejects_sibling_prefix_paths(tmp_path: Path):
"""Ensure sibling directory prefixes (/dev/dri2, /mnt/media2) cannot bypass containment."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
granted_dev = tmp_path / "dev" / "dri"
granted_dev.mkdir(parents=True)
sibling_dev_dir = tmp_path / "dev" / "dri2"
sibling_dev_dir.mkdir(parents=True)
sibling_node = sibling_dev_dir / "renderD128"
sibling_node.write_text("", encoding="utf-8")
granted_media = tmp_path / "mnt" / "media"
granted_media.mkdir(parents=True)
sibling_media = tmp_path / "mnt" / "media2"
sibling_media.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{
"media": {
"devices": [str(granted_dev)],
"readOnlyPaths": [str(granted_media)],
}
},
)
dev_compose = app_dir / "dev-compose.yml"
dev_compose.write_text(
f"services:\n app:\n image: alpine\n devices:\n - '{sibling_node}:/dev/dri/renderD128:rw'\n",
encoding="utf-8",
)
ok_dev, _ = gitops_dispatcher.validate_compose_security(
dev_compose, app_dir, app_name="media", grants_file=grants_file
)
assert ok_dev is False
vol_compose = app_dir / "vol-compose.yml"
vol_compose.write_text(
f"services:\n app:\n image: alpine\n volumes:\n - '{sibling_media}:/media:ro'\n",
encoding="utf-8",
)
ok_vol, _ = gitops_dispatcher.validate_compose_security(
vol_compose, app_dir, app_name="media", grants_file=grants_file
)
assert ok_vol is False
@@ -210,6 +210,7 @@ def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests(
CORE_ROOT / "flake.nix", CORE_ROOT / "flake.nix",
CORE_ROOT / "docker-compose.yml", CORE_ROOT / "docker-compose.yml",
CORE_ROOT / "nixos" / "configuration.nix", CORE_ROOT / "nixos" / "configuration.nix",
CORE_ROOT / "nixos" / "instance.example.nix",
] ]
violations = [] violations = []
@@ -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
@@ -20,6 +20,7 @@ def test_required_architectural_paths_exist():
"SECURITY.md", "SECURITY.md",
"nixos", "nixos",
"nixos/configuration.nix", "nixos/configuration.nix",
"nixos/instance.example.nix",
"nixos/modules/homeserver.nix", "nixos/modules/homeserver.nix",
"nixos/secrets.yaml", "nixos/secrets.yaml",
"scripts/gitops_dispatcher.py", "scripts/gitops_dispatcher.py",
+42
View File
@@ -492,3 +492,45 @@ def test_rbac_viewer_denied_on_sensitive_reads():
enforce_rbac(viewer, sens_op, "snappymail") enforce_rbac(viewer, sens_op, "snappymail")
assert "not permitted to access sensitive operation" in str(exc_info.value) assert "not permitted to access sensitive operation" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_default_deployments_file_resolves_to_workloads_dir(
tmp_path: Path, run_isolated_script_expr
):
"""DEFAULT_DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml."""
resolved = run_isolated_script_expr(
"import appctl_auth; print(appctl_auth.DEFAULT_DEPLOYMENTS_FILE)"
)
assert Path(resolved) == tmp_path / "Workloads" / "deployments.yaml"
def test_load_admitted_workloads_fails_closed_when_absent(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
"""Absent ~/Workloads/deployments.yaml fails closed (empty set, no CORE_DIR fallback)."""
import appctl_auth
monkeypatch.delenv("HOMELAB_DEPLOYMENTS_FILE", raising=False)
monkeypatch.delenv("WORKLOADS_DIR", raising=False)
monkeypatch.delenv("SITES_DIR", raising=False)
monkeypatch.setattr(
appctl_auth, "DEFAULT_DEPLOYMENTS_FILE", tmp_path / "Workloads" / "deployments.yaml"
)
assert appctl_auth.load_admitted_workloads() == set()
def test_load_admitted_workloads_honors_workloads_dir_override(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
"""WORKLOADS_DIR takes precedence when HOMELAB_DEPLOYMENTS_FILE is unset."""
import appctl_auth
custom_workloads = tmp_path / "CustomWorkloads"
custom_workloads.mkdir()
(custom_workloads / "deployments.yaml").write_text(
"repositories:\n custom_app:\n path: ~/Workloads/custom_app\n",
encoding="utf-8",
)
monkeypatch.delenv("HOMELAB_DEPLOYMENTS_FILE", raising=False)
monkeypatch.setenv("WORKLOADS_DIR", str(custom_workloads))
assert appctl_auth.load_admitted_workloads() == {"custom_app"}
+4 -2
View File
@@ -445,12 +445,13 @@ def test_operation_request_backward_compatibility_aliases():
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def test_error_code_taxonomy_contains_exactly_6_canonical_codes(): def test_error_code_taxonomy_contains_exactly_7_canonical_codes():
assert len(ErrorCode) == 6 assert len(ErrorCode) == 7
expected_codes = { expected_codes = {
"ERR_VALIDATION_FAILED", "ERR_VALIDATION_FAILED",
"ERR_AUTH_REQUIRED", "ERR_AUTH_REQUIRED",
"ERR_PERMISSION_DENIED", "ERR_PERMISSION_DENIED",
"ERR_CAPABILITY_NOT_GRANTED",
"ERR_TARGET_NOT_FOUND", "ERR_TARGET_NOT_FOUND",
"ERR_CONCURRENT_MUTATION", "ERR_CONCURRENT_MUTATION",
"ERR_EXECUTION_FAILED", "ERR_EXECUTION_FAILED",
@@ -462,6 +463,7 @@ def test_error_code_http_status_mapping():
assert ErrorCode.ERR_VALIDATION_FAILED.http_status == 400 assert ErrorCode.ERR_VALIDATION_FAILED.http_status == 400
assert ErrorCode.ERR_AUTH_REQUIRED.http_status == 401 assert ErrorCode.ERR_AUTH_REQUIRED.http_status == 401
assert ErrorCode.ERR_PERMISSION_DENIED.http_status == 403 assert ErrorCode.ERR_PERMISSION_DENIED.http_status == 403
assert ErrorCode.ERR_CAPABILITY_NOT_GRANTED.http_status == 403
assert ErrorCode.ERR_TARGET_NOT_FOUND.http_status == 404 assert ErrorCode.ERR_TARGET_NOT_FOUND.http_status == 404
assert ErrorCode.ERR_CONCURRENT_MUTATION.http_status == 409 assert ErrorCode.ERR_CONCURRENT_MUTATION.http_status == 409
assert ErrorCode.ERR_EXECUTION_FAILED.http_status == 500 assert ErrorCode.ERR_EXECUTION_FAILED.http_status == 500
+52
View File
@@ -591,3 +591,55 @@ def test_gitops_dispatcher_delegates_to_daemon(daemon_env, monkeypatch):
) )
assert success is True assert success is True
assert mock_sub.call_count >= 1 assert mock_sub.call_count >= 1
def test_daemon_deployments_file_defaults_to_workloads(
tmp_path: Path, run_isolated_script_expr
):
"""DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml."""
resolved_default = run_isolated_script_expr(
"import appctl_daemon; print(appctl_daemon.DEPLOYMENTS_FILE)"
)
assert Path(resolved_default) == tmp_path / "Workloads" / "deployments.yaml"
def test_daemon_deployments_file_honors_workloads_dir_override(
tmp_path: Path, run_isolated_script_expr
):
"""DEPLOYMENTS_FILE honors WORKLOADS_DIR override when HOMELAB_DEPLOYMENTS_FILE is unset."""
custom_workloads = tmp_path / "CustomWorkloads"
resolved_override = run_isolated_script_expr(
"import appctl_daemon; print(appctl_daemon.DEPLOYMENTS_FILE)",
extra_env={"WORKLOADS_DIR": str(custom_workloads)},
)
assert Path(resolved_override) == custom_workloads / "deployments.yaml"
def test_daemon_operator_fails_closed_when_deployments_file_absent(
daemon_env, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
"""homelab-operator fails closed (403 ERR_PERMISSION_DENIED) when ~/Workloads/deployments.yaml is absent."""
import appctl_auth
# When HOMELAB_DEPLOYMENTS_FILE is unset and ~/Workloads/deployments.yaml is absent,
# homelab-operator must be denied (403) without falling back to CORE_DIR/config/deployments.yaml.
monkeypatch.delenv("HOMELAB_DEPLOYMENTS_FILE", raising=False)
monkeypatch.delenv("WORKLOADS_DIR", raising=False)
monkeypatch.delenv("SITES_DIR", raising=False)
monkeypatch.setattr(
appctl_auth,
"DEFAULT_DEPLOYMENTS_FILE",
tmp_path / "empty-home" / "Workloads" / "deployments.yaml",
)
deploy_req = OperationRequest(
operation=OperationType.WORKLOAD_DEPLOY, target="docs"
)
resp = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=deploy_req,
token=OPERATOR_SECRET,
)
assert resp.success is False
assert resp.error is not None
assert resp.error.code == ErrorCode.ERR_PERMISSION_DENIED
assert resp.error.code.http_status == 403
+100
View File
@@ -1416,6 +1416,7 @@ def test_operational_router_workload_update_propagates_non_zero_exit_and_stderr(
return (0, "", "") return (0, "", "")
with ( with (
patch("appctl_router.load_admitted_workloads", return_value={"snappymail"}),
patch("appctl_router.resolve_app", return_value=mock_app), patch("appctl_router.resolve_app", return_value=mock_app),
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
patch("appctl_router.cmd_sync_homepage"), patch("appctl_router.cmd_sync_homepage"),
@@ -1681,3 +1682,102 @@ def test_operational_router_workload_update_pulls_monorepo_when_parent_git_exist
# Compose commands still run in app_dir # Compose commands still run in app_dir
compose_cwds = [cwd for c, cwd in executed if c[0] == "docker"] 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) assert compose_cwds and all(cwd == mock_workload_dir for cwd in compose_cwds)
def test_operational_router_returns_err_capability_not_granted(
tmp_path: Path, admin_principal: Principal, monkeypatch
):
"""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)
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"}
)
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
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(
{
"schemaVersion": "1.0",
"workloads": {"media": {"readOnlyPaths": [str(media_dir)]}},
}
),
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", "")),
patch("appctl_router.cmd_sync_homepage"),
):
resp_ok = router.dispatch(req, admin_principal)
assert resp_ok.success is True
+12
View File
@@ -355,3 +355,15 @@ description: "Pydantic serialization test"
assert dumped["name"] == "serialized-app" assert dumped["name"] == "serialized-app"
assert dumped["schemaVersion"] == "1.0" assert dumped["schemaVersion"] == "1.0"
assert manifest.to_dict()["name"] == "serialized-app" assert manifest.to_dict()["name"] == "serialized-app"
def test_parse_manifest_rejects_homelab_grants_file_in_env():
"""Ensure HOMELAB_GRANTS_FILE is in RESERVED_ENV_KEYS and cannot be overridden by app.yaml."""
raw_yaml = """
name: "grants-override-app"
env:
HOMELAB_GRANTS_FILE: "/tmp/evil-grants.json"
"""
with pytest.raises(ManifestValidationError):
parse_manifest(raw_yaml)
+164
View File
@@ -0,0 +1,164 @@
"""Unit tests for Pydantic v2 workload capability grants loader (ADR-0005)."""
from __future__ import annotations
import json
import os
from pathlib import Path
from types import SimpleNamespace
import pytest
from pydantic import ValidationError
from workload_grants import (
GrantsRegistry,
WorkloadGrant,
WorkloadGrantsError,
load_workload_grants,
)
def test_load_workload_grants_absent_file_returns_empty(tmp_path: Path) -> None:
missing = tmp_path / "does-not-exist.json"
assert load_workload_grants(missing) == {}
def test_load_workload_grants_honors_env_var_when_none(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text(
json.dumps(
{
"schemaVersion": "1.0",
"workloads": {
"media": {
"devices": ["/dev/dri/renderD128"],
"groups": ["render", "303"],
"readOnlyPaths": ["/mnt/media"],
}
},
}
),
encoding="utf-8",
)
monkeypatch.setenv("HOMELAB_GRANTS_FILE", str(grants_path))
loaded = load_workload_grants(verify_permissions=False)
assert "media" in loaded
assert loaded["media"].devices == ["/dev/dri/renderD128"]
assert loaded["media"].groups == ["render", "303"]
assert loaded["media"].readOnlyPaths == ["/mnt/media"]
@pytest.mark.parametrize("bad_group", ["0", "root", "wheel", "docker", "ROOT", " wheel "])
def test_workload_grant_rejects_privileged_groups(bad_group: str) -> None:
with pytest.raises(ValidationError):
WorkloadGrant(groups=[bad_group])
@pytest.mark.parametrize(
"bad_path",
[
"dev/dri/renderD128",
"../etc/passwd",
"/dev/../etc/shadow",
"/mnt/media/..",
"",
],
)
def test_workload_grant_rejects_relative_and_traversal_paths(bad_path: str) -> None:
with pytest.raises(ValidationError):
WorkloadGrant(devices=[bad_path])
with pytest.raises(ValidationError):
WorkloadGrant(readOnlyPaths=[bad_path])
def test_grants_registry_rejects_extra_fields() -> None:
with pytest.raises(ValidationError):
GrantsRegistry.model_validate(
{
"schemaVersion": "1.0",
"workloads": {"app": {"devices": [], "extra_field": True}},
}
)
def test_grants_registry_rejects_bad_schema_version() -> None:
with pytest.raises(ValidationError):
GrantsRegistry.model_validate({"schemaVersion": "2.0", "workloads": {}})
def test_load_workload_grants_malformed_json_fails_closed(tmp_path: Path) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text("{not valid json", encoding="utf-8")
with pytest.raises(WorkloadGrantsError):
load_workload_grants(grants_path)
def test_load_workload_grants_unreadable_file_fails_closed(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
def raise_perm_error(self: Path, *args: object, **kwargs: object) -> str:
raise PermissionError("Permission denied")
monkeypatch.setattr(Path, "read_text", raise_perm_error)
with pytest.raises(WorkloadGrantsError, match="read"):
load_workload_grants(grants_path)
def test_load_workload_grants_verify_permissions_rejects_symlink(tmp_path: Path) -> None:
real_file = tmp_path / "real.json"
real_file.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
link_file = tmp_path / "grants.json"
link_file.symlink_to(real_file)
with pytest.raises(WorkloadGrantsError, match="symlink"):
load_workload_grants(link_file, verify_permissions=True)
def test_load_workload_grants_verify_permissions_rejects_non_root_owner(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
monkeypatch.setattr(
os,
"lstat",
lambda _p: SimpleNamespace(st_mode=0o100640, st_uid=1000),
)
with pytest.raises(WorkloadGrantsError, match="root"):
load_workload_grants(grants_path, verify_permissions=True)
@pytest.mark.parametrize("bad_mode", [0o100664, 0o100660, 0o100642, 0o100646])
def test_load_workload_grants_verify_permissions_rejects_writable_mode(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bad_mode: int
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
monkeypatch.setattr(
os,
"lstat",
lambda _p: SimpleNamespace(st_mode=bad_mode, st_uid=0),
)
with pytest.raises(WorkloadGrantsError, match="writable"):
load_workload_grants(grants_path, verify_permissions=True)
@pytest.mark.parametrize("good_mode", [0o100640, 0o100644])
def test_load_workload_grants_verify_permissions_accepts_non_writable_mode(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, good_mode: int
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
monkeypatch.setattr(
os,
"lstat",
lambda _p: SimpleNamespace(st_mode=good_mode, st_uid=0),
)
assert load_workload_grants(grants_path, verify_permissions=True) == {}