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 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
17 changed files with 704 additions and 53 deletions

No files matched your search

-2
View File
@@ -9,8 +9,6 @@ on:
jobs:
validate:
runs-on: ubuntu-latest
container:
image: nixery.dev/shell/coreutils/git/nix/nodejs:latest
steps:
- name: Check out repository
uses: actions/checkout@v4
+5 -5
View File
@@ -2,12 +2,12 @@
## 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 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.
- **`~/Sites` owns**: Independently deployed application workloads, workload-specific `docker-compose.yml` topologies, and workload intent (`app.yaml`).
- **Boundary Rule**: Never hardcode *workload-specific* domains, ports, containers, environment variables, or deployment policies in Core (`scripts/appctl*`, GitOps, or Core `docker-compose.yml`), and never move Core platform services into `~/Sites`. When ownership is ambiguous, consult [`docs/architecture.md`](docs/architecture.md) before changing the boundary.
### Core vs. `~/Workloads` Ownership
- **Core owns**: NixOS host configuration (`nixos/instance.example.nix` template for `/etc/nixos/homelab-instance.nix`), shared platform services (edge ingress, SSO/LDAP, mail, log/update monitors), platform-level ports and security policy (including `homelab.workloadGrants` -> `/etc/homelab/grants.json`), and orchestration/deployment mechanics (`appctl`, `gitops_dispatcher.py`, `workload_grants.py`).
- **`~/Workloads` owns**: Independently deployed application workloads, workload-specific `docker-compose.yml` topologies, workload intent (`app.yaml`), and `deployments.yaml`.
- **Boundary Rule**: Never hardcode *workload-specific* domains, ports, containers, environment variables, or deployment policies in Core (`scripts/appctl*`, GitOps, or Core `docker-compose.yml`), and never move Core platform services into `~/Workloads`. When ownership is ambiguous, consult [`docs/architecture.md`](docs/architecture.md) before changing the boundary.
### Context Discovery Hierarchy
Before proposing or implementing changes, establish context in this order:
+5 -4
View File
@@ -4,7 +4,7 @@
It is designed around a strict two-tier boundary:
1. **Canopy NixOS Core (`canopy-homelab/nixos-core`, this repository)**: Owns NixOS operating system configuration, edge TLS ingress, SSO/LDAP directory identity, mail routing, read-only Docker socket isolation, and orchestration/deployment mechanics.
2. **Canopy Workloads (`~/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.
@@ -35,7 +35,7 @@ All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_
├───────────────────────────────┤
│ • Core Services (Homepage, │
│ Dozzle, Stalwart, etc.) │
│ • Workload Apps (~/Sites/*) │
│ • Workload Apps (~/Workloads/*) │
└───────────────┬───────────────┘
│ (Read-Only API via TCP:2375)
▼
@@ -81,7 +81,7 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran
.
├── flake.nix # NixOS host configuration, devShell (.venv symlink), and CI checks
├── 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 template)
├── scripts/
│ ├── appctl # Thin operational CLI delegating to control plane daemon
@@ -95,6 +95,7 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran
│ ├── bootstrap_token.py # Operator Bearer token provisioning helper
│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for app.yaml
│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST validation
│ ├── workload_grants.py # Fail-closed Pydantic v2 loader for /etc/homelab/grants.json
│ └── run-tests # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks)
├── tests/ # Unit, structural, and security invariant test suites
└── docs/ # Architecture references, operational runbooks, and MADR decisions
@@ -166,7 +167,7 @@ systemctl status dynu-monitor.service
| 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. |
| [**`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. |
+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.
> **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). |
| **Operational Auth** | Mandatory SHA-256 Bearer token + 3-role RBAC + UDS `SO_PEERCRED` viewer fallback (`/run/secrets/appctl/tokens.json`). | LLDAP directory RBAC & Authelia ForwardAuth (P5). |
| **Metadata & Schema Engine** | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | Standardized JSON-RPC Model Context Protocol tools over Pydantic v2 schemas (P6). |
| **Deployment Model** | 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). |
| **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). |
@@ -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. |
| **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0 with Pydantic v2 fail-closed models (`core_manifest.py`), two-axis status inspection, unified `appctl_engine.py`. |
| **P4** | **Control Plane Daemon** | API & Dispatch | ✅ **Completed** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. |
| **P4.5** | **Workloads Contract & Agent Readiness** | Monorepo & Grants | ✅ **Completed** *(in `nixos-core`)* | `~/Workloads/deployments.yaml` decoupling, read-only `agents` SSH user, `homelab.workloadGrants` (`ADR-0005`), `nixos/instance.example.nix`, and `:host` CI runner workflow. |
| **P5** | **Identity & Secrets** | Auth & Providers | 🎯 **Current / Up Next** | LLDAP RBAC group mapping, Authelia ForwardAuth header integration, user-scoped token lifecycle, `SecretProvider` reference resolution. |
| **P6** | **Homelab MCP Gateway** | Protocol Integration | ⏳ **Planned** | Standardized JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`), client-side human-in-the-loop approvals, deprecation of on-server AI proposal compilers. |
| **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. |
+9 -2
View File
@@ -3,6 +3,8 @@ services:
image: tecnativa/docker-socket-proxy
container_name: socket-proxy
restart: always
ports:
- "127.0.0.1:2375:2375"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
environment:
@@ -42,7 +44,7 @@ services:
- "80:80"
- "443:443"
environment:
- DYNU_API_KEY=${DYNU_API_KEY}
- CF_DNS_API_TOKEN=${CF_DNS_API_TOKEN}
- DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40}
command:
- "--log.level=INFO"
@@ -59,7 +61,7 @@ services:
- "--entrypoints.websecure.http.tls.domains[0].sans=*.${DOMAIN}"
# SSL Setup
- "--certificatesresolvers.myresolver.acme.dnschallenge=true"
- "--certificatesresolvers.myresolver.acme.dnschallenge.provider=dynu"
- "--certificatesresolvers.myresolver.acme.dnschallenge.provider=cloudflare"
- "--certificatesresolvers.myresolver.acme.email=${ACME_EMAIL}"
- "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"
volumes:
@@ -79,6 +81,11 @@ services:
- "traefik.http.middlewares.authelia-auth.forwardauth.trustForwardHeader=true"
- "traefik.http.middlewares.authelia-auth.forwardauth.authResponseHeaders=Remote-User,Remote-Groups,Remote-Email,Remote-Name"
# Middleware: Public Rate Limit (mitigates scraper/crawler bursts on public routes)
- "traefik.http.middlewares.public-ratelimit.ratelimit.average=20"
- "traefik.http.middlewares.public-ratelimit.ratelimit.burst=40"
- "traefik.http.middlewares.public-ratelimit.ratelimit.period=1s"
# Dashboard - Public (HTTPS)
- "traefik.http.routers.traefik-dash.rule=Host(`traefik.${DOMAIN}`)"
- "traefik.http.routers.traefik-dash.entrypoints=websecure"
+11 -11
View File
@@ -14,7 +14,7 @@ To understand how the system is organized, three architectural dimensions are di
### A. Ownership Boundary
* **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
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.) │
│ Declarative app.yaml Manifests & Compose Stacks │
└───────────────────────────────────┬────────────────────────────────────┘
@@ -51,7 +51,7 @@ The runtime environment consists of four functional layers:
### C. Cross-Cutting Orchestration
Orchestration coordinates operations across the runtime layers:
* **`appctl` Operational Control Plane Daemon (`homelab-appctl.service`, `scripts/appctl_daemon.py`, `scripts/appctl_router.py`)**: Centralized control plane running under isolated service identity `homelab-appctl:homelab-operators`. Exposes `POST /v1/operations` and `GET /v1/health` over `/run/homelab/appctl.sock` (mode `0660`) and `127.0.0.1:9001`, enforcing SHA-256 Bearer token authentication, 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`), per-target `flock` serialization, fail-closed append-only audit logging (`/var/log/homelab/appctl/audit.jsonl`), Pydantic v2 `app.yaml` validation, Compose AST security checks, 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 `~/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`.
- State-modifying and execution endpoints disabled: `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`, `COMMIT=0`, `CONFIGS=0`, `DISTRIBUTION=0`, `NODES=0`, `PLUGINS=0`, `SECRETS=0`, `SWARM=0`, `SYSTEM=0`.
- Read-only inspection endpoints enabled: `CONTAINERS=1`, `NETWORKS=1`, `SERVICES=1`, `TASKS=1`, `IMAGES=1`, `VOLUMES=1`, `INFO=1`, `EVENTS=1`, `PING=1`, `VERSION=1`.
* **Network**: Attached exclusively to `socket-net`. Application containers in `~/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`)
* **`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.
- Authenticates users against the LLDAP directory.
- Outbound mail relay configured to route through an external smart host (Brevo SMTP relay via SOPS secrets).
- *(Note: User-facing webmail, such as SnappyMail, runs as an independent Class B workload in `~/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`)
* **`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`.
### F. Host Foundation & Daemons
@@ -113,7 +113,7 @@ Homelab Core configures two isolated Docker bridge networks:
│ │ • traefik (router) • authelia (sso) │ │
│ │ • lldap (directory) • stalwart (mail) │ │
│ │ • 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.
---
@@ -151,13 +151,13 @@ The host firewall is configured in `nixos/modules/homeserver.nix`:
| **993** | TCP | Stalwart | IMAPS (Secure IMAP) | 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
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.
2. **Compose Configuration (`docker-compose.yml`)**:
@@ -177,4 +177,4 @@ Workloads in `~/Sites/<app>` integrate with Core through three mechanisms:
# If auth is required:
- "traefik.http.routers.${CONTAINER_NAME}.middlewares=authelia-auth@docker"
```
3. **Execution & State Isolation**: `appctl` and `gitops_dispatcher.py` validate the manifest and Compose AST (blocking privilege escalation and out-of-bounds mounts) 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>/`.
+2 -2
View File
@@ -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]
(Ephemeral Container) (Host Daemon)
(:host act_runner) (Host Daemon)
```
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.
- Prevents broken code, misconfigured flakes, or regression bugs from entering `main`.
2. **Post-Merge CD Execution (`homelab-gitops.service`)**:
+53 -5
View File
@@ -109,7 +109,7 @@ tail -n 20 /var/lib/dynu/ip_history.jsonl
## 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
```bash
@@ -145,7 +145,7 @@ appctl restart docs
appctl restart traefik
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
# Stream live container logs
@@ -158,13 +158,13 @@ appctl config docs
### 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.
- **Update Command**: `appctl update <workload>` performs pre-flight verification, branch matching, `git pull --ff-only`, container image pull, stack reload, and dashboard synchronization.
- **GitOps Webhook Dispatch**: Workloads registered in `~/Workloads/deployments.yaml` (with `config/deployments.yaml` as the example template) can be triggered automatically via authenticated GitOps webhooks on Gitea push events.
- **Daemon Permissions**: `homelab-appctl.service` holds read-write permissions over `~/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`)
- **Host Foundation & Invariant Boundary**: Core defines NixOS host definitions, platform secrets, edge ingress, and security sandboxes.
@@ -587,3 +587,51 @@ If unexpected service degradation occurs during the cutover:
3. **Log rollback reason**:
Record the diagnostic failure logs in `journalctl -xe` and investigate before attempting another cutover window.
---
## 8. Read-Only Agent Inspection (`agents` SSH Identity)
For automated troubleshooting and agentic workflows, use the dedicated `agents` SSH user instead of the `operator` account.
### Workstation Setup
1. Generate a dedicated Ed25519 keypair on the workstation (if not already provisioned during setup):
```bash
ssh-keygen -t ed25519 -f ~/.ssh/canopy_agents -C "canopy-agents"
```
2. Register the `.pub` key in `users.users.agents.openssh.authorizedKeys.keys` (`nixos/configuration.nix`) and rebuild NixOS.
3. Add a host entry to `~/.ssh/config` (using your server hostname or `server.example.test`):
```sshconfig
Host server-agents
HostName <server-host>
User agents
IdentityFile ~/.ssh/canopy_agents
IdentitiesOnly yes
```
### Safe Read-Only Usage Examples
Commands are passed non-interactively over SSH and validated by the `ForceCommand` wrapper:
```bash
# Container status and logs (via read-only socket-proxy)
ssh server-agents "docker ps"
ssh server-agents "docker logs --tail 50 <container>"
ssh server-agents "docker inspect <container>"
# Platform & workload status
ssh server-agents "appctl list --core"
ssh server-agents "appctl status"
ssh server-agents "appctl info <app>"
# Systemd service logs
ssh server-agents "journalctl -u homelab-appctl -n 5"
```
### Security Boundaries & Allowlist
The `agents` account is constrained at both the OS and OpenSSH layers (`nixos/configuration.nix` and `nixos/scripts/agents-force-command.sh`):
- **Allowlisted commands only (`Match User agents` `ForceCommand`)**:
- `docker`: `ps`, `logs`, `inspect` only (routed to `DOCKER_HOST=tcp://127.0.0.1:2375`; `-H`, `--host`, `--context`, `-c`, and `--config` overrides are rejected).
- `appctl`: `list`, `status`, `info`, `logs`, `ssl`, `health`, `resolve` only.
- `journalctl`: read-only queries only (mutating flags such as `--flush`, `--rotate`, `--vacuum-*`, `--relinquish-var`, `--sync`, `--setup-keys`, and `--update-catalog` are rejected).
- Empty commands, control characters, and shell metacharacters (`;`, `&`, `|`, `` ` ``, `$`, `(`, `)`, `<`, `>`, `\`, `'`, `"`) are rejected.
- **No privilege escalation or interactive shell**: `agents` is not in `wheel` or `docker`, has no `sudo` access, and OpenSSH enforces `PermitTTY no`, `PasswordAuthentication no`, `AllowTcpForwarding no`, `X11Forwarding no`, and `AllowAgentForwarding no`.
- **No host state write access**: `agents` has no write permissions to `~/Core`, `~/Workloads`, or `~/var/lib/homelab/*`.
+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`).
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
Generated
+7 -7
View File
@@ -2,11 +2,11 @@
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1792773339,
"narHash": "sha256-17eNBI5Khe4JZaRkL5hRGPWf8MZ6qv+bWAr4V8YeKBw=",
"rev": "3ec636362e1816bc2f0888fa0fa2c69f1bc9e504",
"lastModified": 1795234589,
"narHash": "sha256-pAEASBc6wof0S58XcSEdZoQ2iFQDkCnZwH+wFLrkd1Q=",
"rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f",
"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": {
"type": "tarball",
@@ -26,11 +26,11 @@
]
},
"locked": {
"lastModified": 1792056300,
"narHash": "sha256-YU1LjDe1o2Ymg5zEiCHbmMXLkDCtxHQRiVqZ3nC5GGk=",
"lastModified": 1794866654,
"narHash": "sha256-Y28AMB8lyKjASdJ0BVsR2AqR1cUsVuo8RVVpzHoECho=",
"owner": "Mic92",
"repo": "sops-nix",
"rev": "44931708c62937c2b1bf7953902989fa5bb9ee1b",
"rev": "7c637afdccdf9bcf35c4a2d67b58a77c1fd843a4",
"type": "github"
},
"original": {
+30 -2
View File
@@ -68,7 +68,7 @@
networking.hostName = "server";
networking.networkmanager.enable = true;
# ── User account ─────────────────────────────────────────────────────────────
# ── User accounts ────────────────────────────────────────────────────────────
users.users.${config.homelab.operatorUser} = {
isNormalUser = true;
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 ──────────────────────────────────────────────────────────────────────
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;
ports = [ 22 ];
settings.PermitRootLogin = "no";
extraConfig = ''
Match User agents
ForceCommand ${agentsForceCommand}/bin/agents-force-command
AllowTcpForwarding no
X11Forwarding no
AllowAgentForwarding no
PermitTTY no
PasswordAuthentication no
'';
};
# ── Virtualisation ───────────────────────────────────────────────────────────
+4 -2
View File
@@ -110,7 +110,7 @@
'';
# Define the keys to decrypt from secrets.yaml
sops.secrets = (lib.genAttrs [
"dynu/api_key"
"cloudflare/dns_api_token"
"traefik/acme_email"
"authelia/session_secret"
"authelia/storage_encryption_key"
@@ -145,7 +145,7 @@
DOMAIN = config.homelab.domain;
LLDAP_LDAP_BASE_DN = ldapBaseDn;
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";
AUTHELIA_SESSION_SECRET = config.sops.placeholder."authelia/session_secret";
AUTHELIA_STORAGE_ENCRYPTION_KEY = config.sops.placeholder."authelia/storage_encryption_key";
@@ -326,6 +326,8 @@
"d ${config.homelab.coreDir}/config/stalwart/data 0777 ${config.homelab.operatorUser} users -"
"d ${config.homelab.coreDir}/config/stalwart/etc 0777 ${config.homelab.operatorUser} users -"
"d ${config.homelab.sitesDir} 0755 ${config.homelab.operatorUser} users -"
"a+ ${config.homelab.coreDir}/config/authelia - - - - d:u:1000:rwX,u:1000:rwx,m::rwx"
"a+ ${config.homelab.coreDir}/config/authelia/db.sqlite3 - - - - u:1000:rw,m::rw"
"a+ ${config.homelab.coreDir}/config/authelia/emails.txt - - - - u:1000:rw,m::rw"
"d /home/${config.homelab.operatorUser}/.local/state/homelab/gitops 0755 ${config.homelab.operatorUser} users -"
"d /home/${config.homelab.operatorUser}/.local/state/homelab/docker 0755 ${config.homelab.operatorUser} users -"
+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:
smtp_login: ENC[AES256_GCM,data:zfqKsAtoAOWCrSqx38sknwcJZT2m8W2J,iv:tMwTNDf+2CE3/8rKqWTWLl5Zp4LUVNSFV90QN94VXxo=,tag:XYXz9w3oIa0qkcfjCcgcYg==,type:str]
smtp_key: ENC[AES256_GCM,data:YulXyaVF/sLWE9x12yxdBAj9KMbfP/CK/7FS3XkYO8sCj3GWgPbNoSaUT/9quLWHPtCsBxxdLeLoDNa1jE2WRyHP1W+Ioyyx5sAzdzevzHIBmfP+fdw0rKhe,iv:QT0HfzNPsTqXlN3IC/+bBzJfUzN9YkXYiv/3uqkXHBw=,tag:vBetkZPDYoh0Yy3BpMT9BQ==,type:str]
cloudflare:
account_name: ENC[AES256_GCM,data:fIuzvJbLoz/w,iv:tT3rCldA9hqHzKjJa4gENTk/XprzS5X6Wm/rqkb6jow=,tag:p0aEezfUFlJn25PdW/DAOA==,type:str]
global_api_key: ENC[AES256_GCM,data:IDFHetxM2LE1/cytHo2Jn16piLeIvM27ui3Qld4Z5hwWauDRaY05nZH6+V6ic9dYFfagvA==,iv:9q3cosnJ+eC1BLmQ1Hx1y3Dksyc5k4UMQPZ6Or9vWFE=,tag:k/RilX02EJzMWZcfzBtu4A==,type:str]
account_id: ENC[AES256_GCM,data:/IyUXySFGQSGs16Kv6yZajMiGTxwOuxILvcFZ/6YROo=,iv:TdMwtzs/LMnbhpsEbqunj4n+P+JxcscYGKaM42fYQ20=,tag:HHmIq03Jc4g8fBvuaWevAA==,type:str]
dns_api_token: ENC[AES256_GCM,data:lTByYg0BM+mloaHDb2WkN7LY9twnVzKn6NO8W1rTH5FXyWaNlEovLxCPT2sG+JuRfqGJ52w=,iv:nBX3rUSdf1wFSTz0sY/ApNKVaYkCPJAJPhmMu+abzhE=,tag:LK8qyYap/T1HZb+jWnHyuA==,type:str]
appctl:
tokens_json: ENC[AES256_GCM,data:O2vsiMMcZjsduFSRen1MnnckdRYK45aPH40EhX42h1WUwf62Nm58PV5BQJOgJ97AH3hOH97mzg1tjL0C1oV/epXMaypRWY9AGLS00CfzD2sgdM5Wx7VKbfGggFnGqgd7veaCA+pxUC0uTk/Dq2Cz/uhXhLX1wVjafX0OAqS6fxO+L9Oza3+RBtKgx2xX0AKW+KSZQUM1nvNW8R/Eyvnqvw2OSb2FdKN1CKhlVWhCZiaxTe8617BqGhJDL9pu4lfn0m+tdIwvluI3h8cmKuT6dzd01Jxr0EHBY/+mZZ/WQoNhIy4QulFpKiMudiT+WGzUm+UT4mYBoGwzQCVV8MD7W1r84mkbCkLc/HpWG08TqK4tpAdtLgYK3Zslr1+lmboWyJ6WcinmxkhUexhj+gTyfXYmVSB3fF8PIeyQINGB3rLvmpZ7DDMzYa1ICgFbJ6zmYa54TXRDLGzLD09koeDp9FhXNKPvuwz2x4uwWDDUfU8wwTkGbw==,iv:FJpB+WZiE4PKUhIuwBWIB/TLtifwCzGRMtbMx7x6ly8=,tag:NZQXYFnVBqbOONl+Yh3tuA==,type:str]
sops:
@@ -60,7 +65,7 @@ sops:
yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A==
-----END AGE ENCRYPTED FILE-----
recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg
lastmodified: "2026-10-19T20:40:13Z"
mac: ENC[AES256_GCM,data:rui8qF/l3ucq8vrZniHtGjlLGPq7ihteKK7rcaz2prRvmo7nHd97Axt7oElo050HFuoaJB1/coVPzYcAUozjZNsNx3TQYABGFWvxF5Y0SxjdLc1rqAjGR/j2Cf5wmvF9H457KBHfij2gQHY/ZZ2Nyd9aEpAKSFtKkn3aYkmTvW4=,iv:RdQWUpkahFEYEhd9kTpPG0GMJaHr7b+wbhf5MBhk6mo=,tag:1E3mcFk/EMnJNNxuZ6AXAw==,type:str]
lastmodified: "2026-11-23T20:45:18Z"
mac: ENC[AES256_GCM,data:3Rm8olJtCErH+KGisvQENqwFhMF3Y9acXjrBHC7ot3ThRzT8Yo3X1RyxKXzyYzB6Yy2G3ua9yUtgQjydXgjQR1b6KY6ERmyu6H2S1IF/Ps4grYVZ6xEhJMDtjNKDvhtjhRM61eFByeYzJeHWD6K8dsxDcWUI2GKRRH7U8iG95Fo=,iv:/IY6iKamEEoi5vVLRGOmmPpyJte3amLfjVhYIDbMdBE=,tag:gT3RSrnwl0TH14LJvbiPlg==,type:str]
unencrypted_suffix: _unencrypted
version: 3.13.3
+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}"
)
+103 -2
View File
@@ -1394,7 +1394,7 @@ def _fake_group_lookup(key: str | int) -> tuple[str, int]:
raise KeyError(key)
def test_capability_grants_positive_device_group_and_ro_volumes(tmp_path: Path):
def test_validate_compose_security_permits_granted_stack(tmp_path: Path):
"""Positive ADR-0005 grants: render<->303, existing device, short & long :ro readOnlyPaths."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
@@ -1502,6 +1502,7 @@ services:
(" user: '1000:0'", "user"),
(" user: '1000:docker'", "docker"),
(" user: '1000:44'", "44"),
(" user: '1000:999'", "999"),
(" group_add:\n - '303'", "group_add"),
(" network_mode: 'container:traefik'", "container:traefik"),
(" network_mode: 'service:web'", "service:web"),
@@ -1509,7 +1510,7 @@ services:
(" user: '${PUID}:1000'", "interpolation"),
],
)
def test_capability_grants_negative_and_bypass_cases(
def test_validate_compose_security_rejects_ungranted_capabilities(
tmp_path: Path, compose_body: str, expected_substr: str
):
"""Ensure bypass vectors and ungranted capabilities fail closed."""
@@ -1751,3 +1752,103 @@ def test_capability_grants_malformed_grants_fail_closed(tmp_path: Path):
assert ok is False
assert err is not None and "grants" in err.lower()
def test_validate_compose_security_allows_ungranted_gid_1000(tmp_path: Path):
"""Ensure unprivileged numeric GID >= 1000 (1000:1000) is allowed without a grant."""
app_dir = tmp_path / "Workloads" / "ungranted"
app_dir.mkdir(parents=True)
grants_file = _write_grants(tmp_path / "grants.json", {})
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
"services:\n app:\n image: alpine\n user: '1000:1000'\n",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="ungranted",
grants_file=grants_file,
group_lookup=_fake_group_lookup,
)
assert ok is True
assert err is None
def test_validate_compose_security_rejects_high_numeric_gid_for_privileged_group(
tmp_path: Path,
):
"""Ensure numeric GID >= 1000 that resolves to a privileged group (docker) fails closed."""
app_dir = tmp_path / "Workloads" / "ungranted"
app_dir.mkdir(parents=True)
grants_file = _write_grants(tmp_path / "grants.json", {})
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
"services:\n app:\n image: alpine\n user: '1000:1998'\n",
encoding="utf-8",
)
def lookup_with_high_docker(key: str | int) -> tuple[str, int]:
if key in (1998, "1998"):
return ("docker", 1998)
return _fake_group_lookup(key)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="ungranted",
grants_file=grants_file,
group_lookup=lookup_with_high_docker,
)
assert ok is False
assert err is not None and "docker" in err.lower()
def test_validate_compose_security_rejects_sibling_prefix_paths(tmp_path: Path):
"""Ensure sibling directory prefixes (/dev/dri2, /mnt/media2) cannot bypass containment."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
granted_dev = tmp_path / "dev" / "dri"
granted_dev.mkdir(parents=True)
sibling_dev_dir = tmp_path / "dev" / "dri2"
sibling_dev_dir.mkdir(parents=True)
sibling_node = sibling_dev_dir / "renderD128"
sibling_node.write_text("", encoding="utf-8")
granted_media = tmp_path / "mnt" / "media"
granted_media.mkdir(parents=True)
sibling_media = tmp_path / "mnt" / "media2"
sibling_media.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{
"media": {
"devices": [str(granted_dev)],
"readOnlyPaths": [str(granted_media)],
}
},
)
dev_compose = app_dir / "dev-compose.yml"
dev_compose.write_text(
f"services:\n app:\n image: alpine\n devices:\n - '{sibling_node}:/dev/dri/renderD128:rw'\n",
encoding="utf-8",
)
ok_dev, _ = gitops_dispatcher.validate_compose_security(
dev_compose, app_dir, app_name="media", grants_file=grants_file
)
assert ok_dev is False
vol_compose = app_dir / "vol-compose.yml"
vol_compose.write_text(
f"services:\n app:\n image: alpine\n volumes:\n - '{sibling_media}:/media:ro'\n",
encoding="utf-8",
)
ok_vol, _ = gitops_dispatcher.validate_compose_security(
vol_compose, app_dir, app_name="media", grants_file=grants_file
)
assert ok_vol is False
+7 -5
View File
@@ -133,8 +133,9 @@ def test_load_workload_grants_verify_permissions_rejects_non_root_owner(
load_workload_grants(grants_path, verify_permissions=True)
@pytest.mark.parametrize("bad_mode", [0o100664, 0o100660, 0o100642, 0o100646])
def test_load_workload_grants_verify_permissions_rejects_writable_mode(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bad_mode: int
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
@@ -142,14 +143,15 @@ def test_load_workload_grants_verify_permissions_rejects_writable_mode(
monkeypatch.setattr(
os,
"lstat",
lambda _p: SimpleNamespace(st_mode=0o100664, st_uid=0),
lambda _p: SimpleNamespace(st_mode=bad_mode, st_uid=0),
)
with pytest.raises(WorkloadGrantsError, match="writable"):
load_workload_grants(grants_path, verify_permissions=True)
def test_load_workload_grants_verify_permissions_accepts_root_0640(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
@pytest.mark.parametrize("good_mode", [0o100640, 0o100644])
def test_load_workload_grants_verify_permissions_accepts_non_writable_mode(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, good_mode: int
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
@@ -157,6 +159,6 @@ def test_load_workload_grants_verify_permissions_accepts_root_0640(
monkeypatch.setattr(
os,
"lstat",
lambda _p: SimpleNamespace(st_mode=0o100640, st_uid=0),
lambda _p: SimpleNamespace(st_mode=good_mode, st_uid=0),
)
assert load_workload_grants(grants_path, verify_permissions=True) == {}