Compare commits

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

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

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

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

- Link ADR-0004 and ADR-0005 in ROADMAP.md and record Milestone P4.5 completion in nixos-core
2026-11-21 13:22:07 -05:00
kiskaadee ef42bfc801 fix(ci): remove container image from ci.yaml for :host act_runner (#46)
Core Architecture & Invariant CI / validate (push) Successful in 4s
Co-authored-by: kiskaadee <fcortesbio@gmail.com>
2026-11-21 18:13:01 +00:00
kiskaadee 6ba45961ae Merge pull request 'feat(nixos,security): implement homelab.workloadGrants and nixos/instance.example.nix (ADR-0005)' (#44) from feat/workload-capability-grants into main
Core Architecture & Invariant CI / validate (push) Failing after 0s
2026-11-21 17:52:43 +00:00
kiskaadee 1eed45c301 test(security,grants): harden capability grant boundaries and test names
Core Architecture & Invariant CI / validate (pull_request) Failing after 0s
- Parametrize writable and non-writable permission mode tests in tests/unit/test_workload_grants.py across 0o020/0o002 bits (CR-02)

- Add GID 999 vs 1000 boundary, high numeric GID 1998 resolving to docker, and sibling path prefix (/dev/dri2, /mnt/media2) tests in tests/security/test_gitops_security.py (CR-01)

- Rename grant stack/ungranted capability tests to match validate_compose_security() behavior (CR-03, CR-04)
2026-11-21 04:48:13 -05:00
kiskaadee 1a8e3b5eae fix(security,tests): harden compose fallback, root UID check, and split grant tests
Core Architecture & Invariant CI / validate (pull_request) Failing after 0s
- Fail closed in validate_compose_security() when PyYAML is unavailable instead of regex fallback (CR-01)

- Reject zero-padded root UIDs (e.g. 00:1000) in _validate_service_user() via int() parsing (CR-02)

- Extract _resolve_contained_host_path() and _validate_service_volumes() and add docstrings across capability helpers (CR-03, CR-04)

- Fix missing-device-node test and split multi-behavior grant tests into focused single-behavior tests (Axis 3 CR-01, CR-02)
2026-11-21 04:13:59 -05:00
kiskaadee c9f3108805 feat(security): enforce host-granted workload capabilities in validate_compose_security
- Update validate_compose_security() in scripts/gitops_dispatcher.py to enforce fail-closed workloadGrants for devices, group_add, user primary GIDs, and readOnlyPaths

- Permanently block device_cgroup_rules and container:*/service:* namespace sharing, and reject uninterpolated ${...} after resolved_env interpolation

- Pass assembled 6-layer env into validate_compose_security() in scripts/appctl_router.py and map capability denials to ERR_CAPABILITY_NOT_GRANTED

- Add comprehensive Red->Green security and router tests for positive grants and bypass vectors
2026-11-21 04:05:42 -05:00
kiskaadee 4f40668536 feat(security): add Pydantic workload grants loader, RESERVED_ENV_KEYS, and error code
- Add HOMELAB_GRANTS_FILE to RESERVED_ENV_KEYS in scripts/core_manifest.py

- Add ERR_CAPABILITY_NOT_GRANTED (HTTP 403) to ErrorCode in scripts/appctl_contracts.py

- Implement WorkloadGrant, GrantsRegistry, and load_workload_grants in scripts/workload_grants.py with strict Pydantic v2 and fail-closed permission/integrity checks

- Add unit tests for workload_grants, RESERVED_ENV_KEYS, and ErrorCode taxonomy
2026-11-21 03:58:21 -05:00
kiskaadee ce969f4678 feat(nixos): add homelab.workloadGrants option, grants.json projection, and instance.example.nix
- Define homelab.workloadGrants attrsOf submodule in nixos/modules/homeserver.nix with devices, groups, and readOnlyPaths

- Add Nix assertions rejecting privileged groups (0, root, wheel, docker) and relative/traversal paths

- Generate /etc/homelab/grants.json (root:homelab-operators 0640) and wire HOMELAB_GRANTS_FILE into homelab-appctl and homelab-gitops

- Add tracked nixos/instance.example.nix and prioritize /etc/nixos/homelab-instance.nix over nixos/instance.nix

- Add structural and security invariant tests for workloadGrants and instance.example.nix
2026-11-21 03:54:02 -05:00
kiskaadee e807a90017 docs(adr): polish Stage 8 zoom-out nits in ADR-0005
- Replace strict=True and PrivateUsers=true implementation details with architectural invariants
- State unprivileged primary UID/GID rule directly
2026-11-21 03:25:16 -05:00
kiskaadee 37d529848a docs(adr): resolve Stage 7 critic findings in ADR-0005 and README
- Close user: primary GID, device_cgroup_rules:, and network_mode: container:* bypasses
- Specify post-interpolation validation, long/short volume syntax, :ro, and :rwm mknod ban
- Reconcile absent vs unreadable/malformed grants.json behavior and permissions checks
- Add Consequences and More Information sections; sync docs/decisions/README.md
2026-11-21 00:26:44 -05:00
kiskaadee f326b11986 docs(adr): generalize ADR-0005 examples and clarify grants permissions/GIDs
- Replace specific workload names (jellyfin, lg-smtv-mcp) with capability classes
- Clarify /etc/homelab/grants.json ownership (root:homelab-operators 0640)
- Specify bidirectional name <-> GID resolution for group_add validation
- Link ADR-0001 for Tier 2/3 taxonomy and note --impure flake evaluation
2026-11-21 00:06:43 -05:00
kiskaadee 8f3b98344a docs(adr): refine ADR-0005 addressing Zoom Out and Catalyst review findings
- Drop hostNetwork grant from workloadGrants to protect 127.0.0.1:9001 appctl boundary
- Explicitly motivate groups grant by detailing jellyfin GID 303 (render) requirement
- Elevate enforcement specifications to architectural invariants
- Acknowledge host-path coupling trade-off
2026-11-20 22:58:16 -05:00
kiskaadee 92333b017c docs(adr): add ADR-0005 for host-granted workload capabilities
- Record ADR-0005 ('Compose Requests, Nix Grants') amending ADR-0002
- Define homelab.workloadGrants -> /etc/homelab/grants.json and nixos/instance.example.nix contract
- Register ADR-0005 in docs/decisions/README.md
2026-11-20 13:43:14 -05:00
kiskaadee 131e5d75a1 Merge pull request 'feat(nixos): provision read-only agents SSH user for inspection' (#42) from feat/agents-ssh-user into main
Core Architecture & Invariant CI / validate (push) Successful in 1m14s
2026-11-19 09:11:43 -05:00
kiskaadee 158bbb0eed test(security): harden agents SSH access and ForceCommand tests
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m13s
- CR-01: Test post-subcommand Docker connection/context/config override flags across ps, logs, and inspect
- CR-02: Assert exact extraGroups allowlist ({'homelab-operators', 'systemd-journal'}) for users.users.agents
- CR-03: Assert all socket-proxy published ports are non-empty loopback-only strings starting with 127.0.0.1:
- CR-04: Assert Match User agents ForceCommand targets agents-force-command
- CR-05: Add carriage-return (\r) control-character rejection test case
2026-11-18 23:10:44 -05:00
kiskaadee c104c69fbc docs(nixos): document agents SSH key setup and read-only inspection
- docs/setup_guide.md: add Step 8 covering Ed25519 key generation, NixOS authorizedKeys wiring, workstation ~/.ssh/config, and verification commands
- docs/operations.md: add Section 8 covering workstation setup, safe read-only inspection examples, and ForceCommand/group security boundaries
2026-11-18 22:51:04 -05:00
kiskaadee 11aaf6038b feat(nixos,security): provision read-only agents SSH user and ForceCommand allowlist
- Provision users.users.agents in nixos/configuration.nix with homelab-operators and systemd-journal groups (excluding wheel and docker) and canopy-agents SSH key
- Add Match User agents ForceCommand wrapper and SSH hardening (AllowTcpForwarding, X11Forwarding, AllowAgentForwarding, PermitTTY, PasswordAuthentication disabled)
- Implement nixos/scripts/agents-force-command.sh allowlisting read-only docker ps/logs/inspect, journalctl, and appctl read subcommands while rejecting metacharacters and mutating commands/flags
- Bind socket-proxy to 127.0.0.1:2375:2375 in docker-compose.yml for loopback-only read-only Docker API access
- Add TDD security and structural tests in tests/security/test_agents_access.py
2026-11-18 22:46:39 -05:00
kiskaadee 648dd49c82 fix(nixos): preserve operator home traverse ACL after users activation
Core Architecture & Invariant CI / validate (push) Successful in 27m51s
- Add system.activationScripts.homelabHomeAcl ordered after users activation
- Re-applies u:homelab-appctl:x,g:homelab-operators:x,m::rx on /home/<operatorUser>
- Prevents nixos-rebuild switch from resetting POSIX ACL mask::--- via chmod 0700 and causing homelab-appctl 200/CHDIR failures
2026-11-18 21:32:09 -05:00
kiskaadee 365801a169 Merge pull request 'feat(gitops): decouple deployments.yaml into ~/Workloads/deployments.yaml' (#41) from feat/decouple-deployments-yaml into main
Core Architecture & Invariant CI / validate (push) Successful in 21m16s
2026-11-18 21:14:17 -05:00
kiskaadee 7d4cfe1c04 test(gitops,appctl): split deployments.yaml path tests into single-behavior cases
Core Architecture & Invariant CI / validate (pull_request) Successful in 5m8s
- Split test_deployments_file_defaults_to_workloads_and_does_not_fallback in tests/security/test_gitops_security.py into 3 single-behavior tests
- Split test_default_deployments_file_resolves_to_workloads_dir in tests/unit/test_appctl_auth.py into 3 single-behavior tests
- Split test_daemon_deployments_file_defaults_to_workloads_and_honors_override in tests/unit/test_appctl_daemon.py into 2 single-behavior tests
2026-11-18 19:56:45 -05:00
kiskaadee 9306dae56b test(gitops,appctl): extract isolated env subprocess fixture and split daemon test
- Add tests/conftest.py with run_isolated_script_expr fixture stripping HOMELAB_DEPLOYMENTS_FILE, WORKLOADS_DIR, and SITES_DIR and setting HOME/PYTHONPATH
- Refactor gitops_security, appctl_auth, and appctl_daemon tests to use run_isolated_script_expr instead of duplicated subprocess env-isolation boilerplate
- Split test_daemon_deployments_file_defaults_to_workloads_and_fails_closed into a pure default/override test and a daemon_env 403 fail-closed test
2026-11-18 19:45:42 -05:00
kiskaadee c337914fb3 docs(auth,gitops): update deployments.yaml docstrings to reflect ~/Workloads registry
- Update scripts/appctl_auth.py module and load_admitted_workloads docstrings to reference ~/Workloads/deployments.yaml and HOMELAB_DEPLOYMENTS_FILE / WORKLOADS_DIR overrides instead of config/deployments.yaml
- Update scripts/gitops_dispatcher.py get_trusted_repository_mapping docstring to reference the ~/Workloads/deployments.yaml admission registry (templated by config/deployments.yaml)
2026-11-18 19:41:34 -05:00
kiskaadee df7c1f5292 chore(nixos): point deployments registry to ~/Workloads/deployments.yaml
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m14s
- Point HOMELAB_DEPLOYMENTS_FILE in nixos/modules/homeserver.nix to ${config.homelab.sitesDir}/deployments.yaml for both homelab-appctl and homelab-gitops
- Replace config/deployments.yaml with an infrastructure-agnostic schemaVersion 1.0 example template (example-app, example-docs) and remove all personal workload entries
- Sync AGENTS.md, README.md, docs/architecture.md, docs/gitops.md, docs/operations.md, and docs/decisions/README.md to reference ~/Workloads/deployments.yaml as the live registry and config/deployments.yaml as the template
2026-11-18 14:52:12 -05:00
kiskaadee 33fda26dc1 feat(gitops): default deployments.yaml to ~/Workloads/deployments.yaml
- scripts/appctl_auth.py: default DEFAULT_DEPLOYMENTS_FILE to WORKLOADS_DIR/SITES_DIR or ~/Workloads/deployments.yaml and honor WORKLOADS_DIR in load_admitted_workloads()
- scripts/appctl_daemon.py: default DEPLOYMENTS_FILE to WORKLOADS_DIR/deployments.yaml (~/Workloads/deployments.yaml) instead of CORE_DIR/config/deployments.yaml
- scripts/gitops_dispatcher.py: default DEPLOYMENTS_FILE to WORKLOADS_DIR/deployments.yaml and remove CONFIG_DIR/deployments.yaml fallback in get_trusted_repository_mapping() so missing registry fails closed
- tests: add regression tests for default ~/Workloads/deployments.yaml resolution and fail-closed behavior; isolate test_operational_router_workload_update_propagates_non_zero_exit_and_stderr from host registry
2026-11-18 14:47:51 -05:00
kiskaadee f0db802f72 fix(tmpfiles): grant authelia uid 1000 write on emails.txt
Core Architecture & Invariant CI / validate (push) Successful in 1m11s
- Replace the z 0604 rule (other-read only) with an a+ ACL rule
- Grant uid 1000 rw with an explicit m::rw mask; no world-writable mode
- The filesystem notifier opens /config/emails.txt for append at startup,
  so read-only access left authelia in a fatal restart loop
2026-11-18 07:30:10 -05:00
kiskaadee 514409939d feat(nixos): add activation guard preventing example.test domain deployment
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m16s
Core Architecture & Invariant CI / validate (push) Successful in 1m19s
- Add system.activationScripts.checkHomelabDomain that aborts activation
  if homelab.domain defaults to 'example.test'
- Prevents silent deployment with placeholder domains when --impure flag
  is omitted from nixos-rebuild
- Guard runs only during activation (not during nix eval), so workstation
  tests remain unaffected
2026-11-17 16:59:50 -05:00
kiskaadee a5826e0e74 fix(scripts): rename test runner to run-tests to avoid shadowing POSIX test
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m10s
Core Architecture & Invariant CI / validate (push) Successful in 1m9s
- Rename scripts/test to scripts/run-tests to eliminate name collision with standard POSIX test (/usr/bin/test, [)
- Prevent nixos-rebuild-ng activation safety assertions (test -f) from invoking the Python test suite instead of coreutils test
- Update test runner invocation paths across AGENTS.md, README.md, ROADMAP.md, SECURITY.md, and documentation runbooks
2026-11-17 14:53:34 -05:00
kiskaadee cdd2d562c3 feat(gitops): support canopy-workloads monorepo dispatch and remote build URLs (#33)
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m10s
Core Architecture & Invariant CI / validate (push) Successful in 1m15s
- Add is_monorepo_push, extract_monorepo_changed_subdirs, and dispatch_monorepo_push in gitops_dispatcher.py to pull ~/Workloads once under lock and dispatch only affected admitted deployments.yaml subdirectories
- Add build context validation in validate_compose_security() permitting remote Git/HTTP URLs (https://, http://, ssh://, git@, git://), enforcing allowed_root containment on local build contexts, and rejecting ${...} variable interpolation
- Add security tests in test_gitops_security.py for remote build URLs, unsafe build context escapes/interpolation, and monorepo webhook dispatch
2026-11-16 14:08:07 -05:00
kiskaadee 2df95648d4 feat(provenance,router): support hybrid ~/Workloads monorepo subpath inspection and git pull (#33)
- Update provenance.get_local_checkout_status to check <workload_dir>/.git first and fall back to <parent>/.git with subpath-scoped git status --porcelain -- <app>/
- Update OperationalRouter._op_workload_update via _resolve_git_context to target parent monorepo .git for status, pull --ff-only, and rev-parse when <app>/.git is absent
- Add real git init tests in test_provenance.py for monorepo subpath dirty-state isolation and standalone <app>/.git precedence
- Add router unit test in test_appctl_router.py verifying monorepo git pull and subpath status checks during workload.update
2026-11-16 14:03:59 -05:00
kiskaadee 9d7114b547 feat(nixos,core): transition ~/Sites default to ~/Workloads with WORKLOADS_DIR env support (#33)
- Update nixos/modules/homeserver.nix default homelab.sitesDir to ~/Workloads and export both WORKLOADS_DIR and SITES_DIR
- Add ~/Workloads and ~/Workloads/* to programs.git.config.safe.directory in nixos/configuration.nix while retaining ~/Sites/* for transition
- Update all workload paths in config/deployments.yaml from ~/Sites/<app> to ~/Workloads/<app>
- Update appctl_engine.py, appctl_daemon.py, and gitops_dispatcher.py to honor WORKLOADS_DIR -> SITES_DIR -> ~/Workloads and resolve both ~/Workloads/ and ~/Sites/ prefixes in deployments.yaml
- Add TDD security and unit tests covering NixOS defaults, git safe.directory, tilde prefix resolution, and WORKLOADS_DIR env precedence
2026-11-16 14:00:45 -05:00
kiskaadee 9ac44d0baa docs(adr): add ADR-0004 for unified ~/Workloads monorepo and state isolation (#33)
- Author MADR 4.0 ADR-0004 amending ADR-0001 to adopt the unified ~/Workloads Tier 2 monorepo (canopy-workloads), rename ~/Sites to ~/Workloads with WORKLOADS_DIR -> SITES_DIR fallback, and enforce ~/var/lib/homelab/<app>/ state isolation
- Register ADR-0004 in docs/decisions/README.md active decisions table and summaries
2026-11-16 13:57:54 -05:00
kiskaadee 88f8bace04 docs(planning): record Canopy organization board and planning sync contract in AGENTS.md
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m9s
Core Architecture & Invariant CI / validate (push) Successful in 1m9s
2026-11-16 12:45:57 -05:00
kiskaadee 2882dc99b5 docs(branding): adopt Canopy ecosystem branding and canopy-homelab/nixos-core naming
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m9s
Core Architecture & Invariant CI / validate (push) Successful in 1m10s
- Update README.md, ROADMAP.md, SECURITY.md, and AGENTS.md to reflect the Canopy platform identity and canopy-homelab/nixos-core naming
- Correct loopback HTTP port reference in README.md from 9876 to 9001
2026-11-16 12:23:13 -05:00
kiskaadee 2b89ff44c3 fix(nixos,deployments): wire HOMELAB_STATE_ROOT in daemon env and retire docs target
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m15s
Core Architecture & Invariant CI / validate (push) Successful in 1m9s
- Set HOMELAB_STATE_ROOT=/home/<operatorUser>/var/lib/homelab in homelab-appctl and homelab-gitops systemd environments so sandboxed HOME=/var/lib/homelab/appctl does not break state containment checks
- Remove retired docs (homelab-doc2site) entry from config/deployments.yaml
- Set HOMELAB_DEPLOYMENTS_FILE hermetically in test_appctl_daemon.py daemon_env fixture
2026-11-16 11:02:19 -05:00
kiskaadee 99bda8740f fix(nixos,authelia): grant homelab-operators read access to rendered env templates and fix Authelia env syntax
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m15s
Core Architecture & Invariant CI / validate (push) Successful in 1m23s
- Add group = "homelab-operators" and mode = "0440" to sops.templates."homeserver.env" and "traefik-deployments.env" so homelab-appctl.service can read rendered env files
- Remove unsupported second fallback argument from {{ env "LLDAP_LDAP_BASE_DN" }} in config/authelia/configuration.yml
2026-11-15 23:45:54 -05:00
kiskaadee de02b19861 fix(nixos): include explicit POSIX ACL mask (m::rx) on 0700 home directories in tmpfiles
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m38s
Core Architecture & Invariant CI / validate (push) Successful in 1m13s
- Add explicit mask m::rx and group homelab-operators traverse entry to systemd.tmpfiles.rules in nixos/modules/homeserver.nix so systemd-tmpfiles does not leave u:homelab-appctl:x masked out (#effective:---) on 0700 home directories
2026-11-15 22:40:58 -05:00
kiskaadee 99e9c130c0 fix(nixos): resolve writePython3Bin flake8 E501 build failure in dynu-ip-monitor
- Add flakeIgnore = [ "E501" ] to pkgs.writers.writePython3Bin in nixos/modules/dynu.nix
- Wrap lines >79 characters in nixos/scripts/monitor.py to satisfy Nix writer flake8 checks during toplevel system derivation builds
2026-11-15 22:22:54 -05:00
kiskaadee 9c9127b833 Merge pull request 'feat(p4): implement control plane daemon, UDS client, and RBAC operational router' (#1) into main
Core Architecture & Invariant CI / validate (push) Successful in 1m9s
Milestone P4: Control Plane Daemon & Unified Operational Architecture
2026-11-01 00:37:30 -05:00
kiskaadee 76df30747d test(harness): ensure portable socket path length and root-invariant audit failure handling
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m11s
2026-10-31 22:29:52 -05:00
kiskaadee c034afd0f8 test(router): verify non-zero subprocess exit and diagnostic stderr propagation (#24)
Core Architecture & Invariant CI / validate (pull_request) Failing after 59s
2026-10-31 21:43:33 -05:00
kiskaadee af82d4b26d test(daemon): add true multi-threaded lock contention concurrency test (#24) 2026-10-31 21:43:33 -05:00
kiskaadee b7b19ad7f1 test(daemon): replace tautological subprocess.run patches with run_bounded_subprocess seam (#24) 2026-10-31 21:43:33 -05:00
kiskaadee 1fea9024f1 docs(operations): document token bootstrapping and core update policy in cutover runbook (#23)
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m2s
2026-10-31 21:39:30 -05:00
kiskaadee 4622392ca5 fix(nixos): add tmpfiles state dir, optional sandbox paths, and gitops service ordering (#22) 2026-10-31 21:39:30 -05:00
kiskaadee c740ed8c71 chore: add .worktrees/ to .gitignore 2026-10-31 21:39:30 -05:00
kiskaadee 55acf00c10 fix(daemon): catch unhandled exceptions, preserve audit trail, and serialize homepage sync
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m0s
2026-10-31 21:38:46 -05:00
kiskaadee c8c79bef89 fix(router): validate deployment branch instead of source ref during post-pull verification 2026-10-31 21:33:59 -05:00
kiskaadee 5156cf4306 chore: add .worktrees/ to .gitignore
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m9s
2026-10-31 14:07:37 -05:00
kiskaadee 5dfebac35c fix(router): redact evaluated secrets in workload.config and match bare audit keys
- Parse evaluated Compose configuration YAML before applying secret redaction in _op_workload_config (CR-DI-03)
- Update REDACT_KEY_PATTERNS to match bare parameter keys (token, secret, password, key, pass, hash) in audit logging (CR-DI-04)
- Enforce case-insensitive comparison for hex token hashes in TokenStore (CR-DI-10)
- Re-assert immutable platform keys post-environment assembly in assemble_workload_env (CR-DI-07)
- Add unit tests verifying evaluated secret masking, bare-key audit redaction, and uppercase hex token validation
2026-10-31 14:06:39 -05:00
kiskaadee d0213d7209 security(router): prevent workload .env override of reserved platform configuration
- Add platform routing, networking, and Docker config keys to RESERVED_ENV_KEYS (CR-DI-07)
- Add unit tests verifying rejection of reserved platform variables in manifest.env
2026-10-31 14:06:09 -05:00
kiskaadee 178a0c8990 fix(compose): enforce host containment on dictionary volumes and reject variable interpolation
- Default dictionary volume declarations omitting 'type: bind' to host containment checks when 'source' is specified (CR-DI-01)
- Reject volume host paths containing dynamic variable interpolation (${...}) to prevent runtime boundary escapes (CR-DI-02)
- Add security regression tests in tests/security/test_gitops_security.py
2026-10-31 14:04:28 -05:00
kiskaadee 03c8fdcf8e docs(core): reconcile README and SECURITY with Milestone P4 control plane daemon architecture
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m1s
- Update README.md to describe homelab-appctl.service operational control plane daemon architecture over UDS and loopback HTTP
- Update Repository Structure table to include bootstrap_token.py and appctl_*.py daemon modules
- Update Host System Management rebuild commands across docs to use path:$HOME/Core#server --impure
- Document control plane transport isolation, SO_PEERCRED viewer auth, SHA-256 tokens, 3-tier RBAC, per-target flocking, and fail-closed audit logging in SECURITY.md
2026-10-30 13:46:22 -05:00
kiskaadee 3ba8e2b51d docs(operations): include var/lib/homelab state and workload quiescence in operator cutover runbook
- Add explicit guidance to maintain active legacy SSH/terminal session throughout migration to prevent lockout
- Document fallback operator user provisioning if coexistence account is not yet active
- Add /home/<legacy-operator>/var/lib/homelab and ~/.local/state/homelab to initial and final rsync stages to prevent workload state stranding
- Quiesce active workload containers alongside core platform services before final rsync delta to guarantee database consistency
- Extend ownership fixup to /home/operator/var and /home/operator/.local
2026-10-30 13:42:34 -05:00
kiskaadee 4f1a63160b fix(provenance): report non-zero git status exits and update bootstrap rebuild hint
- Update get_local_checkout_status in scripts/provenance.py to surface non-zero git status exit codes as '⚠️ Git Error (exit <code>)' rather than masking them as '✓ Clean'
- Update scripts/bootstrap_token.py rebuild instruction to use path:$HOME/Core#server --impure, ensuring instance.nix evaluation is respected
- Add unit test coverage for non-zero git exit handling and bootstrap rebuild guidance
2026-10-30 13:40:22 -05:00
kiskaadee e2dbc97b0e fix(nixos): add Core to git safe.directory and update nix-switch to path flake scheme
- Update nixos/configuration.nix to include /home/${operatorUser}/Core in programs.git.config.safe.directory, preventing dubious ownership errors when homelab-appctl runs read-only status checks
- Update nix-switch alias in nixos/modules/shell.nix to use path:$HOME/Core#server --impure, ensuring gitignored instance.nix domain injection evaluates reliably
- Add security invariant tests asserting safe.directory configuration and nix-switch alias format
2026-10-30 13:37:10 -05:00
kiskaadee caa8140cd3 feat(nixos): add dual-path instance domain injection and operator cutover runbook
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m0s
- Implement dual-path optional imports in nixos/configuration.nix for instance domain
- Add nixos/instance.nix to .gitignore preserving platform genericism
- Add invariant tests for default domain evaluation and dynamic LDAP base DN derivation
- Document appliance domain injection and path: flake scheme in docs/setup_guide.md
- Document 4-stage staged coexistence cutover runbook and rollback plan in docs/operations.md
- Mark live host execution as BLOCKED pending authorized maintenance window
- Update todo.txt and p4-refactor-and-decoupling-plan.md

Closes #7
Refs #8
2026-10-30 12:13:11 -05:00
kiskaadee eb02543fa6 docs(roadmap): scrub residual DeploymentModel and DeploymentProposal references
- Reconcile ROADMAP.md Invariants 6 & 7 with external MCP Gateway architecture
- Update ROADMAP.md Baseline vs. Target table across metadata, deployment, and GitOps rows
- Update Milestone P7 Operations UI deliverables in ROADMAP.md
- Update ADR-0002 one-line summary in docs/decisions/README.md
- Mark item completed in todo.txt

Closes #13
Refs #13
2026-10-30 10:53:41 -05:00
kiskaadee 24508f8d92 docs(auth): add operator admin token bootstrap helper and provisioning guide
- Implement scripts/bootstrap_token.py generating 256-bit token with 0600 mode
- Enforce parent directory 0700 mode and refuse overwrite without --force
- Output SHA-256 JSON descriptor matching TokenDescriptor for SOPS tokens_json
- Ensure zero plaintext secret leakage to stdout/stderr
- Document token bootstrapping, SOPS configuration, and rotation in docs/appctl.md
- Update control plane token store section in docs/secrets-and-state.md
- Add 10 unit tests covering API, permissions, and CLI paths
- Mark item completed in todo.txt and p4-refactor-and-decoupling-plan.md

Closes #12
Refs #12
2026-10-30 09:54:57 -05:00
kiskaadee 8ad48a49db docs(appctl): document source-built workload policy and build flag semantics
- Document --build, --no-cache, and automatic --pull behavior for appctl up and update
- Add Source-Built Workload Policy note detailing compose_build action sequences
- Mark item completed in todo.txt

Closes #11
Refs #11
2026-10-30 09:33:34 -05:00
kiskaadee f631d5627c feat(build): wire --build/--no-cache flags and pass --pull during compose_build
- Extend DeployParams and UpdateParams with strict no_cache boolean implying build=True
- Wire --build and --no-cache on appctl up, deploy, and update CLI commands
- Update bash completion to suggest --build and --no-cache for up and update
- Pass --pull (and --no-cache when requested) on docker compose build in OperationalRouter
- Add comprehensive unit tests covering contract validation, CLI arguments, and router subprocess calls

Refs #11
2026-10-30 09:32:55 -05:00
kiskaadee 021c01171b feat(cli): restore live container status and default two-axis columns in workload.list
- Query live container status via get_docker_status() for Sites apps and Core services
- Inspect local Git checkout offline by default and query remotes only when --fetch is passed
- Fix get_docker_status failure semantics to return Unknown instead of Stopped when Docker is unreachable
- Format appctl list table with 5 canonical columns (SERVICE | DEPLOYMENT | PROVENANCE | STATUS | DOMAIN)
- Append CERT column when --ssl is passed (6 columns)
- Add comprehensive router and CLI unit tests covering live status and manifest error branches
- Mark item completed in todo.txt

Closes #10
Refs #10
2026-10-30 08:54:16 -05:00
kiskaadee 7c1b9b75c5 fix(cli): enforce fail-closed daemon socket check and remove legacy Bash fallback
- Remove 312 lines of legacy Bash orchestration fallback in scripts/appctl
- Fail closed with exit code 1 and actionable diagnostic error on stderr when socket is absent
- Retain fast-path local shell completion handlers (complete, completion)
- Auto-detect .venv Python interpreter when PYTHON_BIN is unset
- Migrate test_appctl_env_injection_resilience to test production P4 environment assembly
- Add unit tests for missing socket and offline completion in test_appctl_cli.py
- Mark item completed in todo.txt

Closes #9
Refs #9
2026-10-30 07:59:28 -05:00
kiskaadee c86faa8397 merge(main): sync nixpkgs security update (CVE-2026-115557)
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m9s
2026-10-29 22:01:58 -05:00
kiskaadee dae99af189 docs(p4): record completion of Phase 1 host decoupling and track build flag task
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m20s
- Mark Tasks 1.1-1.5 complete in docs/plans/p4-refactor-and-decoupling-plan.md and todo.txt.
- Register Task 2.5 to wire --build/--no-cache and compose_build --pull in the P4 refactor plan and todo.txt.
2026-10-27 00:17:04 -05:00
kiskaadee 8da559381f feat(nixos): decouple operator identity, derive LDAP base DN, and enforce recursive ACLs
- Migrate default administrative user from 'kiskaadee' to generic 'operator' in nixos/configuration.nix.
- Configure programs.git.config.safe.directory to allow the homelab-appctl daemon to execute Git commands against operator Sites repositories.
- Derive LLDAP_LDAP_BASE_DN dynamically from config.homelab.domain in nixos/modules/homeserver.nix and project it to both lldap and authelia in docker-compose.yml.
- Upgrade systemd.tmpfiles.rules for Sites, var/lib, and homepage config to recursive POSIX ACLs ('A+') to ensure automatic permission inheritance for newly created directories and files.
- Add security invariant tests asserting LLDAP/Authelia env wiring, dynamic base DN derivation, and recursive ACL rule syntax.
2026-10-27 00:16:28 -05:00
kiskaadee c86103a14b chore(flake): update nixpkgs input (CVE-2026-115557)
Core Architecture & Invariant CI / validate (push) Successful in 52s
Bump nixpkgs to 2026-10-23 revision (3ec636362e18) providing patched
uv (0.13.4) and updated system CA certificates.
2026-10-26 23:59:37 -05:00
kiskaadee ce7ffa8c46 docs(plan): align roadmap, ADR-0002, and tasks with MCP gateway and decoupling plan
- Add master implementation plan in docs/plans/p4-refactor-and-decoupling-plan.md
  outlining operator identity migration, dynamic LDAP base DN derivation,
  recursive POSIX ACLs, and host Git safe directory requirements.
- Re-scope Milestone P6 in ROADMAP.md, ADR-0002, and decision index to
  Homelab MCP Gateway, formally deprecating on-server AI deployment compilers
  in favor of external JSON-RPC protocol tools with human-in-the-loop gating.
- Reconcile docs/appctl.md regarding bounded container log snapshots (--tail)
  and Core platform update mechanics via NixOS rebuilds.
- Populate todo.txt with prioritized implementation tasks for the upcoming
  decoupling and control plane hardening work.
2026-10-23 16:54:11 -05:00
62 changed files with 6777 additions and 903 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
+6
View File
@@ -6,6 +6,7 @@ backup.zip
.envrc
.direnv
.venv
nixos/instance.nix
# SSL / ACME Certificates & Keys
config/letsencrypt/*
@@ -40,6 +41,7 @@ config/homepage/custom.js
Thumbs.db
.vscode/
.idea/
.worktrees/
# Python & Testing Caches
__pycache__/
@@ -52,3 +54,7 @@ mutants/
# Local Bootstrap & Operational Scripts
scripts/bootstrap_lldap_users.py
scripts/bootstrap_*.py
!scripts/bootstrap_token.py
# Worktrees & Slices
.worktrees/
+15 -8
View File
@@ -1,13 +1,13 @@
# Homelab Core — Agent Guidelines
# Canopy NixOS Core — Agent Guidelines
## 1. Project Overview & Architectural Boundaries
**Homelab Core** defines the declarative NixOS host foundation, shared platform infrastructure services, security boundaries, and the `appctl` operational control plane. Independent application workloads live in `~/Sites/<app>` and integrate through declarative `app.yaml` manifests and workload-scoped Docker Compose files.
**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:
@@ -27,7 +27,7 @@ Every implementation step must close with the automated verification gate before
```bash
# Full verification gate: Ruff + Pyright + Pytest (124+ tests) + nix flake check + NixOS drv eval
./scripts/test
./scripts/run-tests
# Targeted fast iteration commands (inside direnv / nix develop, or via .venv)
ruff check .
@@ -67,7 +67,7 @@ docker compose config -q
1. **Workload Manifests (`app.yaml`)**: Describe declarative workload identity, routing metadata, and deployment intent only. Never introduce arbitrary command execution, host filesystem paths, privileged flags, or Docker control capabilities into `app.yaml`.
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`).
@@ -89,3 +89,10 @@ docker compose config -q
- Never run destructive Git commands (`reset --hard`, `restore`, `clean -fd`, `push --force`) without explicit user confirmation.
- Stage atomic changes and use Conventional Commits (`feat`, `fix`, `refactor`, `test`, `docs`, `chore`), waiting for user approval before committing.
- Preserve [The Unlicense](UNLICENSE) across the repository.
### Organization Planning Sync Contract
- **Ecosystem Hub**: Master roadmap and cross-repo plans live in `canopy-homelab/.profile` (`ROADMAP.md`, `docs/plans/`, `todo.txt`).
- **Organization Kanban Board**: **Canopy Platform** (`https://gitea.<domain>/canopy-homelab/-/projects/7`, Project ID: `7`).
- **Column IDs (Deep Signal)**: `Backlog` -> `30` (default), `Ready` -> `31`, `Work in Progress` -> `32`, `Review` -> `33`, `Completed` -> `34`.
- **Mirror Policy**: Primary sovereign Gitea forge (`canopy-homelab/nixos-core`); GitHub (`canopy-homelab/nixos-core`) is an automated `sync_on_commit` push mirror.
- **Re-sync Trigger**: Re-run `/gitea-plan` on scope shifts or before decomposing the next rolling milestone (P5/P6/P7).
+37 -21
View File
@@ -1,15 +1,15 @@
# Homelab Core
# Canopy — NixOS Core (`canopy-homelab/nixos-core`)
**Homelab Core** is the declarative NixOS host foundation, shared platform infrastructure stack, and `appctl` operational control plane for a self-hosted homelab appliance.
**Canopy NixOS Core** is the declarative NixOS host foundation, shared platform infrastructure stack, and `appctl` operational control plane for the **Canopy** self-hosted homelab ecosystem.
It is designed around a strict two-tier boundary:
1. **Homelab Core (this repository)**: Owns NixOS operating system configuration, edge TLS ingress, SSO/LDAP directory identity, mail routing, read-only Docker socket isolation, and orchestration/deployment mechanics.
2. **Workload Repositories (`~/Sites/<app>`)**: Independently deployed application stacks that integrate with Core through self-describing `app.yaml` manifests and workload-scoped `docker-compose.yml` definitions.
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 (`~/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.
> [!NOTE]
> **Current Implementation Baseline vs. Target Architecture**: This README documents the **currently implemented CLI and runtime baseline (Milestone P3)**. Under [Milestone P4 in `ROADMAP.md`](ROADMAP.md), `appctl` is transitioning from a host CLI orchestrator into a dedicated daemon service (`homelab-appctl.service`) exposing a unified logical API across local Unix socket and HTTP transports. See [`ROADMAP.md`](ROADMAP.md) for the full baseline-to-target matrix.
> **Milestone P4 Control Plane Architecture**: Under [Milestone P4 in `ROADMAP.md`](ROADMAP.md), `appctl` operates as an operational control plane daemon service (`homelab-appctl.service`) exposing a unified logical API across a local Unix Domain Socket (`/run/homelab/appctl.sock`) and loopback HTTP (`127.0.0.1:9001`). The thin `appctl` CLI delegates commands to this daemon with automatic `SO_PEERCRED` identity inspection and token-based RBAC. See [`docs/appctl.md`](docs/appctl.md) and [`ROADMAP.md`](ROADMAP.md) for details.
---
@@ -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)
▼
@@ -49,8 +49,10 @@ All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_
▲
│ (Host Orchestration & CD)
┌───────────────┴───────────────┐
│ Host Control Plane Baseline │
│ • appctl CLI + Engine │
│ Host Control Plane (P4) │
│ • thin appctl CLI │
│ • homelab-appctl.service │
│ (UDS / HTTP daemon) │
│ • homelab-gitops.service │
└───────────────────────────────┘
```
@@ -79,21 +81,29 @@ 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)
├── nixos/ # Declarative NixOS modules, systemd units, SOPS secret wiring & instance.example.nix
├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml template)
├── scripts/
│ ├── appctl # Operational CLI entrypoint and Compose environment orchestrator
│ ├── appctl_engine.py # Discovery, two-axis provenance, TLS inspection, and Homepage sync engine
│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for workload app.yaml
│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST security validation
│ └── test # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks)
│ ├── appctl # Thin operational CLI delegating to control plane daemon
│ ├── appctl_daemon.py # Async HTTP/UDS daemon server (homelab-appctl.service)
│ ├── appctl_router.py # Operational router, locking, RBAC & dispatch
│ ├── appctl_auth.py # SO_PEERCRED & Bearer token RBAC authentication
│ ├── appctl_audit.py # Append-only fail-closed structured audit logger
│ ├── appctl_contracts.py # Pydantic v2 schemas for daemon RPC requests & responses
│ ├── appctl_cli.py # Unified CLI client with dual transport fallbacks
│ ├── appctl_engine.py # Discovery, two-axis provenance, TLS inspection, and Homepage sync
│ ├── 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
```
---
## Quickstart & Operations (Current CLI Baseline)
## Quickstart & Operations (Control Plane Daemon & CLI)
### Development & Verification
@@ -101,7 +111,7 @@ Entering the directory via `direnv` (`use flake`) or `nix develop` provisions th
```bash
# Run full automated verification (Ruff + Pyright + Pytest + nix flake check + NixOS drv eval)
./scripts/test
./scripts/run-tests
# Run individual checks directly
ruff check .
@@ -111,7 +121,12 @@ pyright
### Workload Management (`appctl` CLI)
The thin `appctl` CLI connects directly to `homelab-appctl.service` via Unix Domain Socket (`/run/homelab/appctl.sock`) or loopback HTTP (`127.0.0.1:9876`). Local operators in `homelab-operators` or `wheel` receive read-only viewer access via kernel `SO_PEERCRED` without tokens, while mutating actions consume Bearer tokens from `~/.config/homelab/token`:
```bash
# Check daemon health status
appctl health
# List all workloads with container health and local Git checkout status
appctl list
@@ -121,7 +136,7 @@ appctl list --fetch --ssl --core
# Inspect detailed manifest, provenance, and container diagnostics for a workload
appctl info <service>
# Manage workload or Core service lifecycle (executes docker compose locally in the current baseline)
# Manage workload or Core service lifecycle (dispatched via homelab-appctl daemon)
appctl up <service|core>
appctl down <service|core>
appctl restart <service|core>
@@ -136,11 +151,12 @@ appctl sync
### Host System Management
```bash
# Rebuild and activate the NixOS host configuration
sudo nixos-rebuild switch --flake .#server
# Rebuild and activate the NixOS host configuration (or use the 'nix-switch' alias)
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
# Inspect platform systemd units
systemctl status homeserver-core.service
systemctl status homelab-appctl.service
systemctl status homelab-gitops.service
systemctl status dynu-monitor.service
```
@@ -151,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. |
+21 -20
View File
@@ -1,10 +1,10 @@
# 🗺️ Homelab Core & Appctl Engineering Roadmap
# 🗺️ Canopy — NixOS Core & Appctl Engineering Roadmap
This document serves as the repository-facing projection of the authoritative **Homelab Architecture Consolidation & Control Plane Roadmap (v6)** and the locked Milestone P4 boundary specification ([`docs/plans/p4-readiness-plan.md`](docs/plans/p4-readiness-plan.md)).
This document serves as the repository-facing projection of the authoritative **Canopy Architecture Consolidation & Control Plane Roadmap (v6)** and the locked Milestone P4 boundary specification ([`docs/plans/p4-readiness-plan.md`](docs/plans/p4-readiness-plan.md)).
It describes the implementation trajectory and phased engineering milestones for transitioning Homelab Core into a unified platform driven by the `appctl` Operational Control Plane.
It describes the implementation trajectory and phased engineering milestones for evolving the **Canopy** platform (`canopy-homelab/nixos-core`) around a unified `appctl` Operational Control Plane.
> **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index ([ADR-0001: 3-Tier Provenance Model](docs/decisions/0001-3tier-architecture-and-provenance.md), [ADR-0002: Operational Control Plane Architecture](docs/decisions/0002-appctl-control-plane-architecture.md), and [ADR-0003: Pydantic v2 Runtime Validation](docs/decisions/0003-pydantic-v2-runtime-validation.md)).
> **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index ([ADR-0001: 3-Tier Provenance Model](docs/decisions/0001-3tier-architecture-and-provenance.md), [ADR-0002: Operational Control Plane Architecture](docs/decisions/0002-appctl-control-plane-architecture.md), [ADR-0003: Pydantic v2 Runtime Validation](docs/decisions/0003-pydantic-v2-runtime-validation.md), [ADR-0004: Unified ~/Workloads Monorepo](docs/decisions/0004-unified-workloads-monorepo.md), and [ADR-0005: Host-Granted Workload Capabilities](docs/decisions/0005-workload-capability-grants.md)).
---
@@ -15,8 +15,8 @@ It describes the implementation trajectory and phased engineering milestones for
3. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**: Entering via SSH does not bypass authentication. Every mutating operation and sensitive read (`workload.config`, `workload.logs`) requires an explicit Bearer token; tokenless local UDS calls fall back via `SO_PEERCRED` strictly to `homelab-viewer` read-only inspection.
4. **Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)**: `homelab-appctl.service` executes as isolated user `homelab-appctl:homelab-operators` with mode `0600` append-only `/var/log/homelab/appctl/audit.jsonl`. Mutating operations abort immediately (`500 ERR_EXECUTION_FAILED`) if the pre-execution `DISPATCHED` audit write fails.
5. **Unified Execution, Pre-Flight & Pure-Python Environment (`DEC-04`, `DEC-05`)**: Both CLI and GitOps worker paths execute through the daemon, enforcing Pydantic v2 manifest validation, `validate_compose_security()` AST checks, and inert pure-Python `.env` assembly (no shell `source` or `eval`).
6. **Separation of Intent from Implementation**: `DeploymentModel` captures implementation-agnostic intent; concrete platform descriptors (`app.yaml` + Compose) are materialized and enforced by `appctl`.
7. **AI Authoring Boundary**: AI agents act strictly as proposal generators (`DeploymentProposal`). Humans approve the intent (`DeploymentModel`). The AI possesses zero execution authority.
6. **Separation of Intent from Implementation**: Declarative manifests (`app.yaml` + Compose) versioned in Git capture workload intent and platform descriptors, materialized and enforced deterministically by `appctl`.
7. **AI Authoring Boundary & External MCP Gateway**: AI agents operate externally as proposal generators via client-side Model Context Protocol (MCP) tool integrations. Humans approve intent before any mutation is applied in Git. The server appliance hosts zero autonomous agent loops or on-server compilers.
8. **Secret Reference Invariant**: Deployment definitions store secret references (`secretKeyRef`), never plaintext material, resolved at runtime via `SecretProvider`.
9. **Clean State Root**: Mutable application runtime data resides strictly under `~/var/lib/homelab/<app>/`, isolated from Git repositories.
@@ -28,9 +28,9 @@ 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`. | Unified across `DeploymentModel` materialization (P6). |
| **Deployment Model** | Direct authoring of `app.yaml` and `docker-compose.yml` in `~/Sites/<app>/`. | 5-stage lifecycle (planned in P6): `DeploymentProposal` $\to$ operator-approved `DeploymentModel` in Git $\to$ `appctl` materialization. |
| **GitOps Engine** | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | Integrated with `DeploymentModel` reconciliation (P6). |
| **Metadata & Schema Engine** | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | Standardized JSON-RPC Model Context Protocol tools over Pydantic v2 schemas (P6). |
| **Deployment Model** | Authoritative declarative Git state (`app.yaml`, `docker-compose.yml`, `deployments.yaml`) in `~/Workloads/<app>/`, bounded by `homelab.workloadGrants` (`/etc/homelab/grants.json`). | Standardized JSON-RPC MCP tools (`P6`) and Operations UI (`P7`). |
| **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,8 +45,9 @@ 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** | **Deployment Model & AI**| Intent Authoring | ⏳ **Planned** | Capability catalog, `DeploymentProposal` $\to$ `DeploymentModel` compiler, Git commit pipeline. |
| **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. |
---
@@ -122,15 +123,15 @@ It describes the implementation trajectory and phased engineering milestones for
---
### Milestone P6: Homelab Deployment Model & AI Authoring Workflow
**Status**: ⏳ **Planned**
* **Objective**: Enable safe, human-reviewed workload authoring from upstream repositories.
### Milestone P6: Homelab MCP Gateway (Protocol Tool Integration)
**Status**: ⏳ **Planned** *(Amended: Deprecated on-server `DeploymentProposal` compiler in favor of decoupled Model Context Protocol gateway)*
* **Objective**: Expose `appctl` control plane capabilities over standardized JSON-RPC Model Context Protocol (MCP) tools for external AI assistants (Antigravity, Claude Code, Cursor) without running unverified autonomous agents on the appliance host.
* **Key Deliverables**:
1. *Platform Capability Catalog*: Machine-readable specification of Core capabilities and security invariants.
2. *DeploymentProposal Schema*: Candidate model format produced by AI discovery workflows.
3. *DeploymentModel Git Pipeline*: Operator approves proposal into a `DeploymentModel`; the model is committed to the version-controlled deployment repository (Git).
4. *Materialization & Reconciliation*: `appctl` validates the committed model, provisions state roots, compiles platform descriptors (`app.yaml` + Compose), and reconciles running containers.
* **Exit Criteria**: Human approval gate strictly enforced; AI possesses zero execution authority; generated workloads conform to all Core invariants.
1. *Protocol Tool Gateway*: Standardized MCP server wrapping deterministic `appctl` operations (`appctl_status`, `appctl_logs`, `appctl_deploy`, `appctl_audit`) over JSON-RPC.
2. *Client-Side Human-in-the-Loop Confirmation*: Native IDE/client confirmation gating for all mutating tools before execution.
3. *Deprecate On-Server AI Proposal Compiler*: Remove requirements for server-side `DeploymentProposal` $\to$ `DeploymentModel` pipelines; desired state remains standard Git-tracked declarative YAML (`app.yaml` + Compose).
4. *Schema & Tool Security Guards*: Strict Pydantic parameter validation on incoming MCP tool calls matching `appctl_contracts.py`.
* **Exit Criteria**: External AI clients successfully query status, inspect logs, and request deployments through MCP with strict confirmation gates; Core boundaries remain 100% deterministic with zero autonomous agent code on the host.
---
@@ -138,7 +139,7 @@ It describes the implementation trajectory and phased engineering milestones for
**Status**: ⏳ **Planned**
* **Objective**: Deliver a unified web-based management experience without coupling the control plane to specific frontend engines.
* **Key Deliverables**:
1. *Operations UI Client*: Dedicated lightweight web client consuming the `appctl` API for proposal review, approval, real-time log streaming, and API token management.
1. *Operations UI Client*: Dedicated lightweight web client consuming the `appctl` API for workload inspection, deployment management, real-time log streaming, and API token management.
2. *Homepage Status Integration*: Homepage consumes live status widgets from `appctl` live endpoints or compiled service maps.
* **Exit Criteria**: End-to-end browser and CLI deployment verification; Homepage accurately reflecting live container health.
@@ -148,5 +149,5 @@ It describes the implementation trajectory and phased engineering milestones for
Progress across milestones is governed by explicit verification criteria:
* **Behavioral Invariant Coverage**: All defined domain, authorization, deployment, and security invariants must have automated regression tests.
* **Pre-Merge Validation**: Every commit must pass `./scripts/test` (Ruff linter + Pytest suite + Nix flake check).
* **Pre-Merge Validation**: Every commit must pass `./scripts/run-tests` (Ruff linter + Pytest suite + Nix flake check).
* **Zero Production Regressions**: Platform migrations must include verified pre-flight snapshots, state parity proofs, and documented rollback runbooks.
+15 -3
View File
@@ -1,6 +1,6 @@
# 🛡️ Homelab Core — Security Controls & Hardening
# 🛡️ Canopy NixOS Core — Security Controls & Hardening
This document outlines the security controls, container isolation rules, and operational boundaries implemented in **Homelab Core**.
This document outlines the security controls, container isolation rules, and operational boundaries implemented in **Canopy NixOS Core** (`canopy-homelab/nixos-core`).
---
@@ -31,6 +31,15 @@ This document outlines the security controls, container isolation rules, and ope
* Secrets are stored encrypted in `nixos/secrets.yaml` using Age keys derived from the host SSH key (`/etc/ssh/ssh_host_ed25519_key`).
* Decrypted secrets reside in RAM-backed ephemeral filesystems (`/run/secrets/`, `/run/credentials/`) and are not committed to unencrypted persistent files.
### F. Operational Control Plane Security (`homelab-appctl.service`)
* **Transport Isolation**: Daemon listens on a restricted Unix Domain Socket (`/run/homelab/appctl.sock`, mode `0660`, group `homelab-operators`) and loopback HTTP (`127.0.0.1:9876`). It never binds to public interfaces.
* **Authentication & RBAC**:
- **UDS Peer Credential Identification**: Local connections inspect kernel peer credentials (`SO_PEERCRED`). Callers in `homelab-operators` or `wheel` receive read-only viewer privileges automatically without requiring secrets on disk.
- **Cryptographic Bearer Tokens**: Mutating actions require Bearer tokens defined in SOPS (`/run/secrets/appctl/tokens.json`). Tokens are validated using `hmac.compare_digest` against SHA-256 digests.
- **Three-Tier RBAC**: Granular role enforcement distinguishes read-only inspectors (`viewer`), workload managers (`operator`), and core platform administrators (`admin`).
* **Per-Target Concurrency Control (`flock`)**: Non-blocking file locks (`/run/lock/homelab/<target>.lock`) serialize mutating actions per workload, returning HTTP 409 Conflict if an operation is already in flight.
* **Fail-Closed Structured Audit Logging**: Every operational command is appended synchronously to a tamper-evident audit log (`/var/log/homelab/appctl/audit.jsonl`, mode `0600`). If disk writing fails, the daemon fails closed and rejects the request.
---
## 2. Threat Model & Operational Considerations
@@ -54,6 +63,9 @@ This document outlines the security controls, container isolation rules, and ope
- [x] User identities managed in LLDAP (`users.${HOMELAB_DOMAIN}`).
- [x] `socket-proxy` configured with `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`.
- [x] Webhook HMAC signature verification active on port 9000.
- [x] Invariant test runner (`./scripts/test`) passing on changes.
- [x] Invariant test runner (`./scripts/run-tests`) passing on changes.
- [x] `config/letsencrypt/acme.json` permissions set to `0600`.
- [x] Host firewall ports restricted to declared services in `nixos/modules/homeserver.nix`.
- [x] Control plane daemon (`homelab-appctl.service`) isolated to UDS (`0660`) and loopback HTTP.
- [x] Operational audit log (`/var/log/homelab/appctl/audit.jsonl`) append-only with strict `0600` permissions.
- [x] Control plane mutation endpoints enforce per-target `flock` and SHA-256 Bearer tokens.
+2 -2
View File
@@ -13,7 +13,7 @@ authentication_backend:
address: 'ldap://lldap:3890'
timeout: 5s
start_tls: false
base_dn: '{{ env "LLDAP_LDAP_BASE_DN" "dc=example,dc=test" }}'
base_dn: '{{ env "LLDAP_LDAP_BASE_DN" }}'
additional_users_dn: 'ou=people'
users_filter: '(&({username_attribute}={input})(objectClass=person))'
additional_groups_dn: 'ou=groups'
@@ -24,7 +24,7 @@ authentication_backend:
display_name: 'displayName'
mail: 'mail'
group_name: 'cn'
user: 'uid=admin,ou=people,{{ env "LLDAP_LDAP_BASE_DN" "dc=example,dc=test" }}'
user: 'uid=admin,ou=people,{{ env "LLDAP_LDAP_BASE_DN" }}'
access_control:
default_policy: deny
+12 -47
View File
@@ -1,53 +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 ~/Sites.
# Enforces: strict path containment within ~/Workloads (WORKLOADS_DIR).
schemaVersion: "1.0"
repositories:
snappymail:
path: "~/Sites/snappymail"
example-app:
path: "~/Workloads/example-app"
aliases:
- "homelab-snappymail"
- "mail"
- "webmail"
gitea:
path: "~/Sites/homelab-gitea"
- "example"
- "homelab-example"
example-docs:
path: "~/Workloads/example-docs"
aliases:
- "homelab-gitea"
- "git"
jellyfin:
path: "~/Sites/homelab-jellyfin"
aliases:
- "homelab-jellyfin"
- "media"
docs:
path: "~/Sites/homelab-doc2site"
aliases:
- "doc2site"
- "homelab-doc2site"
courses:
path: "~/Sites/courses"
aliases:
- "homelab-courses"
bdinvite:
path: "~/Sites/homelab-bdinvite"
aliases:
- "homelab-bdinvite"
- "birthday"
landing:
path: "~/Sites/homelab-landing"
aliases:
- "homelab-landing"
mermaid:
path: "~/Sites/homelab-mermaid"
aliases:
- "homelab-mermaid"
excalidraw:
path: "~/Sites/homelab-excalidraw"
aliases:
- "homelab-excalidraw"
houston:
path: "~/Sites/homelab-houston"
aliases:
- "homelab-houston"
- "docs"
+10 -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"
@@ -142,6 +149,7 @@ services:
- ./config/authelia:/config
environment:
- DOMAIN=${DOMAIN}
- LLDAP_LDAP_BASE_DN=${LLDAP_LDAP_BASE_DN}
- AUTHELIA_SESSION_SECRET=${AUTHELIA_SESSION_SECRET}
- AUTHELIA_STORAGE_ENCRYPTION_KEY=${AUTHELIA_STORAGE_ENCRYPTION_KEY}
- AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET=${AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET}
+114 -8
View File
@@ -47,6 +47,98 @@ Under Milestone P4, `appctl` operates as a centralized operational control plane
└────────────────────────────────────────────────┘
```
### Operator Admin Token Bootstrapping & Rotation
`appctl` implements zero-trust authorization across three roles: `homelab-admin`, `homelab-operator`, and `homelab-viewer`. Local Unix domain socket (`/run/homelab/appctl.sock`) callers without a token are granted `homelab-viewer` privileges via `SO_PEERCRED` for non-sensitive read-only commands (e.g., `appctl list`, `appctl status`, `appctl ssl`).
Sensitive inspection (e.g., `appctl config <workload>` which renders secrets in Compose definitions) and all mutating operations (e.g., `appctl up`, `appctl restart`, `appctl update`) require an authenticated Bearer token.
#### Role of `~/.config/homelab/token`
The thin CLI client resolves Bearer tokens in the following order of precedence:
1. Direct CLI flag: `--token <secret>`
2. Environment variable: `APPCTL_TOKEN`
3. Local operator token file: `~/.config/homelab/token` (mode `0600`)
4. System service token file: `/run/secrets/appctl/token`
The standard operator setup stores a 256-bit hex Bearer token with mode `0600` in `~/.config/homelab/token`.
#### Generating a Token (`scripts/bootstrap_token.py`)
To generate an operator token and its matching SHA-256 descriptor:
```bash
python3 scripts/bootstrap_token.py
```
This utility:
1. Generates a cryptographically secure 256-bit token (`secrets.token_hex(32)`).
2. Computes the SHA-256 digest: `hashlib.sha256(raw_token.encode("utf-8")).hexdigest()`.
3. Ensures `~/.config/homelab` exists with mode `0700`.
4. Writes the raw Bearer token to `~/.config/homelab/token` with mode `0600`.
5. Outputs the JSON descriptor matching `TokenDescriptor` in `scripts/appctl_auth.py`:
```json
{
"token_id": "operator-admin",
"identity": "operator",
"role": "homelab-admin",
"sha256": "4a12...<64-hex-sha256>"
}
```
> [!NOTE]
> The raw secret is **never** printed to stdout or stderr. Only the descriptor snippet (containing the SHA-256 digest) is output. To print only the JSON snippet for automation or piping, pass `--print-json`.
#### Registering the Descriptor in SOPS
Insert the generated JSON descriptor into your encrypted SOPS secrets store (`nixos/secrets.yaml`):
```bash
sops nixos/secrets.yaml
```
Under `appctl.tokens_json`, add the entry to the JSON list:
```yaml
appctl:
tokens_json: |
[
{
"token_id": "operator-admin",
"identity": "operator",
"role": "homelab-admin",
"sha256": "<64-hex-sha256>"
}
]
```
Save and exit your editor (SOPS will re-encrypt the file), then project the updated secrets:
```bash
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
```
This updates `/run/secrets/appctl/tokens.json` (owned by `homelab-appctl:homelab-operators`, mode `0400`), which `homelab-appctl.service` consumes.
#### Verifying Token Authentication
Verify permissions using both unauthenticated and authenticated queries:
1. **Viewer Inspection** (succeeds without token via `SO_PEERCRED`):
```bash
appctl health
# Output: OK (homelab-appctl.service operational)
```
2. **Admin-Gated Operation** (requires `homelab-admin` Bearer token):
```bash
appctl config docs
# Renders the resolved Compose YAML with injected secrets
```
If the token is missing or mismatched, `appctl` returns `401 Unauthorized` or `403 Forbidden` with `ERR_PERMISSION_DENIED`.
#### Token Rotation Workflow
To rotate an operator token:
1. Run `python3 scripts/bootstrap_token.py --force --token-id "operator-admin-$(date +%Y%m%d)"`.
2. Open `sops nixos/secrets.yaml` and add the new descriptor to `appctl.tokens_json`. Keep the old entry temporarily if multiple sessions share it, or replace it immediately.
3. Run `sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure` to apply the updated token store.
4. Verify CLI operations (`appctl config docs`).
5. Remove the deprecated token descriptor from `nixos/secrets.yaml` and re-run `nixos-rebuild switch`.
---
## 2. CLI Command Reference
@@ -101,11 +193,13 @@ appctl info docs --ssl
### Lifecycle Management
#### `appctl up <service|core>`
#### `appctl up <service|core> [--build] [--no-cache]`
Starts the specified service stack in detached mode (`--remove-orphans`).
* For a workload in `~/Sites`: starts containers and triggers `appctl sync`.
* For `core`: starts the entire Core Compose stack using `/run/secrets/homeserver.env`.
* For an individual Core service (e.g., `appctl up traefik`): starts that specific container.
* When `--build` is passed: invokes `docker compose build --pull` prior to deployment. The `--pull` flag guarantees base images in Dockerfile `FROM` lines are refreshed from remote registries.
* When `--no-cache` is passed: `--build` is implied (`build: True`) and `docker compose build --pull --no-cache` is executed, forcing a clean rebuild without cached layers.
#### `appctl down <service|core>`
Stops and removes containers defined in the target's Compose file (or stops the targeted Core container).
@@ -116,19 +210,31 @@ Restarts the target stack or individual container:
* `appctl restart core`: Restarts all Core Compose services.
* `appctl restart traefik`: Restarts only the Traefik container.
#### `appctl update <service|core>`
Performs a sequential update workflow:
#### `appctl update <service> [--branch <branch>] [--build] [--no-cache]`
Performs a sequential, revision-consistent update workflow for a Sites workload stack:
1. Verifies that the local Git working tree is clean (aborts if uncommitted changes exist).
2. Runs `git pull --ff-only` to fast-forward the current branch.
3. Runs `docker compose pull` to fetch updated container images.
4. Runs `docker compose up -d --remove-orphans` to recreate containers.
2. Runs `git pull --ff-only [origin <expected_branch>]` to fast-forward the current branch.
3. Re-validates `app.yaml`, expected branch declaration, and Compose security rules against the newly pulled working tree.
4. Executes declared actions in `app.yaml` (`actions: [git_pull, compose_pull, compose_build, compose_up, compose_restart]`):
* `compose_pull`: Runs `docker compose pull` to fetch updated container images.
* `compose_build`: Runs `docker compose build --pull` (and `--no-cache` if requested).
* `compose_up`: Runs `docker compose up -d --remove-orphans` to recreate containers.
* When `--build` is passed via CLI, `compose_build` is automatically executed prior to `compose_up`, even if omitted from manifest actions.
* When `--no-cache` is passed, build is implied and executes with `--no-cache`.
5. Runs `appctl sync` to update the Homepage dashboard.
> [!NOTE]
> **Source-Built Workload Policy**: For workloads built directly from local source Dockerfiles rather than pre-built registry images, declare `compose_build` in `app.yaml` `deployment.actions` (`actions: [git_pull, compose_build, compose_up]`). Both manual `appctl update` and automated GitOps dispatcher runs will execute `docker compose build --pull` before recreating containers, ensuring reproducible builds with current upstream base layers.
> [!NOTE]
> Core platform updates are managed via version-controlled NixOS generations (`git pull` followed by `nixos-rebuild switch`), not through `appctl update core` (as Core is mounted read-only for `homelab-appctl.service`).
#### `appctl pull <service|core>`
Pulls latest container images and recreates the target service.
#### `appctl logs <service|core>`
Streams container logs (`docker compose logs -f`). Supports passing specific container names (`appctl logs core traefik` or `appctl logs stalwart`).
#### `appctl logs <service|core> [--tail N]`
Fetches a bounded snapshot of container logs (default: `--tail 100`). Supports passing a workload or targeted Core service container (e.g., `appctl logs traefik`).
*(Note: As an HTTP/1.1 request-response API, log streaming `-f` is replaced by bounded snapshots).*
#### `appctl config <service|core>`
Validates the manifest and renders the resolved Docker Compose configuration with all injected variables. Fails closed if `app.yaml` is missing or invalid.
+12 -12
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,8 +51,8 @@ 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.
* **`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>/`.
@@ -95,11 +95,10 @@ Chosen option: **Option 3: Authoritative `homelab-appctl.service` Daemon with Si
* Shell `eval` and `source` are completely eliminated. Subprocess environments are assembled in memory via an inert pure-Python `KEY=VALUE` reader enforcing `ENV_KEY_RE`, `RESERVED_ENV_KEYS`, and canonical domain precedence (`HOMELAB_DOMAIN` $\to$ `DOMAIN_SUFFIX` $\to$ `DOMAIN`).
* Every workload mutation and `workload.config` call enforces path containment, `core_manifest.parse_manifest()`, and `validate_compose_security()` pre-flight inspection before invoking Docker Compose.
#### 6. Declarative Git Truth, Five-Stage Deployment Model & AI Boundary (P5–P7 Trajectory)
#### 6. Declarative Git Truth, Model Context Protocol (MCP) Gateway & AI Boundary (P5–P7 Trajectory)
* **Git is Authoritative**: Approved deployment definitions are versioned in Git; `appctl` reconciles desired Git state into running containers.
* **Five-Stage Model Lifecycle (P6)**:
$$\text{Repository} \xrightarrow{\text{Investigation}} \text{Application Profile} \xrightarrow{\text{Proposal}} \text{DeploymentProposal} \xrightarrow{\text{Human Selection}} \text{DeploymentModel (Git)} \xrightarrow{\text{appctl Materialize}} \text{Deployment Definition} \xrightarrow{\text{Reconcile}} \text{Containers}$$
* **AI Authoring Boundary (P6)**: AI agents act strictly as upstream `DeploymentProposal` generators with zero execution or mutation authority.
* **Architecture Amendment (2026-10-23 — MCP Tool Gateway Supersedes On-Server Authoring)**:
The 5-stage on-server AI deployment authoring compiler (`ApplicationProfile` $\to$ `DeploymentProposal` $\to$ `DeploymentModel`) originally planned for Milestone P6 is **deprecated and superseded by a decoupled Model Context Protocol (MCP) Tool Gateway**. Rather than building bespoke AI authoring engines or autonomous agents into the appliance host, platform management operations (`appctl_status`, `appctl_deploy`, `appctl_logs`, `appctl_audit`) will be exposed via standardized JSON-RPC MCP tools consumed by external developer clients (Antigravity, Claude Code, Cursor) with native human-in-the-loop confirmation. The deterministic boundary of `appctl` is preserved, with zero autonomous AI agent code executing inside the appliance host.
* **Secret Reference Invariant (P5)**: Manifests reference secrets by key (`secretKeyRef`) resolved at runtime via `SecretProvider`, never storing plaintext credentials in Git.
* **Client Decoupling (P7)**: Homepage remains a read-only status portal; interactive web management belongs to a dedicated Operations UI client consuming `POST /v1/operations`.
@@ -0,0 +1,91 @@
---
type: decision
status: accepted
project: homelab-core
date: 2026-11-16
tags: [architecture, workloads, monorepo, gitops, state, nixos]
amends: 0001-3tier-architecture-and-provenance.md
---
# ADR 0004: Unified ~/Workloads Monorepo & State Isolation
## Context and Problem Statement
Under [ADR-0001](0001-3tier-architecture-and-provenance.md), Tier 2 deployment descriptors (`app.yaml` and `docker-compose.yml`) were hosted in `~/Sites/<app>` as one standalone Git repository per application. In practice, operating a fleet of 9+ Tier 2 workloads (including both Class A source-backed services and Class B off-the-shelf image-only tools) revealed structural friction:
1. **Per-App Repository Sprawl**: Every third-party tool (`jellyfin`, `snappymail`, `excalidraw`, `mermaid`) required its own Gitea repository, webhook configuration, and clone lifecycle just to version 2–3 declarative files.
2. **Naming Coupling (`~/Sites`)**: The directory name `~/Sites` implied web-only sites rather than general self-hosted workloads (mail, media, diagrams, internal tools).
3. **Cross-Workload Drift & Webhook Overhead**: Coordinating shared network, label, or manifest conventions across N separate deployment repositories required N separate commits and N separate Gitea webhook registrations.
4. **State Co-location Risk**: Moving to a unified monorepo increases the blast radius if any workload stores mutable runtime state inside its deployment directory instead of the isolated host state root (`~/var/lib/homelab/<app>/`).
The central architectural question is: **How should Canopy NixOS Core organize Tier 2 deployment descriptors to eliminate per-app repository sprawl while preserving independent per-workload deployment, backward-compatible migration, and strict runtime state isolation?**
## Decision Drivers
* **Eliminate Tier 2 Repository Sprawl**: Consolidate Tier 2 deployment descriptors (`<app>/app.yaml`, `<app>/docker-compose.yml`) into a single unified `canopy-workloads` monorepo at `~/Workloads`.
* **Preserve Per-Workload Independence**: Pushing to `canopy-workloads` must selectively deploy only the workload subdirectories modified in that push, without restarting unaffected services.
* **Zero-Downtime Migration Compatibility**: Support `WORKLOADS_DIR` as the canonical configuration variable with a clean `SITES_DIR` fallback, and support hybrid per-app `.git` checkouts alongside monorepo subdirectories during transition.
* **Strict State Isolation**: Enforce `~/var/lib/homelab/<app>/` as the sole persistent runtime state root so the `~/Workloads` Git working tree remains 100% declarative and clean.
* **Preserve 3-Tier & Security Boundaries**: Keep Tier 1 application source repositories independent, keep Core platform services in `~/Core`, and maintain `deployments.yaml` allowlisting and Compose AST security validation.
## Considered Options
* **Option 1: Keep Per-App Tier 2 Repositories in `~/Sites/<app>` (Status Quo)**: Maintain one Git repository per workload under `~/Sites`.
* **Option 2: Merge Tier 2 Workloads into `~/Core`**: Place all workload `app.yaml` and `docker-compose.yml` files directly inside `canopy-homelab/nixos-core`.
* **Option 3: Unified `~/Workloads` Monorepo (`canopy-workloads`) with Isolated Host State (Adopted)**: Amend ADR-0001 to rename Tier 2 from `~/Sites` to `~/Workloads`, consolidate Tier 2 manifests into `canopy-workloads`, and enforce `~/var/lib/homelab/<app>/` state isolation.
## Decision Outcome
Chosen option: **Option 3: Unified `~/Workloads` Monorepo (`canopy-workloads`) with Isolated Host State**, because it eliminates Tier 2 repository and webhook sprawl while preserving the 3-tier boundary between Tier 1 application source, Tier 2 deployment intent, and Tier 3 NixOS Core platform infrastructure.
### Summary of Architectural Commitments
This ADR formally amends [ADR-0001](0001-3tier-architecture-and-provenance.md) with the following commitments:
1. **Tier 2 Rename (`~/Sites` $\rightarrow$ `~/Workloads`)**:
* The canonical Tier 2 deployment root is `~/Workloads` (configured via `homelab.workloadsDir` / `homelab.sitesDir` in NixOS and `WORKLOADS_DIR` in Core services).
* Core Python modules (`appctl_engine.py`, `appctl_daemon.py`, `appctl_router.py`, `gitops_dispatcher.py`) default to `~/Workloads`, honoring `WORKLOADS_DIR` first and falling back to `SITES_DIR` for backward compatibility.
2. **Unified `canopy-workloads` Monorepo**:
* Tier 2 workloads reside as subdirectories `~/Workloads/<app>/` inside the `canopy-workloads` monorepo, each owning its own `app.yaml` and `docker-compose.yml`.
* During migration, `~/Workloads/<app>` may operate either as a monorepo subdirectory (sharing `~/Workloads/.git`) or as a standalone checkout (`~/Workloads/<app>/.git`).
3. **Mandatory State Isolation (`~/var/lib/homelab/<app>/`)**:
* All mutable application data (databases, caches, uploads, dynamic configs) must reside under `~/var/lib/homelab/<app>/` (or named Docker volumes) and never inside `~/Workloads/<app>/`.
* NixOS `systemd.tmpfiles.rules` provisions `~/Workloads` and `~/var/lib/homelab` with recursive `A+` POSIX ACLs for `homelab-appctl`.
4. **Core Registry & Safe Directory Containment**:
* `config/deployments.yaml` maps admitted workload identities to canonical `~/Workloads/<app>` paths, enforced by strict containment inside `WORKLOADS_DIR`.
* Host Git `safe.directory` configuration includes `~/Workloads` and `~/Workloads/*` (alongside `~/Core`).
## Pros and Cons of the Options
### Option 1: Keep Per-App Tier 2 Repositories in `~/Sites/<app>`
* Good, because each workload has an isolated Git history and independent webhook.
* Bad, because adding or updating a simple third-party service requires creating and maintaining a full Git repository.
* Bad, because fleet-wide manifest or Compose conventions require N separate PRs and commits.
### Option 2: Merge Tier 2 Workloads into `~/Core`
* Good, because only one repository exists for Core and Workloads.
* Bad, because it violates the 3-tier boundary (ADR-0001), mixing NixOS host/platform configuration with application deployment topologies.
* Bad, because `~/Core` changes would trigger NixOS evaluation/rebuild concerns alongside routine app updates.
### Option 3: Unified `~/Workloads` Monorepo (`canopy-workloads`) with Isolated Host State (Adopted)
* Good, because Tier 2 deployment descriptors are managed in one repository with atomic cross-workload changes and a single GitOps webhook.
* Good, because Tier 1 software repositories and Tier 3 NixOS Core remain strictly decoupled.
* Good, because `WORKLOADS_DIR` $\rightarrow$ `SITES_DIR` fallback allows incremental host cutover without breaking existing environments.
* Bad, because GitOps webhook dispatch and provenance inspection must distinguish monorepo-root `.git` from per-app `.git` checkouts (addressed in follow-up slices).
* Bad, because monorepo commits touching multiple subdirectories require changed-path filtering to avoid redeploying unaffected workloads.
## Consequences
### Positive Consequences
* **Single Tier 2 Control Surface**: One `canopy-workloads` repository versions all workload manifests and Compose topologies.
* **Clean Git Working Tree**: Enforcing `~/var/lib/homelab/<app>/` ensures runtime state never dirties the monorepo checkout.
* **Smooth Cutover**: Dual `WORKLOADS_DIR` / `SITES_DIR` environment support and `homelab.sitesDir` NixOS option compatibility prevent abrupt breakage.
### Negative Consequences & Accepted Trade-offs
* **Hybrid Provenance & Subpath Dispatch Complexity**: Core tooling (`provenance.py`, `gitops_dispatcher.py`) must handle both monorepo-level `.git` and legacy per-app `.git` directories, as well as selective changed-directory deployment on monorepo pushes.
## More Information
* **Amended Decision**: [`0001-3tier-architecture-and-provenance.md`](0001-3tier-architecture-and-provenance.md)
* **Architecture Specification**: [`docs/architecture.md`](../architecture.md)
* **Secrets & State Contract**: [`docs/secrets-and-state.md`](../secrets-and-state.md)
@@ -0,0 +1,101 @@
---
type: decision
status: accepted
project: homelab-core
date: 2026-11-20
tags: [architecture, security, nixos, workloads, appctl, gitops]
amends: 0002-appctl-control-plane-architecture.md
---
# ADR 0005: Host-Granted Workload Capabilities ("Compose Requests, Nix Grants")
## Context and Problem Statement
Under [ADR-0001](0001-3tier-architecture-and-provenance.md), [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`), and [ADR-0004](0004-unified-workloads-monorepo.md), `validate_compose_security()` (shared pre-flight validator invoked authoritatively by `homelab-appctl.service` in `scripts/appctl_router.py` across CLI and GitOps paths) enforces a uniform deny-all policy on Tier 2 workload `docker-compose.yml` files:
* `devices:` mounts are blocked.
* Host bind mounts outside `~/Workloads/<app>` and `~/var/lib/homelab/<app>` are blocked.
* Host namespace sharing (`network_mode: host`, etc.) is blocked.
While this prevents a Tier 2 `git push` from escalating privileges on the host, it blocks required single-operator capability classes:
1. **Hardware-Accelerated & External-Storage Workloads**: Media transcoding or compute workloads requiring an integrated GPU (`/dev/dri/renderD128`) must mount host device nodes, pass a supplementary device group (such as `render` / GID `303`), and read an external read-only storage partition (`/media:ro`). Currently, `devices:` and external bind mounts are blocked, while `group_add:` and `user:` primary GIDs are unconstrained (risking arbitrary host GID elevation to groups such as `docker` or `wheel` unless constrained).
2. **LAN Broadcast / Peer-Discovery Services (Out of Scope for Host Networking)**: Workloads that send Wake-on-LAN magic packets or discover LAN peers cannot traverse Docker bridge L2 isolation, prompting requests for `network_mode: host`. Because blanket host networking collapses network namespace isolation—exposing loopback control services such as `homelab-appctl.service` on `127.0.0.1:9001`—host networking remains out of scope for workload grants and must be handled via isolated L2 Docker networks (`macvlan`/`ipvlan`) or host-side intermediaries.
3. **Host-Agnostic Core Boundary**: Hardcoding `/dev/dri`, `/media`, or specific workload names inside `nixos-core` violates platform portability and couples Core to one machine's hardware and app catalog.
The central architectural question is: **How should Canopy NixOS Core permit hardware devices, supplementary/primary GIDs, and external read-only storage paths for specific workloads without hardcoding personal infrastructure into `nixos-core` or weakening the Tier 2 -> Tier 3 trust boundary?**
## Decision Drivers
* **Preserve the Trust Split**: A push to Tier 2 (`canopy-workloads`) must never grant itself root-equivalent host access; capability grants must originate from root-level Tier 3 NixOS host configuration (`nixos-rebuild switch`).
* **Keep `nixos-core` Generic**: Core defines the capability schema and enforcement logic only, with zero hardcoded personal app names, device nodes, or media paths.
* **Keep `app.yaml` Free of Host Paths**: Workload manifests remain declarative routing/provenance metadata; `docker-compose.yml` already declares requested `devices`, `volumes`, `group_add`, and `user`.
* **Documented Instance Schema**: Provide a tracked `nixos/instance.example.nix` template so new hosts can configure `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants` in `/etc/nixos/homelab-instance.nix` (or gitignored `nixos/instance.nix`).
* **Fail-Closed Validation**: An absent grants file defaults to zero grants (current baseline); a present but unreadable, tampered, or malformed grants file fails closed across all workloads. `privileged: true`, `/var/run/docker.sock`, `cap_add`, `device_cgroup_rules:`, and host/container namespace sharing remain permanently prohibited.
## Considered Options
* **Option 1: Relax `validate_compose_security()` Globally**: Allow `/dev/dri` and arbitrary `:ro` paths for all workloads.
* **Option 2: Store Grants in `~/Workloads/grants.yaml`**: Allow `canopy-workloads` to declare its own exceptions alongside `deployments.yaml`.
* **Option 3: "Compose Requests, Nix Grants" via `homelab.workloadGrants` (Adopted)**: Define a typed `homelab.workloadGrants` option in `nixos-core` rendered to root-owned `/etc/homelab/grants.json`, validated with Pydantic v2 (`extra="forbid"`), and enforced by `validate_compose_security()`.
## Decision Outcome
Chosen option: **Option 3: "Compose Requests, Nix Grants" via `homelab.workloadGrants`**, because it keeps `nixos-core` hardware- and workload-agnostic while preserving the security boundary between Tier 2 Git pushes and Tier 3 `sudo nixos-rebuild switch`.
### Summary of Architectural Commitments
This ADR formally amends [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`) with the following commitments:
1. **Typed Host Grant Schema (`homelab.workloadGrants`)**:
* `nixos/modules/homeserver.nix` defines `homelab.workloadGrants` as an attribute set keyed by workload name, supporting three explicit grant fields:
* `devices` (list of exact device paths; prefer specific nodes such as `"/dev/dri/renderD128"` over whole directories unless display control is required).
* `groups` (list of supplementary/primary group names or GIDs permitted in `group_add` and `user:`, such as `"render"` or `"303"`; privileged host groups `0`/`root`, `wheel`, and `docker` are permanently rejected).
* `readOnlyPaths` (list of host directories permitted for read-only bind mounts only).
* `privileged: true`, `/var/run/docker.sock`, `cap_add`, `device_cgroup_rules:`, and namespace sharing (`network_mode: host`, `network_mode: container:*`, `network_mode: service:*`, `pid`, `ipc`, `uts`, `userns_mode: host`) remain permanently prohibited and are not grantable.
2. **Immutable Host Projection (`/etc/homelab/grants.json`)**:
* NixOS generates `/etc/homelab/grants.json` (`root`-owned, group-owned by `homelab-operators` with mode `0640`, granting read access to both `homelab-appctl` and `operator` without POSIX ACLs; overridable via `HOMELAB_GRANTS_FILE`, which is reserved in `RESERVED_ENV_KEYS` so workload `.env` / `app.yaml` cannot override it).
* In production, the loader verifies regular-file (non-symlink), root-owned, non-world/group-writable permissions before parsing.
* If `/etc/homelab/grants.json` is **absent**, `validate_compose_security()` defaults to zero grants. If it is **present** but unreadable, fails permission checks, or fails Pydantic v2 (`extra="forbid"`) validation, pre-flight fails closed for all workloads.
3. **Exact-Match Pre-Flight Enforcement**:
* `validate_compose_security()` evaluates resolved values (post-6-layer env assembly, or rejects uninterpolated `${...}` in `devices`, `volumes`, `group_add`, and `user`). When `app_name` is `None` or unknown, zero grants apply.
* Every capability requested in `<app>/docker-compose.yml` must match an explicit grant for `<app>`:
* `devices` entries support `host:container[:perms]`, forbid `m` (`mknod`) in permissions, and require the host path to exist and resolve canonically within the granted device node or directory, disallowing `..` traversal or symlink escapes.
* `group_add` transitions from unconstrained to **default-deny** when no `groups` grant exists; `groups` entries canonicalize bidirectionally between group names and integer GIDs via the host group database. `user:` primary GIDs must either fall within granted `groups` or be unprivileged numeric IDs that do not map to privileged or host-sensitive groups.
* `readOnlyPaths` validates both short (`host:container:ro[,opts]`) and long (`type: bind`, `read_only: true`) volume syntax, rejects unsafe bind propagation, and requires the host path to exist and resolve canonically within the granted directory.
4. **Tracked Instance Template (`nixos/instance.example.nix`)**:
* `nixos-core` tracks `nixos/instance.example.nix` documenting `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants`.
* Live hosts keep concrete values in `/etc/nixos/homelab-instance.nix` (loaded via `--impure` flake evaluation, taking precedence over gitignored `nixos/instance.nix` if both exist). Both paths remain optional so pure `nix flake check` CI passes with defaults.
## Pros and Cons of the Options
### Option 1: Relax `validate_compose_security()` Globally
* Good, because it requires minimal code.
* Bad, because it hardcodes host hardware assumptions into `nixos-core` and weakens tenant isolation for all workloads.
### Option 2: Store Grants in `~/Workloads/grants.yaml`
* Good, because grants live next to `deployments.yaml`.
* Bad, because Tier 2 would self-authorize Tier 3 host privileges on a single `git push`.
### Option 3: "Compose Requests, Nix Grants" via `homelab.workloadGrants` (Adopted)
* Good, because `nixos-core` stays generic, `canopy-workloads` remains free of host-privilege grants, and privilege elevation requires explicit host-level `nixos-rebuild switch`.
* Bad, because adding a new privileged capability requires editing `/etc/nixos/homelab-instance.nix` and rebuilding NixOS before `appctl up`.
## Consequences
### Positive Consequences
* **Hardware & Media Operability**: Workloads can use GPU acceleration and external `:ro` storage cleanly via standard `docker-compose.yml` syntax once authorized by the host.
* **Closed GID & Namespace Loopholes**: Transitions `group_add:`, `user:` primary GIDs, `device_cgroup_rules:`, and `network_mode: container:*` to fail-closed enforcement.
* **CI Compatibility**: Pure `nix flake check` evaluates cleanly with empty default grants.
### Negative Consequences & Accepted Trade-offs
* **Tier 2 / Tier 3 Deployment Ordering**: Pushing a Compose file requesting a new capability before running `nixos-rebuild switch` fails closed at pre-flight (surfaced clearly via a distinct capability-denial error/audit signal such as `ERR_CAPABILITY_NOT_GRANTED`).
* **Host Path Coupling**: Workload Compose files declare physical host paths matching host grants; logical capability aliasing via environment-variable injection remains an optional future refinement.
## More Information
* Amends [ADR-0002](0002-appctl-control-plane-architecture.md) (`DEC-04`, `DEC-05`).
* Related specifications: [docs/architecture.md](../architecture.md), [docs/appctl.md](../appctl.md), [docs/secrets-and-state.md](../secrets-and-state.md).
+22 -2
View File
@@ -10,14 +10,34 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
| Decision Record | Status | Date | Scope & One-Line Purpose |
| :--- | :--- | :--- | :--- |
| [**ADR-0005: Host-Granted Workload Capabilities**](0005-workload-capability-grants.md) | `accepted` | 2026-11-20 | Amends ADR-0002 to introduce `homelab.workloadGrants` (`/etc/homelab/grants.json`) and `nixos/instance.example.nix` so NixOS hosts explicitly authorize `devices`, `groups`, and `readOnlyPaths` per workload while keeping host/container networking prohibited. |
| [**ADR-0004: Unified ~/Workloads Monorepo & State Isolation**](0004-unified-workloads-monorepo.md) | `accepted` | 2026-11-16 | Amends ADR-0001 to adopt the unified `~/Workloads` Tier 2 monorepo (`canopy-workloads`), rename `~/Sites` to `~/Workloads` with `WORKLOADS_DIR` fallback, and enforce `~/var/lib/homelab/<app>/` state isolation. |
| [**ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. |
| [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and the 5-stage `DeploymentModel` lifecycle. |
| [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and deterministic Git-backed declarative deployment state. |
| [**ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model**](0001-3tier-architecture-and-provenance.md) | `accepted` | 2026-09-28 | Establishes 3-tier separation (Software, OCI Artifact, Sites Deployment, Core Platform), two workload classes (Source-Backed vs. Image-Only), isolated state root (`~/var/lib/homelab/<app>/`), and two operational inspection axes. |
---
## 🧭 Summaries of Governing Decisions
### [ADR-0005: Host-Granted Workload Capabilities ("Compose Requests, Nix Grants")](0005-workload-capability-grants.md)
* **Canonical Document**: [`0005-workload-capability-grants.md`](0005-workload-capability-grants.md)
* **Status**: `accepted` (Active — Amends ADR-0002)
* **Core Commitments**:
1. **Typed Host Grant Schema (`homelab.workloadGrants`)**: NixOS exposes per-workload `devices`, `groups`, and `readOnlyPaths` grants while keeping `privileged: true`, `docker.sock`, `cap_add`, `device_cgroup_rules`, and host/container namespace sharing permanently forbidden.
2. **Immutable Host Projection (`/etc/homelab/grants.json`)**: Projected root-owned at rebuild time; absent file defaults to zero grants, malformed file fails closed.
3. **Exact-Match Pre-Flight Enforcement**: `validate_compose_security()` allows requested capabilities only when canonically matched against the workload's Nix grant (and `:ro` for `readOnlyPaths`).
4. **Tracked Instance Template (`nixos/instance.example.nix`)**: Documents `homelab.domain`, `homelab.operatorUser`, and `homelab.workloadGrants` for `/etc/nixos/homelab-instance.nix`.
### [ADR-0004: Unified ~/Workloads Monorepo & State Isolation](0004-unified-workloads-monorepo.md)
* **Canonical Document**: [`0004-unified-workloads-monorepo.md`](0004-unified-workloads-monorepo.md)
* **Status**: `accepted` (Active — Amends ADR-0001)
* **Core Commitments**:
1. **Tier 2 Rename (`~/Sites` -> `~/Workloads`)**: Canonical Tier 2 deployment root is `~/Workloads`, with `WORKLOADS_DIR` -> `SITES_DIR` environment fallback.
2. **Unified `canopy-workloads` Monorepo**: Tier 2 workload manifests (`app.yaml`, `docker-compose.yml`) consolidate under `~/Workloads/<app>/`, supporting hybrid per-app `.git` checkouts during migration.
3. **Mandatory State Isolation**: All mutable application data resides strictly under `~/var/lib/homelab/<app>/` (or named Docker volumes), never inside `~/Workloads`.
4. **Workloads Registry & Safe Directory Containment**: `~/Workloads/deployments.yaml` (templated by `config/deployments.yaml`) resolves admitted workloads within `WORKLOADS_DIR`; NixOS `safe.directory` includes `~/Workloads` and `~/Workloads/*`.
### [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md)
* **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md)
* **Status**: `accepted` (Active)
@@ -38,7 +58,7 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
2. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**: Every mutating operation and sensitive read (`workload.config`, `workload.logs`) requires an authenticated SHA-256 Bearer token (`/run/secrets/appctl/tokens.json`); tokenless UDS calls fall back via `SO_PEERCRED` strictly to `homelab-viewer` read-only inspection.
3. **Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)**: Daemon executes as `homelab-appctl:homelab-operators` with mode `0600` append-only `/var/log/homelab/appctl/audit.jsonl` and a pre-execution `DISPATCHED` disk guard.
4. **GitOps Worker Unification & Pure-Python Pre-Flight (`DEC-04`, `DEC-05`)**: `gitops_dispatcher.py` worker delegates `workload.update` to the daemon; shell `source`/`eval` are replaced with pure-Python `.env` parsing and mandatory `validate_compose_security()` pre-flight checks.
5. **Git Truth, Five-Stage Deployment Model & AI Boundary (P5–P7)**: Git remains authoritative deployment state; separates `ApplicationProfile` $\to$ `DeploymentProposal` (AI) $\to$ `DeploymentModel` (human-approved in Git) $\to$ materialized descriptors; resolves workload secrets via `SecretProvider` (`secretKeyRef`).
5. **Git Truth, Model Context Protocol (MCP) Gateway & AI Boundary (P5–P7)**: Git remains authoritative deployment state; on-server AI proposal compilers deprecated in favor of a decoupled Model Context Protocol (MCP) tool gateway with human confirmation gating; resolves workload secrets via `SecretProvider` (`secretKeyRef`).
### [ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model](0001-3tier-architecture-and-provenance.md)
* **Canonical Document**: [`0001-3tier-architecture-and-provenance.md`](0001-3tier-architecture-and-provenance.md)
+4 -4
View File
@@ -27,7 +27,7 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
▼
┌───────────────────────────────────────────────┐
│ 3. Authoritative Registry Resolution │
│ 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.
@@ -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`)**:
+360 -4
View File
@@ -16,9 +16,15 @@ After modifying any file in `nixos/` (including `configuration.nix`, `hardware-c
nix-switch
# Or using the explicit command:
sudo nixos-rebuild switch --flake ~/Core#server
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
```
> [!NOTE]
> **Flake Fetcher Scheme for Untracked Files**:
> When importing the gitignored `nixos/instance.nix`, Nix's default Git fetcher filters it out unless the `path:` scheme is used (`path:/home/operator/Core#server` or `path:~/Core#server`). The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index.
> If using `/etc/nixos/homelab-instance.nix`, a standard `--flake ~/Core#server --impure` works directly since `/etc/nixos` is outside the repository.
### Dry Build Validation & Rollback
```bash
# Validate build without activating (catches evaluation and syntax errors)
@@ -103,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
@@ -139,9 +145,8 @@ appctl restart docs
appctl restart traefik
appctl restart authelia
# Sequential stack update (clean working tree check -> git pull -> compose pull -> up -> sync)
# Sequential stack update for independent Workloads (clean tree check -> git pull -> compose pull -> up -> sync)
appctl update docs
appctl update core
# Stream live container logs
appctl logs docs
@@ -151,6 +156,37 @@ appctl logs -f stalwart
appctl config docs
```
### Workload vs. Core Update Policy
Homelab enforces a strict architectural boundary between independent application workloads (`~/Workloads/<app>`) and Homelab Core (`~/Core`):
#### 1. Independent Workloads (`~/Workloads/<app>`)
- **Automated Lifecycle**: Workloads declare their lifecycle via `app.yaml` manifests and Compose definitions.
- **Update Command**: `appctl update <workload>` performs pre-flight verification, branch matching, `git pull --ff-only`, container image pull, stack reload, and dashboard synchronization.
- **GitOps Webhook Dispatch**: Workloads registered in `~/Workloads/deployments.yaml` (with `config/deployments.yaml` as the example template) can be triggered automatically via authenticated GitOps webhooks on Gitea push events.
- **Daemon Permissions**: `homelab-appctl.service` holds read-write permissions over `~/Workloads` to manage files, compose configurations, and workload state.
#### 2. Homelab Core Platform Stack (`~/Core`)
- **Host Foundation & Invariant Boundary**: Core defines NixOS host definitions, platform secrets, edge ingress, and security sandboxes.
- **No Untrusted Webhooks**: Core does **not** register for webhook dispatch in `~/Workloads/deployments.yaml`. External push events can never trigger an automated deployment or rebuild of Core.
- **Read-Only Sandbox**: Under NixOS systemd sandboxing (`ProtectHome = "read-only"`), `homelab-appctl.service` has strictly read-only access to `/home/operator/Core`. The daemon cannot mutate the Core Git repository or run `git pull` on Core.
- **Operator-Driven Update Workflow**: Core updates must be executed explicitly by the operator:
1. Review and pull repository changes:
```bash
cd ~/Core && git pull --ff-only
```
2. If NixOS modules or secrets changed, evaluate and activate the new system generation:
```bash
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
```
3. If Compose definitions changed, restart the platform stack:
```bash
docker compose up -d --remove-orphans
# or via systemd:
sudo systemctl restart homeserver-core
```
4. Individual platform services can be restarted via appctl using an authenticated admin token (`appctl restart traefik`, `appctl restart authelia`).
---
## 4. User Identity & Access Management (LLDAP & Authelia)
@@ -279,3 +315,323 @@ To bring up a replacement host from version control:
```bash
sudo systemctl start homeserver-core
```
---
## 7. Operator Account Migration Runbook (Decision D2: Staged Coexistence Cutover)
> [!CAUTION]
> **MAINTENANCE WINDOW REQUIRED — EXECUTION ON LIVE HOST CURRENTLY BLOCKED**
> Live execution of this runbook against production hosts is strictly blocked until an authorized platform maintenance window is scheduled. This runbook is codified for procedural readiness and dry-run verification only.
This runbook defines the 4-stage staged coexistence cutover procedure to migrate host operation from a legacy personal operator account (`<legacy-operator>`) to the platform standard `operator` user (`uid = 1000`, `extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]`), fulfilling Decision D2 and eliminating personal identity coupling.
### Stage 1: Pre-Flight Checks & Session Preservation
> [!IMPORTANT]
> **Maintain Active Legacy Shell Session**:
> Do not terminate your active SSH or terminal session as `<legacy-operator>`. Keep at least one authenticated shell open throughout the entire cutover process to prevent lockout in case of SSH key, user profile, or PAM misconfiguration.
1. **Verify or provision `operator` account**:
Check if the `operator` user exists in the running environment:
```bash
id operator
```
If `operator` does not exist yet (as `homelab.operatorUser` has not been switched in the active NixOS generation), provision the initial coexistence user before proceeding:
```bash
sudo useradd -m -s /run/current-system/sw/bin/bash -G wheel,docker,homelab-operators operator
```
2. **Verify SSH key provisioning & permissions**:
Ensure the operator's authorized keys are installed with strict permissions (copying from `<legacy-operator>` if needed):
```bash
sudo mkdir -p /home/operator/.ssh
if [ ! -f /home/operator/.ssh/authorized_keys ] && [ -f /home/<legacy-operator>/.ssh/authorized_keys ]; then
sudo cp /home/<legacy-operator>/.ssh/authorized_keys /home/operator/.ssh/authorized_keys
fi
sudo chmod 700 /home/operator/.ssh
sudo chmod 600 /home/operator/.ssh/authorized_keys
sudo chown -R operator:users /home/operator/.ssh
```
3. **Verify administrative (`sudo`) access**:
Test that `operator` can authenticate and execute privileged commands without failure:
```bash
sudo -u operator sudo -n true || echo "Passwordless or password sudo required for operator"
```
4. **Prepare persistent directories**:
Ensure `/home/operator/Sites`, `/home/operator/Core`, `/home/operator/var/lib/homelab`, and state parent paths are ready:
```bash
sudo mkdir -p /home/operator/{Core,Sites,.config/homelab,var/lib/homelab,.local/state/homelab}
sudo chown -R operator:homelab-operators /home/operator/{Core,Sites,.config,var,.local}
```
---
### Stage 2: State and Repository Synchronization
Synchronize repository checkouts, workload persistent data, and runtime state from the legacy user account to `/home/operator/` using non-destructive archive flags (`-aHAX` preserves hard links, attributes, and extended ACLs):
1. **Initial background synchronization**:
Seed the file trees for Core, Sites, workload databases, and configurations while services continue running:
```bash
sudo rsync -aHAX --info=progress2 \
--exclude=".venv" \
--exclude=".pytest_cache" \
/home/<legacy-operator>/Core/ /home/operator/Core/
sudo rsync -aHAX --info=progress2 \
/home/<legacy-operator>/Sites/ /home/operator/Sites/
if [ -d "/home/<legacy-operator>/var/lib/homelab" ]; then
sudo rsync -aHAX --info=progress2 \
/home/<legacy-operator>/var/lib/homelab/ /home/operator/var/lib/homelab/
fi
if [ -d "/home/<legacy-operator>/.local/state/homelab" ]; then
sudo rsync -aHAX --info=progress2 \
/home/<legacy-operator>/.local/state/homelab/ /home/operator/.local/state/homelab/
fi
if [ -d "/home/<legacy-operator>/.config/homelab" ]; then
sudo rsync -aHAX --info=progress2 \
/home/<legacy-operator>/.config/homelab/ /home/operator/.config/homelab/
fi
```
2. **Quiesce active database writers**:
Stop running workload containers and the Core platform stack to guarantee point-in-time consistency across SQLite databases (e.g. LLDAP `users.db`, Authelia `db.sqlite3`, Stalwart storage, and workload app volumes in `~/var/lib/homelab/`) before the final sync:
```bash
# Stop running workload containers
appctl down --all 2>/dev/null || docker stop $(docker ps -q) 2>/dev/null || true
# Stop platform core services
sudo systemctl stop homeserver-core
sudo systemctl stop homelab-appctl
sudo systemctl stop homelab-gitops
```
3. **Final delta synchronization (`--delete`)**:
Perform a rapid final delta synchronization with `--delete` to capture the quiesced database state and prune removed files:
```bash
sudo rsync -aHAX --delete --info=progress2 \
--exclude=".venv" \
--exclude=".pytest_cache" \
/home/<legacy-operator>/Core/ /home/operator/Core/
sudo rsync -aHAX --delete --info=progress2 \
/home/<legacy-operator>/Sites/ /home/operator/Sites/
if [ -d "/home/<legacy-operator>/var/lib/homelab" ]; then
sudo rsync -aHAX --delete --info=progress2 \
/home/<legacy-operator>/var/lib/homelab/ /home/operator/var/lib/homelab/
fi
if [ -d "/home/<legacy-operator>/.local/state/homelab" ]; then
sudo rsync -aHAX --delete --info=progress2 \
/home/<legacy-operator>/.local/state/homelab/ /home/operator/.local/state/homelab/
fi
```
4. **Fix ownership and permissions**:
Set primary ownership to `operator` and group to `homelab-operators` across all migrated trees:
```bash
sudo chown -R operator:homelab-operators \
/home/operator/Core \
/home/operator/Sites \
/home/operator/.config \
/home/operator/.local \
/home/operator/var
sudo chmod -R u+rwX,g+rX /home/operator/Core /home/operator/Sites /home/operator/var
# ACME certificate security invariant: Traefik strictly requires 0600 on acme.json;
# recursive group read permissions will cause Traefik to refuse to start.
if [ -f /home/operator/Core/config/letsencrypt/acme.json ]; then
sudo chmod 600 /home/operator/Core/config/letsencrypt/acme.json
fi
```
---
### Stage 3: Service Rebuild & Environment Cutover
Activate the declarative configuration under the `operator` profile:
1. **Configure instance domain injection (Decision D1)**:
Ensure `nixos/instance.nix` (or `/etc/nixos/homelab-instance.nix`) is in place with the host's production domain:
```bash
cat << 'EOF' | sudo -u operator tee /home/operator/Core/nixos/instance.nix > /dev/null
{
homelab.domain = "example.com";
}
EOF
chmod 600 /home/operator/Core/nixos/instance.nix
```
2. **Bootstrap appctl control plane tokens (CR-SO-08)**:
The `homelab-appctl.service` control plane daemon enforces 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`) authenticated via SHA-256 Bearer tokens stored in `/run/secrets/appctl/tokens.json`.
Generate the operator administrator token and local CLI credentials:
```bash
sudo -u operator python3 /home/operator/Core/scripts/bootstrap_token.py
```
This command:
- Creates `~/.config/homelab/token` (mode `0600`) owned by `operator:homelab-operators` containing the raw Bearer token used automatically by the `appctl` CLI.
- Outputs the JSON token descriptor containing the SHA-256 digest:
```json
{
"token_id": "operator-admin",
"identity": "operator",
"role": "homelab-admin",
"sha256": "<64-character-sha256-digest>"
}
```
> [!IMPORTANT]
> **Unprovisioned Token Behavior & RBAC Fallback**:
> If tokens are not provisioned in `/run/secrets/appctl/tokens.json`, local UDS connections (`/run/homelab/appctl.sock`) fall back to Linux `SO_PEERCRED` socket credentials, granting callers in `homelab-operators` the read-only `homelab-viewer` role.
> Under `homelab-viewer`, safe queries succeed (`appctl list`, `appctl status`, `appctl health`).
> However, **all mutating and privileged operations** (`appctl up`, `appctl down`, `appctl restart`, `appctl update`, `appctl deploy`, `appctl config`, `appctl info`) **strictly require** a valid Bearer token with `homelab-operator` or `homelab-admin` role. If tokens are not enrolled in SOPS, attempting mutating actions fails with HTTP 403 `ERR_PERMISSION_DENIED`.
Enroll the token descriptor into SOPS secrets:
```bash
sops /home/operator/Core/nixos/secrets.yaml
```
Under `appctl.tokens_json`, insert the descriptor into the JSON array:
```yaml
appctl:
tokens_json: |
[
{
"token_id": "operator-admin",
"identity": "operator",
"role": "homelab-admin",
"sha256": "<paste-sha256-digest-here>"
}
]
```
*(Optional: If GitOps webhook dispatch is enabled, generate and enroll a `gitops-webhook` token with `homelab-operator` role using `python3 scripts/bootstrap_token.py --identity gitops --role homelab-operator --token-id gitops-webhook --print-json`).*
3. **Rebuild NixOS host configuration**:
Execute the rebuild from the new canonical Core path using `--impure` and the `path:` scheme to import the untracked instance profile:
```bash
cd /home/operator/Core
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
```
> [!NOTE]
> The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index, ensuring untracked/gitignored `nixos/instance.nix` is evaluated. (If using `/etc/nixos/homelab-instance.nix`, bare `--flake .#server --impure` works directly). Rebuilding also decrypts and projects `/run/secrets/appctl/tokens.json` via `sops-nix`.
4. **Restart platform services**:
Restart the Core Compose stack and control plane services to consume updated paths and secrets:
```bash
sudo systemctl restart homeserver-core
sudo systemctl restart homelab-appctl
sudo systemctl restart homelab-gitops
```
---
### Stage 4: Post-Flight Verification
Validate system health and operational readiness under the `operator` identity:
1. **Verify Git safe directory**:
Ensure Git does not complain about dubious ownership when invoked by `operator` or `homelab-appctl`:
```bash
sudo -u operator git -C /home/operator/Core status
sudo -u operator git -C /home/operator/Sites/<any-workload> status
```
2. **Verify SOPS secrets and tokens projection**:
Ensure `/run/secrets/appctl/tokens.json` is readable by `homelab-appctl` (mode `0400`, owned by `homelab-appctl:homelab-operators`) and contains valid descriptors:
```bash
sudo ls -l /run/secrets/appctl/tokens.json
```
3. **Verify appctl control plane status & RBAC authentication**:
Execute CLI inspection using both UDS peercred authentication (read-only viewer fallback) and authenticated admin token operations:
```bash
# 1. Peercred UDS inspection (demonstrates viewer fallback for read-only actions)
sudo -u operator appctl list --core
sudo -u operator appctl status
sudo -u operator appctl health
# 2. Authenticated operator admin verification (requires homelab-admin Bearer token)
sudo -u operator appctl info docs
sudo -u operator appctl config docs
```
Confirm that `info` and `config` return resolved configuration without `ERR_PERMISSION_DENIED`, verifying that `~/.config/homelab/token` matches the provisioned SHA-256 digest in `/run/secrets/appctl/tokens.json`.
4. **Verify container reachability & proxy routing**:
Check that external endpoints and internal reverse proxies resolve:
```bash
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
curl -s -k https://127.0.0.1 -H "Host: dashboard.example.com" | head -n 5
```
---
### Rollback Procedure
If unexpected service degradation occurs during the cutover:
1. **Revert NixOS system generation**:
```bash
sudo nixos-rebuild switch --rollback
```
2. **Restart legacy Core services**:
```bash
sudo systemctl restart homeserver-core
sudo systemctl restart homelab-appctl
sudo systemctl restart homelab-gitops
```
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/*`.
+1 -1
View File
@@ -391,4 +391,4 @@ Before marking Milestone P4 complete, the following automated regression suite m
| **Truthful Error Reporting** | `test_execution_failure_audit`: Failing or timing-out Docker/Git subprocess returns `500 ERR_EXECUTION_FAILED` and records `phase: FAILED` in `audit.jsonl`. | Reject PR |
| **Audit Persistence Gate** | `test_audit_failure_blocks_mutation`: Unwritable `audit.jsonl` aborts mutating command with `500 ERR_EXECUTION_FAILED` and zero Docker/Git invocations. | Block Release |
| **Daemon Crash Recovery** | `test_daemon_restart_preserves_state`: Clean stop and restart of daemon unlinks/rebinds socket cleanly and leaves running workloads and Git state undisturbed. | Reject PR |
| **Existing Invariant Regression** | Run `./scripts/test`: All 124 existing unit, security, structural, Ruff, Pyright, and Nix flake sandbox checks pass with 0 regressions. | Block Merge |
| **Existing Invariant Regression** | Run `./scripts/run-tests`: All 124 existing unit, security, structural, Ruff, Pyright, and Nix flake sandbox checks pass with 0 regressions. | Block Merge |
@@ -0,0 +1,106 @@
# 📋 Implementation Plan: Control Plane Hardening, Instance Decoupling & MCP Alignment
**Document Version**: 1.0
**Status**: 🚀 Approved for Implementation
**Date**: 2026-10-23
**Target Milestone**: P4 Hardening & P6 Deprecation
**Branch**: `refactor/appctl-rework`
---
## 1. Executive Summary & Context
During the pre-merge readiness investigation of the `refactor/appctl-rework` branch, four deployment blockers and several architectural divergences were identified:
1. **Unconfigured Root Domain**: `options.homelab.domain` defaulted to `"example.test"`, which would overwrite live routing templates (`homeserver.env`, `traefik-deployments.env`) upon `nixos-rebuild switch`.
2. **Authelia/LLDAP Base DN Desynchronization**: Compose defaulted `LLDAP_LDAP_BASE_DN` to `dc=example,dc=test`, conflicting with the existing on-host LLDAP database (`dc=<domain-prefix>,dc=<tld>`).
3. **Operator Identity Coupling**: Core configurations referenced legacy operator username literals rather than a generic system operator (`operator`).
4. **POSIX ACL & Git Dubious Ownership**: `tmpfiles.rules` used lowercase `a+` (non-recursive), leaving existing checkouts in `~/Sites` unwriteable to `homelab-appctl`. Furthermore, Git 2.35.2+ lacked `safe.directory` declarations for `homelab-appctl`.
5. **AI Authoring Boundary Evolution**: Earlier architectural planning explored an on-server 5-stage deployment authoring pipeline (`ApplicationProfile` $\to$ `DeploymentProposal` $\to$ `DeploymentModel` compiler). This requirement is formally deprecated in favor of a decoupled Model Context Protocol (MCP) tool gateway.
This plan establishes the concrete implementation work packages to resolve these findings and ensure 100% deployment safety.
---
## 2. Architectural Decisions & Scope
### A. Operator Identity Decoupling (Legacy Operator $\to$ `operator`)
- Standardize the primary platform operator as `operator` with home directory `/home/operator`.
- `config.homelab.operatorUser` defaults to `"operator"`.
- NixOS declares user `operator` (`uid = 1000` or standard user, `extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]`).
- Eliminates hardcoded personal usernames from the Core platform foundation.
### B. Platform Genericism & Instance Profile (Decision D1)
- Core modules in `nixos/modules/` remain strictly generic, defaulting to RFC 2606 placeholders (`example.test` and `operator`).
- **Decision D1: Dual-Path Instance Domain Injection**: Rather than committing host-specific production domains to tracked Git files, `nixos/configuration.nix` implements an optional dual-path import mechanism:
```nix
imports = [
./hardware-configuration.nix
./modules/homeserver.nix
./modules/traefik-deployments.nix
./modules/dynu.nix
./modules/shell.nix
] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix
++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix;
```
- `nixos/instance.nix` is git-ignored, allowing host-specific overrides (like `homelab.domain = "example.com";`) without dirtying version control. Alternatively, `/etc/nixos/homelab-instance.nix` provides a persistent host-level configuration path outside the repository checkout.
- `LLDAP_LDAP_BASE_DN` is computed dynamically in Nix from `config.homelab.domain` (`domain: example.test` $\implies$ `dc=example,dc=test`), eliminating hardcoded domain strings across templates and Compose files.
### C. Control Plane Security & POSIX Permissions
- **Recursive ACLs**: Change `a+` to uppercase `A+` for `${config.homelab.sitesDir}` and `${config.homelab.coreDir}/config/homepage` in `systemd.tmpfiles.rules`.
- **Git Safe Directory**: Configure `programs.git.config.safe.directory = [ "/home/operator/Sites/*" ]` for the host.
- **Fail-Closed CLI**: If `/run/homelab/appctl.sock` is unavailable, `scripts/appctl` fails closed with an informative error rather than silently falling back to unauthenticated Bash execution.
- **CLI Status Restoration**: Restore live container inspection (`get_docker_status()`) in `workload.list` and format the `STATUS` column in `scripts/appctl_cli.py`.
### D. Deprecation of On-Server AI Authoring Pipeline (MCP Gateway Adoption)
- As documented in `~/Brain/02-discussions/homelab/mcp-gateway-and-platform-evolution.md`, on-server AI deployment agents (`DeploymentProposal` compilers) are deprecated.
- Milestone P6 is redefined as the **Homelab MCP Gateway**:
- Exposes deterministic `appctl` operations over JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`, `appctl_audit`).
- Gated by native client-side human confirmation (Antigravity, Claude Code, Cursor).
- Keeps Core 100% deterministic with zero autonomous agent loops executing on the appliance host.
---
## 3. Work Breakdown Structure (WBS)
### Phase 1: Host Configuration & Identity Migration
- [x] **Task 1.1**: Update `nixos/configuration.nix` to declare user `operator` and configure `homelab.operatorUser = "operator"` and `homelab.domain` with the configured production domain.
- [x] **Task 1.2**: Declare `programs.git.config.safe.directory = [ "/home/operator/Sites/*" ]` in `nixos/configuration.nix`.
- [x] **Task 1.3**: Derive `LLDAP_LDAP_BASE_DN` dynamically from `config.homelab.domain` in `nixos/modules/homeserver.nix` and pass it to `sops.templates."homeserver.env"`.
- [x] **Task 1.4**: Update `docker-compose.yml` to consume `LLDAP_LDAP_BASE_DN` from `homeserver.env`.
- [x] **Task 1.5**: Update `systemd.tmpfiles.rules` in `nixos/modules/homeserver.nix` from `a+` to recursive `A+` on `sitesDir`.
### Phase 2: CLI Hardening & Status Parity
- [x] **Task 2.1**: Update `scripts/appctl` to fail closed when `[ ! -S "$SOCKET_PATH" ]`, removing the silent fallback to legacy Bash.
- [x] **Task 2.2**: Update `_op_workload_list` in `scripts/appctl_router.py` to query live container health (`get_docker_status()`).
- [x] **Task 2.3**: Update `_format_workload_table` in `scripts/appctl_cli.py` to render the `STATUS` column (`🟢 Running (1)` / `🔴 Stopped`).
- [x] **Task 2.4**: Bootstrap operator admin token documentation and setup instructions in `docs/appctl.md` and `docs/secrets-and-state.md`.
- [x] **Task 2.5**: Wire `--build` and `--no-cache` in `scripts/appctl_cli.py`, pass `--pull` during `compose_build` in `scripts/appctl_router.py`, and document source-built action policy in `docs/appctl.md`.
### Phase 3: Architectural Records & Roadmap Synchronization
- [x] **Task 3.1**: Update `ROADMAP.md` (P6 redefined as Homelab MCP Gateway; on-server AI compiler deprecated).
- [x] **Task 3.2**: Add architectural amendment note to `docs/decisions/0002-appctl-control-plane-architecture.md`.
- [x] **Task 3.3**: Update `docs/decisions/README.md`.
- [x] **Task 3.4**: Update `docs/appctl.md` (clarifying bounded log snapshots and Core update workflow).
- [x] **Task 3.5**: Synchronize `todo.txt` with active implementation tasks.
### Phase 4: Work Package 6 (WP6: Instance Decoupling & Operator Cutover Runbook)
- [x] **Task 4.1**: Update `nixos/configuration.nix` with optional dual-path imports for `./instance.nix` and `/etc/nixos/homelab-instance.nix` (Decision D1).
- [x] **Task 4.2**: Add `nixos/instance.nix` to `.gitignore` to preserve 100% repository genericism.
- [x] **Task 4.3**: Implement automated invariant tests in `tests/security/test_security_invariants.py` (default domain evaluation, dynamic LDAP base DN, instance override, platform genericism).
- [x] **Task 4.4**: Document instance domain injection procedure in `docs/setup_guide.md`.
- [x] **Task 4.5**: Codify the 4-stage Staged Coexistence Cutover Runbook (Decision D2) in `docs/operations.md` with explicit notice blocking live host execution pending maintenance window.
---
## 4. Verification & Quality Gates
The implementation must pass:
1. **Static Analysis & Linting**: `ruff check .` and `pyright` (0 errors, 0 warnings).
2. **Full Regression Suite**: All 283 existing unit, security, and invariant tests passing.
3. **New Test Coverage**:
- Assert dynamic LDAP base DN computation from domain.
- Assert `scripts/appctl` fails closed when socket is absent.
- Assert `appctl list` output formatting includes container status.
- Assert platform genericism invariants across updated Nix modules.
4. **Hermetic Flake Check**: `nix flake check` builds cleanly.
5. **NixOS Evaluation**: `nix eval .#nixosConfigurations.server.config.system.build.toplevel.drvPath` evaluates without warnings.
+3 -3
View File
@@ -64,9 +64,9 @@ Generated by `nixos/modules/traefik-deployments.nix`. Projects shared infrastruc
### C. Control Plane Token Store (`/run/secrets/appctl/tokens.json` & `/run/secrets/gitops/appctl_token`)
Provisioned from `nixos/secrets.yaml` (`appctl/tokens_json` and `gitops/appctl_token`):
* `/run/secrets/appctl/tokens.json`: Owned by `homelab-appctl:homelab-operators` with strict mode `0400` (enforced fail-closed by `TokenStore._verify_permissions()`). Stores SHA-256 hex digests of Bearer secrets mapped to `token_id`, `identity`, and `role` (`homelab-admin`, `homelab-operator`, `homelab-viewer`).
* `/run/secrets/appctl/tokens.json`: Owned by `homelab-appctl:homelab-operators` with strict mode `0400` (enforced fail-closed by `TokenStore._verify_permissions()`, rejecting any write bit or group/world readability). Stores a JSON array of SHA-256 token descriptors (`token_id`, `identity`, `role`, and 64-hex `sha256`) defined under `appctl/tokens_json` in `nixos/secrets.yaml`.
* `/run/secrets/gitops/appctl_token`: Owned by `config.homelab.operatorUser` (mode `0400`). Supplies the `homelab-operator` Bearer secret to `homelab-gitops.service` when delegating `workload.update` to `homelab-appctl.service`.
* `~/.config/homelab/token`: Local operator Bearer token (mode `0600`) read by `appctl_cli.py` for interactive CLI mutations.
* `~/.config/homelab/token`: Local operator Bearer token written with strict mode `0600` (in a mode `0700` directory) by `scripts/bootstrap_token.py`. Automatically discovered and resolved by `appctl_cli.py` for authenticated operator interactions without needing `--token` flags or environment variables.
---
@@ -103,7 +103,7 @@ brevo:
### 3. Save and Apply Changes
Saving the file in your editor automatically re-encrypts it with Age. Apply the updated templates to running services:
```bash
sudo nixos-rebuild switch --flake ~/Core#server
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
```
---
+76 -8
View File
@@ -32,24 +32,64 @@ sudo ls -l /etc/ssh/ssh_host_ed25519_key
sudo chmod 600 /etc/ssh/ssh_host_ed25519_key
```
### Step 2: Apply Declarative NixOS Configuration
### Step 2: Configure Appliance Instance Domain (Decision D1)
To preserve strict platform genericism, the repository files tracked in Git never contain production domains or personal operator identities, defaulting to RFC 2606 placeholders (`example.test` and `operator`).
An appliance host supplies its production domain and local configuration overrides via one of two untracked dual-path files:
1. **Repository-local instance profile (`nixos/instance.nix`)**:
Create an untracked, git-ignored file in `nixos/instance.nix`:
```nix
{
homelab.domain = "example.com";
}
```
When rebuilding via `sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure` (or `path:~/Core#server --impure`), Nix automatically imports `nixos/instance.nix` if present.
> [!NOTE]
> **Flake Fetcher Scheme for Untracked Files**:
> Because `nixos/instance.nix` is gitignored, Nix's default Git fetcher filters it out when evaluating standard Git flake references (e.g. `--flake ~/Core#server`). Prefixing the path with the `path:` scheme (e.g. `path:/home/operator/Core#server` or `path:~/Core#server`) instructs Nix to evaluate directly from the filesystem without filtering by the Git index.
> If using the host-level `/etc/nixos/homelab-instance.nix` instead, a bare `--flake .#server --impure` works directly because `/etc/nixos` resides outside the Git repository tree.
2. **Host-level instance profile (`/etc/nixos/homelab-instance.nix`)**:
Alternatively, create a host-level file outside the Git checkout:
```nix
{
homelab.domain = "example.com";
}
```
This persists configuration across fresh repository clones or ephemeral branches.
Both paths are declared optionally in `nixos/configuration.nix`:
```nix
imports = [
./hardware-configuration.nix
./modules/homeserver.nix
./modules/traefik-deployments.nix
./modules/dynu.nix
./modules/shell.nix
] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix
++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix;
```
When present, `homelab.domain` overrides the default (`example.test`), and all generated templates (`homeserver.env`, Traefik routing rules, and the dynamic `LLDAP_LDAP_BASE_DN`) automatically reflect the production domain without altering any tracked Git files.
### Step 3: Apply Declarative NixOS Configuration
```bash
cd ~/Core
sudo nixos-rebuild switch --flake ~/Core#server
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
```
This configures:
* Docker daemon, host firewall rules, and system packages.
* Decrypted secret files in `/run/secrets/homeserver.env` and `/run/secrets/traefik-deployments.env`.
* Systemd service units (`homeserver-core`, `homelab-gitops`, `dynu-monitor`).
* Systemd service units (`homeserver-core`, `homelab-appctl`, `homelab-gitops`, `dynu-monitor`).
### Step 3: Create External Docker Networks
### Step 4: Create External Docker Networks
The Core Compose stack and workloads require the `proxy-net` and `socket-net` bridge networks:
```bash
docker network create proxy-net 2>/dev/null || true
docker network create socket-net 2>/dev/null || true
```
### Step 4: Start Platform Services
### Step 5: Start Platform Services
```bash
sudo systemctl start homeserver-core
```
@@ -58,7 +98,7 @@ Check running containers:
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
```
### Step 5: Verify DNS & Certificates
### Step 6: Verify DNS & Certificates
1. Trigger an immediate DDNS update:
```bash
sudo systemctl start dynu-monitor
@@ -68,11 +108,39 @@ docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
appctl ssl traefik
```
### Step 6: Initialize LLDAP Directory
### Step 7: Initialize LLDAP Directory
1. Navigate to `https://users.${HOMELAB_DOMAIN}` (e.g., `https://users.example.com`).
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
@@ -167,7 +235,7 @@ Before committing changes to Homelab Core, run the repository test runner:
```bash
cd ~/Core
./scripts/test
./scripts/run-tests
```
This runs:
* Code formatting and lint checks (`ruff`).
Generated
+7 -7
View File
@@ -2,11 +2,11 @@
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1791956154,
"narHash": "sha256-gJX2+xcImvxBCI3bp7zXKLUX2AwsdTxMgJ1UX/5Hm/o=",
"rev": "55bfb4d7437bd4e09ab7cba58a43bd68eb310044",
"lastModified": 1795234589,
"narHash": "sha256-pAEASBc6wof0S58XcSEdZoQ2iFQDkCnZwH+wFLrkd1Q=",
"rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f",
"type": "tarball",
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1092090.55bfb4d7437b/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": {
+46 -5
View File
@@ -12,10 +12,22 @@
./modules/traefik-deployments.nix # Traefik deployment secrets and env templates
./modules/dynu.nix # Dynu DDNS smart IP monitor service
./modules/shell.nix # Declarative bash environment for the server
];
] ++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix
++ lib.optional (!(builtins.pathExists /etc/nixos/homelab-instance.nix) && builtins.pathExists ./instance.nix) ./instance.nix;
# ── Homelab platform settings ────────────────────────────────────────────────
homelab.operatorUser = "kiskaadee";
homelab.operatorUser = "operator";
# ── Host Git Safe Directory ──────────────────────────────────────────────────
programs.git = {
enable = true;
config.safe.directory = [
"/home/${config.homelab.operatorUser}/Core"
"/home/${config.homelab.operatorUser}/Workloads"
"/home/${config.homelab.operatorUser}/Workloads/*"
"/home/${config.homelab.operatorUser}/Sites/*"
];
};
# ── SOPS secrets configuration ──────────────────────────────────────────────
# Set once here to avoid duplicate-option conflicts across submodules
@@ -56,9 +68,10 @@
networking.hostName = "server";
networking.networkmanager.enable = true;
# ── User account ─────────────────────────────────────────────────────────────
users.users.kiskaadee = {
# ── User accounts ────────────────────────────────────────────────────────────
users.users.${config.homelab.operatorUser} = {
isNormalUser = true;
description = "Primary server administrator";
openssh.authorizedKeys.keys = [
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICAVPPMk+WApUd/fo78+lsRGnLKSlY4GDZiNGKwBAifD"
];
@@ -70,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 ───────────────────────────────────────────────────────────
+20
View File
@@ -0,0 +1,20 @@
# Example host-local instance configuration for Canopy NixOS Core.
# Copy to /etc/nixos/homelab-instance.nix (recommended, loaded with --impure)
# or gitignored nixos/instance.nix, and customize for your host.
{ ... }:
{
homelab.domain = "example.com";
homelab.operatorUser = "operator";
# Host-granted workload capabilities ("Compose Requests, Nix Grants" — ADR-0005).
# Keyed by workload name matching ~/Workloads/<app>.
homelab.workloadGrants = {
# Example hardware-accelerated media workload:
# media-server = {
# devices = [ "/dev/dri/renderD128" ];
# groups = [ "render" ];
# readOnlyPaths = [ "/mnt/media" ];
# };
};
}
+3 -1
View File
@@ -7,7 +7,9 @@
let
# Declaratively read the external Python script into the Nix store at evaluation time
ipMonitorScript = pkgs.writers.writePython3Bin "dynu-ip-monitor" { } (builtins.readFile ../scripts/monitor.py);
ipMonitorScript = pkgs.writers.writePython3Bin "dynu-ip-monitor" {
flakeIgnore = [ "E501" ];
} (builtins.readFile ../scripts/monitor.py);
in
{
# Define the keys to decrypt
+113 -19
View File
@@ -23,15 +23,94 @@
};
sitesDir = lib.mkOption {
type = lib.types.str;
default = "/home/${config.homelab.operatorUser}/Sites";
description = "Path to Sites directory";
default = "/home/${config.homelab.operatorUser}/Workloads";
description = "Path to Workloads directory (legacy option name: sitesDir)";
};
workloadGrants = lib.mkOption {
type = lib.types.attrsOf (lib.types.submodule {
options = {
devices = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
description = "Host device paths permitted for this workload (prefer specific nodes such as /dev/dri/renderD128).";
};
groups = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
description = "Host group names or numeric GIDs permitted in group_add and user: primary GID.";
};
readOnlyPaths = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
description = "Host directories permitted for read-only (:ro) bind mounts.";
};
};
});
default = {};
description = "Host-granted hardware devices, groups, and read-only storage paths keyed by workload name.";
};
};
config = {
config = let
domainParts = lib.splitString "." config.homelab.domain;
ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts);
in {
# ── Workload Capability Grant Invariants (ADR-0005) ─────────────────────────
assertions = let
grantsList = lib.mapAttrsToList (app: grant: { inherit app grant; }) config.homelab.workloadGrants;
privilegedGroups = [ "0" "root" "wheel" "docker" ];
hasInvalidPath = p:
!(lib.hasPrefix "/" p)
|| (lib.hasInfix "/../" p)
|| (lib.hasSuffix "/.." p)
|| (p == "..");
in
(map ({ app, grant }: {
assertion = lib.all (g: !(lib.elem (lib.toLower (lib.strings.trim g)) privilegedGroups)) grant.groups;
message = "homelab.workloadGrants.${app}.groups must not contain privileged groups (0, root, wheel, docker).";
}) grantsList)
++ (map ({ app, grant }: {
assertion = lib.all (p: !(hasInvalidPath p)) grant.devices;
message = "homelab.workloadGrants.${app}.devices must contain absolute paths without '..' traversal.";
}) grantsList)
++ (map ({ app, grant }: {
assertion = lib.all (p: !(hasInvalidPath p)) grant.readOnlyPaths;
message = "homelab.workloadGrants.${app}.readOnlyPaths must contain absolute paths without '..' traversal.";
}) grantsList);
# ── Host Capability Grants Projection (/etc/homelab/grants.json) ─────────────
environment.etc."homelab/grants.json" = {
user = "root";
group = "homelab-operators";
mode = "0640";
text = builtins.toJSON {
schemaVersion = "1.0";
workloads = config.homelab.workloadGrants;
};
};
# ── Host Activation Guard ────────────────────────────────────────────────────
# Prevents activating on a live host if homelab.domain defaulted to example.test (e.g. forgot --impure)
system.activationScripts.checkHomelabDomain = {
text = ''
if [ "${config.homelab.domain}" = "example.test" ]; then
echo "❌ [homelab] FATAL: homelab.domain is defaulting to 'example.test'!" >&2
echo "❌ [homelab] Did you run 'nixos-rebuild switch' without the '--impure' flag?" >&2
echo "❌ [homelab] To activate properly: sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure" >&2
exit 1
fi
'';
};
# Re-apply home-dir traverse ACL after `users` activation (chmod 0700 resets POSIX ACL mask::---)
system.activationScripts.homelabHomeAcl = lib.stringAfter [ "users" ] ''
if [ -d "/home/${config.homelab.operatorUser}" ]; then
${pkgs.acl}/bin/setfacl -m u:homelab-appctl:x,g:homelab-operators:x,m::rx "/home/${config.homelab.operatorUser}"
fi
'';
# Define the keys to decrypt from secrets.yaml
sops.secrets = (lib.genAttrs [
"dynu/api_key"
"cloudflare/dns_api_token"
"traefik/acme_email"
"authelia/session_secret"
"authelia/storage_encryption_key"
@@ -60,10 +139,13 @@
# Generate the unified environment file at runtime in /run/secrets/homeserver.env
sops.templates."homeserver.env" = {
owner = config.homelab.operatorUser;
group = "homelab-operators";
mode = "0440";
content = lib.generators.toKeyValue {} {
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";
@@ -99,8 +181,8 @@
# Declarative Dynamic GitOps Webhook Service (Internal Port 9000)
systemd.services.homelab-gitops = {
description = "Dynamic Homelab GitOps Webhook Dispatcher";
after = [ "network-online.target" "docker.service" ];
wants = [ "network-online.target" ];
after = [ "network-online.target" "docker.service" "homelab-appctl.service" ];
wants = [ "network-online.target" "homelab-appctl.service" ];
wantedBy = [ "multi-user.target" ];
path = with pkgs; [
@@ -117,6 +199,11 @@
GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path;
GITOPS_APPCTL_TOKEN_FILE = config.sops.secrets."gitops/appctl_token".path;
DOCKER_CONFIG = "/home/${config.homelab.operatorUser}/.local/state/homelab/docker";
HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab";
WORKLOADS_DIR = config.homelab.sitesDir;
SITES_DIR = config.homelab.sitesDir;
HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.sitesDir}/deployments.yaml";
HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";
};
serviceConfig = {
@@ -150,7 +237,7 @@
ReadWritePaths = [
config.homelab.sitesDir
"/home/${config.homelab.operatorUser}/.local/state/homelab"
"/run/homelab"
"-/run/homelab"
];
};
};
@@ -191,10 +278,13 @@
APPCTL_AUDIT_LOG = "/var/log/homelab/appctl/audit.jsonl";
APPCTL_LOCK_DIR = "/var/lib/homelab/appctl/locks";
APPCTL_TOKENS_FILE = config.sops.secrets."appctl/tokens_json".path;
WORKLOADS_DIR = config.homelab.sitesDir;
SITES_DIR = config.homelab.sitesDir;
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";
HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";
};
serviceConfig = {
@@ -222,11 +312,11 @@
ProtectControlGroups = true;
ReadWritePaths = [
config.homelab.sitesDir
"/home/${config.homelab.operatorUser}/var/lib/homelab"
"${config.homelab.coreDir}/config/homepage"
"-/home/${config.homelab.operatorUser}/var/lib/homelab"
"-${config.homelab.coreDir}/config/homepage"
"/var/log/homelab/appctl"
"/var/lib/homelab/appctl"
"/run/homelab"
"-/var/lib/homelab/appctl"
"-/run/homelab"
];
};
};
@@ -236,14 +326,18 @@
"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 -"
# POSIX ACLs granting homelab-appctl traverse and access to operator sites & homepage config
"a+ /home/${config.homelab.operatorUser} - - - - u:homelab-appctl:x"
"a+ ${config.homelab.coreDir} - - - - u:homelab-appctl:x"
"a+ ${config.homelab.sitesDir} - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
"a+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
"a+ ${config.homelab.coreDir}/config/homepage - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
"d /home/${config.homelab.operatorUser}/var/lib/homelab 0755 ${config.homelab.operatorUser} users -"
# POSIX ACLs granting homelab-appctl and homelab-operators traverse & access (explicit mask m:: required on 0700 home dirs)
"a+ /home/${config.homelab.operatorUser} - - - - u:homelab-appctl:x,g:homelab-operators:x,m::rx"
"a+ ${config.homelab.coreDir} - - - - u:homelab-appctl:x,g:homelab-operators:x,m::rx"
"A+ ${config.homelab.sitesDir} - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
"A+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
"A+ ${config.homelab.coreDir}/config/homepage - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"
];
# Open ports in the firewall for Traefik, Gitea SSH, GitOps Webhook Receiver, and Mail (SMTP, Submission, SMTPS, IMAPS, ManageSieve)
+2 -2
View File
@@ -62,8 +62,8 @@
reload = "exec bash";
pgoog = "ping google.com -c 3";
wifi = "nmtui";
# NixOS rebuild targeting this flake
nix-switch = "sudo nixos-rebuild switch --flake ~/Core#server";
# NixOS rebuild targeting this flake (path scheme + impure required for instance.nix)
nix-switch = "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure";
};
interactiveShellInit = ''
+2
View File
@@ -20,6 +20,8 @@
# Generate the unified environment file at runtime in /run/secrets/traefik-deployments.env
sops.templates."traefik-deployments.env" = {
owner = config.homelab.operatorUser;
group = "homelab-operators";
mode = "0440";
content = lib.generators.toKeyValue {} {
# --- Core / Infrastructure Settings ---
PROXY_NETWORK = "proxy-net";
+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
+12 -4
View File
@@ -78,7 +78,8 @@ def get_public_ip():
for provider in PROVIDERS:
try:
req = urllib.request.Request(
provider, headers={"User-Agent": "Mozilla/5.0 (NixOS WAN Monitor)"}
provider,
headers={"User-Agent": "Mozilla/5.0 (NixOS WAN Monitor)"},
)
# Fetch with 5s timeout to avoid hanging the systemd service
with urllib.request.urlopen(req, timeout=5) as response:
@@ -91,7 +92,8 @@ def get_public_ip():
errors.append(f"{provider}: {e!s}")
print(
f"Error: All IP discovery providers failed. Details: {errors}", file=sys.stderr
f"Error: All IP discovery providers failed. Details: {errors}",
file=sys.stderr,
)
return None
@@ -128,7 +130,11 @@ def record_ip(ip, status, details=None):
Appends a new event entry into the JSONLines history registry.
"""
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
entry = {"timestamp": datetime.now(tz=UTC).isoformat(), "ip": ip, "status": status}
entry = {
"timestamp": datetime.now(tz=UTC).isoformat(),
"ip": ip,
"status": status,
}
if details:
entry["details"] = details
try:
@@ -156,7 +162,9 @@ def trigger_ddclient():
if res.returncode == 0:
return True, None
else:
err_msg = f"systemctl exited with {res.returncode}: {res.stderr.strip()}"
err_msg = (
f"systemctl exited with {res.returncode}: {res.stderr.strip()}"
)
return False, err_msg
except (OSError, subprocess.SubprocessError) as e:
return False, str(e)
+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
+34 -304
View File
@@ -1,189 +1,26 @@
#!/usr/bin/env bash
# appctl - Unified, Manifest-Driven Container Orchestrator
# Discovers individual application repositories located in ~/Sites/*/
# Injects global homelab secrets, per-app metadata from app.yaml, and monitors Git sync
# Thin CLI wrapper delegating operational commands to homelab-appctl.service over UDS
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENGINE="$SCRIPT_DIR/appctl_engine.py"
PYTHON_BIN="${PYTHON_BIN:-python3}"
if [ -z "$PYTHON_BIN" ]; then
if [ -x "$SCRIPT_DIR/../.venv/bin/python3" ]; then
PYTHON_BIN="$SCRIPT_DIR/../.venv/bin/python3"
else
PYTHON_BIN="python3"
fi
fi
SOCKET_PATH="${APPCTL_SOCKET_PATH:-/run/homelab/appctl.sock}"
CLI_CLIENT="$SCRIPT_DIR/appctl_cli.py"
# If daemon Unix domain socket exists, delegate operational commands directly to thin client
# (fast-path local completion and resolution helpers through appctl_engine.py)
# Fast-path local shell completion helpers
case "${1:-}" in
complete|completion|resolve)
;;
*)
if [ -S "$SOCKET_PATH" ] && [ -f "$CLI_CLIENT" ]; then
exec "$PYTHON_BIN" "$CLI_CLIENT" "$@"
fi
;;
esac
ENV_FILE="/run/secrets/rendered/traefik-deployments.env"
if [ ! -f "$ENV_FILE" ] && [ -f "/run/secrets/traefik-deployments.env" ]; then
ENV_FILE="/run/secrets/traefik-deployments.env"
fi
export SITES_DIR="${SITES_DIR:-$HOME/Sites}"
export CORE_DIR="${CORE_DIR:-$HOME/Core}"
export ENV_FILE
# Source global secrets/environment if available
HOMESERVER_ENV="/run/secrets/rendered/homeserver.env"
if [ ! -f "$HOMESERVER_ENV" ] && [ -f "/run/secrets/homeserver.env" ]; then
HOMESERVER_ENV="/run/secrets/homeserver.env"
fi
if [ -f "$HOMESERVER_ENV" ]; then
set -a
# shellcheck disable=SC1090
source "$HOMESERVER_ENV"
set +a
fi
if [ -f "$ENV_FILE" ]; then
set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a
fi
# Lock the homelab root domain before setup_app_env can mutate $DOMAIN
# Canonical precedence: HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN
export HOMELAB_DOMAIN="${HOMELAB_DOMAIN:-${DOMAIN_SUFFIX:-${DOMAIN:-}}}"
# Show help usage
show_help() {
echo "🚀 appctl - Homelab Container Orchestrator"
echo ""
echo "Usage: appctl <command> [service] [options...]"
echo ""
echo "Commands:"
echo " list, status [--fetch] [--core] [--ssl] List all applications with Git sync & container status"
echo " ssl [service] Inspect SSL/TLS certificates across homelab domains"
echo " info <service> [--ssl] Display comprehensive application & Git diagnostics"
echo " up <service|core> Start/build a service stack or Core component"
echo " down <service|core> Stop and remove a service stack or Core component"
echo " restart <service|core> Restart a service stack, Core component, or entire Core"
echo " update <service> Full stack update (git pull -> compose pull -> recreate)"
echo " pull <service|core> Pull latest images and recreate service or Core component"
echo " logs <service|core> Stream service or Core component logs"
echo " config <service|core> Validate and view resolved compose configuration"
echo " sync Synchronize Homepage dashboard services.yaml from app.yaml"
echo " completion [bash] Output shell autocompletion script"
}
# Setup application environment based on resolved metadata
setup_app_env() {
local query="$1"
local resolved_json
resolved_json=$("$PYTHON_BIN" "$ENGINE" resolve "$query" || true)
if [ -z "$resolved_json" ]; then
echo "❌ Error: Service '$query' not found under $SITES_DIR or Core"
exit 1
fi
# Extract fields via python json
TARGET_TYPE=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('type', 'app'))" "$resolved_json")
APP_DIR=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['dir_path'])" "$resolved_json")
CANONICAL_NAME=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['name'])" "$resolved_json")
TARGET_CONTAINER=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('container', ''))" "$resolved_json")
if [ "$TARGET_TYPE" = "core" ] || [ "$TARGET_TYPE" = "core_service" ]; then
if [ ! -d "$CORE_DIR" ]; then
echo "❌ Error: Core directory not found at $CORE_DIR"
exit 1
fi
CORE_ENV_FILE="/run/secrets/rendered/homeserver.env"
if [ ! -f "$CORE_ENV_FILE" ] && [ -f "/run/secrets/homeserver.env" ]; then
CORE_ENV_FILE="/run/secrets/homeserver.env"
fi
COMPOSE_ENV_ARG=()
if [ -f "$CORE_ENV_FILE" ]; then
COMPOSE_ENV_ARG=(--env-file "$CORE_ENV_FILE")
fi
return
fi
RESOLVED_DOMAIN=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['domain'])" "$resolved_json")
# 1. Base infrastructure defaults
export PROXY_NETWORK="${PROXY_NETWORK:-proxy-net}"
export NETWORK_NAME="${NETWORK_NAME:-$PROXY_NETWORK}"
export CERT_RESOLVER="${CERT_RESOLVER:-myresolver}"
export DOMAIN_SUFFIX="${DOMAIN_SUFFIX:-$HOMELAB_DOMAIN}"
# 2. Canonical application identity
export SERVICE_NAME="$CANONICAL_NAME"
export CONTAINER_NAME="$CANONICAL_NAME"
export SERVICE_DOMAIN="$RESOLVED_DOMAIN"
export DOMAIN="$RESOLVED_DOMAIN"
# 3. Dynamic environment variables from app.yaml (e.g. PROJECT_PATH, MEDIA_PATH, etc.)
while IFS= read -r -d '' k && IFS= read -r -d '' v; do
export "$k=$v"
done < <("$PYTHON_BIN" -c "
import json, re, sys
RESERVED = {'PATH', 'LD_PRELOAD', 'IFS', 'SHELL', 'USER', 'CORE_DIR', 'SITES_DIR', 'ENV_FILE', 'HOMESERVER_ENV'}
d = json.loads(sys.argv[1])
env_dict = d.get('env', {})
if isinstance(env_dict, dict):
for k, v in env_dict.items():
k_str = str(k).strip()
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', k_str) or k_str in RESERVED:
continue
if v is not None and v != '':
sys.stdout.buffer.write(k_str.encode('utf-8') + b'\0' + str(v).encode('utf-8') + b'\0')
" "$resolved_json")
# 4. Source local .env if present
if [ -f "$APP_DIR/.env" ]; then
set -a
# shellcheck disable=SC1090
source "$APP_DIR/.env"
set +a
fi
# 5. Source local app.env if present
if [ -f "$APP_DIR/app.env" ]; then
set -a
# shellcheck disable=SC1090
source "$APP_DIR/app.env"
set +a
fi
}
if [ $# -lt 1 ]; then
show_help
exit 1
fi
COMMAND=$1
APP=$2
case "$COMMAND" in
list|status)
"$PYTHON_BIN" "$ENGINE" list "${@:2}"
;;
ssl)
"$PYTHON_BIN" "$ENGINE" ssl "${@:2}"
;;
info)
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
"$PYTHON_BIN" "$ENGINE" info "${@:2}"
;;
sync)
"$PYTHON_BIN" "$ENGINE" sync "${@:2}"
;;
complete)
"$PYTHON_BIN" "$ENGINE" complete "${@:2}"
;;
resolve)
"$PYTHON_BIN" "$ENGINE" resolve "${@:2}"
exec "$PYTHON_BIN" "$ENGINE" complete "${@:2}"
;;
completion)
cat <<'EOF'
@@ -199,7 +36,7 @@ _appctl_completions() {
cword=$COMP_CWORD
fi
local commands="list status ssl info up down restart update pull logs config sync completion"
local commands="list status ssl info up down restart update pull logs config sync health resolve completion"
if [ "$cword" -eq 1 ]; then
COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
@@ -233,7 +70,25 @@ _appctl_completions() {
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
fi
;;
up|down|restart|update|pull|logs|config)
up|deploy)
if [[ "$cur" == -* ]]; then
COMPREPLY=( $(compgen -W "--build --no-cache" -- "$cur") )
else
local services
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
fi
;;
update)
if [[ "$cur" == -* ]]; then
COMPREPLY=( $(compgen -W "--branch --build --no-cache" -- "$cur") )
else
local services
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
fi
;;
down|restart|pull|logs|config)
local services
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
@@ -245,138 +100,13 @@ _appctl_completions() {
}
complete -F _appctl_completions appctl
EOF
;;
up)
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
setup_app_env "$APP"
if [ "$TARGET_TYPE" = "core" ]; then
echo "🚀 Starting Core stack ($CORE_DIR)..."
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "${@:3}"
elif [ "$TARGET_TYPE" = "core_service" ]; then
echo "🚀 Starting Core service: $TARGET_CONTAINER ($CORE_DIR)..."
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "$TARGET_CONTAINER" "${@:3}"
else
echo "🚀 Starting $CANONICAL_NAME ($APP_DIR)..."
cd "$APP_DIR" && docker compose up -d --remove-orphans "${@:3}"
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
fi
;;
down)
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
setup_app_env "$APP"
if [ "$TARGET_TYPE" = "core" ]; then
echo "🛑 Stopping Core stack ($CORE_DIR)..."
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" down "${@:3}"
elif [ "$TARGET_TYPE" = "core_service" ]; then
echo "🛑 Stopping Core service: $TARGET_CONTAINER ($CORE_DIR)..."
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" stop "$TARGET_CONTAINER" "${@:3}"
else
echo "🛑 Stopping $CANONICAL_NAME ($APP_DIR)..."
cd "$APP_DIR" && docker compose down "${@:3}"
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
fi
;;
restart)
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
setup_app_env "$APP"
if [ "$TARGET_TYPE" = "core" ]; then
if [ -n "$3" ] && [[ "$3" != -* ]]; then
echo "🔄 Restarting Core service: $3 ($CORE_DIR)..."
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "$3" "${@:4}"
else
echo "🔄 Restarting Core stack ($CORE_DIR)..."
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "${@:3}"
fi
elif [ "$TARGET_TYPE" = "core_service" ]; then
echo "🔄 Restarting Core service: $TARGET_CONTAINER ($CORE_DIR)..."
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "$TARGET_CONTAINER" "${@:3}"
else
echo "🔄 Restarting $CANONICAL_NAME ($APP_DIR)..."
cd "$APP_DIR" && docker compose down && docker compose up -d "${@:3}"
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
fi
;;
update)
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
setup_app_env "$APP"
if [ "$TARGET_TYPE" = "core" ]; then
echo "🔄 Updating Core stack ($CORE_DIR)..."
if [ -d "$CORE_DIR/.git" ]; then
if [ -n "$(git -C "$CORE_DIR" status --porcelain)" ]; then
echo "❌ Error: Cannot update. Working tree in $CORE_DIR has uncommitted changes."
exit 1
fi
echo "📥 Pulling latest git changes for Core..."
git -C "$CORE_DIR" pull --ff-only
fi
echo "🐳 Pulling latest Core container images..."
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull
echo "🚀 Recreating Core container stack..."
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "${@:3}"
echo "✨ Core successfully updated!"
exit 0
fi
echo "🔄 Updating $CANONICAL_NAME ($APP_DIR)..."
if [ -d "$APP_DIR/.git" ]; then
if [ -n "$(git -C "$APP_DIR" status --porcelain)" ]; then
echo "❌ Error: Cannot update. Working tree in $APP_DIR has uncommitted changes."
echo "Commit or stash your changes before updating."
exit 1
fi
echo "📥 Pulling latest git changes..."
git -C "$APP_DIR" pull --ff-only
fi
echo "🐳 Pulling latest container images..."
cd "$APP_DIR" && docker compose pull
echo "🚀 Recreating container stack..."
cd "$APP_DIR" && docker compose up -d --remove-orphans "${@:3}"
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
echo "✨ $CANONICAL_NAME successfully updated!"
;;
pull)
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
setup_app_env "$APP"
if [ "$TARGET_TYPE" = "core" ]; then
echo "📥 Pulling latest images for Core stack..."
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull "${@:3}"
elif [ "$TARGET_TYPE" = "core_service" ]; then
echo "📥 Pulling latest image for Core service: $TARGET_CONTAINER..."
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull "$TARGET_CONTAINER" "${@:3}"
else
echo "📥 Pulling latest images for $CANONICAL_NAME..."
cd "$APP_DIR" && docker compose pull && docker compose up -d --remove-orphans "${@:3}"
fi
;;
logs)
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
setup_app_env "$APP"
if [ "$TARGET_TYPE" = "core" ]; then
if [ -n "$3" ] && [[ "$3" != -* ]]; then
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "$3" "${@:4}"
else
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "${@:3}"
fi
elif [ "$TARGET_TYPE" = "core_service" ]; then
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "$TARGET_CONTAINER" "${@:3}"
else
cd "$APP_DIR" && docker compose logs -f "${@:3}"
fi
;;
config)
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
setup_app_env "$APP"
if [ "$TARGET_TYPE" = "core" ] || [ "$TARGET_TYPE" = "core_service" ]; then
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" config "${@:3}"
else
cd "$APP_DIR" && docker compose config "${@:3}"
fi
;;
*)
show_help
if [ ! -S "$SOCKET_PATH" ]; then
echo "❌ Error: appctl daemon socket not found at $SOCKET_PATH. Ensure homelab-appctl.service is running." >&2
exit 1
fi
exec "$PYTHON_BIN" "$CLI_CLIENT" "$@"
;;
esac
+7 -3
View File
@@ -28,7 +28,7 @@ DEFAULT_AUDIT_LOG = Path("/var/log/homelab/appctl/audit.jsonl")
DEFAULT_LOCK_DIR = Path("/var/lib/homelab/appctl/locks")
REDACT_KEY_PATTERNS = re.compile(
r".*(?:_KEY|_SECRET|_PASSWORD|_TOKEN|_PASS|_HASH)$", re.IGNORECASE
r"^(?:.*_)?(?:KEY|SECRET|PASSWORD|TOKEN|PASS|HASH)$", re.IGNORECASE
)
@@ -105,7 +105,9 @@ class ConcurrentMutationError(Exception):
def __init__(self, target: str, message: str | None = None) -> None:
self.target = target
msg = message or f"Operation on target '{target}' is locked by a concurrent task."
msg = (
message or f"Operation on target '{target}' is locked by a concurrent task."
)
super().__init__(msg)
@@ -116,7 +118,9 @@ def redact_sensitive_data(val: Any) -> Any:
"""
if isinstance(val, dict):
return {
k: "[REDACTED]" if REDACT_KEY_PATTERNS.match(str(k)) else redact_sensitive_data(v)
k: "[REDACTED]"
if REDACT_KEY_PATTERNS.match(str(k))
else redact_sensitive_data(v)
for k, v in val.items()
}
if isinstance(val, list):
+58 -20
View File
@@ -6,7 +6,7 @@ Implements the zero-trust authorization pipeline for homelab-appctl.service:
- Unix domain socket SO_PEERCRED fallback to homelab-viewer for zero-friction local reads
- 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
@@ -33,9 +33,17 @@ except ImportError:
yaml = None # type: ignore[assignment]
DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json")
DEFAULT_DEPLOYMENTS_FILE = Path(__file__).resolve().parent.parent / "config" / "deployments.yaml"
DEFAULT_DEPLOYMENTS_FILE = (
Path(
os.environ.get("WORKLOADS_DIR")
or os.environ.get("SITES_DIR")
or os.path.expanduser("~/Workloads")
)
/ "deployments.yaml"
)
CORE_TARGETS: frozenset[str] = frozenset({
CORE_TARGETS: frozenset[str] = frozenset(
{
"core",
"traefik",
"authelia",
@@ -46,29 +54,36 @@ CORE_TARGETS: frozenset[str] = frozenset({
"homepage",
"diun",
"watchtower",
})
}
)
SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset({
SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset(
{
OperationType.WORKLOAD_CONFIG,
OperationType.WORKLOAD_LOGS,
})
}
)
MUTATING_OPERATIONS: frozenset[OperationType] = frozenset({
MUTATING_OPERATIONS: frozenset[OperationType] = frozenset(
{
OperationType.WORKLOAD_DEPLOY,
OperationType.WORKLOAD_STOP,
OperationType.WORKLOAD_RESTART,
OperationType.WORKLOAD_UPDATE,
OperationType.WORKLOAD_PULL,
OperationType.PLATFORM_SYNC_HOMEPAGE,
})
}
)
READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset({
READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset(
{
OperationType.WORKLOAD_LIST,
OperationType.WORKLOAD_GET,
OperationType.WORKLOAD_RESOLVE,
OperationType.PLATFORM_SSL,
OperationType.PLATFORM_HEALTH,
})
}
)
class Role(StrEnum):
@@ -119,7 +134,11 @@ class TokenDescriptor(StrictModel):
class AuthenticationError(Exception):
"""Raised when authentication fails (401 Unauthorized)."""
def __init__(self, message: str = "Authentication required", code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED) -> None:
def __init__(
self,
message: str = "Authentication required",
code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED,
) -> None:
super().__init__(message)
self.code = code
self.http_status = 401
@@ -128,7 +147,11 @@ class AuthenticationError(Exception):
class AuthorizationError(Exception):
"""Raised when an authenticated principal lacks required role or scope (403 Forbidden)."""
def __init__(self, message: str = "Permission denied", code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED) -> None:
def __init__(
self,
message: str = "Permission denied",
code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED,
) -> None:
super().__init__(message)
self.code = code
self.http_status = 403
@@ -181,13 +204,15 @@ class TokenStore:
constant-time hmac.compare_digest.
"""
if not secret:
raise AuthenticationError("Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED)
raise AuthenticationError(
"Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED
)
secret_hash = hashlib.sha256(secret.encode("utf-8")).hexdigest()
tokens = self.load_tokens()
for token in tokens:
if hmac.compare_digest(secret_hash, token.sha256):
if hmac.compare_digest(secret_hash, token.sha256.lower()):
return Principal(
identity=token.identity,
role=token.role,
@@ -195,18 +220,25 @@ class TokenStore:
auth_method="bearer_token",
)
raise AuthenticationError("Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED)
raise AuthenticationError(
"Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED
)
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:
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
@@ -235,7 +267,13 @@ def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[s
if isinstance(alias, str) and alias.strip():
admitted.add(alias.strip())
return admitted
except (OSError, UnicodeDecodeError, ValueError, json.JSONDecodeError, *yaml_errors):
except (
OSError,
UnicodeDecodeError,
ValueError,
json.JSONDecodeError,
*yaml_errors,
):
return set()
@@ -310,7 +348,7 @@ def enforce_rbac(
return
# Target checks for operations targeting infrastructure
if target is not None and target in CORE_TARGETS:
if target is not None and target.strip().lower() in CORE_TARGETS:
raise AuthorizationError(
f"Role 'homelab-operator' is not permitted to target core service '{target}'",
code=ErrorCode.ERR_PERMISSION_DENIED,
+35 -14
View File
@@ -58,28 +58,33 @@ def _format_workload_table(workloads: list[dict[str, Any]]) -> str:
if has_ssl:
lines.append(
f"{'SERVICE':<18} {'TYPE':<14} {'DOMAIN':<30} {'CERT':<24} {'DESCRIPTION'}"
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
)
lines.append(
f"{'-------':<18} {'----':<14} {'------':<30} {'----':<24} {'-----------'}"
f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
)
else:
lines.append(
f"{'SERVICE':<18} {'TYPE':<14} {'DOMAIN':<30} {'DESCRIPTION'}"
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN'}"
)
lines.append(
f"{'-------':<18} {'----':<14} {'------':<30} {'-----------'}"
f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------'}"
)
for w in workloads:
name = str(w.get("name", "-"))
w_type = str(w.get("type", w.get("app_type", "app")))
domain = str(w.get("domain", "-"))
desc = str(w.get("description", ""))
name = str(w.get("name") or "-")
domain = str(w.get("domain") or "-")
status = str(w.get("status") or "-")
if w.get("manifest_error"):
desc = f"⚠️ {w['manifest_error']}"
elif w.get("deployment_status"):
desc = f"{w['deployment_status']} ({w.get('provenance_status', '-')})"
dep = "⚠️ Manifest Error"
prov = "⚠️ Invalid Manifest"
elif "deployment_status" in w:
dep = str(w["deployment_status"])
prov = str(w.get("provenance_status") or "-")
else:
dep = "-"
prov = str(w.get("provenance_status") or "-")
if has_ssl:
ssl_info = w.get("ssl")
@@ -89,10 +94,12 @@ def _format_workload_table(workloads: list[dict[str, Any]]) -> str:
else "-"
)
lines.append(
f"{name:<18} {w_type:<14} {domain:<30} {cert_status:<24} {desc}"
f"{name:<16} {dep:<22} {prov:<22} {status:<15} {domain:<28} {cert_status}"
)
else:
lines.append(f"{name:<18} {w_type:<14} {domain:<30} {desc}")
lines.append(
f"{name:<16} {dep:<22} {prov:<24} {status:<15} {domain}"
)
return "\n".join(lines)
@@ -247,6 +254,7 @@ def run_cli(argv: list[str] | None = None) -> int:
up_p = subparsers.add_parser("up", aliases=["deploy"], parents=[common_parser], help="Deploy workload")
up_p.add_argument("target", help="Workload or core target")
up_p.add_argument("--build", action="store_true", help="Rebuild container images")
up_p.add_argument("--no-cache", action="store_true", help="Rebuild container images without cache")
# down / stop
down_p = subparsers.add_parser("down", aliases=["stop"], parents=[common_parser], help="Stop workload")
@@ -260,6 +268,8 @@ def run_cli(argv: list[str] | None = None) -> int:
update_p = subparsers.add_parser("update", parents=[common_parser], help="Update workload revision")
update_p.add_argument("target", help="Workload target")
update_p.add_argument("--branch", default=None, help="Expected git branch")
update_p.add_argument("--build", action="store_true", help="Rebuild container images")
update_p.add_argument("--no-cache", action="store_true", help="Rebuild container images without cache")
# pull
pull_p = subparsers.add_parser("pull", parents=[common_parser], help="Pull workload images")
@@ -316,10 +326,15 @@ def run_cli(argv: list[str] | None = None) -> int:
elif cmd == "health":
op_req = OperationRequest(operation=OperationType.PLATFORM_HEALTH)
elif cmd in ("up", "deploy"):
build_flag = getattr(parsed, "build", False)
no_cache_flag = getattr(parsed, "no_cache", False)
op_req = OperationRequest(
operation=OperationType.WORKLOAD_DEPLOY,
target=parsed.target,
parameters={"build": getattr(parsed, "build", False)},
parameters={
"build": build_flag or no_cache_flag,
"no_cache": no_cache_flag,
},
)
elif cmd in ("down", "stop"):
op_req = OperationRequest(
@@ -335,6 +350,12 @@ def run_cli(argv: list[str] | None = None) -> int:
params = {}
if getattr(parsed, "branch", None):
params["expected_branch"] = parsed.branch
build_flag = getattr(parsed, "build", False)
no_cache_flag = getattr(parsed, "no_cache", False)
if build_flag or no_cache_flag:
params["build"] = True
if no_cache_flag:
params["no_cache"] = True
op_req = OperationRequest(
operation=OperationType.WORKLOAD_UPDATE,
target=parsed.target,
+17 -1
View File
@@ -116,11 +116,12 @@ FlexibleWorkloadAction = FlexibleOperationType
class ErrorCode(StrEnum):
"""Canonical 6-code error taxonomy for homelab-appctl.service."""
"""Canonical 7-code error taxonomy for homelab-appctl.service."""
ERR_VALIDATION_FAILED = "ERR_VALIDATION_FAILED"
ERR_AUTH_REQUIRED = "ERR_AUTH_REQUIRED"
ERR_PERMISSION_DENIED = "ERR_PERMISSION_DENIED"
ERR_CAPABILITY_NOT_GRANTED = "ERR_CAPABILITY_NOT_GRANTED"
ERR_TARGET_NOT_FOUND = "ERR_TARGET_NOT_FOUND"
ERR_CONCURRENT_MUTATION = "ERR_CONCURRENT_MUTATION"
ERR_EXECUTION_FAILED = "ERR_EXECUTION_FAILED"
@@ -134,6 +135,7 @@ ERROR_HTTP_STATUS: dict[ErrorCode, int] = {
ErrorCode.ERR_VALIDATION_FAILED: 400,
ErrorCode.ERR_AUTH_REQUIRED: 401,
ErrorCode.ERR_PERMISSION_DENIED: 403,
ErrorCode.ERR_CAPABILITY_NOT_GRANTED: 403,
ErrorCode.ERR_TARGET_NOT_FOUND: 404,
ErrorCode.ERR_CONCURRENT_MUTATION: 409,
ErrorCode.ERR_EXECUTION_FAILED: 500,
@@ -161,6 +163,13 @@ class DeployParams(StrictModel):
recreate: StrictBool = True
remove_orphans: StrictBool = True
build: StrictBool = False
no_cache: StrictBool = False
@model_validator(mode="after")
def imply_build_from_no_cache(self) -> DeployParams:
if self.no_cache:
self.build = True
return self
class UpdateParams(StrictModel):
@@ -168,6 +177,13 @@ class UpdateParams(StrictModel):
expected_branch: Annotated[StrictStr, Field(min_length=1)] | None = None
build: StrictBool = False
no_cache: StrictBool = False
@model_validator(mode="after")
def imply_build_from_no_cache(self) -> UpdateParams:
if self.no_cache:
self.build = True
return self
class LogsParams(StrictModel):
+21 -2
View File
@@ -57,9 +57,14 @@ from pydantic import ValidationError
logger = logging.getLogger("appctl_daemon")
CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent))
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
WORKLOADS_DIR = Path(
os.environ.get("WORKLOADS_DIR")
or os.environ.get("SITES_DIR")
or os.path.expanduser("~/Workloads")
)
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(
@@ -386,6 +391,7 @@ class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
return
# Dispatch operation to OperationalRouter
try:
resp = self.appctl_server.router.dispatch(
request=req,
principal=principal,
@@ -393,6 +399,19 @@ class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
origin=origin,
client=client_header,
)
except Exception as exc:
logger.exception("Top-level unhandled exception during operation dispatch")
self._send_operation_error(
status_code=500,
error=OperationError(
code=ErrorCode.ERR_EXECUTION_FAILED,
message=f"Internal daemon execution error: {exc}",
),
operation=req.operation,
target=req.target,
op_id=generate_operation_id(),
)
return
status_code = resp.error.code.http_status if (not resp.success and resp.error) else 200
self._send_operation_response(status_code, resp)
+33 -7
View File
@@ -37,12 +37,19 @@ CORE_DIR = os.environ.get(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
)
SITES_DIR = os.environ.get(
"SITES_DIR",
os.path.join(os.path.dirname(CORE_DIR), "Sites")
if os.path.isdir(os.path.join(os.path.dirname(CORE_DIR), "Sites"))
else os.path.expanduser("~/Sites"),
)
def _resolve_default_workloads_dir() -> str:
"""Resolve workloads root honoring WORKLOADS_DIR, SITES_DIR, sibling Workloads, or ~/Workloads."""
env_dir = os.environ.get("WORKLOADS_DIR") or os.environ.get("SITES_DIR")
if env_dir:
return env_dir
sibling_workloads = os.path.join(os.path.dirname(CORE_DIR), "Workloads")
if os.path.isdir(sibling_workloads):
return sibling_workloads
return os.path.expanduser("~/Workloads")
WORKLOADS_DIR = _resolve_default_workloads_dir()
SITES_DIR = WORKLOADS_DIR
HOMELAB_DOMAIN = (
os.environ.get("HOMELAB_DOMAIN")
@@ -108,6 +115,10 @@ class CoreService(App):
app_type: str = "core_service"
dir_path: str = CORE_DIR
@property
def container_name(self) -> str:
return self.container
@dataclass
class SitesApp(App):
@@ -411,6 +422,11 @@ def get_docker_status(
text=True,
check=False,
)
if inspect_res.returncode != 0:
err = (inspect_res.stderr or "").lower()
if "no such object" in err or "no such container" in err:
return "🔴 Stopped"
return "❓ Unknown"
state = inspect_res.stdout.strip()
if state.lower() == "true":
return "🟢 Running (1)"
@@ -431,6 +447,9 @@ def get_docker_status(
text=True,
check=False,
)
if res.returncode != 0:
return "❓ Unknown"
container_ids = [c for c in res.stdout.strip().splitlines() if c]
if not container_ids:
return "🔴 Stopped"
@@ -441,6 +460,9 @@ def get_docker_status(
text=True,
check=False,
)
if inspect_res.returncode != 0:
return "❓ Unknown"
running_states = inspect_res.stdout.strip().splitlines()
running_count = sum(1 for s in running_states if s.lower() == "true")
total_count = len(container_ids)
@@ -727,8 +749,12 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
lines.append("")
content = "\n".join(lines).strip() + "\n"
with open(services_yaml_path, "w", encoding="utf-8") as f:
tmp_services_path = services_yaml_path + ".tmp"
with open(tmp_services_path, "w", encoding="utf-8") as f:
f.write(content)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_services_path, services_yaml_path)
print(
f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)"
+294 -60
View File
@@ -12,12 +12,16 @@ Implements the single command execution pipeline for homelab-appctl.service:
from __future__ import annotations
import logging
import os
import subprocess
import time
from pathlib import Path
from typing import Any
import yaml
logger = logging.getLogger("appctl_router")
from appctl_audit import (
AuditLogger,
AuditPersistenceError,
@@ -63,6 +67,7 @@ from appctl_engine import (
check_ssl_cert,
cmd_sync_homepage,
get_core_services,
get_docker_status,
get_sites_apps,
resolve_app,
)
@@ -74,18 +79,22 @@ from core_manifest import (
parse_manifest,
)
from gitops_dispatcher import validate_compose_security
from provenance import inspect_workload_two_axis
from provenance import get_local_checkout_status, inspect_workload_two_axis
MAX_OUTPUT_BYTES = 256 * 1024 # 256 KiB cap per invocation
class RouterValidationError(Exception):
"""Raised when request payload or pre-flight validation fails (400 Bad Request)."""
"""Raised when request payload or pre-flight validation fails (400 Bad Request or 403 Capability Denied)."""
def __init__(self, message: str) -> None:
def __init__(
self,
message: str,
code: ErrorCode = ErrorCode.ERR_VALIDATION_FAILED,
) -> None:
super().__init__(message)
self.code = ErrorCode.ERR_VALIDATION_FAILED
self.http_status = 400
self.code = code
self.http_status = code.http_status
class RouterExecutionError(Exception):
@@ -207,6 +216,18 @@ def assemble_workload_env(
if local_env.is_file():
env.update(parse_dotenv(local_env, validate_keys=True))
# Re-assert immutable platform infrastructure keys (defense-in-depth)
env["HOMELAB_DOMAIN"] = domain
env["DOMAIN_SUFFIX"] = domain
env["DOMAIN"] = domain
env["PROXY_NETWORK"] = os.environ.get("PROXY_NETWORK", "proxy-net")
env["CERT_RESOLVER"] = os.environ.get("CERT_RESOLVER", "myresolver")
env["SERVICE_NAME"] = app_name
env["CONTAINER_NAME"] = app_name
env["SERVICE_DOMAIN"] = f"{app_name}.{domain}"
if "DOCKER_CONFIG" in os.environ:
env["DOCKER_CONFIG"] = os.environ["DOCKER_CONFIG"]
return env
@@ -289,19 +310,38 @@ def validate_workload_preflight(
try:
manifest = parse_manifest(manifest_file)
except ManifestValidationError as err:
raise RouterValidationError(f"Workload manifest validation failed: {err}") from err
raise RouterValidationError(
f"Workload manifest validation failed: {err}"
) from err
effective_name = app_name or manifest.name
compose_file = _resolve_compose_file(app_dir)
if compose_file.exists():
resolved_env = assemble_workload_env(app_dir, manifest, effective_name)
ok, reason = validate_compose_security(
compose_file=compose_file,
allowed_root=app_dir,
app_name=effective_name,
resolved_env=resolved_env,
)
if not ok:
is_cap_denial = bool(
reason
and reason.startswith(
(
"Capability not granted:",
"Capability grants integrity check failed:",
)
)
)
err_code = (
ErrorCode.ERR_CAPABILITY_NOT_GRANTED
if is_cap_denial
else ErrorCode.ERR_VALIDATION_FAILED
)
raise RouterValidationError(
f"Compose AST security validation failed for '{effective_name}': {reason}"
f"Compose AST security validation failed for '{effective_name}': {reason}",
code=err_code,
)
return manifest, compose_file
@@ -327,7 +367,9 @@ def validate_core_preflight(
if not compose_file.is_file():
raise RouterValidationError(f"Core compose file not found at '{compose_file}'")
if compose_file.is_symlink() and not compose_file.resolve().is_relative_to(core_dir_resolved):
if compose_file.is_symlink() and not compose_file.resolve().is_relative_to(
core_dir_resolved
):
raise RouterValidationError(
f"Core compose file symlink escapes Core root: '{compose_file}'"
)
@@ -591,7 +633,9 @@ class OperationalRouter:
elif operation == OperationType.WORKLOAD_PULL:
result_data = self._op_workload_pull(resolved_app)
elif operation == OperationType.WORKLOAD_UPDATE:
result_data, commit_sha = self._op_workload_update(request, resolved_app)
result_data, commit_sha = self._op_workload_update(
request, resolved_app
)
elif operation == OperationType.PLATFORM_SYNC_HOMEPAGE:
result_data = self._op_platform_sync_homepage()
else:
@@ -600,7 +644,12 @@ class OperationalRouter:
duration_ms = int((time.perf_counter() - start_time) * 1000)
# Audit COMPLETED for mutating ops and sensitive reads
if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS:
# Audit COMPLETED for mutating ops and sensitive reads
if (
operation in MUTATING_OPERATIONS
or operation in SENSITIVE_READ_OPERATIONS
):
try:
self.audit_logger.log_completed(
operation_id=op_id,
principal=principal_audit,
@@ -612,8 +661,12 @@ class OperationalRouter:
parameters=request.parameters,
duration_ms=duration_ms,
commit_sha=commit_sha,
message=result_data.get("message", "Operation completed successfully"),
message=result_data.get(
"message", "Operation completed successfully"
),
)
except AuditPersistenceError as audit_err:
logger.error("Failed to persist COMPLETED audit record: %s", audit_err)
return OperationResponse(
version="1.0",
@@ -629,7 +682,11 @@ class OperationalRouter:
except (RouterValidationError, RouterExecutionError) as err:
duration_ms = int((time.perf_counter() - start_time) * 1000)
if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS:
if (
operation in MUTATING_OPERATIONS
or operation in SENSITIVE_READ_OPERATIONS
):
try:
self.audit_logger.log_failed(
operation_id=op_id,
principal=principal_audit,
@@ -644,6 +701,8 @@ class OperationalRouter:
error_code=err.code.value,
message=str(err),
)
except AuditPersistenceError as audit_err:
logger.error("Failed to persist FAILED audit record: %s", audit_err)
return OperationResponse(
version="1.0",
success=False,
@@ -653,6 +712,42 @@ class OperationalRouter:
duration_ms=duration_ms,
error=OperationError(code=err.code, message=str(err)),
)
except Exception as err:
logger.exception("Unexpected execution error in router")
duration_ms = int((time.perf_counter() - start_time) * 1000)
if (
operation in MUTATING_OPERATIONS
or operation in SENSITIVE_READ_OPERATIONS
):
try:
self.audit_logger.log_failed(
operation_id=op_id,
principal=principal_audit,
action=operation.value,
target=target,
transport=transport,
origin=origin,
client=client,
parameters=request.parameters,
duration_ms=duration_ms,
exit_code=1,
error_code=ErrorCode.ERR_EXECUTION_FAILED.value,
message=f"Unexpected execution failure: {err}",
)
except AuditPersistenceError as audit_err:
logger.error("Failed to persist FAILED audit record: %s", audit_err)
return OperationResponse(
version="1.0",
success=False,
operation_id=op_id,
operation=operation,
target=target,
duration_ms=duration_ms,
error=OperationError(
code=ErrorCode.ERR_EXECUTION_FAILED,
message=f"Unexpected execution failure: {err}",
),
)
# -----------------------------------------------------------------------
# Domain Operation Implementations
@@ -667,24 +762,41 @@ class OperationalRouter:
for app in apps:
item = app.to_dict()
app_path = Path(app.dir_path)
if params.fetch:
docker_status = get_docker_status(dir_path=app_path)
item["status"] = docker_status
if app.manifest_error:
item["deployment_status"] = "⚠️ Manifest Error"
item["provenance_status"] = "⚠️ Invalid Manifest"
else:
manifest_obj = app.manifest_obj or Manifest(
name=app.name, domain=app.domain
)
two_axis = inspect_workload_two_axis(
app_dir=app_path,
manifest=manifest_obj,
fetch_upstream=True,
fetch_upstream=params.fetch,
docker_status=docker_status,
)
item["deployment_status"] = two_axis.checkout.status_label
item["provenance_status"] = two_axis.provenance.status.value
if params.ssl and not app.is_internal:
item["ssl"] = check_ssl_cert(app.domain)
apps_data.append(item)
if params.core:
for svc in get_core_services(core_dir=str(self.core_dir)):
core_checkout = get_local_checkout_status(self.core_dir)
for i, svc in enumerate(get_core_services(core_dir=str(self.core_dir))):
svc_dict = svc.to_dict()
svc_dict["status"] = get_docker_status(
dir_path=self.core_dir,
container_name=svc.container_name,
)
svc_dict["deployment_status"] = (
core_checkout.status_label if i == 0 else ""
)
svc_dict["provenance_status"] = "— Core Platform"
if params.ssl and not svc.is_internal:
svc_dict["ssl"] = check_ssl_cert(svc.domain)
apps_data.append(svc_dict)
@@ -710,9 +822,14 @@ class OperationalRouter:
domain = target or resolve_canonical_domain()
try:
cert_info = check_ssl_cert(domain)
return {"ssl": cert_info, "message": f"SSL certificate inspected for {domain}"}
return {
"ssl": cert_info,
"message": f"SSL certificate inspected for {domain}",
}
except Exception as err:
raise RouterExecutionError(f"SSL inspection failed for '{domain}': {err}") from err
raise RouterExecutionError(
f"SSL inspection failed for '{domain}': {err}"
) from err
def _op_platform_health(self) -> dict[str, Any]:
return {
@@ -726,13 +843,23 @@ class OperationalRouter:
app_dir, _, compose_file, env, _ = self._prepare_target_context(app)
cmd = ["docker", "compose", "-f", str(compose_file), "config"]
code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0)
code, stdout, stderr = run_bounded_subprocess(
cmd, cwd=app_dir, env=env, timeout=15.0
)
if code != 0:
raise RouterExecutionError(f"docker compose config failed: {stderr}", exit_code=code)
raise RouterExecutionError(
f"docker compose config failed: {stderr}", exit_code=code
)
config_output = stdout
if principal.role != Role.ADMIN:
# Redact secrets for non-admin callers
try:
parsed_yaml = yaml.safe_load(stdout)
if isinstance(parsed_yaml, (dict, list)):
redacted_parsed = redact_sensitive_data(parsed_yaml)
config_output = yaml.safe_dump(redacted_parsed, sort_keys=False)
except (yaml.YAMLError, ValueError):
config_output = redact_sensitive_data(config_output)
return {"output": config_output, "message": "Evaluated compose configuration"}
@@ -755,13 +882,23 @@ class OperationalRouter:
if container:
cmd.append(container)
code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0)
code, stdout, stderr = run_bounded_subprocess(
cmd, cwd=app_dir, env=env, timeout=15.0
)
if code != 0:
raise RouterExecutionError(f"docker compose logs failed: {stderr}", exit_code=code)
raise RouterExecutionError(
f"docker compose logs failed: {stderr}", exit_code=code
)
return {"output": stdout, "tail": params.tail, "message": f"Tail {params.tail} logs"}
return {
"output": stdout,
"tail": params.tail,
"message": f"Tail {params.tail} logs",
}
def _op_workload_deploy(self, request: OperationRequest, app: Any) -> dict[str, Any]:
def _op_workload_deploy(
self, request: OperationRequest, app: Any
) -> dict[str, Any]:
params = request.parse_parameters()
assert isinstance(params, DeployParams)
app_dir, _, compose_file, env, container = self._prepare_target_context(app)
@@ -769,12 +906,25 @@ class OperationalRouter:
# Optional build
if params.build:
build_cmd = ["docker", "compose", "-f", str(compose_file), "build"]
build_cmd = [
"docker",
"compose",
"-f",
str(compose_file),
"build",
"--pull",
]
if params.no_cache:
build_cmd.append("--no-cache")
if container:
build_cmd.append(container)
code, out, err = run_bounded_subprocess(build_cmd, cwd=app_dir, env=env, timeout=300.0)
code, out, err = run_bounded_subprocess(
build_cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0:
raise RouterExecutionError(f"docker compose build failed: {err}", exit_code=code)
raise RouterExecutionError(
f"docker compose build failed: {err}", exit_code=code
)
# Deploy up
up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d"]
@@ -783,9 +933,13 @@ class OperationalRouter:
if container:
up_cmd.append(container)
code, out, err = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0)
code, out, err = run_bounded_subprocess(
up_cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0:
raise RouterExecutionError(f"docker compose up failed: {err}", exit_code=code)
raise RouterExecutionError(
f"docker compose up failed: {err}", exit_code=code
)
# Trigger Homepage sync for Sites workloads
if not is_core:
@@ -806,13 +960,21 @@ class OperationalRouter:
else:
cmd = ["docker", "compose", "-f", str(compose_file), "down"]
code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0)
code, out, err = run_bounded_subprocess(
cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0:
raise RouterExecutionError(f"docker compose stop/down failed: {err}", exit_code=code)
raise RouterExecutionError(
f"docker compose stop/down failed: {err}", exit_code=code
)
if not is_core:
self._trigger_homepage_sync()
return {"output": out, "action": "stopped", "message": f"Workload '{app.name}' stopped"}
return {
"output": out,
"action": "stopped",
"message": f"Workload '{app.name}' stopped",
}
def _op_workload_restart(self, app: Any) -> dict[str, Any]:
app_dir, _, compose_file, env, container = self._prepare_target_context(app)
@@ -822,13 +984,21 @@ class OperationalRouter:
if container:
cmd.append(container)
code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0)
code, out, err = run_bounded_subprocess(
cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0:
raise RouterExecutionError(f"docker compose restart failed: {err}", exit_code=code)
raise RouterExecutionError(
f"docker compose restart failed: {err}", exit_code=code
)
if not is_core:
self._trigger_homepage_sync()
return {"output": out, "action": "restarted", "message": f"Workload '{app.name}' restarted"}
return {
"output": out,
"action": "restarted",
"message": f"Workload '{app.name}' restarted",
}
def _op_workload_pull(self, app: Any) -> dict[str, Any]:
app_dir, _, compose_file, env, container = self._prepare_target_context(app)
@@ -837,20 +1007,49 @@ class OperationalRouter:
pull_cmd = ["docker", "compose", "-f", str(compose_file), "pull"]
if container:
pull_cmd.append(container)
code, _, err = run_bounded_subprocess(pull_cmd, cwd=app_dir, env=env, timeout=300.0)
code, _, err = run_bounded_subprocess(
pull_cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0:
raise RouterExecutionError(f"docker compose pull failed: {err}", exit_code=code)
raise RouterExecutionError(
f"docker compose pull failed: {err}", exit_code=code
)
up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"]
up_cmd = [
"docker",
"compose",
"-f",
str(compose_file),
"up",
"-d",
"--remove-orphans",
]
if container:
up_cmd.append(container)
code, out_up, err_up = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0)
code, out_up, err_up = run_bounded_subprocess(
up_cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0:
raise RouterExecutionError(f"docker compose up failed after pull: {err_up}", exit_code=code)
raise RouterExecutionError(
f"docker compose up failed after pull: {err_up}", exit_code=code
)
if not is_core:
self._trigger_homepage_sync()
return {"output": out_up, "action": "pulled", "message": f"Workload '{app.name}' pulled and updated"}
return {
"output": out_up,
"action": "pulled",
"message": f"Workload '{app.name}' pulled and updated",
}
@staticmethod
def _resolve_git_context(app_dir: Path) -> tuple[Path, str | None]:
"""Resolve (git_root, subpath) supporting standalone <app>/.git and parent monorepo .git."""
if (app_dir / ".git").exists():
return app_dir, None
if (app_dir.parent / ".git").exists():
return app_dir.parent, f"{app_dir.name}/"
return app_dir, None
def _op_workload_update(
self, request: OperationRequest, app: Any
@@ -868,11 +1067,17 @@ class OperationalRouter:
app_dir = Path(app.dir_path)
is_core = self._is_core_target(app)
container = self._target_container(app)
git_root, git_subpath = (
(app_dir, None) if is_core else self._resolve_git_context(app_dir)
)
# 1. Clean working tree check
status_cmd = ["git", "-C", str(git_root), "status", "--porcelain"]
if git_subpath is not None:
status_cmd.extend(["--", git_subpath])
code, status_out, _ = run_bounded_subprocess(
["git", "-C", str(app_dir), "status", "--porcelain"],
cwd=app_dir,
status_cmd,
cwd=git_root,
timeout=5.0,
)
if code != 0 or status_out.strip():
@@ -881,14 +1086,16 @@ class OperationalRouter:
)
# 2. git pull --ff-only
pull_cmd = ["git", "-C", str(app_dir), "pull", "--ff-only"]
pull_cmd = ["git", "-C", str(git_root), "pull", "--ff-only"]
if params.expected_branch:
pull_cmd.extend(["origin", params.expected_branch])
pull_cmd.extend(["origin", "--", params.expected_branch])
code, pull_out, pull_err = run_bounded_subprocess(
pull_cmd, cwd=app_dir, timeout=60.0
pull_cmd, cwd=git_root, timeout=60.0
)
if code != 0:
raise RouterExecutionError(f"git pull failed for '{app.name}': {pull_err}", exit_code=code)
raise RouterExecutionError(
f"git pull failed for '{app.name}': {pull_err}", exit_code=code
)
# 3. Post-pull re-validation of manifest and expected_branch
if is_core:
@@ -896,15 +1103,17 @@ class OperationalRouter:
manifest = None
declared_actions = ["compose_pull", "compose_up"]
else:
manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name)
manifest, compose_file = validate_workload_preflight(
app_dir, self.sites_dir, app.name
)
if (
params.expected_branch
and manifest.source
and manifest.source.ref != params.expected_branch
and manifest.deployment
and manifest.deployment.branch != params.expected_branch
):
raise RouterValidationError(
f"Post-pull branch mismatch for '{app.name}': expected '{params.expected_branch}', "
f"manifest declared '{manifest.source.ref}'"
f"manifest declared '{manifest.deployment.branch}'"
)
declared_actions = manifest.deployment.actions or ["compose_up"]
@@ -912,15 +1121,33 @@ class OperationalRouter:
env = assemble_workload_env(app_dir, manifest, app.name)
output_log = [f"git: {pull_out.strip()}"]
for action in declared_actions:
actions = list(declared_actions)
if params.build and "compose_build" not in actions:
if "compose_up" in actions:
idx = actions.index("compose_up")
actions.insert(idx, "compose_build")
else:
actions.append("compose_build")
for action in actions:
if action == "git_pull":
continue # already executed in step 2
elif action == "compose_pull":
cmd = ["docker", "compose", "-f", str(compose_file), "pull"]
elif action == "compose_build" or (params.build and action == "compose_up"):
cmd = ["docker", "compose", "-f", str(compose_file), "build"]
elif action == "compose_build":
cmd = ["docker", "compose", "-f", str(compose_file), "build", "--pull"]
if params.no_cache:
cmd.append("--no-cache")
elif action == "compose_up":
cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"]
cmd = [
"docker",
"compose",
"-f",
str(compose_file),
"up",
"-d",
"--remove-orphans",
]
elif action == "compose_restart":
cmd = ["docker", "compose", "-f", str(compose_file), "restart"]
else:
@@ -929,7 +1156,9 @@ class OperationalRouter:
if container:
cmd.append(container)
code, act_out, act_err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0)
code, act_out, act_err = run_bounded_subprocess(
cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0:
raise RouterExecutionError(
f"Action '{action}' failed during workload.update for '{app.name}': {act_err}",
@@ -939,8 +1168,8 @@ class OperationalRouter:
# 5. Extract current commit SHA
_, sha_out, _ = run_bounded_subprocess(
["git", "-C", str(app_dir), "rev-parse", "--short", "HEAD"],
cwd=app_dir,
["git", "-C", str(git_root), "rev-parse", "--short", "HEAD"],
cwd=git_root,
timeout=5.0,
)
commit_sha = sha_out.strip() or None
@@ -957,13 +1186,18 @@ class OperationalRouter:
}, commit_sha
def _op_platform_sync_homepage(self) -> dict[str, Any]:
self._trigger_homepage_sync()
return {"action": "sync_homepage", "message": "Homepage dashboard synchronized successfully"}
cmd_sync_homepage()
return {
"action": "sync_homepage",
"message": "Homepage dashboard synchronized successfully",
}
def _trigger_homepage_sync(self) -> None:
"""Atomic compile of Homepage dashboard services.yaml under _homepage_sync.lock."""
try:
with self.lock_manager.homepage_sync_lock():
cmd_sync_homepage()
except (OSError, ValueError, RuntimeError) as exc:
except (OSError, ValueError, RuntimeError, ConcurrentMutationError) as exc:
import sys
print(f"Warning: Homepage sync non-fatal error: {exc}", file=sys.stderr)
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""
bootstrap_token.py — Operator Admin Token Bootstrap & Rotation Helper (WP4)
Generates a 256-bit cryptographically secure Bearer token, saves it locally
with strict mode 0600 permissions (~/.config/homelab/token), and prints the
corresponding JSON descriptor for insertion into the SOPS tokens store
(nixos/secrets.yaml -> appctl/tokens_json).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import secrets
import stat
import sys
from pathlib import Path
from typing import Any
# Ensure scripts directory is in sys.path when executed directly
_scripts_dir = Path(__file__).resolve().parent
if str(_scripts_dir) not in sys.path:
sys.path.insert(0, str(_scripts_dir))
from appctl_auth import Role, TokenDescriptor
DEFAULT_TOKEN_PATH = Path.home() / ".config/homelab/token"
DEFAULT_TOKEN_ID = "operator-admin"
DEFAULT_IDENTITY = "operator"
DEFAULT_ROLE = Role.ADMIN.value
def generate_token() -> tuple[str, str]:
"""Generate a 256-bit cryptographically secure Bearer token and its SHA-256 digest."""
raw_token = secrets.token_hex(32)
digest = hashlib.sha256(raw_token.encode()).hexdigest()
return raw_token, digest
def write_token_file(path: Path, raw_token: str, force: bool = False) -> None:
"""
Write raw Bearer token to path with mode 0600.
Ensures parent directory exists with mode 0700.
Fails closed if the destination exists and force is False.
"""
path = path.expanduser().resolve()
if path.exists() and not force:
raise FileExistsError(
f"Token file '{path}' already exists. Use --force / -f to overwrite."
)
parent = path.parent
if not parent.exists():
parent.mkdir(mode=0o700, parents=True, exist_ok=True)
try:
parent.chmod(0o700)
except OSError:
pass
elif stat.S_IMODE(parent.stat().st_mode) != 0o700:
try:
parent.chmod(0o700)
except OSError:
pass
fd = os.open(str(path), os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o600)
try:
content = f"{raw_token}\n".encode()
os.write(fd, content)
finally:
os.close(fd)
path.chmod(0o600)
def bootstrap_token(
output_path: Path | str = DEFAULT_TOKEN_PATH,
token_id: str = DEFAULT_TOKEN_ID,
identity: str = DEFAULT_IDENTITY,
role: str = DEFAULT_ROLE,
force: bool = False,
) -> dict[str, Any]:
"""
Generate Bearer token, persist to file with strict permissions,
and return the validated TokenDescriptor dictionary.
"""
path = Path(output_path).expanduser().resolve()
raw_token, digest = generate_token()
write_token_file(path, raw_token, force=force)
# Validate against TokenDescriptor model
validated = TokenDescriptor(
token_id=token_id,
identity=identity,
role=Role(role),
sha256=digest,
)
return validated.model_dump(mode="json")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Bootstrap or rotate an operator Bearer token for appctl."
)
parser.add_argument(
"-o",
"--output",
default=str(DEFAULT_TOKEN_PATH),
help=f"Destination token file path (default: {DEFAULT_TOKEN_PATH})",
)
parser.add_argument(
"--token-id",
default=DEFAULT_TOKEN_ID,
help=f"Token descriptor ID (default: {DEFAULT_TOKEN_ID})",
)
parser.add_argument(
"--identity",
default=DEFAULT_IDENTITY,
help=f"Caller identity (default: {DEFAULT_IDENTITY})",
)
parser.add_argument(
"--role",
default=DEFAULT_ROLE,
choices=[r.value for r in Role],
help=f"Role assignment (default: {DEFAULT_ROLE})",
)
parser.add_argument(
"-f",
"--force",
action="store_true",
help="Overwrite existing token file if present",
)
parser.add_argument(
"--print-json",
action="store_true",
help="Output only the JSON descriptor snippet for piping/automation",
)
args = parser.parse_args(argv)
try:
descriptor = bootstrap_token(
output_path=args.output,
token_id=args.token_id,
identity=args.identity,
role=args.role,
force=args.force,
)
except FileExistsError as err:
sys.stderr.write(f"Error: {err}\n")
return 1
json_snippet = json.dumps(descriptor, indent=2)
if args.print_json:
sys.stdout.write(f"{json_snippet}\n")
else:
sys.stdout.write(
f"Generated Bearer token and saved to {args.output} (mode 0600).\n\n"
f"Add the following descriptor to your SOPS tokens store (nixos/secrets.yaml -> appctl/tokens_json):\n\n"
f"{json_snippet}\n\n"
f"After updating nixos/secrets.yaml with `sops nixos/secrets.yaml`, apply changes with:\n"
f" sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure\n"
)
return 0
if __name__ == "__main__":
sys.exit(main())
+17 -6
View File
@@ -72,10 +72,26 @@ RESERVED_ENV_KEYS = {
"SITES_DIR",
"ENV_FILE",
"HOMESERVER_ENV",
"HOMELAB_DOMAIN",
"DOMAIN_SUFFIX",
"DOMAIN",
"PROXY_NETWORK",
"CERT_RESOLVER",
"DOCKER_CONFIG",
"SERVICE_NAME",
"CONTAINER_NAME",
"SERVICE_DOMAIN",
"HOMELAB_GRANTS_FILE",
}
ALLOWED_STRATEGIES = {"compose"}
ALLOWED_ACTIONS = {"git_pull", "compose_pull", "compose_up", "compose_build", "compose_restart"}
ALLOWED_ACTIONS = {
"git_pull",
"compose_pull",
"compose_up",
"compose_build",
"compose_restart",
}
def validate_transport(url: str) -> tuple[TransportScheme, str]:
@@ -168,13 +184,11 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]:
return RefType.BRANCH, ref
class SourceConfig(BaseModel):
"""Upstream source provenance descriptor."""
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
url: str
ref: str = "main"
type: str = "git"
@@ -223,7 +237,6 @@ class DeploymentConfig(BaseModel):
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
strategy: str = "compose"
branch: str = "main"
actions: list[str] = Field(default_factory=lambda: ["git_pull", "compose_up"])
@@ -264,7 +277,6 @@ class HomepageConfig(BaseModel):
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
title: str
group: str = "Applications"
icon: str = "default.png"
@@ -295,7 +307,6 @@ class Manifest(BaseModel):
ignored_types=(dict,),
)
name: str
schema_version: str = Field(default="1.0", alias="schemaVersion")
domain: str = ""
File diff suppressed because it is too large. Load diff
+27 -9
View File
@@ -92,10 +92,17 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
"""
Inspect local git repository checkout state.
Reports clean/dirty status, active branch/ref, and current commit SHA.
Supports standalone <dir_path>/.git checkouts (checked first) and
unified monorepo checkouts where <dir_path>.parent/.git exists.
"""
path = Path(dir_path)
git_dir = path / ".git"
if not git_dir.exists():
subpath: str | None = None
if (path / ".git").exists():
git_root = path
elif (path.parent / ".git").exists():
git_root = path.parent
subpath = f"{path.name}/"
else:
return CheckoutStatus(
is_git=False,
is_dirty=False,
@@ -107,27 +114,35 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
# Clean git environment so calls are not polluted by outer hooks
git_env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
# 1. Check cleanliness
# 1. Check cleanliness (scoped to workload subpath in monorepo mode)
is_dirty = False
git_error: str | None = None
status_cmd = ["git", "-C", str(git_root), "status", "--porcelain"]
if subpath is not None:
status_cmd.extend(["--", subpath])
try:
status_res = subprocess.run(
["git", "-C", str(path), "status", "--porcelain"],
status_cmd,
capture_output=True,
text=True,
check=False,
timeout=5.0,
env=git_env,
)
if status_res.returncode == 0 and status_res.stdout.strip():
if status_res.returncode == 0:
if status_res.stdout.strip():
is_dirty = True
except (subprocess.SubprocessError, OSError):
else:
git_error = f"⚠️ Git Error (exit {status_res.returncode})"
except (subprocess.SubprocessError, OSError) as exc:
is_dirty = False
git_error = f"⚠️ Git Error ({exc.__class__.__name__})"
# 2. Get active branch
branch = ""
try:
branch_res = subprocess.run(
["git", "-C", str(path), "rev-parse", "--abbrev-ref", "HEAD"],
["git", "-C", str(git_root), "rev-parse", "--abbrev-ref", "HEAD"],
capture_output=True,
text=True,
check=False,
@@ -139,7 +154,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
if branch == "HEAD":
# Detached HEAD, check describe
desc_res = subprocess.run(
["git", "-C", str(path), "describe", "--tags", "--exact-match"],
["git", "-C", str(git_root), "describe", "--tags", "--exact-match"],
capture_output=True,
text=True,
check=False,
@@ -155,7 +170,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
commit_sha = ""
try:
sha_res = subprocess.run(
["git", "-C", str(path), "rev-parse", "--short", "HEAD"],
["git", "-C", str(git_root), "rev-parse", "--short", "HEAD"],
capture_output=True,
text=True,
check=False,
@@ -168,6 +183,9 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
commit_sha = ""
# 4. Format status label
if git_error:
status_label = git_error
else:
state_symbol = "* Dirty" if is_dirty else "✓ Clean"
ref_desc = f"{branch}@{commit_sha}" if commit_sha else branch
status_label = f"{state_symbol} ({ref_desc})" if ref_desc else state_symbol
+1 -1
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
# scripts/test - Automated test & invariant verification runner for Homelab Core
# scripts/run-tests - Automated test & invariant verification runner for Homelab Core
set -euo pipefail
cd "$(dirname "$0")/.."
+149
View File
@@ -0,0 +1,149 @@
"""
workload_grants.py — Host-Granted Workload Capability Loader & Schema (ADR-0005)
Loads and validates /etc/homelab/grants.json (or HOMELAB_GRANTS_FILE) using strict
Pydantic v2 models (ConfigDict(extra="forbid")).
"""
from __future__ import annotations
import json
import os
import stat
from pathlib import Path, PurePosixPath
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
DEFAULT_GRANTS_FILE = Path("/etc/homelab/grants.json")
PRIVILEGED_GROUPS: frozenset[str] = frozenset({"0", "root", "wheel", "docker"})
class WorkloadGrantsError(Exception):
"""Raised when the host capability grants file fails integrity or schema checks."""
class WorkloadGrant(BaseModel):
"""Explicit host-granted capabilities for a single workload."""
model_config = ConfigDict(extra="forbid")
devices: list[str] = Field(default_factory=list)
groups: list[str] = Field(default_factory=list)
readOnlyPaths: list[str] = Field(default_factory=list)
@field_validator("groups")
@classmethod
def _validate_groups(cls, values: list[str]) -> list[str]:
cleaned: list[str] = []
for raw in values:
group = raw.strip()
if not group:
raise ValueError("Granted group entry cannot be empty.")
if group.lower() in PRIVILEGED_GROUPS:
raise ValueError(
f"Privileged group '{group}' cannot be granted to workloads."
)
cleaned.append(group)
return cleaned
@field_validator("devices", "readOnlyPaths")
@classmethod
def _validate_absolute_paths(cls, values: list[str]) -> list[str]:
cleaned: list[str] = []
for raw in values:
path_str = raw.strip()
if not path_str:
raise ValueError("Granted path entry cannot be empty.")
posix = PurePosixPath(path_str)
if not posix.is_absolute():
raise ValueError(
f"Granted path '{path_str}' must be an absolute path."
)
if ".." in posix.parts:
raise ValueError(
f"Granted path '{path_str}' must not contain '..' traversal."
)
cleaned.append(path_str)
return cleaned
class GrantsRegistry(BaseModel):
"""Root schema for /etc/homelab/grants.json."""
model_config = ConfigDict(extra="forbid")
schemaVersion: Literal["1.0"] = "1.0"
workloads: dict[str, WorkloadGrant] = Field(default_factory=dict)
def load_workload_grants(
grants_file: Path | None = None,
*,
verify_permissions: bool | None = None,
) -> dict[str, WorkloadGrant]:
"""
Load host-granted workload capabilities from grants_file or HOMELAB_GRANTS_FILE.
- If the target file does not exist (and is not a symlink), returns {} (zero grants).
- If the file is present (or is a symlink) and fails permission/integrity checks,
is unreadable, or fails JSON/Pydantic validation, raises WorkloadGrantsError.
"""
if grants_file is None:
env_path = os.environ.get("HOMELAB_GRANTS_FILE", "").strip()
target_path = Path(env_path) if env_path else DEFAULT_GRANTS_FILE
else:
target_path = grants_file
should_verify = (
(target_path == DEFAULT_GRANTS_FILE)
if verify_permissions is None
else verify_permissions
)
if not target_path.exists() and not target_path.is_symlink():
return {}
if should_verify:
try:
st = os.lstat(target_path)
except OSError as exc:
raise WorkloadGrantsError(
f"Failed to stat grants file '{target_path}': {exc}"
) from exc
if stat.S_ISLNK(st.st_mode) or not stat.S_ISREG(st.st_mode):
raise WorkloadGrantsError(
f"Grants file '{target_path}' must be a regular non-symlink file."
)
if st.st_uid != 0:
raise WorkloadGrantsError(
f"Grants file '{target_path}' must be owned by root (uid 0)."
)
if (st.st_mode & 0o022) != 0:
raise WorkloadGrantsError(
f"Grants file '{target_path}' must not be group- or world-writable."
)
try:
raw_text = target_path.read_text(encoding="utf-8")
except OSError as exc:
raise WorkloadGrantsError(
f"Failed to read grants file '{target_path}': {exc}"
) from exc
try:
payload = json.loads(raw_text)
except json.JSONDecodeError as exc:
raise WorkloadGrantsError(
f"Malformed JSON in grants file '{target_path}': {exc}"
) from exc
try:
registry = GrantsRegistry.model_validate(payload)
except ValidationError as exc:
raise WorkloadGrantsError(
f"Invalid schema in grants file '{target_path}': {exc}"
) from exc
return registry.workloads
+53
View File
@@ -0,0 +1,53 @@
"""Shared pytest fixtures for Canopy NixOS Core test suites."""
from __future__ import annotations
import os
import subprocess
import sys
from pathlib import Path
from typing import Protocol
import pytest
_STRIPPED_WORKLOAD_ENV_VARS = frozenset(
{"HOMELAB_DEPLOYMENTS_FILE", "WORKLOADS_DIR", "SITES_DIR"}
)
_SCRIPTS_DIR = Path(__file__).resolve().parent.parent / "scripts"
class IsolatedScriptRunner(Protocol):
"""Callable protocol for executing a Python expression in an isolated env."""
def __call__(
self, expr: str, extra_env: dict[str, str] | None = None
) -> str: ...
@pytest.fixture
def run_isolated_script_expr(tmp_path: Path) -> IsolatedScriptRunner:
"""
Execute a Python expression in a clean subprocess with workload env vars stripped.
Strips ``HOMELAB_DEPLOYMENTS_FILE``, ``WORKLOADS_DIR``, and ``SITES_DIR``,
sets ``HOME`` to ``tmp_path`` and ``PYTHONPATH`` to ``scripts/``, and
merges any optional ``extra_env`` overrides.
"""
def _run(expr: str, extra_env: dict[str, str] | None = None) -> str:
env = {
k: v
for k, v in os.environ.items()
if k not in _STRIPPED_WORKLOAD_ENV_VARS
}
env["HOME"] = str(tmp_path)
env["PYTHONPATH"] = str(_SCRIPTS_DIR)
if extra_env:
env.update(extra_env)
return subprocess.check_output(
[sys.executable, "-c", expr],
env=env,
text=True,
).strip()
return _run
+338
View File
@@ -0,0 +1,338 @@
"""
Security and structural tests for the read-only `agents` SSH user,
`ForceCommand` allowlist wrapper, and loopback-only `socket-proxy` binding.
"""
import os
import re
import shutil
import subprocess
from pathlib import Path
import pytest
import yaml
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
NIXOS_CONFIG = CORE_ROOT / "nixos" / "configuration.nix"
COMPOSE_FILE = CORE_ROOT / "docker-compose.yml"
FORCE_COMMAND_SCRIPT = CORE_ROOT / "nixos" / "scripts" / "agents-force-command.sh"
EXPECTED_AGENT_PUBKEY = (
"ssh-ed25519 "
"AAAAC3NzaC1lZDI1NTE5AAAAIE1pxTdygG5696q0jT7clfJZWtx48ugfUjpzvkHzovVd "
"canopy-agents"
)
def _extract_nix_block(content: str, header_pattern: str) -> str:
"""Extract a brace-delimited Nix attribute block starting at header_pattern."""
match = re.search(header_pattern, content)
assert match is not None, f"Missing Nix block matching: {header_pattern}"
pos = match.end()
# Skip `let ... in` bindings if present before the attribute set `{ ... }`
tail = content[pos:]
if re.match(r"\s*let\b", tail):
in_match = re.search(r"\bin\s*\{", tail)
assert in_match is not None, f"Missing 'in {{' for let-block: {header_pattern}"
start = pos + in_match.end() - 1
else:
start = content.find("{", pos)
assert start != -1, f"Opening brace not found for: {header_pattern}"
depth = 0
for idx in range(start, len(content)):
ch = content[idx]
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return content[start : idx + 1]
raise AssertionError(f"Unclosed Nix block for: {header_pattern}")
def _setup_mock_bin(tmp_path: Path) -> tuple[Path, Path]:
"""Create mock docker, journalctl, and appctl binaries that log invocations."""
mock_bin = tmp_path / "mock_bin"
mock_bin.mkdir()
invocations_log = tmp_path / "invocations.log"
bash_bin = shutil.which("bash") or "/bin/bash"
for cmd in ("docker", "journalctl", "appctl"):
stub = mock_bin / cmd
stub.write_text(
f"#!{bash_bin}\n"
f'printf "%s|%s|%s|%s|%s\\n" '
f'"{cmd}" "$*" "${{CORE_DIR:-}}" "${{WORKLOADS_DIR:-}}" "${{DOCKER_HOST:-}}" '
f'>> "{invocations_log}"\n',
encoding="utf-8",
)
stub.chmod(0o755)
return mock_bin, invocations_log
def _run_force_command(
ssh_original_command: str | None,
tmp_path: Path,
) -> tuple[subprocess.CompletedProcess[str], Path]:
"""Execute agents-force-command.sh with isolated mock PATH and SSH_ORIGINAL_COMMAND."""
assert FORCE_COMMAND_SCRIPT.exists(), (
f"ForceCommand script not found at {FORCE_COMMAND_SCRIPT}"
)
mock_bin, invocations_log = _setup_mock_bin(tmp_path)
env = {
"PATH": f"{mock_bin}:{os.environ.get('PATH', '/usr/bin:/bin')}",
"HOME": str(tmp_path),
}
if ssh_original_command is not None:
env["SSH_ORIGINAL_COMMAND"] = ssh_original_command
bash_bin = shutil.which("bash") or "/bin/bash"
proc = subprocess.run(
[bash_bin, str(FORCE_COMMAND_SCRIPT)],
env=env,
capture_output=True,
text=True,
check=False,
)
return proc, invocations_log
def test_socket_proxy_binds_loopback_only():
"""Ensure socket-proxy publishes port 2375 strictly on 127.0.0.1."""
compose = yaml.safe_load(COMPOSE_FILE.read_text(encoding="utf-8"))
services = compose.get("services", {})
assert "socket-proxy" in services, "socket-proxy service must exist"
ports = services["socket-proxy"].get("ports", [])
assert isinstance(ports, list) and len(ports) > 0, (
"socket-proxy must declare non-empty ports list"
)
assert all(isinstance(p, str) and p.startswith("127.0.0.1:") for p in ports), (
f"Every socket-proxy port must bind strictly to 127.0.0.1, got: {ports!r}"
)
assert "127.0.0.1:2375:2375" in ports, (
"socket-proxy must bind 127.0.0.1:2375:2375"
)
def test_nixos_agents_user_least_privilege():
"""Verify users.users.agents has read-only groups and excludes wheel/docker."""
content = NIXOS_CONFIG.read_text(encoding="utf-8")
agents_block = _extract_nix_block(content, r"users\.users\.agents\s*=")
assert re.search(r"isNormalUser\s*=\s*true\s*;", agents_block), (
"users.users.agents must set isNormalUser = true"
)
assert EXPECTED_AGENT_PUBKEY in agents_block, (
"users.users.agents must configure the canopy-agents SSH public key"
)
groups_match = re.search(r"extraGroups\s*=\s*\[(.*?)\]\s*;", agents_block, re.DOTALL)
assert groups_match is not None, "users.users.agents must declare extraGroups"
groups_text = groups_match.group(1)
actual_groups = set(re.findall(r'"([^"]+)"', groups_text))
assert actual_groups == {"homelab-operators", "systemd-journal"}, (
f"agents extraGroups must be strictly {{'homelab-operators', 'systemd-journal'}}, got: {actual_groups!r}"
)
def test_nixos_openssh_match_user_agents_hardening():
"""Verify services.openssh configures Match User agents with ForceCommand and hardening."""
content = NIXOS_CONFIG.read_text(encoding="utf-8")
ssh_block = _extract_nix_block(content, r"services\.openssh\s*=")
assert "Match User agents" in ssh_block, (
"services.openssh must configure Match User agents"
)
match_section = ssh_block[ssh_block.index("Match User agents") :]
required_directives = [
r"ForceCommand\s+\S*agents-force-command\b",
r"AllowTcpForwarding\s+no",
r"X11Forwarding\s+no",
r"AllowAgentForwarding\s+no",
r"PermitTTY\s+no",
r"PasswordAuthentication\s+no",
]
for pattern in required_directives:
assert re.search(pattern, match_section), (
f"Match User agents must include directive matching: {pattern}"
)
def test_force_command_script_has_no_eval_or_sh_c():
"""Ensure agents-force-command.sh never uses eval or subshell invocation."""
assert FORCE_COMMAND_SCRIPT.exists(), (
f"ForceCommand script not found at {FORCE_COMMAND_SCRIPT}"
)
content = FORCE_COMMAND_SCRIPT.read_text(encoding="utf-8")
assert "eval " not in content, "Dangerous 'eval' detected in ForceCommand script"
assert "sh -c" not in content, "Dangerous 'sh -c' detected in ForceCommand script"
assert "bash -c" not in content, "Dangerous 'bash -c' detected in ForceCommand script"
def test_force_command_exports_expected_environment(tmp_path: Path):
"""Verify ForceCommand exports CORE_DIR, WORKLOADS_DIR, and loopback DOCKER_HOST."""
proc, invocations_log = _run_force_command("docker ps", tmp_path)
assert proc.returncode == 0, f"Unexpected failure: {proc.stderr}"
lines = invocations_log.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 1
cmd, args, core_dir, workloads_dir, docker_host = lines[0].split("|")
assert cmd == "docker"
assert args == "ps"
assert core_dir == "/home/operator/Core"
assert workloads_dir == "/home/operator/Workloads"
assert docker_host == "tcp://127.0.0.1:2375"
@pytest.mark.parametrize(
("command", "expected_bin", "expected_args"),
[
("docker ps", "docker", "ps"),
("docker ps -a --format {{.Names}}", "docker", "ps -a --format {{.Names}}"),
("docker logs --tail 50 traefik", "docker", "logs --tail 50 traefik"),
("docker inspect traefik", "docker", "inspect traefik"),
(
"journalctl -u homelab-appctl -n 50 --no-pager",
"journalctl",
"-u homelab-appctl -n 50 --no-pager",
),
("appctl list --core", "appctl", "list --core"),
("appctl status", "appctl", "status"),
("appctl info traefik", "appctl", "info traefik"),
("appctl logs traefik", "appctl", "logs traefik"),
("appctl ssl --all", "appctl", "ssl --all"),
("appctl health", "appctl", "health"),
("appctl resolve traefik", "appctl", "resolve traefik"),
],
)
def test_force_command_allows_read_only_commands(
tmp_path: Path, command: str, expected_bin: str, expected_args: str
):
"""Verify allowlisted read-only commands execute cleanly with exact arguments."""
proc, invocations_log = _run_force_command(command, tmp_path)
assert proc.returncode == 0, f"Allowed command '{command}' failed: {proc.stderr}"
lines = invocations_log.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 1
cmd, args, *_ = lines[0].split("|")
assert cmd == expected_bin
assert args == expected_args
@pytest.mark.parametrize(
"bad_command",
[
None,
"",
" ",
"docker ps; id",
"docker ps && id",
"docker ps || id",
"docker ps | cat",
"docker ps `id`",
"docker ps $(id)",
"docker ps > /tmp/pwn",
"docker ps < /etc/passwd",
"docker ps\nid",
"docker ps\rid",
"docker ps 'traefik'",
'docker ps "traefik"',
"docker ps \\ id",
],
)
def test_force_command_rejects_empty_and_metacharacters(
tmp_path: Path, bad_command: str | None
):
"""Verify empty commands and shell metacharacters are rejected without execution."""
proc, invocations_log = _run_force_command(bad_command, tmp_path)
assert proc.returncode != 0, f"Dangerous input was unexpectedly allowed: {bad_command!r}"
assert not invocations_log.exists(), (
f"Command stub should not have been executed for: {bad_command!r}"
)
@pytest.mark.parametrize(
"disallowed_command",
[
"sudo id",
"su root",
"sh",
"bash",
"cat /etc/shadow",
"rm -rf /tmp/foo",
"systemctl restart docker",
"docker",
"docker run alpine",
"docker exec -it traefik sh",
"docker rm traefik",
"docker build .",
"docker stop traefik",
"docker start traefik",
"docker restart traefik",
"docker kill traefik",
"docker compose up -d",
"docker -H unix:///var/run/docker.sock ps",
"journalctl --flush",
"journalctl --rotate",
"journalctl --vacuum-size=1M",
"journalctl --vacuum-time=1d",
"journalctl --vacuum-files=1",
"journalctl --relinquish-var",
"journalctl --sync",
"journalctl --setup-keys",
"journalctl --update-catalog",
"appctl",
"appctl up traefik",
"appctl down traefik",
"appctl restart traefik",
"appctl update traefik",
"appctl pull traefik",
"appctl sync",
"appctl config",
"appctl deploy traefik",
"appctl complete services",
],
)
def test_force_command_rejects_disallowed_commands_and_subcommands(
tmp_path: Path, disallowed_command: str
):
"""Verify disallowed binaries, mutating subcommands, and mutating flags are rejected."""
proc, invocations_log = _run_force_command(disallowed_command, tmp_path)
assert proc.returncode != 0, (
f"Disallowed command was unexpectedly allowed: {disallowed_command!r}"
)
assert not invocations_log.exists(), (
f"Command stub should not have been executed for: {disallowed_command!r}"
)
@pytest.mark.parametrize("subcmd", ["ps", "logs", "inspect"])
@pytest.mark.parametrize(
"override_flag",
[
"-H unix:///var/run/docker.sock",
"-H=unix:///var/run/docker.sock",
"--host unix:///var/run/docker.sock",
"--host=unix:///var/run/docker.sock",
"--context default",
"--context=default",
"-c default",
"-c=default",
"--config /tmp",
"--config=/tmp",
],
)
def test_force_command_rejects_post_subcommand_docker_override_flags(
tmp_path: Path, subcmd: str, override_flag: str
):
"""Verify Docker connection/context/config override flags are rejected after valid subcommands."""
command = f"docker {subcmd} {override_flag}"
proc, invocations_log = _run_force_command(command, tmp_path)
assert proc.returncode != 0, (
f"Docker override flag was unexpectedly allowed: {command!r}"
)
assert not invocations_log.exists(), (
f"Command stub should not have been executed for: {command!r}"
)
+784
View File
@@ -228,6 +228,34 @@ def test_missing_or_corrupt_registry_fails_closed(tmp_path: Path, monkeypatch):
# Missing registry must fail closed: empty mapping, no resolution
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
def test_registry_resolves_workloads_and_sites_tilde_prefixes(
tmp_path: Path, monkeypatch
):
"""Ensure ~/Workloads/<app> and legacy ~/Sites/<app> paths resolve cleanly inside SITES_DIR."""
workloads_dir = tmp_path / "Workloads"
app_a = workloads_dir / "snappymail"
app_b = workloads_dir / "legacy-app"
app_a.mkdir(parents=True)
app_b.mkdir(parents=True)
registry = tmp_path / "deployments.yaml"
registry.write_text(
'schemaVersion: "1.0"\n'
"repositories:\n"
" snappymail:\n"
' path: "~/Workloads/snappymail"\n'
" legacy:\n"
' path: "~/Sites/legacy-app"\n',
encoding="utf-8",
)
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", workloads_dir)
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
assert gitops_dispatcher.resolve_repository("snappymail") == app_a.resolve()
assert gitops_dispatcher.resolve_repository("legacy") == app_b.resolve()
assert gitops_dispatcher.resolve_repository("valid") is None
# Corrupt YAML registry must also fail closed
@@ -241,6 +269,48 @@ def test_missing_or_corrupt_registry_fails_closed(tmp_path: Path, monkeypatch):
assert gitops_dispatcher.resolve_repository("valid") is None
def test_deployments_file_defaults_to_workloads(
tmp_path: Path, run_isolated_script_expr
):
"""Ensure DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml."""
resolved_default = run_isolated_script_expr(
"import gitops_dispatcher; print(gitops_dispatcher.DEPLOYMENTS_FILE)"
)
assert Path(resolved_default) == tmp_path / "Workloads" / "deployments.yaml"
def test_deployments_file_fails_closed_without_config_dir_fallback(
tmp_path: Path, monkeypatch
):
"""Ensure missing DEPLOYMENTS_FILE fails closed even when CONFIG_DIR/deployments.yaml exists."""
config_dir = tmp_path / "config-fallback"
config_dir.mkdir()
(config_dir / "deployments.yaml").write_text(
'schemaVersion: "1.0"\n'
"repositories:\n"
" docs:\n"
' path: "~/Workloads/docs"\n',
encoding="utf-8",
)
monkeypatch.setattr(
gitops_dispatcher, "DEPLOYMENTS_FILE", tmp_path / "Workloads" / "deployments.yaml"
)
monkeypatch.setattr(gitops_dispatcher, "CONFIG_DIR", config_dir)
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
def test_deployments_file_honors_workloads_dir_override(
tmp_path: Path, run_isolated_script_expr
):
"""Ensure DEPLOYMENTS_FILE honors WORKLOADS_DIR override when HOMELAB_DEPLOYMENTS_FILE is unset."""
custom_workloads = tmp_path / "CustomWorkloads"
resolved_override = run_isolated_script_expr(
"import gitops_dispatcher; print(gitops_dispatcher.DEPLOYMENTS_FILE)",
extra_env={"WORKLOADS_DIR": str(custom_workloads)},
)
assert Path(resolved_override) == custom_workloads / "deployments.yaml"
def test_webhook_verification_valid_signature():
"""Ensure valid HMAC-SHA256 signature passes verification."""
import hashlib
@@ -1068,3 +1138,717 @@ services:
)
assert valid is False
assert err is not None and "security_opt" in err.lower()
def test_validate_compose_security_rejects_dict_volume_without_type_bind(
tmp_path: Path,
):
"""Ensure dictionary volume declarations without explicit type: bind enforce host containment (CR-DI-01)."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
volumes:
- source: /etc/shadow
target: /app/shadow
""",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is False
assert err is not None and "prohibited host bind mount" in err.lower()
def test_validate_compose_security_rejects_variable_interpolation_in_volume_host_path(
tmp_path: Path,
):
"""Ensure volume host paths containing variable interpolation (${...}) fail closed (CR-DI-02)."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
volumes:
- "${HOST_DIR}/data:/data"
""",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is False
assert err is not None and "variable interpolation" in err.lower()
def test_validate_compose_security_rejects_variable_interpolation_in_dict_volume_source(
tmp_path: Path,
):
"""Ensure dictionary volume source containing variable interpolation (${...}) fails closed (CR-DI-02)."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
volumes:
- source: "${HOST_DIR}/data"
target: /data
""",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is False
assert err is not None and "variable interpolation" in err.lower()
def test_validate_compose_security_allows_valid_dict_volume_within_workload(
tmp_path: Path,
):
"""Ensure valid dictionary volume within workload root is accepted even without type: bind."""
(tmp_path / "data").mkdir()
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
volumes:
- source: ./data
target: /data
""",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is True
assert err is None
def test_validate_compose_security_allows_remote_git_build_urls(tmp_path: Path):
"""Ensure validate_compose_security permits remote Git/HTTP build URLs (#33)."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
https_app:
build: https://git.example.com/operator/app.git#main
ssh_dict_app:
build:
context: ssh://git@git.example.com:2223/operator/app.git
dockerfile: Dockerfile
scp_git_app:
build: git@git.example.com:operator/app.git
local_app:
build:
context: ./docker
""",
encoding="utf-8",
)
(tmp_path / "docker").mkdir()
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is True
assert err is None
@pytest.mark.parametrize(
"build_yaml,expected_substr",
[
("build: /etc", "escaping workload root"),
("build:\n context: ../../outside", "escaping workload root"),
('build: "${BUILD_CTX}/app"', "variable interpolation"),
('build:\n context: "${BUILD_CTX}/app"', "variable interpolation"),
],
)
def test_validate_compose_security_rejects_unsafe_build_contexts(
tmp_path: Path, build_yaml: str, expected_substr: str
):
"""Ensure validate_compose_security blocks local build host-path escapes and ${...} interpolation (#33)."""
app_dir = tmp_path / "Workloads" / "my-app"
app_dir.mkdir(parents=True)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"services:\n app:\n {build_yaml}\n",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="my-app"
)
assert valid is False
assert err is not None and expected_substr in err.lower()
def test_monorepo_webhook_dispatch_pulls_once_and_deploys_only_admitted_changed_subdirs(
tmp_path: Path, monkeypatch
):
"""Ensure canopy-workloads push pulls ~/Workloads once and dispatches only admitted changed subdirs (#33)."""
workloads_dir = tmp_path / "Workloads"
(workloads_dir / ".git").mkdir(parents=True)
snappymail_dir = workloads_dir / "snappymail"
gitea_dir = workloads_dir / "homelab-gitea"
rogue_dir = workloads_dir / "rogue-app"
for d in (snappymail_dir, gitea_dir, rogue_dir):
d.mkdir(parents=True)
(d / "app.yaml").write_text(f"name: {d.name}\n", encoding="utf-8")
registry = tmp_path / "deployments.yaml"
registry.write_text(
'schemaVersion: "1.0"\n'
"repositories:\n"
" snappymail:\n"
' path: "~/Workloads/snappymail"\n'
" gitea:\n"
' path: "~/Workloads/homelab-gitea"\n',
encoding="utf-8",
)
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", workloads_dir)
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
monkeypatch.setattr(gitops_dispatcher, "STATE_DIR", tmp_path / "state")
payload = {
"ref": "refs/heads/main",
"after": "deadbeef1234",
"repository": {"name": "canopy-workloads"},
"commits": [
{
"added": ["rogue-app/app.yaml", "README.md"],
"modified": ["snappymail/docker-compose.yml"],
"removed": ["../Core/scripts/appctl"],
}
],
}
git_calls: list[list[str]] = []
enqueued: list[Path] = []
spawned: list[str] = []
def mock_run(cmd, *args, **kwargs):
git_calls.append(cmd)
return MagicMock(returncode=0, stdout="", stderr="")
monkeypatch.setattr(gitops_dispatcher.subprocess, "run", mock_run)
monkeypatch.setattr(
gitops_dispatcher,
"enqueue_deployment",
lambda target_dir, cfg, branch, commit_sha="": enqueued.append(target_dir),
)
monkeypatch.setattr(
gitops_dispatcher,
"spawn_worker_async",
lambda target_name: spawned.append(target_name),
)
assert gitops_dispatcher.is_monorepo_push(payload) is True
ok, dispatched, _ = gitops_dispatcher.dispatch_monorepo_push(payload, "push")
assert ok is True
assert dispatched == [snappymail_dir.resolve()]
assert enqueued == [snappymail_dir.resolve()]
assert spawned == ["snappymail"]
# Pulled ~/Workloads exactly once
pull_calls = [c for c in git_calls if "pull" in c]
assert len(pull_calls) == 1
assert str(workloads_dir) in pull_calls[0]
# ---------------------------------------------------------------------------
# ADR-0005 Host-Granted Workload Capabilities ("Compose Requests, Nix Grants")
# ---------------------------------------------------------------------------
def _write_grants(path: Path, workloads: dict) -> Path:
import json
path.write_text(
json.dumps({"schemaVersion": "1.0", "workloads": workloads}),
encoding="utf-8",
)
return path
def _fake_group_lookup(key: str | int) -> tuple[str, int]:
table = {
"render": ("render", 303),
303: ("render", 303),
"video": ("video", 44),
44: ("video", 44),
"docker": ("docker", 998),
998: ("docker", 998),
"wheel": ("wheel", 10),
10: ("wheel", 10),
"root": ("root", 0),
0: ("root", 0),
}
lookup_key = int(key) if isinstance(key, str) and key.isdigit() else key
if lookup_key in table:
return table[lookup_key]
raise KeyError(key)
def test_validate_compose_security_permits_granted_stack(tmp_path: Path):
"""Positive ADR-0005 grants: render<->303, existing device, short & long :ro readOnlyPaths."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
dev_dir = tmp_path / "dev" / "dri"
dev_dir.mkdir(parents=True)
render_node = dev_dir / "renderD128"
render_node.write_text("", encoding="utf-8")
media_dir = tmp_path / "mnt" / "media"
media_sub = media_dir / "movies"
media_sub.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{
"media": {
"devices": [str(render_node)],
"groups": ["render"],
"readOnlyPaths": [str(media_dir)],
}
},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
jellyfin:
image: jellyfin/jellyfin:latest
user: "1000:303"
group_add:
- "303"
devices:
- "{render_node}:/dev/dri/renderD128:rw"
volumes:
- "{media_sub}:/media/movies:ro"
- type: bind
source: "{media_dir}"
target: /media/all
read_only: true
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="media",
grants_file=grants_file,
group_lookup=_fake_group_lookup,
)
assert ok is True, f"Expected granted capabilities to pass, got: {err}"
assert err is None
def test_capability_grants_evaluates_resolved_env_interpolation(tmp_path: Path):
"""Post-interpolation values from resolved_env are evaluated and permitted when granted."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"groups": ["303"], "readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
user: "${PUID:-1000}:${PGID:-1000}"
group_add:
- "${RENDER_GID}"
volumes:
- "${MEDIA_PATH}:/media:ro"
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="media",
resolved_env={
"PUID": "1000",
"PGID": "1000",
"RENDER_GID": "render",
"MEDIA_PATH": str(media_dir),
},
grants_file=grants_file,
group_lookup=_fake_group_lookup,
)
assert ok is True, f"Expected resolved env capabilities to pass, got: {err}"
@pytest.mark.parametrize(
"compose_body,expected_substr",
[
(" user: '0:131'", "user"),
(" user: '00:1000'", "root"),
(" user: '1000:0'", "user"),
(" user: '1000:docker'", "docker"),
(" user: '1000:44'", "44"),
(" user: '1000:999'", "999"),
(" group_add:\n - '303'", "group_add"),
(" network_mode: 'container:traefik'", "container:traefik"),
(" network_mode: 'service:web'", "service:web"),
(" device_cgroup_rules:\n - 'c 226:* rmw'", "device_cgroup_rules"),
(" user: '${PUID}:1000'", "interpolation"),
],
)
def test_validate_compose_security_rejects_ungranted_capabilities(
tmp_path: Path, compose_body: str, expected_substr: str
):
"""Ensure bypass vectors and ungranted capabilities fail closed."""
app_dir = tmp_path / "Workloads" / "ungranted"
app_dir.mkdir(parents=True)
grants_file = _write_grants(tmp_path / "grants.json", {})
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"services:\n app:\n image: alpine\n{compose_body}\n",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="ungranted",
grants_file=grants_file,
group_lookup=_fake_group_lookup,
)
assert ok is False
assert err is not None
assert expected_substr.lower() in err.lower()
def test_validate_compose_security_fails_closed_when_pyyaml_missing(
tmp_path: Path, monkeypatch
):
"""Ensure validate_compose_security fails closed when PyYAML is unavailable."""
app_dir = tmp_path / "Workloads" / "app"
app_dir.mkdir(parents=True)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text("services:\n app:\n image: alpine\n", encoding="utf-8")
monkeypatch.setattr(gitops_dispatcher, "yaml", None)
ok, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir)
assert ok is False
assert err is not None and "pyyaml" in err.lower()
def test_capability_grants_device_mknod_rejected(tmp_path: Path):
"""Ensure :rwm (mknod) is rejected even when the device node exists and is granted."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
dev_dir = tmp_path / "dev" / "dri"
dev_dir.mkdir(parents=True)
render_node = dev_dir / "renderD128"
render_node.write_text("", encoding="utf-8")
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"devices": [str(render_node)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
devices:
- "{render_node}:/dev/dri/renderD128:rwm"
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
assert err is not None and "mknod" in err.lower()
def test_capability_grants_missing_device_node_rejected(tmp_path: Path):
"""Ensure a granted device path that does not exist on the host fails closed."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
missing_node = tmp_path / "dev" / "dri" / "renderD999"
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"devices": [str(missing_node)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
devices:
- "{missing_node}:/dev/dri/renderD999:rw"
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
assert err is not None and "does not exist" in err.lower()
def test_capability_grants_volumes_reject_rw_long_syntax(tmp_path: Path):
"""Ensure readOnlyPaths rejects long-syntax bind mounts without read_only: true."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
volumes:
- type: bind
source: "{media_dir}"
target: /media
read_only: false
""",
encoding="utf-8",
)
ok, _ = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
def test_capability_grants_volumes_reject_unsafe_propagation(tmp_path: Path):
"""Ensure readOnlyPaths rejects long-syntax bind mounts with unsafe propagation (rshared)."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
volumes:
- type: bind
source: "{media_dir}"
target: /media
read_only: true
bind:
propagation: rshared
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
assert err is not None and "propagation" in err.lower()
def test_capability_grants_volumes_reject_symlink_escape(tmp_path: Path):
"""Ensure readOnlyPaths rejects symlinks resolving outside the granted directory."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
outside_dir = tmp_path / "etc"
outside_dir.mkdir(parents=True)
escaped_link = media_dir / "escape"
escaped_link.symlink_to(outside_dir)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
volumes:
- "{escaped_link}:/media:ro"
""",
encoding="utf-8",
)
ok, _ = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
def test_capability_grants_app_name_none_receives_zero_grants(tmp_path: Path):
"""Ensure app_name=None receives zero grants even when grants.json defines workloads."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
volumes:
- "{media_dir}:/media:ro"
""",
encoding="utf-8",
)
ok, _ = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name=None, grants_file=grants_file
)
assert ok is False
def test_capability_grants_malformed_grants_fail_closed(tmp_path: Path):
"""Ensure malformed grants.json fails closed even on a plain compose file."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
plain_compose = app_dir / "plain.yml"
plain_compose.write_text("services:\n app:\n image: alpine\n", encoding="utf-8")
bad_grants = tmp_path / "bad_grants.json"
bad_grants.write_text("{corrupt", encoding="utf-8")
ok, err = gitops_dispatcher.validate_compose_security(
plain_compose, app_dir, app_name="media", grants_file=bad_grants
)
assert ok is False
assert err is not None and "grants" in err.lower()
def test_validate_compose_security_allows_ungranted_gid_1000(tmp_path: Path):
"""Ensure unprivileged numeric GID >= 1000 (1000:1000) is allowed without a grant."""
app_dir = tmp_path / "Workloads" / "ungranted"
app_dir.mkdir(parents=True)
grants_file = _write_grants(tmp_path / "grants.json", {})
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
"services:\n app:\n image: alpine\n user: '1000:1000'\n",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="ungranted",
grants_file=grants_file,
group_lookup=_fake_group_lookup,
)
assert ok is True
assert err is None
def test_validate_compose_security_rejects_high_numeric_gid_for_privileged_group(
tmp_path: Path,
):
"""Ensure numeric GID >= 1000 that resolves to a privileged group (docker) fails closed."""
app_dir = tmp_path / "Workloads" / "ungranted"
app_dir.mkdir(parents=True)
grants_file = _write_grants(tmp_path / "grants.json", {})
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
"services:\n app:\n image: alpine\n user: '1000:1998'\n",
encoding="utf-8",
)
def lookup_with_high_docker(key: str | int) -> tuple[str, int]:
if key in (1998, "1998"):
return ("docker", 1998)
return _fake_group_lookup(key)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file,
app_dir,
app_name="ungranted",
grants_file=grants_file,
group_lookup=lookup_with_high_docker,
)
assert ok is False
assert err is not None and "docker" in err.lower()
def test_validate_compose_security_rejects_sibling_prefix_paths(tmp_path: Path):
"""Ensure sibling directory prefixes (/dev/dri2, /mnt/media2) cannot bypass containment."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
granted_dev = tmp_path / "dev" / "dri"
granted_dev.mkdir(parents=True)
sibling_dev_dir = tmp_path / "dev" / "dri2"
sibling_dev_dir.mkdir(parents=True)
sibling_node = sibling_dev_dir / "renderD128"
sibling_node.write_text("", encoding="utf-8")
granted_media = tmp_path / "mnt" / "media"
granted_media.mkdir(parents=True)
sibling_media = tmp_path / "mnt" / "media2"
sibling_media.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{
"media": {
"devices": [str(granted_dev)],
"readOnlyPaths": [str(granted_media)],
}
},
)
dev_compose = app_dir / "dev-compose.yml"
dev_compose.write_text(
f"services:\n app:\n image: alpine\n devices:\n - '{sibling_node}:/dev/dri/renderD128:rw'\n",
encoding="utf-8",
)
ok_dev, _ = gitops_dispatcher.validate_compose_security(
dev_compose, app_dir, app_name="media", grants_file=grants_file
)
assert ok_dev is False
vol_compose = app_dir / "vol-compose.yml"
vol_compose.write_text(
f"services:\n app:\n image: alpine\n volumes:\n - '{sibling_media}:/media:ro'\n",
encoding="utf-8",
)
ok_vol, _ = gitops_dispatcher.validate_compose_security(
vol_compose, app_dir, app_name="media", grants_file=grants_file
)
assert ok_vol is False
+383 -30
View File
@@ -2,13 +2,18 @@
Security invariant tests for Docker Compose and container isolation.
"""
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path
import yaml
from appctl_audit import AuditLogger, TargetLockManager
from appctl_auth import Principal, Role
from appctl_contracts import OperationRequest
from appctl_router import OperationalRouter, assemble_workload_env
from core_manifest import parse_manifest
# Comment-out reason: testing pyproject-level pythonpath definition
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
@@ -101,10 +106,9 @@ def test_no_eval_in_appctl_script():
assert "eval " not in content, "Dangerous 'eval' detected in scripts/appctl!"
def test_appctl_env_injection_resilience(tmp_path: Path):
def test_appctl_env_injection_resilience(tmp_path: Path, monkeypatch):
"""Ensure environment values from app.yaml cannot execute shell commands via command substitution
in scripts/appctl during environment setup. Executes scripts/appctl directly with a mock docker binary.
during P4 production environment assembly and router dispatch. Executes OperationalRouter with a mock docker binary.
"""
canary = tmp_path / "pwned.txt"
payload = f"$(touch {canary})"
@@ -127,14 +131,22 @@ env:
"services:\n web:\n image: nginx\n", encoding="utf-8"
)
# 2. Setup mock docker binary to capture environment without requiring a running Docker daemon
# 2. Verify unit-level pure Python environment assembly
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
manifest = parse_manifest(app_dir / "app.yaml")
assembled_env = assemble_workload_env(app_dir, manifest, "vuln-app")
assert not canary.exists(), "Command substitution executed during assemble_workload_env!"
assert assembled_env["INJECTION_TEST"] == payload
assert assembled_env["NORMAL_VAR"] == "safe_value"
# 3. Setup mock docker binary to capture environment without requiring a running Docker daemon
mock_bin = tmp_path / "bin"
mock_bin.mkdir()
mock_docker = mock_bin / "docker"
bash_bin = shutil.which("bash") or "bash"
mock_docker_script = f"""#!{bash_bin}
if [ "$1" = "compose" ] && [ "$2" = "config" ]; then
if [ "$1" = "compose" ] && [ "$4" = "config" ]; then
echo "MOCK_DOCKER_COMPOSE_CONFIG"
echo "CAPTURED_INJECTION=$INJECTION_TEST"
echo "CAPTURED_NORMAL=$NORMAL_VAR"
@@ -145,36 +157,39 @@ exit 0
mock_docker.write_text(mock_docker_script, encoding="utf-8")
mock_docker.chmod(0o755)
# 3. Execute scripts/appctl config vuln-app directly
appctl_path = CORE_ROOT / "scripts" / "appctl"
env = os.environ.copy()
if "NIX_PYTHONPATH" in env and "PYTHONPATH" not in env:
env["PYTHONPATH"] = env["NIX_PYTHONPATH"]
env["PATH"] = f"{mock_bin}:{Path(sys.executable).parent}:{env['PATH']}"
env["PYTHON_BIN"] = sys.executable
env["SITES_DIR"] = str(sites_dir)
env["HOMELAB_DOMAIN"] = "example.test"
env["CORE_DIR"] = str(CORE_ROOT)
res = subprocess.run(
[bash_bin, str(appctl_path), "config", "vuln-app"],
env=env,
capture_output=True,
text=True,
check=False,
# 4. Dispatch workload.config through OperationalRouter
monkeypatch.setenv("PATH", f"{mock_bin}:{os.environ.get('PATH', '')}")
router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=sites_dir,
core_dir=CORE_ROOT,
)
req = OperationRequest.model_validate({
"operation": "workload.config",
"target": "vuln-app",
})
admin_principal = Principal(
identity="operator",
role=Role.ADMIN,
token_id="tok_admin",
auth_method="bearer_token",
)
# 4. Assertions: command substitution was not executed, script ran, and mock docker received literal value
resp = router.dispatch(req, admin_principal)
# 5. Assertions: command substitution was not executed, router succeeded, mock docker received literal value
assert not canary.exists(), (
"Command substitution was executed on the host during environment setup!"
)
assert res.returncode == 0, (
f"appctl config failed: {res.stderr}\nStdout: {res.stdout}"
assert resp.success is True, (
f"OperationalRouter dispatch failed: {resp.error}"
)
assert "MOCK_DOCKER_COMPOSE_CONFIG" in res.stdout
assert f"CAPTURED_INJECTION={payload}" in res.stdout
assert "CAPTURED_NORMAL=safe_value" in res.stdout
assert "/dangerous/override" not in res.stdout
assert resp.result is not None
output = resp.result.get("output", "")
assert "MOCK_DOCKER_COMPOSE_CONFIG" in output
assert f"CAPTURED_INJECTION={payload}" in output
assert "CAPTURED_NORMAL=safe_value" in output
def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests():
@@ -194,6 +209,8 @@ def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests(
CORE_ROOT / "SECURITY.md",
CORE_ROOT / "flake.nix",
CORE_ROOT / "docker-compose.yml",
CORE_ROOT / "nixos" / "configuration.nix",
CORE_ROOT / "nixos" / "instance.example.nix",
]
violations = []
@@ -218,3 +235,339 @@ def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests(
assert not violations, "Platform genericism violations detected:\n" + "\n".join(
violations
)
def test_docker_compose_authelia_and_lldap_base_dn():
"""Ensure both lldap and authelia services receive LLDAP_LDAP_BASE_DN in docker-compose.yml."""
compose_path = CORE_ROOT / "docker-compose.yml"
with open(compose_path, encoding="utf-8") as f:
compose = yaml.safe_load(f)
services = compose.get("services", {})
assert "lldap" in services, "lldap service must exist in docker-compose.yml"
assert "authelia" in services, "authelia service must exist in docker-compose.yml"
def get_env_map(svc_def: dict) -> dict[str, str]:
env_items = svc_def.get("environment", [])
res = {}
for item in env_items:
if isinstance(item, str) and "=" in item:
k, v = item.split("=", 1)
res[k.strip()] = v.strip()
return res
lldap_env = get_env_map(services["lldap"])
authelia_env = get_env_map(services["authelia"])
assert "LLDAP_LDAP_BASE_DN" in lldap_env, (
"LLDAP_LDAP_BASE_DN must be declared in lldap environment"
)
assert "LLDAP_LDAP_BASE_DN" in authelia_env, (
"LLDAP_LDAP_BASE_DN must be passed to authelia environment for LDAP template expansion"
)
def test_nixos_homeserver_env_template_defines_dynamic_base_dn():
"""Ensure homeserver.nix derives LLDAP_LDAP_BASE_DN dynamically from homelab.domain."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert "LLDAP_LDAP_BASE_DN" in content, (
"homeserver.nix must define LLDAP_LDAP_BASE_DN in homeserver.env template"
)
assert 'lib.splitString "."' in content or "splitString" in content, (
"homeserver.nix must compute LDAP base DN dynamically from domain components"
)
def test_nixos_tmpfiles_rules_use_recursive_acls():
"""Ensure tmpfiles.rules uses uppercase A+ for recursive ACL inheritance on sites and homepage."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert '"A+ ${config.homelab.sitesDir}' in content, (
"tmpfiles.rules must use uppercase 'A+' for recursive ACL inheritance on sitesDir"
)
assert '"A+ ${config.homelab.coreDir}/config/homepage' in content, (
"tmpfiles.rules must use uppercase 'A+' for recursive ACL inheritance on homepage config"
)
def test_nixos_tmpfiles_rules_creates_operator_var_lib_homelab():
"""Ensure tmpfiles.rules creates operator var/lib/homelab state dir before ACL assignment (#22)."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
expected_create = '"d /home/${config.homelab.operatorUser}/var/lib/homelab 0755 ${config.homelab.operatorUser} users -"'
expected_acl = '"A+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"'
assert expected_create in content, (
"tmpfiles.rules must declare creation of operator var/lib/homelab directory"
)
assert expected_acl in content, (
"tmpfiles.rules must declare ACLs for operator var/lib/homelab directory"
)
assert content.index(expected_create) < content.index(expected_acl), (
"operator var/lib/homelab directory creation must precede its ACL rule"
)
def test_nixos_appctl_readwritepaths_optional_prefixes():
"""Ensure appctl service ReadWritePaths uses '-' prefix for optional runtime paths (#22)."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert '"-/home/${config.homelab.operatorUser}/var/lib/homelab"' in content
assert '"-${config.homelab.coreDir}/config/homepage"' in content
assert '"-/var/lib/homelab/appctl"' in content
assert '"-/run/homelab"' in content
def test_nixos_gitops_orders_after_appctl():
"""Ensure homelab-gitops service declares after and wants dependency on homelab-appctl.service (#22)."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert '"homelab-appctl.service"' in content
nix_bin = shutil.which("nix")
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
for attr in ["after", "wants"]:
cmd = [
nix_bin,
"eval",
f".#nixosConfigurations.server.config.systemd.services.homelab-gitops.{attr}",
"--json",
]
res = subprocess.run(
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
)
data = json.loads(res.stdout)
assert "homelab-appctl.service" in data, (
f"homelab-gitops {attr} must include homelab-appctl.service"
)
def test_default_homelab_domain_evaluates_to_example_test():
"""Assert default homelab.domain in NixOS config evaluates to 'example.test'."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert 'default = "example.test";' in content, (
"homeserver.nix must set default homelab.domain to 'example.test'"
)
nix_bin = shutil.which("nix")
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
cmd = [
nix_bin,
"eval",
".#nixosConfigurations.server.config.homelab.domain",
"--raw",
]
res = subprocess.run(
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
)
assert res.stdout.strip() == "example.test", (
f"Default homelab.domain must be 'example.test', got '{res.stdout.strip()}'"
)
def test_dynamic_lldap_base_dn_splits_domain_components():
"""Assert dynamic LLDAP_LDAP_BASE_DN splits domain into dc=... components for any domain."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert "LLDAP_LDAP_BASE_DN = ldapBaseDn;" in content, (
"homeserver.nix must bind LLDAP_LDAP_BASE_DN to ldapBaseDn in homeserver.env template"
)
assert 'domainParts = lib.splitString "." config.homelab.domain;' in content, (
"homeserver.nix must split homelab.domain by '.'"
)
assert 'ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts);' in content, (
"homeserver.nix must map domain components into dc=${part}"
)
nix_bin = shutil.which("nix")
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
cases = [
("example.test", "dc=example,dc=test"),
("my.homelab.internal", "dc=my,dc=homelab,dc=internal"),
("local", "dc=local"),
]
for domain, expected_dn in cases:
expr = (
f'let flake = builtins.getFlake (toString ./.); lib = flake.inputs.nixpkgs.lib; '
f'domainParts = lib.splitString "." "{domain}"; '
f'in lib.concatStringsSep "," (map (part: "dc=${{part}}") domainParts)'
)
cmd = [
nix_bin,
"eval",
"--impure",
"--expr",
expr,
"--raw",
]
res = subprocess.run(
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
)
assert res.stdout.strip() == expected_dn, (
f"Expected {expected_dn} for domain {domain}, got {res.stdout.strip()}"
)
# Also assert rendered sops template in default configuration contains correct LLDAP_LDAP_BASE_DN
cmd_tpl = [
nix_bin,
"eval",
'.#nixosConfigurations.server.config.sops.templates."homeserver.env".content',
"--raw",
]
res_tpl = subprocess.run(
cmd_tpl, cwd=CORE_ROOT, capture_output=True, text=True, check=True
)
assert "LLDAP_LDAP_BASE_DN=dc=example,dc=test" in res_tpl.stdout
def test_dual_path_import_overrides_homelab_domain():
"""Assert dual-path import overrides homelab.domain when ./nixos/instance.nix is present."""
nix_bin = shutil.which("nix")
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
instance_nix = CORE_ROOT / "nixos" / "instance.nix"
try:
instance_nix.write_text(
'{ homelab.domain = "custom.internal"; }\n', encoding="utf-8"
)
cmd = [
nix_bin,
"eval",
"--impure",
"path:.#nixosConfigurations.server.config.homelab.domain",
"--raw",
]
res = subprocess.run(
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
)
assert res.stdout.strip() == "custom.internal", (
f"Expected homelab.domain to be overridden to 'custom.internal', got '{res.stdout.strip()}'"
)
finally:
if instance_nix.exists():
instance_nix.unlink()
def test_nixos_configuration_declares_dual_path_instance_imports():
"""Ensure nixos/configuration.nix includes optional dual-path instance imports."""
config_nix = CORE_ROOT / "nixos" / "configuration.nix"
content = config_nix.read_text(encoding="utf-8")
assert "builtins.pathExists ./instance.nix" in content, (
"nixos/configuration.nix must check for ./instance.nix via builtins.pathExists"
)
assert "builtins.pathExists /etc/nixos/homelab-instance.nix" in content, (
"nixos/configuration.nix must check for /etc/nixos/homelab-instance.nix via builtins.pathExists"
)
def test_gitignore_includes_instance_nix():
"""Ensure nixos/instance.nix is ignored in .gitignore to preserve platform genericism."""
gitignore = CORE_ROOT / ".gitignore"
content = gitignore.read_text(encoding="utf-8")
lines = [line.strip() for line in content.splitlines()]
assert "nixos/instance.nix" in lines, (
"nixos/instance.nix must be explicitly ignored in .gitignore"
)
def test_nixos_switch_alias_uses_path_and_impure():
"""Ensure nix-switch alias in nixos/modules/shell.nix uses path: and --impure to prevent silent fail-open."""
shell_nix = CORE_ROOT / "nixos" / "modules" / "shell.nix"
content = shell_nix.read_text(encoding="utf-8")
assert 'nix-switch = "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure";' in content, (
"nixos/modules/shell.nix must configure nix-switch alias with path:$HOME/Core#server --impure"
)
def test_nixos_safe_directory_includes_core_and_sites():
"""Ensure programs.git.config.safe.directory includes Core, Workloads, and Sites to prevent dubious ownership errors."""
config_nix = CORE_ROOT / "nixos" / "configuration.nix"
content = config_nix.read_text(encoding="utf-8")
assert '"/home/${config.homelab.operatorUser}/Core"' in content, (
"nixos/configuration.nix must include Core in git safe.directory"
)
assert '"/home/${config.homelab.operatorUser}/Workloads"' in content, (
"nixos/configuration.nix must include Workloads in git safe.directory"
)
assert '"/home/${config.homelab.operatorUser}/Workloads/*"' in content, (
"nixos/configuration.nix must include Workloads/* in git safe.directory"
)
assert '"/home/${config.homelab.operatorUser}/Sites/*"' in content, (
"nixos/configuration.nix must include Sites/* in git safe.directory"
)
nix_bin = shutil.which("nix")
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
cmd = [
nix_bin,
"eval",
".#nixosConfigurations.server.config.programs.git.config",
"--json",
]
res = subprocess.run(
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
)
import json
configs = json.loads(res.stdout)
safe_dirs = []
for cfg in configs:
if isinstance(cfg, dict) and "safe" in cfg and "directory" in cfg["safe"]:
dirs = cfg["safe"]["directory"]
if isinstance(dirs, list):
safe_dirs.extend(dirs)
else:
safe_dirs.append(dirs)
assert "/home/operator/Core" in safe_dirs, (
f"Expected '/home/operator/Core' in git safe.directory, got {safe_dirs}"
)
assert "/home/operator/Workloads" in safe_dirs, (
f"Expected '/home/operator/Workloads' in git safe.directory, got {safe_dirs}"
)
assert "/home/operator/Workloads/*" in safe_dirs, (
f"Expected '/home/operator/Workloads/*' in git safe.directory, got {safe_dirs}"
)
assert "/home/operator/Sites/*" in safe_dirs, (
f"Expected '/home/operator/Sites/*' in git safe.directory, got {safe_dirs}"
)
def test_nixos_homeserver_defaults_to_workloads_dir():
"""Ensure homeserver.nix defaults sitesDir to ~/Workloads and exports WORKLOADS_DIR + SITES_DIR (#33)."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert 'default = "/home/${config.homelab.operatorUser}/Workloads";' in content, (
"homelab.sitesDir must default to /home/${config.homelab.operatorUser}/Workloads"
)
assert "WORKLOADS_DIR = config.homelab.sitesDir;" in content, (
"homeserver.nix must export WORKLOADS_DIR"
)
assert "SITES_DIR = config.homelab.sitesDir;" in content, (
"homeserver.nix must export SITES_DIR for backward compatibility"
)
def test_nixos_workload_grants_option_and_projection():
"""Ensure homeserver.nix defines homelab.workloadGrants, /etc/homelab/grants.json, and HOMELAB_GRANTS_FILE."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert "workloadGrants = lib.mkOption" in content
assert 'environment.etc."homelab/grants.json"' in content
assert 'user = "root";' in content
assert 'group = "homelab-operators";' in content
assert 'mode = "0640";' in content
assert content.count('HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";') >= 2
assert "PrivateUsers" not in content
@@ -20,6 +20,7 @@ def test_required_architectural_paths_exist():
"SECURITY.md",
"nixos",
"nixos/configuration.nix",
"nixos/instance.example.nix",
"nixos/modules/homeserver.nix",
"nixos/secrets.yaml",
"scripts/gitops_dispatcher.py",
+30 -14
View File
@@ -8,7 +8,6 @@ test_<subject>_<accepts|rejects|enforces>_<condition>
from __future__ import annotations
import json
import os
import stat
from pathlib import Path
@@ -232,6 +231,31 @@ def test_redact_sensitive_data_masks_secret_keys():
assert redacted["nested"]["list_items"][1] == "safe_string"
def test_redact_sensitive_data_masks_bare_keys():
"""Ensure bare keys (token, secret, password, key, pass, hash) without underscores are redacted (CR-DI-04)."""
raw_params = {
"token": "tok_12345",
"secret": "shh_secret",
"password": "mypassword",
"key": "encryption_key",
"pass": "quick_pass",
"hash": "$2b$12$hashval",
"TOKEN": "uppercase_tok",
"SECRET": "uppercase_sec",
"normal_field": "keep_this",
}
redacted = redact_sensitive_data(raw_params)
assert redacted["token"] == "[REDACTED]"
assert redacted["secret"] == "[REDACTED]"
assert redacted["password"] == "[REDACTED]"
assert redacted["key"] == "[REDACTED]"
assert redacted["pass"] == "[REDACTED]"
assert redacted["hash"] == "[REDACTED]"
assert redacted["TOKEN"] == "[REDACTED]"
assert redacted["SECRET"] == "[REDACTED]"
assert redacted["normal_field"] == "keep_this"
def test_audit_logger_automatically_redacts_sensitive_parameters(
temp_audit_file: Path, sample_principal: PrincipalAudit
):
@@ -260,17 +284,12 @@ def test_audit_logger_automatically_redacts_sensitive_parameters(
def test_audit_logger_fails_closed_when_audit_log_unwritable(
tmp_path: Path, sample_principal: PrincipalAudit
):
read_only_dir = tmp_path / "readonly_audit"
read_only_dir.mkdir(parents=True, exist_ok=True)
unwritable_file = read_only_dir / "audit.jsonl"
unwritable_file.touch(mode=0o400)
os.chmod(unwritable_file, 0o400)
# Using a directory as the audit path causes os.open with O_WRONLY to fail with
# EISDIR / OSError across all platforms and environments (including root containers).
unwritable_target = tmp_path / "unwritable_audit_dir"
unwritable_target.mkdir(parents=True, exist_ok=True)
# In addition, make directory read-only
os.chmod(read_only_dir, 0o500)
try:
logger = AuditLogger(unwritable_file)
logger = AuditLogger(unwritable_target)
with pytest.raises(AuditPersistenceError) as exc_info:
logger.log_dispatched(
operation_id="op_105",
@@ -283,9 +302,6 @@ def test_audit_logger_fails_closed_when_audit_log_unwritable(
parameters={"recreate": True},
)
assert "Failed to persist audit event" in str(exc_info.value)
finally:
os.chmod(read_only_dir, 0o700)
os.chmod(unwritable_file, 0o600)
# ---------------------------------------------------------------------------
+187 -34
View File
@@ -37,8 +37,12 @@ def secret_tokens() -> dict[str, str]:
@pytest.fixture
def temp_tokens_file(tmp_path: Path, secret_tokens: dict[str, str]) -> Path:
tokens_path = tmp_path / "tokens.json"
admin_hash = hashlib.sha256(secret_tokens["admin_secret"].encode("utf-8")).hexdigest()
op_hash = hashlib.sha256(secret_tokens["operator_secret"].encode("utf-8")).hexdigest()
admin_hash = hashlib.sha256(
secret_tokens["admin_secret"].encode("utf-8")
).hexdigest()
op_hash = hashlib.sha256(
secret_tokens["operator_secret"].encode("utf-8")
).hexdigest()
data = [
{
@@ -121,6 +125,31 @@ def test_token_store_authenticates_valid_bearer_secrets(
assert p_op.token_id == "tok_gitops_01"
def test_token_store_authenticates_uppercase_hex_descriptor(tmp_path: Path):
"""Ensure tokens with uppercase hex characters in tokens.json authenticate cleanly (CR-DI-10)."""
raw_secret = "my_custom_secret_token"
raw_hash_upper = hashlib.sha256(raw_secret.encode("utf-8")).hexdigest().upper()
tokens_file = tmp_path / "upper_tokens.json"
tokens_file.write_text(
json.dumps(
[
{
"token_id": "tok_upper_01",
"identity": "upper-user",
"role": "homelab-operator",
"sha256": raw_hash_upper,
}
]
),
encoding="utf-8",
)
os.chmod(tokens_file, 0o400)
store = TokenStore(tokens_file)
principal = store.authenticate_bearer(raw_secret)
assert principal.identity == "upper-user"
assert principal.role == Role.OPERATOR
def test_token_store_rejects_invalid_bearer_secret(temp_tokens_file: Path):
store = TokenStore(temp_tokens_file)
@@ -178,7 +207,9 @@ def test_authenticate_request_over_uds_falls_back_to_viewer(
# Explicit Bearer token over UDS confers full privileges
auth_header = f"Bearer {secret_tokens['admin_secret']}"
p_admin = authenticate_request("unix_socket", auth_header, peer_uid=1000, token_store=store)
p_admin = authenticate_request(
"unix_socket", auth_header, peer_uid=1000, token_store=store
)
assert p_admin.role == Role.ADMIN
assert p_admin.auth_method == "bearer_token"
@@ -196,7 +227,8 @@ def test_authenticate_request_over_uds_rejects_missing_peer_uid():
def test_load_admitted_workloads_parses_names_and_aliases(tmp_path: Path):
deploy_file = tmp_path / "deployments.yaml"
deploy_file.write_text("""
deploy_file.write_text(
"""
schemaVersion: "1.0"
repositories:
snappymail:
@@ -208,7 +240,9 @@ repositories:
path: "/home/operator/Sites/homelab-jellyfin"
aliases:
- "media"
""", encoding="utf-8")
""",
encoding="utf-8",
)
admitted = load_admitted_workloads(deploy_file)
assert "snappymail" in admitted
@@ -221,14 +255,19 @@ repositories:
def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: Path):
deploy_file = tmp_path / "deployments.json"
deploy_file.write_text(json.dumps({
deploy_file.write_text(
json.dumps(
{
"repositories": {
"app1": {
"path": "/home/operator/Sites/app1",
"aliases": [123, None, " ", "valid_alias"]
"aliases": [123, None, " ", "valid_alias"],
}
}
}), encoding="utf-8")
}
),
encoding="utf-8",
)
admitted = load_admitted_workloads(deploy_file)
assert "app1" in admitted
@@ -238,13 +277,17 @@ def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: P
assert "" not in admitted
def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
def test_load_admitted_workloads_fails_closed_on_missing_file(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
admitted = load_admitted_workloads(tmp_path / "missing.yaml")
assert admitted == set()
# Test HOMELAB_DEPLOYMENTS_FILE fallback
deploy_file = tmp_path / "env_deploy.yaml"
deploy_file.write_text("repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8")
deploy_file.write_text(
"repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8"
)
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deploy_file))
admitted_env = load_admitted_workloads(None)
assert "env_app" in admitted_env
@@ -258,12 +301,16 @@ def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path, mo
def test_rbac_admin_permitted_across_all_operations_and_targets(
admitted_workloads: set[str],
):
admin = Principal(identity="admin_user", role=Role.ADMIN, auth_method="bearer_token")
admin = Principal(
identity="admin_user", role=Role.ADMIN, auth_method="bearer_token"
)
# Mutations across Core and Sites
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads)
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "traefik", admitted_workloads)
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads)
enforce_rbac(
admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads
)
enforce_rbac(admin, OperationType.WORKLOAD_CONFIG, "core", admitted_workloads)
enforce_rbac(admin, OperationType.WORKLOAD_LOGS, "traefik", admitted_workloads)
enforce_rbac(admin, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads)
@@ -273,79 +320,139 @@ def test_rbac_admin_permitted_across_all_operations_and_targets(
def test_rbac_operator_permitted_on_admitted_workloads(
admitted_workloads: set[str],
):
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
operator = Principal(
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
# Permitted on admitted workload
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads)
enforce_rbac(
operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads
)
enforce_rbac(operator, OperationType.WORKLOAD_UPDATE, "mail", admitted_workloads)
enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads)
enforce_rbac(
operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads
)
enforce_rbac(operator, OperationType.WORKLOAD_LOGS, "docs", admitted_workloads)
enforce_rbac(operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads)
enforce_rbac(
operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads
)
enforce_rbac(operator, OperationType.WORKLOAD_LIST, None, admitted_workloads)
def test_rbac_operator_denied_on_core_targets(
admitted_workloads: set[str],
):
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
operator = Principal(
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
# Targeting "core" stack
with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads)
enforce_rbac(
operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads
)
assert "not permitted to target core service 'core'" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
# Targeting core services (traefik, stalwart, etc.)
for core_svc in ["traefik", "authelia", "stalwart", "socket-proxy"]:
with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads)
assert f"not permitted to target core service '{core_svc}'" in str(exc_info.value)
enforce_rbac(
operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads
)
assert f"not permitted to target core service '{core_svc}'" in str(
exc_info.value
)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_operator_denied_on_case_variant_core_targets(admitted_workloads: set[str]):
"""Ensure case variants ('Core', 'TRAEFIK', 'Authelia') are rejected for operator role (CR-DI-06)."""
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
for variant in ["Core", "CORE", "Traefik", "TRAEFIK", "Authelia"]:
with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, variant, admitted_workloads)
assert "not permitted to target core service" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_operator_denied_without_target_on_mutating_or_sensitive_ops(
admitted_workloads: set[str],
):
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
operator = Principal(
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
for op in [OperationType.WORKLOAD_DEPLOY, OperationType.WORKLOAD_UPDATE, OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]:
for op in [
OperationType.WORKLOAD_DEPLOY,
OperationType.WORKLOAD_UPDATE,
OperationType.WORKLOAD_CONFIG,
OperationType.WORKLOAD_LOGS,
]:
with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, op, None, admitted_workloads)
assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value)
assert f"Operation '{op.value}' requires an explicit workload target" in str(
exc_info.value
)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, op, "", admitted_workloads)
assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value)
assert f"Operation '{op.value}' requires an explicit workload target" in str(
exc_info.value
)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_operator_with_default_admitted_workloads(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
def test_rbac_operator_with_default_admitted_workloads(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
):
deployments_file = tmp_path / "deployments.yaml"
deployments_file.write_text("repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8")
deployments_file.write_text(
"repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8"
)
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file))
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "customapp", admitted_workloads=None)
operator = Principal(
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
enforce_rbac(
operator, OperationType.WORKLOAD_DEPLOY, "customapp", admitted_workloads=None
)
with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unknownapp", admitted_workloads=None)
enforce_rbac(
operator,
OperationType.WORKLOAD_DEPLOY,
"unknownapp",
admitted_workloads=None,
)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_operator_denied_on_unregistered_workload(
admitted_workloads: set[str],
):
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
operator = Principal(
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unregistered_app", admitted_workloads)
enforce_rbac(
operator,
OperationType.WORKLOAD_DEPLOY,
"unregistered_app",
admitted_workloads,
)
assert "not registered in deployments.yaml" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_viewer_permitted_only_on_non_sensitive_reads():
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
viewer = Principal(
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
)
# Permitted reads
enforce_rbac(viewer, OperationType.WORKLOAD_LIST, None)
@@ -356,7 +463,9 @@ def test_rbac_viewer_permitted_only_on_non_sensitive_reads():
def test_rbac_viewer_denied_on_mutations():
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
viewer = Principal(
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
)
mutations = [
OperationType.WORKLOAD_DEPLOY,
@@ -374,10 +483,54 @@ def test_rbac_viewer_denied_on_mutations():
def test_rbac_viewer_denied_on_sensitive_reads():
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
viewer = Principal(
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
)
for sens_op in [OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]:
with pytest.raises(AuthorizationError) as exc_info:
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, run_isolated_script_expr
):
"""DEFAULT_DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml."""
resolved = run_isolated_script_expr(
"import appctl_auth; print(appctl_auth.DEFAULT_DEPLOYMENTS_FILE)"
)
assert Path(resolved) == tmp_path / "Workloads" / "deployments.yaml"
def test_load_admitted_workloads_fails_closed_when_absent(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
"""Absent ~/Workloads/deployments.yaml fails closed (empty set, no CORE_DIR fallback)."""
import appctl_auth
monkeypatch.delenv("HOMELAB_DEPLOYMENTS_FILE", raising=False)
monkeypatch.delenv("WORKLOADS_DIR", raising=False)
monkeypatch.delenv("SITES_DIR", raising=False)
monkeypatch.setattr(
appctl_auth, "DEFAULT_DEPLOYMENTS_FILE", tmp_path / "Workloads" / "deployments.yaml"
)
assert appctl_auth.load_admitted_workloads() == set()
def test_load_admitted_workloads_honors_workloads_dir_override(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
"""WORKLOADS_DIR takes precedence when HOMELAB_DEPLOYMENTS_FILE is unset."""
import appctl_auth
custom_workloads = tmp_path / "CustomWorkloads"
custom_workloads.mkdir()
(custom_workloads / "deployments.yaml").write_text(
"repositories:\n custom_app:\n path: ~/Workloads/custom_app\n",
encoding="utf-8",
)
monkeypatch.delenv("HOMELAB_DEPLOYMENTS_FILE", raising=False)
monkeypatch.setenv("WORKLOADS_DIR", str(custom_workloads))
assert appctl_auth.load_admitted_workloads() == {"custom_app"}
+244 -10
View File
@@ -107,6 +107,81 @@ def test_cli_dispatches_mutation_command():
assert "Workload deployed" in mock_stdout.getvalue()
def test_cli_up_and_deploy_build_and_no_cache_flags():
"""Ensure appctl up/deploy with --build and --no-cache flags dispatches correct parameters."""
mock_resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_build_01",
operation=OperationType.WORKLOAD_DEPLOY,
target="jellyfin",
result={"action": "deployed", "message": "Workload deployed"},
)
# 1. up with --build
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
ret = run_cli(["up", "jellyfin", "--build", "--token", "tok_secret"])
assert ret == 0
req: OperationRequest = mock_send.call_args[1]["operation_request"]
assert req.operation == OperationType.WORKLOAD_DEPLOY
assert req.parameters.get("build") is True
assert req.parameters.get("no_cache") is False
# 2. up with --no-cache implies build=True
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
ret = run_cli(["up", "jellyfin", "--no-cache", "--token", "tok_secret"])
assert ret == 0
req = mock_send.call_args[1]["operation_request"]
assert req.parameters.get("no_cache") is True
assert req.parameters.get("build") is True
# 3. deploy alias with --no-cache
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
ret = run_cli(["deploy", "jellyfin", "--no-cache", "--token", "tok_secret"])
assert ret == 0
req = mock_send.call_args[1]["operation_request"]
assert req.parameters.get("no_cache") is True
assert req.parameters.get("build") is True
def test_cli_update_build_and_no_cache_flags():
"""Ensure appctl update with --build and --no-cache flags dispatches correct parameters."""
mock_resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_upd_01",
operation=OperationType.WORKLOAD_UPDATE,
target="jellyfin",
result={"action": "updated", "message": "Workload updated"},
)
# 1. update with --build
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
ret = run_cli(["update", "jellyfin", "--build", "--token", "tok_secret"])
assert ret == 0
req: OperationRequest = mock_send.call_args[1]["operation_request"]
assert req.operation == OperationType.WORKLOAD_UPDATE
assert req.parameters.get("build") is True
assert req.parameters.get("no_cache", False) is False
# 2. update with --no-cache implies build=True
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
ret = run_cli(["update", "jellyfin", "--no-cache", "--token", "tok_secret"])
assert ret == 0
req = mock_send.call_args[1]["operation_request"]
assert req.parameters.get("no_cache") is True
assert req.parameters.get("build") is True
# 3. update with --branch and --no-cache
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
ret = run_cli(["update", "jellyfin", "--branch", "main", "--no-cache", "--token", "tok_secret"])
assert ret == 0
req = mock_send.call_args[1]["operation_request"]
assert req.parameters.get("expected_branch") == "main"
assert req.parameters.get("no_cache") is True
assert req.parameters.get("build") is True
def test_cli_handles_missing_socket():
"""Ensure friendly stderr message when socket is absent."""
with patch("appctl_cli.send_daemon_request", side_effect=FileNotFoundError), patch("sys.stderr", new_callable=io.StringIO) as mock_stderr:
@@ -116,7 +191,7 @@ def test_cli_handles_missing_socket():
def test_cli_format_response_renders_workload_list_table():
"""Ensure workload.list renders a human-readable table instead of suppressing it behind result['message']."""
"""Ensure workload.list renders the canonical 5-column layout matching docs/appctl.md."""
resp = OperationResponse(
version="1.0",
success=True,
@@ -129,13 +204,17 @@ def test_cli_format_response_renders_workload_list_table():
"name": "snappymail",
"type": "app",
"domain": "mail.example.test",
"description": "Webmail client",
"deployment_status": "✓ Synced (main)",
"provenance_status": "✓ Synced",
"status": "🟢 Running (1)",
},
{
"name": "traefik",
"type": "core_service",
"domain": "traefik.example.test",
"description": "Edge Reverse Proxy",
"deployment_status": "",
"provenance_status": "— Core Platform",
"status": "🟢 Running (1)",
},
],
"message": "Found 2 workloads",
@@ -143,15 +222,89 @@ def test_cli_format_response_renders_workload_list_table():
output="",
)
rendered = format_response(resp, raw_json=False)
assert "SERVICE" in rendered
assert "DOMAIN" in rendered
assert "snappymail" in rendered
assert "mail.example.test" in rendered
assert "traefik" in rendered
assert "Edge Reverse Proxy" in rendered
lines = rendered.splitlines()
assert len(lines) >= 4
assert lines[0] == "SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN"
assert lines[1] == "------- ---------- ---------- ------ ------"
assert "snappymail" in lines[2]
assert "✓ Synced (main)" in lines[2]
assert "✓ Synced" in lines[2]
assert "🟢 Running (1)" in lines[2]
assert "mail.example.test" in lines[2]
assert "traefik" in lines[3]
assert "— Core Platform" in lines[3]
assert "🟢 Running (1)" in lines[3]
assert "traefik.example.test" in lines[3]
assert "✨ Found 2 workloads" not in rendered
def test_cli_format_response_renders_workload_list_table_with_ssl():
"""Ensure workload.list with SSL renders the canonical 6-column layout with CERT."""
resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_list_ssl_01",
operation=OperationType.WORKLOAD_LIST,
result={
"total": 1,
"workloads": [
{
"name": "snappymail",
"type": "app",
"domain": "mail.example.test",
"deployment_status": "✓ Synced (main)",
"provenance_status": "✓ Synced",
"status": "🟢 Running (1)",
"ssl": {"status": "🟢 80d remaining"},
},
],
"message": "Found 1 workloads",
},
output="",
)
rendered = format_response(resp, raw_json=False)
lines = rendered.splitlines()
assert len(lines) >= 3
assert lines[0] == "SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN CERT"
assert lines[1] == "------- ---------- ---------- ------ ------ ----"
assert "snappymail" in lines[2]
assert "🟢 80d remaining" in lines[2]
def test_cli_format_response_renders_workload_list_table_with_manifest_error():
"""Ensure workload.list renders ⚠️ Manifest Error and ⚠️ Invalid Manifest, and status=None renders as '-'."""
resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_list_err",
operation=OperationType.WORKLOAD_LIST,
result={
"total": 1,
"workloads": [
{
"name": "broken-app",
"type": "app",
"domain": "broken.example.test",
"manifest_error": "Syntax error in app.yaml",
"status": None,
},
],
"message": "Found 1 workloads",
},
output="",
)
rendered = format_response(resp, raw_json=False)
lines = rendered.splitlines()
assert len(lines) >= 3
assert "broken-app" in lines[2]
assert "⚠️ Manifest Error" in lines[2]
assert "⚠️ Invalid Manifest" in lines[2]
# Ensure status is '-' and NOT 'None'
assert " None " not in lines[2]
assert " - " in lines[2]
def test_cli_format_response_renders_workload_get_info():
"""Ensure workload.get (appctl info) renders structured workload metadata."""
resp = OperationResponse(
@@ -320,9 +473,11 @@ def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path,
import socket as std_socket
import subprocess
import sys
import tempfile
bash_bin = shutil.which("bash") or "bash"
sock_path = tmp_path / "appctl.sock"
sock_dir = tempfile.TemporaryDirectory(prefix="appctl_sock_", dir="/tmp")
sock_path = Path(sock_dir.name) / "appctl.sock"
srv = std_socket.socket(std_socket.AF_UNIX, std_socket.SOCK_STREAM)
srv.bind(str(sock_path))
try:
@@ -359,4 +514,83 @@ def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path,
assert "core" in res_words.stdout
finally:
srv.close()
sock_dir.cleanup()
def test_appctl_wrapper_fails_closed_when_socket_is_missing(tmp_path: Path):
"""Ensure scripts/appctl fails closed with exit code 1 and diagnostic stderr when socket is missing."""
import os
import shutil
import subprocess
import sys
bash_bin = shutil.which("bash") or "bash"
non_existent_sock = tmp_path / "missing_appctl.sock"
appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl"
env = {
"PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"),
"PYTHON_BIN": sys.executable,
"HOMELAB_DOMAIN": "example.test",
"APPCTL_SOCKET_PATH": str(non_existent_sock),
"SITES_DIR": str(tmp_path),
}
if "PYTHONPATH" in os.environ:
env["PYTHONPATH"] = os.environ["PYTHONPATH"]
res = subprocess.run(
[bash_bin, str(appctl_script), "status"],
env=env,
capture_output=True,
text=True,
check=False,
)
assert res.returncode == 1
assert "daemon socket not found" in res.stderr
def test_appctl_wrapper_fast_paths_completion_without_socket(tmp_path: Path):
"""Ensure scripts/appctl completes offline via appctl_engine.py even when socket is missing."""
import os
import shutil
import subprocess
import sys
bash_bin = shutil.which("bash") or "bash"
non_existent_sock = tmp_path / "missing_appctl.sock"
appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl"
env = {
"PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"),
"PYTHON_BIN": sys.executable,
"HOMELAB_DOMAIN": "example.test",
"APPCTL_SOCKET_PATH": str(non_existent_sock),
"SITES_DIR": str(tmp_path),
}
if "PYTHONPATH" in os.environ:
env["PYTHONPATH"] = os.environ["PYTHONPATH"]
res_comp = subprocess.run(
[bash_bin, str(appctl_script), "completion", "bash"],
env=env,
capture_output=True,
text=True,
check=False,
)
assert res_comp.returncode == 0
assert "_appctl_completions()" in res_comp.stdout
assert "up|deploy)" in res_comp.stdout
assert "--build --no-cache" in res_comp.stdout
res_words = subprocess.run(
[bash_bin, str(appctl_script), "complete", "services"],
env=env,
capture_output=True,
text=True,
check=False,
)
assert res_words.returncode == 0
assert "traefik" in res_words.stdout
assert "core" in res_words.stdout
+38 -7
View File
@@ -210,12 +210,24 @@ def test_deploy_params_defaults_and_explicit_bounds():
assert p_default.recreate is True
assert p_default.remove_orphans is True
assert p_default.build is False
assert p_default.no_cache is False
# Explicit
p_custom = DeployParams(recreate=False, remove_orphans=False, build=True)
p_custom = DeployParams(recreate=False, remove_orphans=False, build=True, no_cache=False)
assert p_custom.recreate is False
assert p_custom.remove_orphans is False
assert p_custom.build is True
assert p_custom.no_cache is False
# no_cache implies build=True
p_no_cache = DeployParams(no_cache=True)
assert p_no_cache.no_cache is True
assert p_no_cache.build is True
# no_cache overrides explicit build=False
p_override = DeployParams(build=False, no_cache=True)
assert p_override.no_cache is True
assert p_override.build is True
def test_deploy_params_rejects_non_strict_types():
@@ -226,6 +238,8 @@ def test_deploy_params_rejects_non_strict_types():
DeployParams(remove_orphans=bad_bool) # type: ignore[arg-type]
with pytest.raises(ValidationError):
DeployParams(build=bad_bool) # type: ignore[arg-type]
with pytest.raises(ValidationError):
DeployParams(no_cache=bad_bool) # type: ignore[arg-type]
def test_deploy_params_rejects_extra_fields():
@@ -238,23 +252,38 @@ def test_update_params_defaults_and_explicit():
p_default = UpdateParams()
assert p_default.expected_branch is None
assert p_default.build is False
assert p_default.no_cache is False
# Explicit
p_custom = UpdateParams(expected_branch="main", build=True)
p_custom = UpdateParams(expected_branch="main", build=True, no_cache=False)
assert p_custom.expected_branch == "main"
assert p_custom.build is True
assert p_custom.no_cache is False
# no_cache implies build=True
p_no_cache = UpdateParams(no_cache=True)
assert p_no_cache.no_cache is True
assert p_no_cache.build is True
# no_cache overrides explicit build=False
p_override = UpdateParams(build=False, no_cache=True)
assert p_override.no_cache is True
assert p_override.build is True
def test_update_params_rejects_empty_branch_and_non_strict_types():
for bad_bool in ["true", "false", 1, 0, None, [True]]:
with pytest.raises(ValidationError):
UpdateParams(build=bad_bool) # type: ignore[arg-type]
with pytest.raises(ValidationError):
UpdateParams(no_cache=bad_bool) # type: ignore[arg-type]
with pytest.raises(ValidationError):
UpdateParams(expected_branch="") # min_length=1
with pytest.raises(ValidationError):
UpdateParams(expected_branch=123) # type: ignore[arg-type]
with pytest.raises(ValidationError):
UpdateParams(build="true") # type: ignore[arg-type]
with pytest.raises(ValidationError):
UpdateParams.model_validate({"build": False, "extra": "prohibited"})
@@ -416,12 +445,13 @@ def test_operation_request_backward_compatibility_aliases():
# ---------------------------------------------------------------------------
def test_error_code_taxonomy_contains_exactly_6_canonical_codes():
assert len(ErrorCode) == 6
def test_error_code_taxonomy_contains_exactly_7_canonical_codes():
assert len(ErrorCode) == 7
expected_codes = {
"ERR_VALIDATION_FAILED",
"ERR_AUTH_REQUIRED",
"ERR_PERMISSION_DENIED",
"ERR_CAPABILITY_NOT_GRANTED",
"ERR_TARGET_NOT_FOUND",
"ERR_CONCURRENT_MUTATION",
"ERR_EXECUTION_FAILED",
@@ -433,6 +463,7 @@ def test_error_code_http_status_mapping():
assert ErrorCode.ERR_VALIDATION_FAILED.http_status == 400
assert ErrorCode.ERR_AUTH_REQUIRED.http_status == 401
assert ErrorCode.ERR_PERMISSION_DENIED.http_status == 403
assert ErrorCode.ERR_CAPABILITY_NOT_GRANTED.http_status == 403
assert ErrorCode.ERR_TARGET_NOT_FOUND.http_status == 404
assert ErrorCode.ERR_CONCURRENT_MUTATION.http_status == 409
assert ErrorCode.ERR_EXECUTION_FAILED.http_status == 500
+130 -12
View File
@@ -18,15 +18,19 @@ Asserts:
from __future__ import annotations
import concurrent.futures
import hashlib
import json
import socket
import tempfile
import threading
import time
from pathlib import Path
from unittest.mock import patch
import gitops_dispatcher
import pytest
from appctl_audit import AuditLogger, TargetLockManager
from appctl_audit import AuditLogger, AuditPersistenceError, TargetLockManager
from appctl_auth import Role, TokenDescriptor, TokenStore
from appctl_contracts import ErrorCode, OperationRequest, OperationType
from appctl_daemon import (
@@ -61,7 +65,8 @@ def daemon_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
- Valid 0600 audit log file
"""
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
socket_path = tmp_path / "appctl.sock"
sock_dir = tempfile.TemporaryDirectory(prefix="appctl_sock_", dir="/tmp")
socket_path = Path(sock_dir.name) / "appctl.sock"
http_port = get_free_port()
http_host = "127.0.0.1"
@@ -148,6 +153,7 @@ def daemon_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
f' path: "{docs_dir}"\n',
encoding="utf-8",
)
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file))
router = OperationalRouter(
audit_logger=audit_logger,
@@ -188,6 +194,7 @@ def daemon_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
yield ctx
finally:
daemon.stop()
sock_dir.cleanup()
def test_health_endpoint(daemon_env):
@@ -287,7 +294,7 @@ def test_auth_missing_token_fails_closed(daemon_env):
"""
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
with patch("subprocess.run") as mock_subproc:
with patch("appctl_router.run_bounded_subprocess") as mock_subproc:
# Over HTTP without token
resp_http = send_daemon_request(
endpoint=daemon_env.http_url,
@@ -401,7 +408,7 @@ def test_daemon_preflight_and_dotenv_safety(daemon_env):
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
with patch("subprocess.run") as mock_subproc:
with patch("appctl_router.run_bounded_subprocess") as mock_subproc:
resp = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=deploy_req,
@@ -435,6 +442,55 @@ def test_concurrent_mutation_conflict(daemon_env):
assert resp.error.code.http_status == 409
def test_daemon_multi_threaded_lock_contention_rejects_concurrent_mutation(daemon_env):
"""
Simultaneous mutating requests for the same target result in one 200 SUCCESS
and one 409 ERR_CONCURRENT_MUTATION via multi-threaded lock contention.
"""
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
first_started = threading.Event()
def slow_subproc(cmd, *args, **kwargs):
first_started.set()
time.sleep(0.2)
return (0, "Started", "")
def send_first():
return send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=deploy_req,
token=ADMIN_SECRET,
)
def send_second():
first_started.wait(timeout=2.0)
return send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=deploy_req,
token=ADMIN_SECRET,
)
with (
patch("appctl_router.run_bounded_subprocess", side_effect=slow_subproc),
patch("appctl_router.OperationalRouter._trigger_homepage_sync"),
concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor,
):
fut1 = executor.submit(send_first)
fut2 = executor.submit(send_second)
resp1 = fut1.result(timeout=5.0)
resp2 = fut2.result(timeout=5.0)
responses = [resp1, resp2]
successes = [r for r in responses if r.success]
conflicts = [r for r in responses if not r.success and r.error and r.error.code == ErrorCode.ERR_CONCURRENT_MUTATION]
assert len(successes) == 1
assert len(conflicts) == 1
assert successes[0].result is not None
assert successes[0].result["action"] == "deployed"
assert conflicts[0].error.code.http_status == 409
def test_execution_failure_audit(daemon_env):
"""
Failing Docker subprocess returns 500 ERR_EXECUTION_FAILED and records phase: FAILED.
@@ -467,10 +523,16 @@ def test_audit_failure_blocks_mutation(daemon_env):
Unwritable audit.jsonl aborts mutating command with 500 ERR_EXECUTION_FAILED
and zero Docker invocations.
"""
daemon_env.audit_file.chmod(0o400)
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
with patch("subprocess.run") as mock_subproc:
with (
patch.object(
daemon_env.daemon.audit_logger,
"emit_event",
side_effect=AuditPersistenceError("Simulated disk full or permission error"),
),
patch("appctl_router.run_bounded_subprocess") as mock_subproc,
):
resp = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=deploy_req,
@@ -482,9 +544,6 @@ def test_audit_failure_blocks_mutation(daemon_env):
assert resp.error.code.http_status == 500
assert mock_subproc.call_count == 0
# Restore write permission for teardown
daemon_env.audit_file.chmod(0o600)
def test_daemon_restart_preserves_state(daemon_env):
"""
@@ -515,13 +574,72 @@ def test_gitops_dispatcher_delegates_to_daemon(daemon_env, monkeypatch):
monkeypatch.setenv("GITOPS_APPCTL_TOKEN", OPERATOR_SECRET)
monkeypatch.setenv("APPCTL_SOCKET_PATH", str(daemon_env.socket_path))
with patch.object(daemon_env.daemon.router, "_op_workload_update") as mock_update:
mock_update.return_value = ({"action": "updated", "message": "Updated via daemon"}, "sha12345")
def mock_subproc(cmd, *args, **kwargs):
if "status" in cmd:
return (0, "", "")
if "rev-parse" in cmd:
return (0, "sha12345", "")
return (0, "ok", "")
with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc) as mock_sub, patch(
"appctl_router.OperationalRouter._trigger_homepage_sync"
):
success = gitops_dispatcher.execute_deployment(
target_dir=daemon_env.docs_dir,
deployment_config={"branch": "main", "actions": ["git_pull", "compose_up"]},
branch="main",
)
assert success is True
assert mock_update.call_count == 1
assert mock_sub.call_count >= 1
def test_daemon_deployments_file_defaults_to_workloads(
tmp_path: Path, run_isolated_script_expr
):
"""DEPLOYMENTS_FILE defaults to ~/Workloads/deployments.yaml."""
resolved_default = run_isolated_script_expr(
"import appctl_daemon; print(appctl_daemon.DEPLOYMENTS_FILE)"
)
assert Path(resolved_default) == tmp_path / "Workloads" / "deployments.yaml"
def test_daemon_deployments_file_honors_workloads_dir_override(
tmp_path: Path, run_isolated_script_expr
):
"""DEPLOYMENTS_FILE honors WORKLOADS_DIR override when HOMELAB_DEPLOYMENTS_FILE is unset."""
custom_workloads = tmp_path / "CustomWorkloads"
resolved_override = run_isolated_script_expr(
"import appctl_daemon; print(appctl_daemon.DEPLOYMENTS_FILE)",
extra_env={"WORKLOADS_DIR": str(custom_workloads)},
)
assert Path(resolved_override) == custom_workloads / "deployments.yaml"
def test_daemon_operator_fails_closed_when_deployments_file_absent(
daemon_env, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
"""homelab-operator fails closed (403 ERR_PERMISSION_DENIED) when ~/Workloads/deployments.yaml is absent."""
import appctl_auth
# When HOMELAB_DEPLOYMENTS_FILE is unset and ~/Workloads/deployments.yaml is absent,
# homelab-operator must be denied (403) without falling back to CORE_DIR/config/deployments.yaml.
monkeypatch.delenv("HOMELAB_DEPLOYMENTS_FILE", raising=False)
monkeypatch.delenv("WORKLOADS_DIR", raising=False)
monkeypatch.delenv("SITES_DIR", raising=False)
monkeypatch.setattr(
appctl_auth,
"DEFAULT_DEPLOYMENTS_FILE",
tmp_path / "empty-home" / "Workloads" / "deployments.yaml",
)
deploy_req = OperationRequest(
operation=OperationType.WORKLOAD_DEPLOY, target="docs"
)
resp = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=deploy_req,
token=OPERATOR_SECRET,
)
assert resp.success is False
assert resp.error is not None
assert resp.error.code == ErrorCode.ERR_PERMISSION_DENIED
assert resp.error.code.http_status == 403
+123
View File
@@ -200,6 +200,7 @@ def test_docker_status_parser_running(monkeypatch):
def mock_run(args, **kwargs):
mock = MagicMock()
mock.returncode = 0
if "ps" in args:
mock.stdout = "container123\n"
if "inspect" in args:
@@ -217,6 +218,7 @@ def test_docker_status_parser_stopped(monkeypatch):
def mock_run(args, **kwargs):
mock = MagicMock()
mock.returncode = 0
if "ps" in args:
mock.stdout = ""
return mock
@@ -232,6 +234,7 @@ def test_docker_status_parser_degraded(monkeypatch):
def mock_run(args, **kwargs):
mock = MagicMock()
mock.returncode = 0
if "ps" in args:
mock.stdout = "c1\nc2\n"
if "inspect" in args:
@@ -256,6 +259,7 @@ def test_docker_status_single_container(monkeypatch):
def mock_run(args, **kwargs):
mock = MagicMock()
mock.returncode = 0
if "authelia" in args:
mock.stdout = "true\n"
else:
@@ -268,6 +272,72 @@ def test_docker_status_single_container(monkeypatch):
assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped"
def test_docker_status_compose_ps_daemon_error(monkeypatch):
"""Ensure get_docker_status returns '❓ Unknown' when docker compose ps fails (e.g. daemon unreachable)."""
import subprocess
def mock_run(args, **kwargs):
return subprocess.CompletedProcess(
args=args,
returncode=1,
stdout="",
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
)
monkeypatch.setattr("subprocess.run", mock_run)
assert engine.get_docker_status("/fake/dir") == "❓ Unknown"
def test_docker_status_compose_inspect_error(monkeypatch):
"""Ensure get_docker_status returns '❓ Unknown' when docker inspect fails for compose containers."""
import subprocess
def mock_run(args, **kwargs):
if "ps" in args:
return subprocess.CompletedProcess(args=args, returncode=0, stdout="c1\n", stderr="")
return subprocess.CompletedProcess(
args=args,
returncode=1,
stdout="",
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
)
monkeypatch.setattr("subprocess.run", mock_run)
assert engine.get_docker_status("/fake/dir") == "❓ Unknown"
def test_docker_status_single_container_daemon_error(monkeypatch):
"""Ensure get_docker_status returns '❓ Unknown' when inspecting single container fails due to daemon error."""
import subprocess
def mock_run(args, **kwargs):
return subprocess.CompletedProcess(
args=args,
returncode=1,
stdout="",
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
)
monkeypatch.setattr("subprocess.run", mock_run)
assert engine.get_docker_status("", container_name="traefik") == "❓ Unknown"
def test_docker_status_single_container_no_such_object(monkeypatch):
"""Ensure get_docker_status returns '🔴 Stopped' when container does not exist."""
import subprocess
def mock_run(args, **kwargs):
return subprocess.CompletedProcess(
args=args,
returncode=1,
stdout="",
stderr="Error: No such object: traefik",
)
monkeypatch.setattr("subprocess.run", mock_run)
assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped"
def test_docker_status_error_handling(monkeypatch):
"""Ensure get_docker_status handles subprocess failures gracefully."""
@@ -484,3 +554,56 @@ def test_cmd_list_flags_manifest_error(
engine.cmd_list([])
captured = capsys.readouterr()
assert "Manifest Error" in captured.out
def test_workloads_dir_env_precedence_and_fallback(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
"""Ensure WORKLOADS_DIR > SITES_DIR > ~/Workloads fallback across core modules (#33)."""
import importlib
import appctl_daemon
import gitops_dispatcher
workloads_override = tmp_path / "custom-workloads"
sites_override = tmp_path / "legacy-sites"
fake_home = tmp_path / "home"
fake_core = tmp_path / "repo" / "core"
fake_core.mkdir(parents=True)
try:
# 1. WORKLOADS_DIR takes precedence over SITES_DIR
monkeypatch.setenv("CORE_DIR", str(fake_core))
monkeypatch.setenv("WORKLOADS_DIR", str(workloads_override))
monkeypatch.setenv("SITES_DIR", str(sites_override))
importlib.reload(engine)
importlib.reload(appctl_daemon)
importlib.reload(gitops_dispatcher)
assert engine.SITES_DIR == str(workloads_override)
assert appctl_daemon.SITES_DIR == workloads_override
assert gitops_dispatcher.SITES_DIR == workloads_override
# 2. SITES_DIR acts as fallback when WORKLOADS_DIR is unset
monkeypatch.delenv("WORKLOADS_DIR", raising=False)
importlib.reload(engine)
importlib.reload(appctl_daemon)
importlib.reload(gitops_dispatcher)
assert engine.SITES_DIR == str(sites_override)
assert appctl_daemon.SITES_DIR == sites_override
assert gitops_dispatcher.SITES_DIR == sites_override
# 3. Default resolves to ~/Workloads when neither env var is set
monkeypatch.delenv("SITES_DIR", raising=False)
monkeypatch.setenv("HOME", str(fake_home))
importlib.reload(engine)
importlib.reload(appctl_daemon)
importlib.reload(gitops_dispatcher)
expected_default = fake_home / "Workloads"
assert engine.SITES_DIR == str(expected_default)
assert appctl_daemon.SITES_DIR == expected_default
assert gitops_dispatcher.SITES_DIR == expected_default
finally:
monkeypatch.undo()
importlib.reload(engine)
importlib.reload(appctl_daemon)
importlib.reload(gitops_dispatcher)
File diff suppressed because it is too large. Load diff
+176
View File
@@ -0,0 +1,176 @@
"""
tests/unit/test_bootstrap_token.py — Unit Tests for Operator Admin Token Bootstrap Helper (WP4)
Verifies:
- 256-bit secure token generation (64 hex characters) and matching SHA-256 digest
- Strict 0600 file mode and 0700 parent directory creation
- TokenDescriptor Pydantic validation (scripts/appctl_auth.py)
- Refusal to overwrite existing token file without --force
- Overwriting existing token file when --force is supplied
- Secrets leakage prevention: raw Bearer token never appears in stdout/stderr
- Machine-readable JSON output via --print-json
"""
from __future__ import annotations
import hashlib
import json
import stat
import string
from pathlib import Path
from typing import Any
import pytest
from appctl_auth import Role, TokenDescriptor
from bootstrap_token import (
bootstrap_token,
generate_token,
main,
write_token_file,
)
def test_generate_token_produces_64_hex_token_and_valid_sha256() -> None:
raw_token, digest = generate_token()
assert len(raw_token) == 64
assert all(c in string.hexdigits for c in raw_token)
assert len(digest) == 64
assert all(c in string.hexdigits for c in digest)
expected_digest = hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
assert digest == expected_digest
def test_write_token_file_creates_file_and_enforces_0600(tmp_path: Path) -> None:
token_file = tmp_path / "subdir" / "token"
write_token_file(token_file, "secret-token-12345")
assert token_file.is_file()
assert stat.S_IMODE(token_file.stat().st_mode) == 0o600
assert stat.S_IMODE(token_file.parent.stat().st_mode) == 0o700
assert token_file.read_text(encoding="utf-8") == "secret-token-12345\n"
def test_bootstrap_token_generates_file_with_strict_mode_0600(tmp_path: Path) -> None:
nested_dir = tmp_path / "nested" / "homelab"
token_file = nested_dir / "token"
descriptor = bootstrap_token(output_path=token_file)
assert token_file.is_file()
# Check parent directory mode is 0700
parent_mode = stat.S_IMODE(nested_dir.stat().st_mode)
assert parent_mode == 0o700, f"Expected parent mode 0700, got {oct(parent_mode)}"
# Check token file mode is 0600
file_mode = stat.S_IMODE(token_file.stat().st_mode)
assert file_mode == 0o600, f"Expected file mode 0600, got {oct(file_mode)}"
raw_token = token_file.read_text(encoding="utf-8").strip()
assert len(raw_token) == 64
assert hashlib.sha256(raw_token.encode("utf-8")).hexdigest() == descriptor["sha256"]
def test_bootstrap_token_descriptor_validates_against_token_descriptor(tmp_path: Path) -> None:
token_file = tmp_path / "custom_token"
descriptor = bootstrap_token(
output_path=token_file,
token_id="custom-admin",
identity="operator",
role="homelab-admin",
)
validated = TokenDescriptor.model_validate(descriptor)
assert validated.token_id == "custom-admin"
assert validated.identity == "operator"
assert validated.role == Role.ADMIN
assert len(validated.sha256) == 64
def test_bootstrap_token_refuses_overwrite_without_force(tmp_path: Path) -> None:
token_file = tmp_path / "token"
bootstrap_token(output_path=token_file)
original_token = token_file.read_text(encoding="utf-8")
with pytest.raises(FileExistsError, match="already exists"):
bootstrap_token(output_path=token_file, force=False)
assert token_file.read_text(encoding="utf-8") == original_token
def test_bootstrap_token_overwrites_with_force(tmp_path: Path) -> None:
token_file = tmp_path / "token"
descriptor1 = bootstrap_token(output_path=token_file)
first_token = token_file.read_text(encoding="utf-8").strip()
descriptor2 = bootstrap_token(output_path=token_file, force=True)
second_token = token_file.read_text(encoding="utf-8").strip()
assert first_token != second_token
assert descriptor1["sha256"] != descriptor2["sha256"]
assert descriptor2["sha256"] == hashlib.sha256(second_token.encode("utf-8")).hexdigest()
def test_bootstrap_cli_never_prints_raw_secret_to_stdout_or_stderr(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
token_file = tmp_path / "token"
ret = main(["--output", str(token_file)])
assert ret == 0
raw_token = token_file.read_text(encoding="utf-8").strip()
captured = capsys.readouterr()
# RAW SECRET MUST NEVER APPEAR IN STDOUT OR STDERR
assert raw_token not in captured.out, "Leak: raw token found in stdout!"
assert raw_token not in captured.err, "Leak: raw token found in stderr!"
# Ensure stdout provides helpful human guidance
assert "operator-admin" in captured.out
assert "sops nixos/secrets.yaml" in captured.out
assert "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure" in captured.out
def test_bootstrap_cli_print_json_outputs_valid_json_descriptor(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
token_file = tmp_path / "token"
ret = main(["--output", str(token_file), "--print-json"])
assert ret == 0
raw_token = token_file.read_text(encoding="utf-8").strip()
captured = capsys.readouterr()
assert raw_token not in captured.out
assert captured.err == ""
# Must be cleanly parseable as pure JSON
data: dict[str, Any] = json.loads(captured.out.strip())
validated = TokenDescriptor.model_validate(data)
assert validated.token_id == "operator-admin"
assert validated.identity == "operator"
assert validated.role == Role.ADMIN
assert validated.sha256 == hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
def test_bootstrap_cli_refuses_overwrite_and_exits_nonzero(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
token_file = tmp_path / "token"
assert main(["--output", str(token_file)]) == 0
ret = main(["--output", str(token_file)])
assert ret != 0
captured = capsys.readouterr()
assert "already exists" in captured.err
def test_bootstrap_cli_force_overwrites(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
token_file = tmp_path / "token"
assert main(["--output", str(token_file)]) == 0
tok1 = token_file.read_text(encoding="utf-8").strip()
assert main(["--output", str(token_file), "--force"]) == 0
tok2 = token_file.read_text(encoding="utf-8").strip()
assert tok1 != tok2
+31 -4
View File
@@ -66,7 +66,9 @@ def test_validate_transport_rejects_http(insecure_url: str):
],
)
def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url):
with pytest.raises(ManifestValidationError, match=r"^Source URL cannot be empty\.$"):
with pytest.raises(
ManifestValidationError, match=r"^Source URL cannot be empty\.$"
):
validate_transport(empty_or_invalid_url) # type: ignore[arg-type]
@@ -77,7 +79,9 @@ def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url):
("ssh://git.example.com/", "SSH"),
],
)
def test_validate_transport_rejects_root_repository_path(root_path_url: str, scheme: str):
def test_validate_transport_rejects_root_repository_path(
root_path_url: str, scheme: str
):
with pytest.raises(
ManifestValidationError,
match=rf"^Malformed {scheme} source URL \(missing repository path\)",
@@ -132,8 +136,10 @@ def test_classify_ref_branches():
"feat/manifest-engine",
)
assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0")
assert classify_ref("custom-adhoc-branch") == (RefType.BRANCH, "custom-adhoc-branch")
assert classify_ref("custom-adhoc-branch") == (
RefType.BRANCH,
"custom-adhoc-branch",
)
def test_classify_ref_tags():
@@ -271,6 +277,15 @@ def test_parse_manifest_from_path(tmp_path: Path):
"IFS",
"CORE_DIR",
"SITES_DIR",
"HOMELAB_DOMAIN",
"DOMAIN_SUFFIX",
"DOMAIN",
"PROXY_NETWORK",
"CERT_RESOLVER",
"DOCKER_CONFIG",
"SERVICE_NAME",
"CONTAINER_NAME",
"SERVICE_DOMAIN",
],
)
def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str):
@@ -340,3 +355,15 @@ description: "Pydantic serialization test"
assert dumped["name"] == "serialized-app"
assert dumped["schemaVersion"] == "1.0"
assert manifest.to_dict()["name"] == "serialized-app"
def test_parse_manifest_rejects_homelab_grants_file_in_env():
"""Ensure HOMELAB_GRANTS_FILE is in RESERVED_ENV_KEYS and cannot be overridden by app.yaml."""
raw_yaml = """
name: "grants-override-app"
env:
HOMELAB_GRANTS_FILE: "/tmp/evil-grants.json"
"""
with pytest.raises(ManifestValidationError):
parse_manifest(raw_yaml)
+113
View File
@@ -250,3 +250,116 @@ def test_resolve_upstream_provenance_class_b_and_default_timeout():
prov = resolve_upstream_provenance(source, local_commit="abc1234")
assert prov.status == ProvenanceStatus.SYNCED
assert mock_run.call_args[1]["timeout"] == 10.0
def test_get_local_checkout_status_git_error(tmp_path: Path):
app_dir = tmp_path / "git_error_app"
app_dir.mkdir()
(app_dir / ".git").mkdir()
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(
returncode=128, stdout="", stderr="fatal: dubious ownership"
)
status = get_local_checkout_status(app_dir)
assert status.is_git is True
assert status.is_dirty is False
assert status.status_label == "⚠️ Git Error (exit 128)"
def _init_git_repo(repo_dir: Path, branch: str = "main") -> None:
env = _clean_git_env()
subprocess.run(
["git", "-C", str(repo_dir), "init", "-b", branch],
check=True,
capture_output=True,
env=env,
)
subprocess.run(
["git", "-C", str(repo_dir), "config", "user.email", "test@example.com"],
check=True,
env=env,
)
subprocess.run(
["git", "-C", str(repo_dir), "config", "user.name", "Test"],
check=True,
env=env,
)
def test_get_local_checkout_status_monorepo_subpath_isolation(tmp_path: Path):
"""Ensure monorepo subpath inspection isolates dirty state per workload directory (#33)."""
workloads_dir = tmp_path / "Workloads"
app_a = workloads_dir / "app_a"
app_b = workloads_dir / "app_b"
app_a.mkdir(parents=True)
app_b.mkdir(parents=True)
_init_git_repo(workloads_dir, branch="main")
(app_a / "app.yaml").write_text("name: app_a\n", encoding="utf-8")
(app_b / "app.yaml").write_text("name: app_b\n", encoding="utf-8")
env = _clean_git_env()
subprocess.run(["git", "-C", str(workloads_dir), "add", "."], check=True, env=env)
subprocess.run(
["git", "-C", str(workloads_dir), "commit", "-m", "init monorepo"],
check=True,
capture_output=True,
env=env,
)
# Dirty only app_b
(app_b / "app.yaml").write_text("name: app_b_dirty\n", encoding="utf-8")
(app_b / "untracked.txt").write_text("dirty\n", encoding="utf-8")
status_a = get_local_checkout_status(app_a)
assert status_a.is_git is True
assert status_a.is_dirty is False
assert status_a.branch == "main"
assert status_a.commit_sha != ""
assert "✓ Clean" in status_a.status_label
status_b = get_local_checkout_status(app_b)
assert status_b.is_git is True
assert status_b.is_dirty is True
assert status_b.branch == "main"
assert "* Dirty" in status_b.status_label
def test_get_local_checkout_status_hybrid_precedence_standalone_over_monorepo(
tmp_path: Path,
):
"""Ensure standalone <app>/.git takes precedence over parent monorepo .git (#33)."""
workloads_dir = tmp_path / "Workloads"
app_a = workloads_dir / "app_a"
app_a.mkdir(parents=True)
_init_git_repo(workloads_dir, branch="main")
env = _clean_git_env()
(workloads_dir / "README.md").write_text("monorepo\n", encoding="utf-8")
subprocess.run(
["git", "-C", str(workloads_dir), "add", "README.md"], check=True, env=env
)
subprocess.run(
["git", "-C", str(workloads_dir), "commit", "-m", "monorepo root"],
check=True,
capture_output=True,
env=env,
)
# Nested standalone .git inside app_a on a distinct branch
_init_git_repo(app_a, branch="standalone-branch")
(app_a / "app.yaml").write_text("name: app_a\n", encoding="utf-8")
subprocess.run(["git", "-C", str(app_a), "add", "app.yaml"], check=True, env=env)
subprocess.run(
["git", "-C", str(app_a), "commit", "-m", "standalone commit"],
check=True,
capture_output=True,
env=env,
)
status_a = get_local_checkout_status(app_a)
assert status_a.is_git is True
assert status_a.is_dirty is False
assert status_a.branch == "standalone-branch"
+164
View File
@@ -0,0 +1,164 @@
"""Unit tests for Pydantic v2 workload capability grants loader (ADR-0005)."""
from __future__ import annotations
import json
import os
from pathlib import Path
from types import SimpleNamespace
import pytest
from pydantic import ValidationError
from workload_grants import (
GrantsRegistry,
WorkloadGrant,
WorkloadGrantsError,
load_workload_grants,
)
def test_load_workload_grants_absent_file_returns_empty(tmp_path: Path) -> None:
missing = tmp_path / "does-not-exist.json"
assert load_workload_grants(missing) == {}
def test_load_workload_grants_honors_env_var_when_none(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text(
json.dumps(
{
"schemaVersion": "1.0",
"workloads": {
"media": {
"devices": ["/dev/dri/renderD128"],
"groups": ["render", "303"],
"readOnlyPaths": ["/mnt/media"],
}
},
}
),
encoding="utf-8",
)
monkeypatch.setenv("HOMELAB_GRANTS_FILE", str(grants_path))
loaded = load_workload_grants(verify_permissions=False)
assert "media" in loaded
assert loaded["media"].devices == ["/dev/dri/renderD128"]
assert loaded["media"].groups == ["render", "303"]
assert loaded["media"].readOnlyPaths == ["/mnt/media"]
@pytest.mark.parametrize("bad_group", ["0", "root", "wheel", "docker", "ROOT", " wheel "])
def test_workload_grant_rejects_privileged_groups(bad_group: str) -> None:
with pytest.raises(ValidationError):
WorkloadGrant(groups=[bad_group])
@pytest.mark.parametrize(
"bad_path",
[
"dev/dri/renderD128",
"../etc/passwd",
"/dev/../etc/shadow",
"/mnt/media/..",
"",
],
)
def test_workload_grant_rejects_relative_and_traversal_paths(bad_path: str) -> None:
with pytest.raises(ValidationError):
WorkloadGrant(devices=[bad_path])
with pytest.raises(ValidationError):
WorkloadGrant(readOnlyPaths=[bad_path])
def test_grants_registry_rejects_extra_fields() -> None:
with pytest.raises(ValidationError):
GrantsRegistry.model_validate(
{
"schemaVersion": "1.0",
"workloads": {"app": {"devices": [], "extra_field": True}},
}
)
def test_grants_registry_rejects_bad_schema_version() -> None:
with pytest.raises(ValidationError):
GrantsRegistry.model_validate({"schemaVersion": "2.0", "workloads": {}})
def test_load_workload_grants_malformed_json_fails_closed(tmp_path: Path) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text("{not valid json", encoding="utf-8")
with pytest.raises(WorkloadGrantsError):
load_workload_grants(grants_path)
def test_load_workload_grants_unreadable_file_fails_closed(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
def raise_perm_error(self: Path, *args: object, **kwargs: object) -> str:
raise PermissionError("Permission denied")
monkeypatch.setattr(Path, "read_text", raise_perm_error)
with pytest.raises(WorkloadGrantsError, match="read"):
load_workload_grants(grants_path)
def test_load_workload_grants_verify_permissions_rejects_symlink(tmp_path: Path) -> None:
real_file = tmp_path / "real.json"
real_file.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
link_file = tmp_path / "grants.json"
link_file.symlink_to(real_file)
with pytest.raises(WorkloadGrantsError, match="symlink"):
load_workload_grants(link_file, verify_permissions=True)
def test_load_workload_grants_verify_permissions_rejects_non_root_owner(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
monkeypatch.setattr(
os,
"lstat",
lambda _p: SimpleNamespace(st_mode=0o100640, st_uid=1000),
)
with pytest.raises(WorkloadGrantsError, match="root"):
load_workload_grants(grants_path, verify_permissions=True)
@pytest.mark.parametrize("bad_mode", [0o100664, 0o100660, 0o100642, 0o100646])
def test_load_workload_grants_verify_permissions_rejects_writable_mode(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bad_mode: int
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
monkeypatch.setattr(
os,
"lstat",
lambda _p: SimpleNamespace(st_mode=bad_mode, st_uid=0),
)
with pytest.raises(WorkloadGrantsError, match="writable"):
load_workload_grants(grants_path, verify_permissions=True)
@pytest.mark.parametrize("good_mode", [0o100640, 0o100644])
def test_load_workload_grants_verify_permissions_accepts_non_writable_mode(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, good_mode: int
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
monkeypatch.setattr(
os,
"lstat",
lambda _p: SimpleNamespace(st_mode=good_mode, st_uid=0),
)
assert load_workload_grants(grants_path, verify_permissions=True) == {}
+10
View File
@@ -35,3 +35,13 @@ x 2026-10-19 (A) Restore human-readable tabular output, list filter parameters,
x 2026-10-19 (A) Add operatorUser to homelab-operators group and configure daemon systemd sandbox HOME and DOCKER_CONFIG in nixos/modules/homeserver.nix +nixos @p4
x 2026-10-19 (A) Provision SOPS appctl/tokens_json and gitops/appctl_token secrets and wire GITOPS_APPCTL_TOKEN_FILE in nixos/secrets.yaml and nixos/modules/homeserver.nix +secrets @p4
x 2026-10-19 (B) Reconcile operational documentation and ROADMAP.md with Milestone P4 control plane daemon architecture +docs @p4
x 2026-10-23 (A) Migrate operator user from kiskaadee to operator in nixos/configuration.nix and homeserver.nix +nixos @core
x 2026-10-23 (A) Derive LLDAP_LDAP_BASE_DN dynamically from homelab.domain in nixos/modules/homeserver.nix and docker-compose.yml +nixos @auth
x 2026-10-23 (A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms
x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git
x 2026-10-30 (B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security
x 2026-10-30 (B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux
x 2026-10-30 (B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth
x 2026-10-30 (B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4
x 2026-10-30 (C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap
x 2026-10-30 (A) Implement instance domain injection dual-path import and operator cutover runbook in nixos/configuration.nix and docs/ +generic @nixos