From 33fda26dc1bef0bc749b9b4d67298419f2f2a94d Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Wed, 18 Nov 2026 14:47:51 -0500 Subject: [PATCH 1/5] 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 --- scripts/appctl_auth.py | 15 ++++-- scripts/appctl_daemon.py | 2 +- scripts/gitops_dispatcher.py | 8 +--- tests/security/test_gitops_security.py | 50 ++++++++++++++++++++ tests/unit/test_appctl_auth.py | 45 ++++++++++++++++++ tests/unit/test_appctl_daemon.py | 63 ++++++++++++++++++++++++++ tests/unit/test_appctl_router.py | 1 + 7 files changed, 174 insertions(+), 10 deletions(-) diff --git a/scripts/appctl_auth.py b/scripts/appctl_auth.py index 3d41b7e..0d914a5 100644 --- a/scripts/appctl_auth.py +++ b/scripts/appctl_auth.py @@ -34,7 +34,12 @@ except ImportError: DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json") 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( @@ -227,8 +232,12 @@ def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[s """ if deployments_path is not None: reg_file = Path(deployments_path) - elif "HOMELAB_DEPLOYMENTS_FILE" in os.environ: - reg_file = Path(os.environ["HOMELAB_DEPLOYMENTS_FILE"]) + elif env_deploy := os.environ.get("HOMELAB_DEPLOYMENTS_FILE"): + reg_file = Path(env_deploy) + elif env_workloads := ( + os.environ.get("WORKLOADS_DIR") or os.environ.get("SITES_DIR") + ): + reg_file = Path(env_workloads) / "deployments.yaml" else: reg_file = DEFAULT_DEPLOYMENTS_FILE diff --git a/scripts/appctl_daemon.py b/scripts/appctl_daemon.py index 8d544d9..df18223 100755 --- a/scripts/appctl_daemon.py +++ b/scripts/appctl_daemon.py @@ -64,7 +64,7 @@ WORKLOADS_DIR = Path( ) SITES_DIR = WORKLOADS_DIR 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( diff --git a/scripts/gitops_dispatcher.py b/scripts/gitops_dispatcher.py index 20262f0..a95f6c8 100755 --- a/scripts/gitops_dispatcher.py +++ b/scripts/gitops_dispatcher.py @@ -47,7 +47,7 @@ CONFIG_DIR = Path( os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab")) ) 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( os.environ.get("GITOPS_SECRET_FILE", "/run/secrets/gitops/webhook_secret") @@ -265,11 +265,7 @@ def get_trusted_repository_mapping() -> dict[str, Path]: """ mapping: dict[str, Path] = {} - registry_file = ( - DEPLOYMENTS_FILE - if DEPLOYMENTS_FILE.is_file() - else (CONFIG_DIR / "deployments.yaml") - ) + registry_file = DEPLOYMENTS_FILE if not registry_file.is_file(): logger.error( f"Authoritative registry {registry_file} not found. Failing closed with zero admitted repositories." diff --git a/tests/security/test_gitops_security.py b/tests/security/test_gitops_security.py index f949a49..f923e24 100644 --- a/tests/security/test_gitops_security.py +++ b/tests/security/test_gitops_security.py @@ -269,6 +269,56 @@ def test_registry_resolves_workloads_and_sites_tilde_prefixes( assert gitops_dispatcher.resolve_repository("valid") is None +def test_deployments_file_defaults_to_workloads_and_does_not_fallback( + tmp_path: Path, monkeypatch +): + """Ensure DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml and fails closed without CONFIG_DIR/CORE_DIR fallback.""" + import os + import subprocess + import sys + + scripts_dir = str(Path(__file__).resolve().parents[2] / "scripts") + base_env = { + k: v + for k, v in os.environ.items() + if k not in {"HOMELAB_DEPLOYMENTS_FILE", "WORKLOADS_DIR", "SITES_DIR"} + } + base_env["HOME"] = str(tmp_path) + base_env["PYTHONPATH"] = scripts_dir + + resolved_default = subprocess.check_output( + [sys.executable, "-c", "import gitops_dispatcher; print(gitops_dispatcher.DEPLOYMENTS_FILE)"], + env=base_env, + text=True, + ).strip() + expected_default = tmp_path / "Workloads" / "deployments.yaml" + assert Path(resolved_default) == expected_default + + # Even if CONFIG_DIR/deployments.yaml exists, missing DEPLOYMENTS_FILE must fail closed + 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", expected_default) + monkeypatch.setattr(gitops_dispatcher, "CONFIG_DIR", config_dir) + assert gitops_dispatcher.get_trusted_repository_mapping() == {} + + # WORKLOADS_DIR override when HOMELAB_DEPLOYMENTS_FILE is unset + custom_workloads = tmp_path / "CustomWorkloads" + env_with_workloads = dict(base_env, WORKLOADS_DIR=str(custom_workloads)) + resolved_override = subprocess.check_output( + [sys.executable, "-c", "import gitops_dispatcher; print(gitops_dispatcher.DEPLOYMENTS_FILE)"], + env=env_with_workloads, + text=True, + ).strip() + assert Path(resolved_override) == custom_workloads / "deployments.yaml" + + def test_webhook_verification_valid_signature(): """Ensure valid HMAC-SHA256 signature passes verification.""" import hashlib diff --git a/tests/unit/test_appctl_auth.py b/tests/unit/test_appctl_auth.py index 97c9b15..20eee2c 100644 --- a/tests/unit/test_appctl_auth.py +++ b/tests/unit/test_appctl_auth.py @@ -492,3 +492,48 @@ def test_rbac_viewer_denied_on_sensitive_reads(): enforce_rbac(viewer, sens_op, "snappymail") assert "not permitted to access sensitive operation" in str(exc_info.value) assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED + + +def test_default_deployments_file_resolves_to_workloads_dir( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """DEFAULT_DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml and fails closed when absent.""" + import os + import subprocess + import sys + + import appctl_auth + + scripts_dir = str(Path(__file__).resolve().parents[2] / "scripts") + env = { + k: v + for k, v in os.environ.items() + if k not in {"HOMELAB_DEPLOYMENTS_FILE", "WORKLOADS_DIR", "SITES_DIR"} + } + env["HOME"] = str(tmp_path) + env["PYTHONPATH"] = scripts_dir + + resolved = subprocess.check_output( + [sys.executable, "-c", "import appctl_auth; print(appctl_auth.DEFAULT_DEPLOYMENTS_FILE)"], + env=env, + text=True, + ).strip() + expected = tmp_path / "Workloads" / "deployments.yaml" + assert Path(resolved) == expected + + # Absent ~/Workloads/deployments.yaml must fail closed (no CORE_DIR fallback) + 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", expected) + assert appctl_auth.load_admitted_workloads() == set() + + # WORKLOADS_DIR takes precedence when HOMELAB_DEPLOYMENTS_FILE is unset + 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.setenv("WORKLOADS_DIR", str(custom_workloads)) + assert appctl_auth.load_admitted_workloads() == {"custom_app"} diff --git a/tests/unit/test_appctl_daemon.py b/tests/unit/test_appctl_daemon.py index 56106ff..9ae95fe 100644 --- a/tests/unit/test_appctl_daemon.py +++ b/tests/unit/test_appctl_daemon.py @@ -591,3 +591,66 @@ def test_gitops_dispatcher_delegates_to_daemon(daemon_env, monkeypatch): ) assert success is True assert mock_sub.call_count >= 1 + + +def test_daemon_deployments_file_defaults_to_workloads_and_fails_closed( + daemon_env, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """ + DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml (or WORKLOADS_DIR/deployments.yaml) + and homelab-operator fails closed (403) when ~/Workloads/deployments.yaml is absent. + """ + import os + import subprocess + import sys + + import appctl_auth + + scripts_dir = str(Path(__file__).resolve().parents[2] / "scripts") + base_env = { + k: v + for k, v in os.environ.items() + if k not in {"HOMELAB_DEPLOYMENTS_FILE", "WORKLOADS_DIR", "SITES_DIR"} + } + base_env["HOME"] = str(tmp_path) + base_env["PYTHONPATH"] = scripts_dir + + resolved_default = subprocess.check_output( + [sys.executable, "-c", "import appctl_daemon; print(appctl_daemon.DEPLOYMENTS_FILE)"], + env=base_env, + text=True, + ).strip() + assert Path(resolved_default) == tmp_path / "Workloads" / "deployments.yaml" + + # WORKLOADS_DIR override when HOMELAB_DEPLOYMENTS_FILE is unset + custom_workloads = tmp_path / "CustomWorkloads" + env_with_workloads = dict(base_env, WORKLOADS_DIR=str(custom_workloads)) + resolved_override = subprocess.check_output( + [sys.executable, "-c", "import appctl_daemon; print(appctl_daemon.DEPLOYMENTS_FILE)"], + env=env_with_workloads, + text=True, + ).strip() + assert Path(resolved_override) == custom_workloads / "deployments.yaml" + + # 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 diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 70ee7b1..9b45cef 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -1416,6 +1416,7 @@ def test_operational_router_workload_update_propagates_non_zero_exit_and_stderr( return (0, "", "") with ( + patch("appctl_router.load_admitted_workloads", return_value={"snappymail"}), patch("appctl_router.resolve_app", return_value=mock_app), patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), patch("appctl_router.cmd_sync_homepage"), From df7c1f52924c1d708e7d7717e063812d62ef7f9f Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Wed, 18 Nov 2026 14:52:12 -0500 Subject: [PATCH 2/5] chore(nixos): point deployments registry to ~/Workloads/deployments.yaml - 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 --- AGENTS.md | 2 +- README.md | 2 +- config/deployments.yaml | 54 ++++++++---------------------------- docs/architecture.md | 2 +- docs/decisions/README.md | 2 +- docs/gitops.md | 4 +-- docs/operations.md | 4 +-- nixos/modules/homeserver.nix | 3 +- 8 files changed, 22 insertions(+), 51 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 927415d..87dc2d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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`. 2. **GitOps Trust Boundary (`scripts/gitops_dispatcher.py`)**: - Webhook admission requires cryptographic authentication (HMAC-SHA256). - - Repository identity and filesystem paths must be resolved strictly through 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`). 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`). diff --git a/README.md b/README.md index 5c8f073..28d009c 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,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 -├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml) +├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml template) ├── scripts/ │ ├── appctl # Thin operational CLI delegating to control plane daemon │ ├── appctl_daemon.py # Async HTTP/UDS daemon server (homelab-appctl.service) diff --git a/config/deployments.yaml b/config/deployments.yaml index 35b7016..00f921a 100644 --- a/config/deployments.yaml +++ b/config/deployments.yaml @@ -1,48 +1,18 @@ -# Core Authoritative Repository Identity Registry -# Governs admitted continuous deployment targets for GitOps webhook execution. +# Example Repository Identity Registry Template +# Live production deployments are configured in ~/Workloads/deployments.yaml +# (or overridden via the HOMELAB_DEPLOYMENTS_FILE environment variable). +# # Owns: repository identity, canonical filesystem path, and aliases. -# Enforces: strict path containment within ~/Workloads. +# Enforces: strict path containment within ~/Workloads (WORKLOADS_DIR). schemaVersion: "1.0" repositories: - snappymail: - path: "~/Workloads/snappymail" + example-app: + path: "~/Workloads/example-app" aliases: - - "homelab-snappymail" - - "mail" - - "webmail" - gitea: - path: "~/Workloads/homelab-gitea" + - "example" + - "homelab-example" + example-docs: + path: "~/Workloads/example-docs" aliases: - - "homelab-gitea" - - "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" + - "docs" diff --git a/docs/architecture.md b/docs/architecture.md index e60ea1c..438eb3a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -52,7 +52,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. -* **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. --- diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 4bc6ed3..a3b57b8 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -26,7 +26,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. 2. **Unified `canopy-workloads` Monorepo**: Tier 2 workload manifests (`app.yaml`, `docker-compose.yml`) consolidate under `~/Workloads//`, supporting hybrid per-app `.git` checkouts during migration. 3. **Mandatory State Isolation**: All mutable application data resides strictly under `~/var/lib/homelab//` (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) * **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md) diff --git a/docs/gitops.md b/docs/gitops.md index ed30e70..4bf1c60 100644 --- a/docs/gitops.md +++ b/docs/gitops.md @@ -27,7 +27,7 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni ▼ ┌───────────────────────────────────────────────┐ │ 3. Authoritative Registry Resolution │ - │ Maps names via Core/config/deployments.yaml│ + │ Maps names via ~/Workloads/deployments.yaml│ │ 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`) * 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`. * **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. diff --git a/docs/operations.md b/docs/operations.md index 7fa71bd..48e22ac 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -163,12 +163,12 @@ Homelab enforces a strict architectural boundary between independent application #### 1. Independent Sites Workloads (`~/Sites/`) - **Automated Lifecycle**: Workloads declare their lifecycle via `app.yaml` manifests and Compose definitions. - **Update Command**: `appctl update ` 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. #### 2. Homelab Core Platform Stack (`~/Core`) - **Host Foundation & Invariant Boundary**: Core defines NixOS host definitions, platform secrets, edge ingress, and security sandboxes. -- **No Untrusted Webhooks**: Core does **not** register for webhook dispatch in `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. - **Operator-Driven Update Workflow**: Core updates must be executed explicitly by the operator: 1. Review and pull repository changes: diff --git a/nixos/modules/homeserver.nix b/nixos/modules/homeserver.nix index a619586..0f798d8 100644 --- a/nixos/modules/homeserver.nix +++ b/nixos/modules/homeserver.nix @@ -138,6 +138,7 @@ HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab"; WORKLOADS_DIR = config.homelab.sitesDir; SITES_DIR = config.homelab.sitesDir; + HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.sitesDir}/deployments.yaml"; }; serviceConfig = { @@ -217,7 +218,7 @@ CORE_DIR = config.homelab.coreDir; HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab"; HOMELAB_CONFIG_DIR = "/home/${config.homelab.operatorUser}/.config/homelab"; - HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.coreDir}/config/deployments.yaml"; + HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.sitesDir}/deployments.yaml"; }; serviceConfig = { From c337914fb32ea5db09458b32b030dcbcd1bc4674 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Wed, 18 Nov 2026 19:41:34 -0500 Subject: [PATCH 3/5] 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) --- scripts/appctl_auth.py | 5 +++-- scripts/gitops_dispatcher.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/scripts/appctl_auth.py b/scripts/appctl_auth.py index 0d914a5..4764c73 100644 --- a/scripts/appctl_auth.py +++ b/scripts/appctl_auth.py @@ -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 - Mandatory Bearer tokens for all network (HTTP) operations and all mutations / sensitive reads - 3-role RBAC enforcement (homelab-admin, homelab-operator, homelab-viewer) -- Workload scope gating against 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 @@ -227,7 +227,8 @@ class TokenStore: 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. """ if deployments_path is not None: diff --git a/scripts/gitops_dispatcher.py b/scripts/gitops_dispatcher.py index a95f6c8..cdb8336 100755 --- a/scripts/gitops_dispatcher.py +++ b/scripts/gitops_dispatcher.py @@ -260,7 +260,7 @@ def get_trusted_repository_mapping() -> dict[str, Path]: """ Build authoritative mapping of logical repository identities to local paths. 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. """ mapping: dict[str, Path] = {} From 9306dae56b19ca45b3749e11f9d7f89c22c7a1b5 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Wed, 18 Nov 2026 19:45:42 -0500 Subject: [PATCH 4/5] 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 --- tests/conftest.py | 53 ++++++++++++++++++++++++++ tests/security/test_gitops_security.py | 33 ++++------------ tests/unit/test_appctl_auth.py | 23 ++--------- tests/unit/test_appctl_daemon.py | 49 +++++++++--------------- 4 files changed, 82 insertions(+), 76 deletions(-) create mode 100644 tests/conftest.py diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..5619b86 --- /dev/null +++ b/tests/conftest.py @@ -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 diff --git a/tests/security/test_gitops_security.py b/tests/security/test_gitops_security.py index f923e24..d4ccaef 100644 --- a/tests/security/test_gitops_security.py +++ b/tests/security/test_gitops_security.py @@ -270,27 +270,12 @@ def test_registry_resolves_workloads_and_sites_tilde_prefixes( def test_deployments_file_defaults_to_workloads_and_does_not_fallback( - tmp_path: Path, monkeypatch + tmp_path: Path, monkeypatch, run_isolated_script_expr ): """Ensure DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml and fails closed without CONFIG_DIR/CORE_DIR fallback.""" - import os - import subprocess - import sys - - scripts_dir = str(Path(__file__).resolve().parents[2] / "scripts") - base_env = { - k: v - for k, v in os.environ.items() - if k not in {"HOMELAB_DEPLOYMENTS_FILE", "WORKLOADS_DIR", "SITES_DIR"} - } - base_env["HOME"] = str(tmp_path) - base_env["PYTHONPATH"] = scripts_dir - - resolved_default = subprocess.check_output( - [sys.executable, "-c", "import gitops_dispatcher; print(gitops_dispatcher.DEPLOYMENTS_FILE)"], - env=base_env, - text=True, - ).strip() + resolved_default = run_isolated_script_expr( + "import gitops_dispatcher; print(gitops_dispatcher.DEPLOYMENTS_FILE)" + ) expected_default = tmp_path / "Workloads" / "deployments.yaml" assert Path(resolved_default) == expected_default @@ -310,12 +295,10 @@ def test_deployments_file_defaults_to_workloads_and_does_not_fallback( # WORKLOADS_DIR override when HOMELAB_DEPLOYMENTS_FILE is unset custom_workloads = tmp_path / "CustomWorkloads" - env_with_workloads = dict(base_env, WORKLOADS_DIR=str(custom_workloads)) - resolved_override = subprocess.check_output( - [sys.executable, "-c", "import gitops_dispatcher; print(gitops_dispatcher.DEPLOYMENTS_FILE)"], - env=env_with_workloads, - text=True, - ).strip() + 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" diff --git a/tests/unit/test_appctl_auth.py b/tests/unit/test_appctl_auth.py index 20eee2c..81ec52e 100644 --- a/tests/unit/test_appctl_auth.py +++ b/tests/unit/test_appctl_auth.py @@ -495,29 +495,14 @@ def test_rbac_viewer_denied_on_sensitive_reads(): def test_default_deployments_file_resolves_to_workloads_dir( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run_isolated_script_expr ): """DEFAULT_DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml and fails closed when absent.""" - import os - import subprocess - import sys - import appctl_auth - scripts_dir = str(Path(__file__).resolve().parents[2] / "scripts") - env = { - k: v - for k, v in os.environ.items() - if k not in {"HOMELAB_DEPLOYMENTS_FILE", "WORKLOADS_DIR", "SITES_DIR"} - } - env["HOME"] = str(tmp_path) - env["PYTHONPATH"] = scripts_dir - - resolved = subprocess.check_output( - [sys.executable, "-c", "import appctl_auth; print(appctl_auth.DEFAULT_DEPLOYMENTS_FILE)"], - env=env, - text=True, - ).strip() + resolved = run_isolated_script_expr( + "import appctl_auth; print(appctl_auth.DEFAULT_DEPLOYMENTS_FILE)" + ) expected = tmp_path / "Workloads" / "deployments.yaml" assert Path(resolved) == expected diff --git a/tests/unit/test_appctl_daemon.py b/tests/unit/test_appctl_daemon.py index 9ae95fe..91b0323 100644 --- a/tests/unit/test_appctl_daemon.py +++ b/tests/unit/test_appctl_daemon.py @@ -593,45 +593,30 @@ def test_gitops_dispatcher_delegates_to_daemon(daemon_env, monkeypatch): assert mock_sub.call_count >= 1 -def test_daemon_deployments_file_defaults_to_workloads_and_fails_closed( - daemon_env, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +def test_daemon_deployments_file_defaults_to_workloads_and_honors_override( + tmp_path: Path, run_isolated_script_expr ): - """ - DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml (or WORKLOADS_DIR/deployments.yaml) - and homelab-operator fails closed (403) when ~/Workloads/deployments.yaml is absent. - """ - import os - import subprocess - import sys - - import appctl_auth - - scripts_dir = str(Path(__file__).resolve().parents[2] / "scripts") - base_env = { - k: v - for k, v in os.environ.items() - if k not in {"HOMELAB_DEPLOYMENTS_FILE", "WORKLOADS_DIR", "SITES_DIR"} - } - base_env["HOME"] = str(tmp_path) - base_env["PYTHONPATH"] = scripts_dir - - resolved_default = subprocess.check_output( - [sys.executable, "-c", "import appctl_daemon; print(appctl_daemon.DEPLOYMENTS_FILE)"], - env=base_env, - text=True, - ).strip() + """DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml and honors WORKLOADS_DIR override.""" + resolved_default = run_isolated_script_expr( + "import appctl_daemon; print(appctl_daemon.DEPLOYMENTS_FILE)" + ) assert Path(resolved_default) == tmp_path / "Workloads" / "deployments.yaml" # WORKLOADS_DIR override when HOMELAB_DEPLOYMENTS_FILE is unset custom_workloads = tmp_path / "CustomWorkloads" - env_with_workloads = dict(base_env, WORKLOADS_DIR=str(custom_workloads)) - resolved_override = subprocess.check_output( - [sys.executable, "-c", "import appctl_daemon; print(appctl_daemon.DEPLOYMENTS_FILE)"], - env=env_with_workloads, - text=True, - ).strip() + 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) From 7d4cfe1c048b8ab0592eb0fb79e6007da6ae4472 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Wed, 18 Nov 2026 19:56:45 -0500 Subject: [PATCH 5/5] test(gitops,appctl): split deployments.yaml path tests into single-behavior cases - 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 --- tests/security/test_gitops_security.py | 25 ++++++++++++++------- tests/unit/test_appctl_auth.py | 30 ++++++++++++++++++-------- tests/unit/test_appctl_daemon.py | 10 ++++++--- 3 files changed, 45 insertions(+), 20 deletions(-) diff --git a/tests/security/test_gitops_security.py b/tests/security/test_gitops_security.py index d4ccaef..5ebe9b8 100644 --- a/tests/security/test_gitops_security.py +++ b/tests/security/test_gitops_security.py @@ -269,17 +269,20 @@ def test_registry_resolves_workloads_and_sites_tilde_prefixes( assert gitops_dispatcher.resolve_repository("valid") is None -def test_deployments_file_defaults_to_workloads_and_does_not_fallback( - tmp_path: Path, monkeypatch, run_isolated_script_expr +def test_deployments_file_defaults_to_workloads( + tmp_path: Path, run_isolated_script_expr ): - """Ensure DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml and fails closed without CONFIG_DIR/CORE_DIR fallback.""" + """Ensure DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml.""" resolved_default = run_isolated_script_expr( "import gitops_dispatcher; print(gitops_dispatcher.DEPLOYMENTS_FILE)" ) - expected_default = tmp_path / "Workloads" / "deployments.yaml" - assert Path(resolved_default) == expected_default + assert Path(resolved_default) == tmp_path / "Workloads" / "deployments.yaml" - # Even if CONFIG_DIR/deployments.yaml exists, missing DEPLOYMENTS_FILE must fail closed + +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( @@ -289,11 +292,17 @@ def test_deployments_file_defaults_to_workloads_and_does_not_fallback( ' path: "~/Workloads/docs"\n', encoding="utf-8", ) - monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", expected_default) + 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() == {} - # WORKLOADS_DIR override when HOMELAB_DEPLOYMENTS_FILE is unset + +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)", diff --git a/tests/unit/test_appctl_auth.py b/tests/unit/test_appctl_auth.py index 81ec52e..a34f2ac 100644 --- a/tests/unit/test_appctl_auth.py +++ b/tests/unit/test_appctl_auth.py @@ -495,30 +495,42 @@ def test_rbac_viewer_denied_on_sensitive_reads(): def test_default_deployments_file_resolves_to_workloads_dir( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run_isolated_script_expr + tmp_path: Path, run_isolated_script_expr ): - """DEFAULT_DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml and fails closed when absent.""" - import appctl_auth - + """DEFAULT_DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml.""" resolved = run_isolated_script_expr( "import appctl_auth; print(appctl_auth.DEFAULT_DEPLOYMENTS_FILE)" ) - expected = tmp_path / "Workloads" / "deployments.yaml" - assert Path(resolved) == expected + 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 - # Absent ~/Workloads/deployments.yaml must fail closed (no CORE_DIR fallback) 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", expected) + monkeypatch.setattr( + appctl_auth, "DEFAULT_DEPLOYMENTS_FILE", tmp_path / "Workloads" / "deployments.yaml" + ) assert appctl_auth.load_admitted_workloads() == set() - # WORKLOADS_DIR takes precedence when HOMELAB_DEPLOYMENTS_FILE is unset + +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"} diff --git a/tests/unit/test_appctl_daemon.py b/tests/unit/test_appctl_daemon.py index 91b0323..4ad4f11 100644 --- a/tests/unit/test_appctl_daemon.py +++ b/tests/unit/test_appctl_daemon.py @@ -593,16 +593,20 @@ def test_gitops_dispatcher_delegates_to_daemon(daemon_env, monkeypatch): assert mock_sub.call_count >= 1 -def test_daemon_deployments_file_defaults_to_workloads_and_honors_override( +def test_daemon_deployments_file_defaults_to_workloads( tmp_path: Path, run_isolated_script_expr ): - """DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml and honors WORKLOADS_DIR override.""" + """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" - # WORKLOADS_DIR override when HOMELAB_DEPLOYMENTS_FILE is unset + +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)",