Compare commits

..
133 Commits
Author SHA1 Message Date
kiskaadee 0e341ea6d8 chore(nixos): retire deprecated dynu-monitor and ddclient units (#34)
Core Architecture & Invariant CI / validate (push) Successful in 23s
- nixos/modules/shell.nix: preserve sops.secrets."system/pdf_decrypt_password" (owner: config.homelab.operatorUser) for pdf_dc

- nixos/configuration.nix: remove ./modules/dynu.nix import

- remove nixos/modules/dynu.nix, nixos/scripts/monitor.py, and nixos/scripts/ddclient.conf
2026-11-23 16:26:12 -05:00
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
kiskaadee 3230e08bf9 test(mutation): harden assertion boundaries and eliminate surviving mutants across unit suite
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m14s
Harden unit test assertions and coverage across core control plane modules
based on mutation testing findings.

- tests/unit/test_appctl_cli.py: preserve PYTHONPATH in subprocess environment; add
  coverage for empty workload lists, core service display, rich metadata, SSL
  status formatting (_format_ssl_info), and resolve JSON output.
- tests/unit/test_appctl_auth.py: assert specific ErrorCode on permission denials;
  verify operator denial without explicit target on mutating operations.
- tests/unit/test_appctl_audit.py: verify journal serialization and entry ordering.
- tests/unit/test_appctl_contracts.py: verify sanitize_validation_error strips secret
  token values and exact error details.
- tests/unit/test_appctl_router.py: assert RouterValidationError on whitespace domains
  and verify domain canonicalization.
- tests/unit/test_core_manifest.py: anchor empty URL regex validation; verify
  rejection of root repository URLs (https://git.example.com/).
- tests/unit/test_provenance.py: verify Class B workload image-only status and default
  timeout enforcement in resolve_upstream_provenance().

Rationale: Mutation analysis identified weak substring assertions and missing branch
coverage across CLI output formatting and security boundaries. Hardening these
assertions kills surviving mutants and prevents behavioral regressions.
2026-10-23 16:18:02 -05:00
kiskaadee b6ec909bb6 fix(core): resolve AST parser and strict model incompatibilities for mutation testing
Configure mutmut mutation testing framework, eliminate Parso AST syntax
errors in appctl engine, permit dynamic mutant injection on strict
Pydantic models, and prune redundant dead code.

- Tooling & Configuration:
  - Add setup.cfg defining authoritative [mutmut] runner configuration and file copy targets.
  - Update .gitignore to exclude mutants/ and .mutmut-cache/ directories.
- AST Parser Compatibility:
  - scripts/appctl_engine.py: rewrite parenthesized multi-context statements with
    'as' targets to nested with blocks (# noqa: SIM117) to prevent Parso 0.8.7
    grammar syntax errors during AST mutation.
- Pydantic v2 Invariants & Dead Code Removal:
  - scripts/appctl_contracts.py: configure ignored_types=(dict,) on StrictModel and
    OperationRequest to permit unannotated class-level mutant injection; replace
    unreachable OPERATION_PARAMS_MAP fallback defaults with direct mapping access.
  - scripts/core_manifest.py: configure ignored_types=(dict,) on strict manifest
    models; prune redundant branch patterns in classify_ref() down to single fallback.
  - scripts/appctl_auth.py: remove redundant target == "core" check in enforce_rbac().

Rationale: Mutmut failed to parse scripts/appctl_engine.py and threw PydanticUserError
when injecting unannotated mutant dictionaries into strict models with extra="forbid".
Resolving these AST and contract barriers allows mutation test runners to analyze
core control plane scripts hermetically.
2026-10-23 15:47:33 -05:00
kiskaadee 25e79898af docs(p4): reconcile operational documentation with control plane daemon architecture
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m13s
Closes #6
2026-10-19 17:05:20 -05:00
kiskaadee 528bd0d4bc feat(secrets): bootstrap SOPS appctl tokens and wire GitOps worker token
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m1s
Closes #5
2026-10-19 15:45:00 -05:00
kiskaadee 2668dcc5a8 fix(nixos): add operator to homelab-operators and configure daemon systemd sandbox
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m2s
Closes #4
2026-10-19 15:38:59 -05:00
kiskaadee 0b5ba58ecf fix(cli): restore human-readable tabular output and bash autocompletion
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m1s
Closes #3
2026-10-19 15:34:24 -05:00
kiskaadee 154cde272b fix(router): enable Core platform stack dispatch and manifest-free orchestration
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m9s
Closes #2
2026-10-19 15:25:37 -05:00
kiskaadee 8cc06e2470 chore(core): scrub personal domain/username literals and enforce pyright in flake checks
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m16s
2026-10-19 13:59:18 -05:00
kiskaadee 53404914c3 feat(appctl): implement thin UDS client and declare homelab-appctl service
- Implement scripts/appctl_cli.py as a lightweight HTTP/1.1 UDS client over /run/homelab/appctl.sock with token resolution and formatted responses.
- Wire scripts/appctl to delegate directly to appctl_cli.py when the daemon socket is active.
- Declare homelab-appctl.service, homelab-appctl user, and homelab-operators group in nixos/modules/homeserver.nix.
- Configure systemd sandboxing, managed runtime/state/log directories, and POSIX ACLs in systemd.tmpfiles.rules.
- Add unit tests for appctl_cli.py in tests/unit/test_appctl_cli.py (253 total passing tests).
2026-10-19 13:46:44 -05:00
kiskaadee 194d1bf3ff feat(appctl): implement dual-transport daemon and wire gitops worker to daemon
- Add multi-threaded HTTP/1.1 AppctlDaemon over UDS (/run/homelab/appctl.sock, mode 0660) and loopback TCP (127.0.0.1:9001).
- Implement 64 KiB request body cap and routes GET /v1/health and POST /v1/operations.
- Extract Linux SO_PEERCRED on UDS connections for peer_uid and viewer fallback.
- Authenticate Bearer tokens, enforce RBAC policy, log append-only audit events, and dispatch through OperationalRouter.
- Rewire gitops_dispatcher.py to parse manifests via core_manifest.parse_manifest() and delegate workload.update to daemon over UDS.
- Add comprehensive test suite in tests/unit/test_appctl_daemon.py (12 new tests, 248 total passing).
2026-10-19 13:34:36 -05:00
kiskaadee 9e30e113a0 feat(appctl): implement operational router, pure-Python dotenv loader, and pre-flight gate 2026-10-19 13:18:17 -05:00
kiskaadee d092ca17b8 feat(appctl): implement Bearer token authenticator, UDS peercred fallback, and 3-role RBAC gate 2026-10-19 13:12:35 -05:00
kiskaadee 8ce74ff520 feat(appctl): implement append-only audit logger and per-target lock manager 2026-10-19 13:08:35 -05:00
kiskaadee b5a3db6f1b feat(appctl): implement Pydantic v2 API contracts and compose_pull action 2026-10-19 13:04:36 -05:00
kiskaadee e23ff941d8 docs(p4): add ADR-0001 and ADR-0002 architecture records and update roadmap 2026-10-19 13:04:25 -05:00
kiskaadee dc880928a9 style: format python files with ruff 2026-10-16 23:21:34 -05:00
kiskaadee 51c43f71ff docs(p4): reconcile architecture decisions and readiness plan for control-plane daemon
Core Architecture & Invariant CI / validate (push) Successful in 50s
Codify locked decisions DEC-01 through DEC-05 and secondary operational
specifications in readiness documentation prior to P4 implementation.

- docs/plans/p4-readiness-plan.md:
  * Record locked transport contract (HTTP/1.1 over UDS and TCP, POST /v1/operations).
  * Record authentication contract (SOPS Bearer tokens, UDS SO_PEERCRED fallback to viewer).
  * Record service identity and audit threat model (homelab-appctl user, 503 fail-closed audit).
  * Record GitOps integration (dispatcher delegates worker to workload.update over UDS).
  * Record role-scoped target resolution and unified pre-flight pipeline.
  * Define concurrency locking, homepage sync lock, subprocess bounds, and error envelopes.
- ROADMAP.md: Align Milestone P4 deliverables and defer Authelia ForwardAuth to P5.
- docs/operations.md: Advance current operational baseline to Milestone P4.
- todo.txt: Update active backlog with P4 implementation slices 1 through 6.
2026-10-16 14:25:54 -05:00
kiskaadee d5ba44f676 chore(flake): bump nixpkgs and sops-nix inputs
Core Architecture & Invariant CI / validate (push) Successful in 51s
- nixpkgs: bump 7fd4004d...55bfb4d7 (1763 commits, nixos-unstable channel)

- sops-nix: bump ee48786c...44931708 (improved secret key type error messages)
2026-10-15 20:02:17 -05:00
kiskaadee dcacf976bf docs(core): reconcile docs/ with P1-P3 implementation and enforce genericism invariant
- Update docs/appctl.md to cover core_manifest.py, Schema v1.0, Class A/B
  source provenance, and two-axis status output.
- Align docs/architecture.md, docs/secrets-and-state.md, and docs/operations.md
  with P1 mail topology (Stalwart on smtp.<domain>, SnappyMail in ~/Sites,
  workload state under ~/var/lib/homelab/<app>/).
- Remove external vault path references from docs/decisions/README.md and
  scrub remaining personal domains/usernames across docs/ and SECURITY.md.
- Extend platform genericism security invariant test to guard docs/ and root
  markdown/flake files.
2026-10-15 19:52:08 -05:00
kiskaadee 61a2798d4f build(nix): unify Python dev environment via .venv symlink and add pyright to scripts/test
- Extract shared pythonEnv in flake.nix and symlink .venv in devShell
  shellHook so IDEs, terminal, and Nix checks share one Python 3.14 env.
- Add pyright static type checking to scripts/test and align pre-commit
  with the unified Nix environment.
- Remove personal domain from flake.nix description and ignore .venv.
2026-10-15 19:27:30 -05:00
kiskaadee 2bf0635ba9 docs(core): rewrite AGENTS.md and README.md for self-contained governance
- Structure AGENTS.md around the 6-section agents.md framework covering
  context discovery hierarchy, Core vs. ~/Sites ownership boundaries,
  anti-tautology TDD rules, verification gates (./scripts/test and pyright),
  declarative-vs-runtime state invariants, and MADR/Git hygiene.
- Redesign README.md into a 5-section instance-agnostic entrypoint explicitly
  scoped to the current CLI baseline, with a pointer to ROADMAP.md for the
  Milestone P4 daemon transition.
- Move the Current Baseline vs. Target Architecture matrix to ROADMAP.md,
  use descriptive phrasing for P1 historical endpoints, and define the
  explicit P4-to-P5 authorization gate handoff.
2026-10-15 19:27:09 -05:00
kiskaadee 7d516579ef fix(scripts): support PYTHON_BIN in appctl and unmask resolve stderr
- Introduce configurable PYTHON_BIN="${PYTHON_BIN:-python3}" in scripts/appctl.
- Remove blind '2>/dev/null' on engine resolve in setup_app_env to prevent
  masking manifest validation failures and runtime exceptions.
- Propagate active Python interpreter and PYTHONPATH in security invariant
  injection test to prevent Nix wrapper bare-python PATH shadowing.
2026-10-15 18:43:53 -05:00
kiskaadee 6997da3a58 chore(engine): retire appctl_engine_v2.py backward-compatibility shim
- Remove unused 16-line re-export shim scripts/appctl_engine_v2.py
- Update implementation inventory in docs/plans/p4-readiness-plan.md
- Confirm zero active callers across scripts, tests, and configuration
2026-10-15 16:41:32 -05:00
kiskaadee 1d196cbdd5 fix(engine): resolve pyright type narrowing issues and align pyproject.toml
- Add explicit None checks in SitesApp.to_dict() to eliminate reportOptionalMemberAccess
- Type-narrow app to SitesApp in cmd_info() eliminating reportAttributeAccessIssue
- Defensively parse X.509 peer cert RDN tuples in check_ssl_cert() resolving reportCallIssue
- Configure venvPath and venv in pyproject.toml [tool.pyright] and remove appctl_engine exclude
- Clean up Manifest type assertion in test_core_manifest.py
2026-10-15 15:17:30 -05:00
kiskaadee fe4111a628 feat(manifest): migrate core_manifest.py to Pydantic v2 and record ADR 0003
- Author MADR 4.0 ADR 0003 committing to centralized runtime validation and serialization via Pydantic v2
- Migrate SourceConfig, DeploymentConfig, HomepageConfig, and Manifest to Pydantic v2 models with ConfigDict(extra="forbid")
- Enforce fail-closed validation, strict typing, and secret-safe ManifestValidationError error transformation
- Update SitesApp.to_dict() in appctl_engine.py to recursively serialize nested Pydantic models
- Add unit tests verifying extra field rejection and model serialization in test_core_manifest.py
- Synchronize todo.txt marking manifest migration deliverable complete
2026-10-15 06:13:59 -05:00
kiskaadee fae36700b7 docs(p4): clarify pydantic target architecture and domain precedence in readiness plan
- Clarify Pydantic v2 as the target architecture for Milestone P4 implementation rather than existing code
- Detail strict type validation vs extra="forbid" rules, forbidding type coercion on operations, targets, flags, and tokens
- Specify error response transformation and information disclosure prevention (omitting raw secret values)
- Formalize domain configuration precedence (HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN -> fail closed) and RFC 2606 placeholders
- Synchronize todo.txt with completed pre-P4 tasks and schedule follow-up repository-wide domain scrub
2026-10-15 05:25:57 -05:00
kiskaadee 4786bbe1ca test(security): execute scripts/appctl directly in env injection resilience test
- De-tautologize test_appctl_env_injection_resilience by replacing copy-pasted inline bash loop with direct execution of scripts/appctl config
- Mount a mock docker binary in PATH to capture resolved environment variables without requiring a running Docker daemon
- Verify end-to-end that command substitution payloads ($(touch ...)) remain unexpanded literals and reserved environment keys cannot be overridden
- Ensure compatibility across standard environments and Nix sandbox flake checks using resolved bash interpreter
2026-10-15 05:15:41 -05:00
kiskaadee fbfbe9375f feat(core): enforce platform genericism invariant and scrub hardcoded domains
- Remove hardcoded roadtotech.me domain defaults in scripts/appctl and scripts/appctl_engine.py
- Enforce domain environment variable precedence (HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN)
- Replace personal domains and operator usernames across test fixtures with RFC 2606 placeholders (example.com, example.org, example.test)
- Add automated CI invariant test verifying zero personal domain/operator literals in scripts and tests
2026-10-15 03:45:22 -05:00
kiskaadee ea0ce0b1d6 fix(gitops): wire app_name and harden compose validator for env_file and volumes
- Pass app_name=canonical_app_name to validate_compose_security in execute_deployment
- Block env_file path escapes outside workload root to prevent secret exfiltration
- Normalize string security_opt directives before capability validation
- Reject ambiguous volume paths not declared in top-level volumes
- Add unit tests verifying env_file containment, string security_opt, and volume safety
2026-10-15 03:40:11 -05:00
kiskaadee 66c5e4280a feat(nixos): add pydantic to host runtime environment and constrain dependency range
- Add pydantic to environment.systemPackages in nixos/configuration.nix

- Add pydantic to homelab-gitops.service path in nixos/modules/homeserver.nix

- Constrain pydantic dependency to >=2.0,<3.0 in pyproject.toml
2026-10-15 03:38:08 -05:00
kiskaadee 68c149d9af feat(core): codify platform genericism invariant and add pydantic dependency
- Add Architectural Invariant 8 (Platform Genericism & Domain Decoupling) to AGENTS.md
- Add pydantic to flake.nix, pyproject.toml, and scripts/test
- Update docs/plans/p4-readiness-plan.md for Pydantic v2 pipeline and genericism
- Synchronize todo.txt with completed security gate and prioritized P4 tasks
2026-10-15 02:08:30 -05:00
kiskaadee ec0a461b2e chore: update todo.txt for completed manifest unification 2026-10-15 01:59:51 -05:00
kiskaadee 5ed61acf32 fix(engine): unify manifest parsing with core_manifest and fail closed on errors
- Delegate workload manifest parsing strictly to core_manifest.parse_manifest

- Remove duplicate SourceConfig and HomepageConfig dataclasses in appctl_engine

- Fail closed in cmd_resolve on corrupted manifests or missing app.yaml

- Display manifest errors explicitly in cmd_list and cmd_info without fallback

- Add unit tests verifying schema delegation, env validation, and fail-closed resolution
2026-10-15 01:58:05 -05:00
kiskaadee 93feb0d3f2 docs(gitops): document registry authority, AST security validation, and evict stale brain references 2026-10-15 01:53:00 -05:00
kiskaadee 8356819f08 fix(gitops): harden compose validator against relative traversal, tenant escape, and breakouts
Closes containment and privilege escalation bypasses in validate_compose_security()
by enforcing strict path resolution, cross-tenant state isolation, and capability bans.

Previously, `validate_compose_security()` only inspected absolute host paths starting
with `/` or `~`, allowing relative traversal paths (`../../Core/nixos`) to skip
validation entirely. Furthermore, state root containment was evaluated against the
parent `~/var/lib/homelab`, allowing one workload to mount another workload's state,
and container breakouts (`cap_add`, `devices`, host namespaces, top-level `include`)
were not inspected.

- Resolve relative host paths against `allowed_root` and enforce containment strictly
  within either the workload root or the workload's dedicated state root
  (`~/var/lib/homelab/<app_name>/`), blocking cross-tenant state directory access.
- Reject container breakout capabilities (`cap_add`, `devices`), unconfined security
  profiles, host namespaces (`pid: host`, `ipc: host`, etc.), and top-level `include`.
- Reject `docker-compose.yml` symlinks that escape the workload root.
- Add 12 adversarial regression tests in `test_gitops_security.py`.
- Mark Pre-P4 compose hardening task completed in `todo.txt`.

Part of Pre-P4 Security Gate (Milestone P4 readiness).
2026-10-15 01:52:08 -05:00
kiskaadee 0d9a2ce511 fix(gitops): enforce deployments.yaml as sole registry authority and remove dynamic discovery
Closes an admission authority bypass in the webhook continuous deployment engine by
strictly requiring targets to be registered in Core/config/deployments.yaml.

Previously, `get_trusted_repository_mapping()` attempted to load `deployments.yaml`
in Step 1, but unconditionally fell back to Step 2 (scanning all directories in
`~/Sites` with an `app.yaml`). This allowed unapproved workloads or experimental
directories to receive automated webhook deployment authority simply by existing on
disk, and failed open when `deployments.yaml` was missing or malformed.

- Remove dynamic `SITES_DIR` directory scanning from `get_trusted_repository_mapping()`.
- Enforce `deployments.yaml` as the sole authority, failing closed with an empty
  mapping if the registry is missing, unreadable, or malformed.
- Update admission test fixtures to explicitly declare registered repositories.
- Add regression tests verifying rejection of unregistered `~/Sites` directories
  and fail-closed behavior on corrupted/missing registry configurations.
- Update `todo.txt` task tracking.

Part of Pre-P4 Security Gate (Milestone P4 readiness).
2026-10-15 01:28:47 -05:00
kiskaadee 667f8d19b9 fix(appctl): eliminate eval injection and enforce manifest env key validation
Eliminates arbitrary shell command injection via workload manifest environment
variables and strictly enforces POSIX identifier validation during schema parsing.

Previously, `scripts/appctl` evaluated environment dictionaries from `app.yaml`
using `eval "$(python3 ...)"`, allowing command substitution (e.g. `$(...)`, backticks)
and unescaped quotes in manifest values to execute arbitrary commands with host
privileges. Furthermore, `core_manifest.py` accepted unconstrained variable keys,
risking environment corruption via platform-reserved identifiers.

- Replace `eval` in `scripts/appctl` with a zero-evaluation NUL-delimited stream
  piped directly into `export "$k=$v"`, preserving environment values strictly as data.
- Enforce POSIX variable naming regex (`^[a-zA-Z_][a-zA-Z0-9_]*$`) in `core_manifest.py`
  and reject reserved environment identifiers (`PATH`, `LD_PRELOAD`, `IFS`, etc.).
- Add adversarial regression tests in `test_security_invariants.py` and unit tests
  in `test_core_manifest.py` verifying command substitution resilience.
- Track Pre-P4 Security Gate tasks in `todo.txt`.

Part of Pre-P4 Security Gate (Milestone P4 readiness).
2026-10-14 23:05:42 -05:00
kiskaadee bbbf58a27c docs(p4): approve and lock control plane readiness plan and boundary specifications
Core Architecture & Invariant CI / validate (push) Successful in 38s
2026-10-14 15:25:47 -05:00
kiskaadee a9ada28c65 fix(appctl): set app_type to core when resolving core stack query
Core Architecture & Invariant CI / validate (push) Successful in 38s
2026-10-14 14:16:53 -05:00
kiskaadee 6052019f2c fix(appctl): lock HOMELAB_DOMAIN at startup to prevent application
Core Architecture & Invariant CI / validate (push) Successful in 40s
domain leaks during sync
2026-10-14 13:41:17 -05:00
kiskaadee 298ae728e1 chore(tooling): enforce python >=3.13 requirement and align uv lockfile
- Declare project.requires-python = ">=3.13" in pyproject.toml
- Lock dependencies and virtual package in uv.lock
- Update datetime.timezone.utc usages to datetime.UTC across scripts
2026-10-14 13:41:17 -05:00
kiskaadee ecacb1cc39 docs(p4): formalize control plane readiness plan and boundary specifications
- Reconcile appctl implementation inventory and caller map
- Define canonical command and error contract with schema v1.0
- Close authorization design with strict token enforcement everywhere
- Specify daemon execution boundaries and fixed subprocess allowlist
- Formalize append-only audit telemetry schema and failure-handling semantics
- Establish P4 acceptance test matrix and definition of done
- Synchronize ROADMAP.md milestone table and todo.txt task tracking
2026-10-14 13:41:17 -05:00
kiskaadee f261b80477 chore(uv): bump python requirement to >=3.13 in uv.lock 2026-10-14 13:41:17 -05:00
kiskaadee 2c99e3e92e chore(flake): update nixpkgs and sops-nix inputs.
- bump nixpkgs to nixos-unstable 7fdd4004(2026-10-11)
- bump sops-nix to ee48786 with systemd shutdown fxi and nested JSON key
  support
2026-10-14 13:41:17 -05:00
kiskaadee 9381f3e070 feat(nixos): configure automated nix store garbage collection and deduplication
- Enable weekly garbage collection retaining generations newer than 14 days

- Enable automatic nix store hardlink deduplication
2026-10-14 13:41:17 -05:00
kiskaadee f0e0fc41a1 feat(appctl): promote engine v2 to authoritative appctl_engine and complete Milestone P3
- Promote scripts/appctl_engine_v2.py to authoritative scripts/appctl_engine.py
- Add full two-axis inspection, Homepage synchronization, and schema v1.0 support
- Convert scripts/appctl_engine_v2.py into a backward-compatibility shim
- Rename tests/unit/test_appctl_engine_v2.py to test_appctl_engine.py and remove xfail marker
- Update README.md, docs/appctl.md, and docs/architecture.md to reference appctl_engine
- Synchronize todo.txt and mark Milestone P3 as completed in ROADMAP.md
2026-10-14 13:41:17 -05:00
kiskaadee c78550abea feat(provenance): implement two-axis inspection engine and bounded upstream resolver
- Implement scripts/provenance.py evaluating local deployment checkout state independently from upstream software provenance.
- Add bounded git ls-remote provenance resolver with 10s timeout to prevent hanging on unresponsive remotes during --fetch.
- Add 10 unit tests in tests/unit/test_provenance.py covering clean/dirty detection, synced vs update-available states, timeout handling, and unreachable remotes.
- Include git in test-suite nativeBuildInputs in flake.nix for hermetic sandbox execution.
- Update todo.txt marking Tasks 3, 4, & 5 of Milestone P3 completed.
2026-10-14 13:41:17 -05:00
kiskaadee 2779c06d8f feat(manifest): implement authoritative schema v1.0 and transport parser library
- Implement scripts/core_manifest.py with strongly-typed dataclasses for Manifest, SourceConfig, DeploymentConfig, and HomepageConfig.
- Enforce strict transport scheme validation (https://, ssh://, git@) and reject unencrypted HTTP or path traversal attempts.
- Classify upstream git references into semantic types (BRANCH, TAG, COMMIT).
- Add 19 unit tests in tests/unit/test_core_manifest.py covering manifest models, transport validation, ref classification, and failure modes.
- Update todo.txt marking Tasks 1 & 2 of Milestone P3 completed.
2026-10-13 07:59:19 -05:00
kiskaadee c9b22af663 docs(agents): codify live task tracking in AGENTS.md and initialize todo.txt for Milestone P3
- Add Live Task Tracking rule to AGENTS.md mandating synchronized, comment-free todo.txt.
- Initialize todo.txt with 7 prioritized deliverables for Milestone P3.
2026-10-13 07:43:01 -05:00
kiskaadee ccea8abb4a fix(nixos): correct python3.withPackages syntax in systemPackages and add toplevel evaluation to test script
Core Architecture & Invariant CI / validate (push) Successful in 34s
- Wrap python3.withPackages in outer parentheses with proper whitespace for argument application.
- Enhance scripts/test to evaluate nixosConfigurations.server toplevel derivation during pre-merge testing.
2026-10-13 07:12:53 -05:00
kiskaadee 5d2aff3f90 merge(origin/main): sync mail topology realignment into refactor/appctl-rework
Core Architecture & Invariant CI / validate (push) Successful in 33s
2026-10-13 06:53:22 -05:00
kiskaadee 6836233c95 feat(nixos): sandbox homelab-gitops service and update roadmap for Milestone P2
- Apply systemd sandboxing to homelab-gitops service: ProtectSystem=strict, ProtectHome=read-only, NoNewPrivileges=true, PrivateTmp=true, and kernel tunables protection.
- Restrict filesystem write paths to ~/Sites and ~/.local/state/homelab.
- Explicitly set DOCKER_CONFIG to isolated state directory to avoid home directory pollution.
- Prune obsolete SnappyMail tmpfiles rule and ensure gitops state directories exist.
- Mark Milestone P2 as completed in ROADMAP.md and advance Milestone P3 to current up next.
2026-10-13 06:51:27 -05:00
kiskaadee 61627cdd5d feat(gitops): implement authoritative registry, compose AST validation, and evict brain vault
- Add config/deployments.yaml as the authoritative Core repository registry enforcing strict containment within ~/Sites.
- Add validate_compose_security() AST pre-flight validator in gitops_dispatcher to reject privileged: true, Docker socket mounts, host networking, and unauthorized host bind mounts.
- Evict BRAIN_DIR constants and special-case bypasses from GitOps dispatcher; decouple knowledge vault synchronization from continuous workload deployment.
- Update tests to verify vault rejection, registry containment enforcement, and compose security AST validation.
2026-10-13 06:49:39 -05:00
kiskaadee c549ada3b4 docs(roadmap): mark Milestone P1 as completed and P2 as current up next 2026-10-13 04:02:23 -05:00
kiskaadee 0312812c3b feat(topology): re-home stalwart to smtp and remove snappymail from core compose
Core Architecture & Invariant CI / validate (push) Successful in 1m5s
- Re-home Stalwart public URL and Traefik router rules to smtp.${DOMAIN}.
- Remove SnappyMail service definition from Core docker-compose.yml.
- Update legacy appctl_engine.py service inventory and Homepage metadata.
2026-10-13 03:42:13 -05:00
kiskaadee 10468c4afa refactor(appctl): update stalwart domain to smtp and remove deprecated portainer
- Update Stalwart CoreService domain to smtp.${HOMELAB_DOMAIN} in preparation for mail topology realignment (Milestone P1).
- Prune deprecated Portainer CoreService entry from core service inventory.
2026-10-13 03:41:02 -05:00
kiskaadee 7ae03f2176 docs(architecture): realign repository documentation with control-plane baseline and roadmap v5
- Update root README.md with Appctl Core's identity, control-plane mental model, and explicit contrast between current implementation baseline and target architecture.
- Add root ROADMAP.md as repository-facing projection of Roadmap v5 (milestones P0–P7).
- Add docs/decisions/README.md as lightweight navigation index for governing ADRs.
- Add contextual implementation scope notes to docs/architecture.md and docs/appctl.md.
2026-10-08 00:03:56 -05:00
kiskaadee 2297cd5cba merge(refactor/appctl-rework): consolidate appctl v2 engine and provenance models into main
Core Architecture & Invariant CI / validate (push) Successful in 35s
2026-10-07 21:53:27 -05:00
kiskaadee 82edd74aac feat(appctl): implement docker status inspection and image revision extraction
- Implement get_docker_status supporting compose directories and single core containers
- Implement get_docker_image_revision for OCI image provenance label extraction
- Unmark test_docker_status_parser_running from xfail in test suite
- Add unit tests for stopped, degraded, non-stack, single container, and error states
2026-10-07 07:17:04 -05:00
kiskaadee 964e633da2 chore(tooling): exclude legacy engine from pyright and narrow gitops target type
- Add scripts/appctl_engine.py to pyproject.toml [tool.pyright] exclude list
- Add assert target_dir is not None guard in gitops_dispatcher after webhook admission
2026-10-07 07:15:31 -05:00
kiskaadee aca5a71bca docs(agents): align knowledge preservation with global documentation-router 2026-09-29 14:52:01 -05:00
kiskaadee be954a1d39 docs(agents): align knowledge preservation with global documentation-router 2026-09-29 14:51:51 -05:00
75 changed files with 18463 additions and 2661 deletions

No files matched your search

-2
View File
@@ -9,8 +9,6 @@ on:
jobs: jobs:
validate: validate:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container:
image: nixery.dev/shell/coreutils/git/nix/nodejs:latest
steps: steps:
- name: Check out repository - name: Check out repository
uses: actions/checkout@v4 uses: actions/checkout@v4
+18 -10
View File
@@ -1,9 +1,9 @@
#!/usr/bin/env bash #!/usr/bin/env bash
set -e set -euo pipefail
# ============================================================================== # ==============================================================================
# Homelab Core Pre-Commit Invariant & Quality Gate Hook # Homelab Core Pre-Commit Invariant & Quality Gate Hook
# Runs linter (Ruff) and architecture & security test suite (Pytest) # Runs linter (Ruff), static type checker (Pyright), and test suite (Pytest)
# ============================================================================== # ==============================================================================
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
@@ -13,26 +13,34 @@ echo "🔍 [pre-commit] Executing Homelab Core invariant checks..."
# 1. Run Ruff Linter # 1. Run Ruff Linter
echo " ↳ Linting repository with Ruff..." echo " ↳ Linting repository with Ruff..."
if command -v uv >/dev/null 2>&1; then if command -v ruff >/dev/null 2>&1; then
uv run ruff check .
elif command -v ruff >/dev/null 2>&1; then
ruff check . ruff check .
elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then
nix develop --command ruff check . nix develop --command ruff check .
else else
echo "⚠️ [pre-commit] Neither uv, ruff, nor nix found; skipping ruff" echo "⚠️ [pre-commit] Neither ruff nor nix found; skipping ruff"
fi fi
# 2. Run Pytest Suite # 2. Run Pyright Type Checker
echo " ↳ Checking static types with Pyright..."
if command -v pyright >/dev/null 2>&1; then
pyright
elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then
nix develop --command pyright
else
echo "⚠️ [pre-commit] Neither pyright nor nix found; skipping pyright"
fi
# 3. Run Pytest Suite
echo " ↳ Running structural and security test suite with Pytest..." echo " ↳ Running structural and security test suite with Pytest..."
if command -v uv >/dev/null 2>&1; then if [ -x ".venv/bin/pytest" ]; then
uv run --with pytest --with pyyaml pytest tests/ .venv/bin/pytest tests/
elif command -v pytest >/dev/null 2>&1; then elif command -v pytest >/dev/null 2>&1; then
pytest tests/ pytest tests/
elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then
nix develop --command pytest tests/ nix develop --command pytest tests/
else else
echo "⚠️ [pre-commit] Neither uv, pytest, nor nix found; skipping pytest" echo "⚠️ [pre-commit] Neither pytest nor nix found; skipping pytest"
fi fi
echo "✅ [pre-commit] All repository checks passed successfully!" echo "✅ [pre-commit] All repository checks passed successfully!"
+9
View File
@@ -5,6 +5,8 @@ secrets.txt
backup.zip backup.zip
.envrc .envrc
.direnv .direnv
.venv
nixos/instance.nix
# SSL / ACME Certificates & Keys # SSL / ACME Certificates & Keys
config/letsencrypt/* config/letsencrypt/*
@@ -39,13 +41,20 @@ config/homepage/custom.js
Thumbs.db Thumbs.db
.vscode/ .vscode/
.idea/ .idea/
.worktrees/
# Python & Testing Caches # Python & Testing Caches
__pycache__/ __pycache__/
*.pyc *.pyc
.pytest_cache/ .pytest_cache/
.ruff_cache/ .ruff_cache/
mutants/
.mutmut-cache/
# Local Bootstrap & Operational Scripts # Local Bootstrap & Operational Scripts
scripts/bootstrap_lldap_users.py scripts/bootstrap_lldap_users.py
scripts/bootstrap_*.py scripts/bootstrap_*.py
!scripts/bootstrap_token.py
# Worktrees & Slices
.worktrees/
+70 -130
View File
@@ -1,158 +1,98 @@
# Homelab Core — Agent Guidelines # Canopy NixOS Core — Agent Guidelines
This repository defines the host foundation and Core platform for the ## 1. Project Overview & Architectural Boundaries
`roadtotech.me` homelab.
It contains NixOS configuration, shared infrastructure services, orchestration **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.
tools, security policy, and operational configuration.
Independent application workloads live in `~/Sites` and are integrated with ### Core vs. `~/Workloads` Ownership
Core through their application manifests and Docker Compose configuration. - **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:
1. **Architectural Decisions (`docs/decisions/`)**: Check [`docs/decisions/README.md`](docs/decisions/README.md) and local ADRs for binding design commitments.
2. **Runtime Contracts (`docs/`)**: Consult [`docs/architecture.md`](docs/architecture.md), [`docs/appctl.md`](docs/appctl.md), [`docs/gitops.md`](docs/gitops.md), and [`docs/secrets-and-state.md`](docs/secrets-and-state.md) for current behavior.
3. **Trajectory & Active Work (`ROADMAP.md`, `todo.txt`, `git log`)**: Verify whether a capability belongs to the current baseline or a planned milestone before modifying code.
When a requested change conflicts with an architectural invariant or accepted ADR, **stop and surface the conflict** before implementing a workaround.
--- ---
## Architectural Invariants ## 2. Build, Lint & Verification Commands
### 1. Core / Sites Boundary The Python environment (`python3`, `pytest`, `pydantic`, `pyyaml`, `types-pyyaml`) and static analysis tools (`ruff`, `pyright`) are provisioned hermetically by `flake.nix` and automatically symlinked to `.venv` via the Nix `devShell` hook (`.envrc`). Do not create separate `uv` or `pip` virtual environments that split from the Nix store environment.
**Core owns:** Every implementation step must close with the automated verification gate before proposing a commit:
- NixOS host configuration and system services
- Shared platform and infrastructure services
- Ingress, identity, security boundaries, and host-level policy
- Orchestration and deployment mechanics
**`~/Sites` owns:**
- Independently deployed application workloads
- Application-specific Docker Compose configuration
- Application-specific `app.yaml` metadata and workload intent
Do not move workload-specific configuration into Core merely because Core
consumes or manages the workload.
Do not move Core-owned platform services into `~/Sites`.
When ownership is unclear, consult current architecture documentation before
changing the boundary.
### 2. Workload Manifests
Every `~/Sites` workload is self-describing through its `app.yaml`.
Do not hardcode workload-specific domains, ports, environment variables,
containers, or deployment configuration inside `scripts/appctl`,
`scripts/appctl_engine.py`, or GitOps logic.
`app.yaml` describes workload identity, integration metadata, and deployment
intent. Core owns deployment mechanics.
Never introduce arbitrary command execution, host filesystem paths,
privileged operations, or Docker control capabilities into workload manifests.
### 3. GitOps Trust Boundary
GitOps must remain a constrained deployment mechanism.
- Webhook authentication is mandatory.
- Repository identity is resolved through trusted Core logic.
- Filesystem paths must never be selected directly by webhook payloads.
- Deployment execution must remain closed and explicitly allowlisted.
- Repository-controlled configuration must never become arbitrary shell input.
- Deployment serialization and superseding behavior must be preserved.
Do not weaken these constraints for convenience.
### 4. Docker Isolation
- `socket-proxy` is the only Core Compose service that may mount
`/var/run/docker.sock`.
- The socket proxy must expose only explicitly approved read-only Docker API capabilities; state-changing and command-execution endpoints must remain disabled.
- Do not add `privileged: true` without an explicit architectural decision.
- Workload containers must not gain direct access to the Docker socket.
### 5. Secrets & Persistent State
Never commit plaintext secrets, credentials, password hashes, private keys,
certificates, runtime databases, or other generated/persistent state.
Secrets are managed through SOPS and projected to runtime paths under
`/run/secrets/`.
Do not move secrets into application manifests or source code.
### 6. Declarative Configuration vs Runtime State
Git contains declarative configuration and reproducible definitions.
Persistent runtime state belongs in the appropriate state directories or
Docker volumes and must remain excluded from version control.
Do not convert runtime state into committed configuration merely to simplify
development or recovery.
### 7. Core Service Ownership
Core Compose is the execution boundary for Core-owned platform services.
Workload-specific services belong in `~/Sites` unless an explicit architectural
decision establishes them as Core-owned.
Do not introduce application-specific deployment policy into the Core stack.
Do not make Core orchestration depend on implementation details of a workload
when the workload's declared contract can be used instead.
### 8. License
Preserve The Unlicense across Core and related Sites repositories.
---
## Verification & Architectural Integrity
When a requested change conflicts with an invariant, stop and resolve the
architectural conflict before implementing a workaround.
Before committing architectural or security-sensitive changes:
```bash ```bash
./scripts/test # Full verification gate: Ruff + Pyright + Pytest (124+ tests) + nix flake check + NixOS drv eval
nix flake check ./scripts/run-tests
# Targeted fast iteration commands (inside direnv / nix develop, or via .venv)
ruff check .
pyright
.venv/bin/pytest tests/
``` ```
Run additional validation appropriate to the change, such as: When modifying container or Compose definitions, also validate Compose syntax:
```bash ```bash
docker compose config -q docker compose config -q
``` ```
Architectural invariants should be encoded as tests whenever practical. ---
Do not bypass failing invariant tests by weakening or removing the invariant ## 3. Code Style & Contract Guidelines
unless the architecture itself has intentionally changed.
- **Fail-Closed Validation (`scripts/core_manifest.py`)**: All external inputs (`app.yaml` manifests, webhook payloads, CLI arguments, daemon payloads) must be validated through strict Pydantic v2 models (`ConfigDict(extra="forbid")`).
- **Explicit Error Handling**: Never swallow diagnostic `stderr` silently (e.g., avoid blind `2>/dev/null` on engine or manifest commands). Surface actionable validation errors while redacting sensitive material.
- **Platform Genericism**: Keep all code, templates, tests, and documentation strictly instance-agnostic:
- Inject routing and service identities at runtime via environment variables (`HOMELAB_DOMAIN`, `DOMAIN_SUFFIX`).
- Use RFC 2606 placeholders (`example.com`, `example.org`, `example.test`) in tests and configuration examples—never personal domains or operator usernames.
- In historical documentation or milestone records, use descriptive phrasing (e.g., *"the configured `smtp.<domain>` endpoint"*) rather than fabricating placeholder domains as historical facts.
--- ---
## Documentation ## 4. Testing Instructions (TDD)
Use the repository's current architecture and operational documentation as the - **TDD-First**: Write or update failing unit, structural, or security tests in `tests/` before or alongside implementation changes.
source of truth for ownership, protocols, and system behavior. - **No Tautological Tests**: Every test must import and execute real production modules or scripts (`core_manifest`, `appctl_engine`, `gitops_dispatcher`, `scripts/appctl`) and assert on observable outcomes. Never write tests that only inspect local mock strings, hardcode expected outputs into the fixture under test, or continue passing when the production invariant is broken.
- **Protect Invariants**: Do not bypass failing tests by weakening or deleting an invariant assertion unless the architecture itself has intentionally changed via an approved ADR.
Record significant architectural decisions in the appropriate ADR or Brain
documentation rather than expanding this file into an architecture manual.
All documentation must remain GitHub-flavored Markdown compatible with Obsidian
and the live documentation viewer.
--- ---
## Engineering Knowledge Capture ## 5. Security & State Invariants
Significant engineering knowledge should be externalized to the project's external knowledge base when such a system is configured: 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 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`).
- Never add `privileged: true`, host namespace sharing, or direct Docker socket mounts to workload or control-plane containers.
4. **Declarative Configuration vs. Secrets & Runtime State**:
- Git stores declarative configuration and reproducible definitions only. Never commit plaintext secrets, keys, password hashes, certificates, or runtime databases.
- Host secrets are managed via SOPS (`sops-nix`) and projected to `/run/secrets/`.
- Persistent mutable runtime state belongs in dedicated host state directories (`~/var/lib/homelab/<app>/`) or Docker volumes excluded from version control.
- Architectural decisions with lasting trade-offs ---
- Threat model or security posture modifications
- Non-obvious root cause discoveries and diagnostic breakthroughs
- Transferable implementation lessons
Guidelines: ## 6. Documentation, Task Tracking & Git Workflow
- Do not duplicate repository documentation, runtime configs, or appliance manuals in external records.
- Preserve repository-local documentation (e.g., `docs/`, inline comments, commit rationale) as the primary source of truth for runtime behavior. - **Synchronize Documentation (`docs/`)**: Update repository documentation alongside code changes that alter behavior, contracts, or operations. Keep all Markdown formatted in GitHub-Flavored Markdown compatible with both Obsidian and the live documentation viewer.
- **Architecture Decision Records (`docs/decisions/`)**: Record binding repository-level architectural decisions in MADR 4.0 format (`NNNN-slug.md`) and register them in [`docs/decisions/README.md`](docs/decisions/README.md).
- **Live Task Tracking (`todo.txt`)**: Maintain a comment-free root `todo.txt` formatted for `tuxedo` / `todo.sh` (`(A)`–`(C)` priorities, `+<project>`, `@<context>`) reflecting the current milestone. Mark verified deliverables completed (`x YYYY-MM-DD ...`) immediately.
- **Git & Commits**:
- Never commit directly to `main`/`master`.
- 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).
+122 -94
View File
@@ -1,157 +1,185 @@
# 🌐 Homelab Core — Appliance & Platform Reference # Canopy — NixOS Core (`canopy-homelab/nixos-core`)
**Homelab Core** is the declarative NixOS appliance and platform foundation for the `roadtotech.me` homelab cluster. **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 provides host operating system configuration, edge routing, automated wildcard TLS certificate issuance, identity and access management, mail transport, container socket isolation, workload orchestration, and continuous GitOps deployment. It is designed around a strict two-tier boundary:
1. **Canopy NixOS Core (`canopy-homelab/nixos-core`, this repository)**: Owns NixOS operating system configuration, edge TLS ingress, SSO/LDAP directory identity, mail routing, read-only Docker socket isolation, and orchestration/deployment mechanics.
2. **Canopy Workloads (`~/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]
> **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.
--- ---
## 🏛️ System Architecture & Boundaries ## System Architecture at a Glance
The homelab ecosystem separates **ownership**, **runtime architecture**, and **cross-cutting orchestration**: ```text
### 1. Ownership: Core vs. Sites
* **Core (`~/Core`) owns platform mechanics**: System services, host firewall, edge ingress, security barriers, deployment serialization, and secret distribution.
* **Workload Plane (`~/Sites`) owns application intent**: Workloads are self-describing via `app.yaml` and independent `docker-compose.yml` configurations. Workloads declare application intent; Core executes deployment.
### 2. Runtime Architecture
The system operates across four runtime layers:
1. **Host Foundation**: Headless NixOS Linux, disk configuration, Docker daemon, systemd daemons, firewall rules, and in-memory secret files under `/run/secrets/`.
2. **Edge Gateway**: Traefik (v3.6) reverse proxy terminating wildcard TLS (`*.roadtotech.me`) via Dynu DNS-01 Let's Encrypt validation.
3. **Core Platform Services**: Central services in `docker-compose.yml` (Authelia SSO, LLDAP directory, Stalwart mail, SnappyMail, Homepage dashboard, Dozzle, Watchtower, Diun, and socket-proxy).
4. **Workload Plane**: Independent application stacks in `~/Sites` connected to the platform over the `proxy-net` Docker network.
### 3. Cross-Cutting Orchestration
* **`appctl` CLI & Engine**: Coordinates discovery, environment injection, container lifecycle actions, and Homepage compilation across workloads and Core.
* **GitOps Webhook Dispatcher**: Listens on port 9000 (`homelab-gitops.service`), validating incoming Git push webhooks and executing declared deployment actions.
---
## 🗺️ System Topology & Network Architecture
```
Internet Internet
│ │
▼ ▼
┌───────────────────────────────┐ ┌───────────────────────────────┐
│ Traefik Edge Proxy (:443) │ │ Traefik Edge Proxy (:443) │
│ Wildcard TLS (*.roadtotech.me│ │ Wildcard TLS (*.example.com) │
└───────┬───────────────┬───────┘ └───────┬───────────────┬───────┘
│ │ │ │
Public Traffic │ │ ForwardAuth Protected Public Traffic │ │ ForwardAuth Protected
(e.g., mail, landing) │ │ (authelia-auth@docker) (e.g., SMTP, public) │ │ (authelia-auth@docker)
▼ ▼ ▼ ▼
[ Public Services ] [ Authelia SSO / 2FA ] [ Public Services ] [ Authelia SSO / 2FA ]
│ │ (LDAP -> LLDAP) │ │ (LDAP -> LLDAP)
│ │
▼ ▼ ▼ ▼
┌───────────────────────────────┐ ┌───────────────────────────────┐
│ Docker proxy-net │ │ Docker proxy-net │
├───────────────────────────────┤ ├───────────────────────────────┤
│ • Core Services (Homepage, │ │ • Core Services (Homepage, │
│ Dozzle, etc.) │ │ Dozzle, Stalwart, etc.) │
│ • Workload Apps (~/Sites/*) │ │ • Workload Apps (~/Workloads/*) │
└───────────────────────────────┘ └───────────────┬───────────────┘
│ │ (Read-Only API via TCP:2375)
(Protected API via TCP:2375)
▼ ▼
┌───────────────────────────────┐ ┌───────────────────────────────┐
│ Docker socket-proxy │ │ Docker socket-proxy │
│ (socket-net, Read-Only) │ │ (socket-net, Read-Only) │
└───────────────┬───────────────┘ └───────────────┬───────────────┘
│ (read-only mount) │ (read-only mount :ro)
▼ ▼
/var/run/docker.sock /var/run/docker.sock
▲
│ (Host Orchestration & CD)
┌───────────────┴───────────────┐
│ Host Control Plane (P4) │
│ • thin appctl CLI │
│ • homelab-appctl.service │
│ (UDS / HTTP daemon) │
│ • homelab-gitops.service │
└───────────────────────────────┘
``` ```
### Core Services (`docker-compose.yml`) For detailed runtime layers, network segmentation, and the P4 control-plane transport architecture, see [`docs/architecture.md`](docs/architecture.md) and [`ROADMAP.md`](ROADMAP.md).
| Service | Domain / Ingress | Function | Auth Policy |
### Core Platform Services (`docker-compose.yml`)
| Service | Default Endpoint | Role | Access Policy |
| :--- | :--- | :--- | :--- | | :--- | :--- | :--- | :--- |
| **`traefik`** | `traefik.roadtotech.me` | Edge reverse proxy, Dynu DNS-01 ACME TLS | Authelia Guard | | **`traefik`** | `traefik.${HOMELAB_DOMAIN}` | Edge reverse proxy & DNS-01 ACME wildcard TLS | Authelia Guard |
| **`socket-proxy`** | Internal (`socket-net:2375`) | Read-only Docker API gateway barrier | Internal Only | | **`socket-proxy`** | Internal (`socket-net:2375`) | Read-only Docker API security barrier (`POST=0`, `DELETE=0`) | Internal Only |
| **`lldap`** | `users.roadtotech.me` | LDAP directory & user database | Authelia Guard | | **`lldap`** | `users.${HOMELAB_DOMAIN}` | Central LDAP user directory | Authelia Guard |
| **`authelia`** | `auth.roadtotech.me` | Single Sign-On (SSO) & ForwardAuth middleware | Public (Bypass) | | **`authelia`** | `auth.${HOMELAB_DOMAIN}` | Single Sign-On (SSO), 2FA & ForwardAuth | Public (Auth Endpoint) |
| **`stalwart`** | `mail.roadtotech.me` | Mail Server (SMTP/IMAP/JMAP/Sieve) | Native / LLDAP | | **`stalwart`** | `smtp.${HOMELAB_DOMAIN}` | Mail server (SMTP/IMAP/JMAP/Sieve) | Native / LLDAP |
| **`snappymail`** | `webmail.roadtotech.me` | Webmail client connected to Stalwart | Native / Stalwart | | **`homepage`** | `dashboard.${HOMELAB_DOMAIN}` | Service portal dynamically synced via `appctl` | Authelia Guard |
| **`homepage`** | `dashboard.roadtotech.me` | Service portal & system dashboard | Authelia Guard | | **`dozzle`** | `logs.${HOMELAB_DOMAIN}` | Real-time container log viewer (via `socket-proxy`) | Authelia Guard |
| **`dozzle`** | `logs.roadtotech.me` | Container log viewer (via socket-proxy) | Authelia Guard |
| **`watchtower`** | Internal | Automated container image updater | Internal Only | | **`watchtower`** | Internal | Automated container image updater | Internal Only |
| **`diun`** | Internal | Container image update notifier | Internal Only | | **`diun`** | Internal | Container image update notifier | Internal Only |
--- ---
## ⚡ Quick Start & Operator Workflows ## Repository Structure
### Host & System Operations ```text
```bash .
# Rebuild and switch NixOS configuration ├── flake.nix # NixOS host configuration, devShell (.venv symlink), and CI checks
sudo nixos-rebuild switch --flake ~/Core#server ├── docker-compose.yml # Core platform service stack
# or use the built-in shell alias: ├── nixos/ # Declarative NixOS modules, systemd units, SOPS secret wiring & instance.example.nix
nix-switch ├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml template)
├── scripts/
# Inspect systemd platform services │ ├── appctl # Thin operational CLI delegating to control plane daemon
systemctl status homeserver-core.service # Core Compose stack │ ├── appctl_daemon.py # Async HTTP/UDS daemon server (homelab-appctl.service)
systemctl status homelab-gitops.service # GitOps webhook engine │ ├── appctl_router.py # Operational router, locking, RBAC & dispatch
systemctl status dynu-monitor.service # Smart DDNS IP monitor │ ├── appctl_auth.py # SO_PEERCRED & Bearer token RBAC authentication
systemctl status dynu-monitor.timer # DDNS timer (every 30m) │ ├── 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
``` ```
### Workload Management (`appctl`) ---
## Quickstart & Operations (Control Plane Daemon & CLI)
### Development & Verification
Entering the directory via `direnv` (`use flake`) or `nix develop` provisions the hermetic Nix Python environment and symlinks `.venv` for IDE static analysis:
```bash ```bash
# List all application stacks with container health and Git tracking status # Run full automated verification (Ruff + Pyright + Pytest + nix flake check + NixOS drv eval)
./scripts/run-tests
# Run individual checks directly
ruff check .
pyright
.venv/bin/pytest tests/
```
### 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 appctl list
# Fetch upstream changes across all repos and inspect with SSL certificates # Include upstream Git provenance (--fetch), TLS certificate expiry (--ssl), and Core services (--core)
appctl list --fetch --ssl --core appctl list --fetch --ssl --core
# Inspect full diagnostic metadata for a service # Inspect detailed manifest, provenance, and container diagnostics for a workload
appctl info jellyfin appctl info <service>
# Start, stop, or restart an application or Core service # Manage workload or Core service lifecycle (dispatched via homelab-appctl daemon)
appctl up docs appctl up <service|core>
appctl down mongodb appctl down <service|core>
appctl restart traefik appctl restart <service|core>
# Sequential stack update (clean working tree check -> git pull -> compose pull -> up -> sync) # Full stack update (clean tree check -> git pull --ff-only -> compose pull -> recreate -> sync)
appctl update docs appctl update <service|core>
appctl update core
# Recompile Homepage services.yaml from active app.yaml manifests # Recompile Homepage dashboard configuration from discovered app.yaml manifests
appctl sync appctl sync
``` ```
### Testing & Verification ### Host System Management
```bash
# Run the repository test suite (linting + pytest + nix flake check)
./scripts/test
# Run Nix sandbox flake evaluation and checks ```bash
nix flake check # 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
``` ```
--- ---
## 📚 Repository Documentation Index ## Documentation Index
| Document | Description | | Document | Scope |
| :--- | :--- | | :--- | :--- |
| [**Architecture Guide**](docs/architecture.md) | Details system layers, component roles, network isolation, and security controls. | | [**`docs/architecture.md`**](docs/architecture.md) | Runtime layers, network segmentation, and Core / `~/Workloads` boundaries. |
| [**Operator Runbook**](docs/operations.md) | Day-to-day administration, updates, maintenance, troubleshooting, and recovery procedures. | | [**`docs/decisions/README.md`**](docs/decisions/README.md) | Architecture Decision Records (MADR 4.0) governing platform evolution. |
| [**Appctl Reference**](docs/appctl.md) | CLI command reference and consumed `app.yaml` manifest fields. | | [**`ROADMAP.md`**](ROADMAP.md) | Phased engineering milestones (P0–P7) and baseline-to-target architecture matrix. |
| [**GitOps Engine**](docs/gitops.md) | Webhook admission pipeline, HMAC authentication, lock serialization, and execution boundaries. | | [**`docs/appctl.md`**](docs/appctl.md) | Current `appctl` CLI commands, resolution hierarchy, and `app.yaml` schema v1.0 contract. |
| [**Secrets & State**](docs/secrets-and-state.md) | SOPS encryption, runtime secret projections, user directory management, and persistent storage. | | [**`docs/gitops.md`**](docs/gitops.md) | Webhook admission pipeline, HMAC verification, Compose AST validation, and locking. |
| [**Setup & Provisioning**](docs/setup_guide.md) | Procedures for provisioning a server host and onboarding workloads. | | [**`docs/secrets-and-state.md`**](docs/secrets-and-state.md) | SOPS secret management, `/run/secrets/` projections, and persistent state paths. |
| [**Security Policy**](SECURITY.md) | Security controls, container isolation policies, and threat model. | | [**`docs/operations.md`**](docs/operations.md) | Day-2 operational runbook, updates, backups, and recovery procedures. |
| [**`docs/setup_guide.md`**](docs/setup_guide.md) | Bare-metal NixOS installation and host bootstrapping guide. |
| [**`SECURITY.md`**](SECURITY.md) | Security controls, Docker socket isolation, and threat model. |
| [**`AGENTS.md`**](AGENTS.md) | Architectural invariants, TDD rules, and verification gates for contributors and agents. |
--- ---
## 🧠 Relationship to Brain Vault ## License
* **Repository Documentation (`~/Core/docs/`)**: Describes *what exists* and *how to operate it*. It serves as the operational manual for the current repository.
* **Brain Vault (`~/Brain/projects/homelab/`)**: Captures *why it was built this way* — preserving architectural decision records (ADRs), historical trade-off discussions, active roadmaps, and deep debugging discoveries.
---
## 📄 License
This repository is released into the public domain under [The Unlicense](UNLICENSE). This repository is released into the public domain under [The Unlicense](UNLICENSE).
+153
View File
@@ -0,0 +1,153 @@
# 🗺️ Canopy — NixOS Core & Appctl Engineering Roadmap
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 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), [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)).
---
## 🎯 Architectural Invariants Governing Execution
1. **Git is the Authoritative Source of Deployment State**: All workload configurations are versioned in Git. `appctl` reconciles desired Git state into running containers.
2. **One Logical API Across Dual Transports (`DEC-01`)**: The control-plane API is a single logical HTTP/1.1 command contract (`POST /v1/operations` + `GET /v1/health`) served identically over Unix domain socket (`/run/homelab/appctl.sock`) and loopback TCP (`127.0.0.1:9001`).
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**: 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.
---
## 🔍 Current Implementation Baseline vs. Target Architecture
| Architectural Area | Current Implementation Baseline (Milestone P4) | Target Architecture (Roadmap v6) |
| :--- | :--- | :--- |
| **`appctl` Architecture** | Dedicated daemon service (`homelab-appctl.service`, user `homelab-appctl`) exposing `POST /v1/operations` over Unix socket and loopback HTTP, with thin-client CLI (`scripts/appctl_cli.py`). | Expand with Operations UI and external ForwardAuth integration (P5–P7). |
| **Operational Auth** | Mandatory SHA-256 Bearer token + 3-role RBAC + UDS `SO_PEERCRED` viewer fallback (`/run/secrets/appctl/tokens.json`). | LLDAP directory RBAC & Authelia ForwardAuth (P5). |
| **Metadata & Schema Engine** | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | Standardized JSON-RPC Model Context Protocol tools over Pydantic v2 schemas (P6). |
| **Deployment Model** | 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). |
---
## 📊 Milestone Overview
| Milestone | Title | Focus Area | Status | Deliverables Summary |
| :--- | :--- | :--- | :--- | :--- |
| **P0** | **Baseline Consolidation** | Git & Architecture | ✅ **Completed** | Synchronized `refactor/appctl-rework` with `main`, recorded control plane ADR, scaffolded v2 metadata engine. |
| **P1** | **Mail Topology Realignment** | Topology & State | ✅ **Completed** | Re-homed Stalwart to the dedicated `smtp.` subdomain; migrated SnappyMail to `~/Sites/snappymail` with zero data loss. |
| **P2** | **GitOps Hardening** | Ingress Security | ✅ **Completed** | Authoritative Core repository registry (`deployments.yaml`), Compose AST security validator, systemd sandboxing. |
| **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0 with Pydantic v2 fail-closed models (`core_manifest.py`), two-axis status inspection, unified `appctl_engine.py`. |
| **P4** | **Control Plane Daemon** | API & Dispatch | ✅ **Completed** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. |
| **P4.5** | **Workloads Contract & Agent Readiness** | Monorepo & Grants | ✅ **Completed** *(in `nixos-core`)* | `~/Workloads/deployments.yaml` decoupling, read-only `agents` SSH user, `homelab.workloadGrants` (`ADR-0005`), `nixos/instance.example.nix`, and `:host` CI runner workflow. |
| **P5** | **Identity & Secrets** | Auth & Providers | 🎯 **Current / Up Next** | LLDAP RBAC group mapping, Authelia ForwardAuth header integration, user-scoped token lifecycle, `SecretProvider` reference resolution. |
| **P6** | **Homelab MCP Gateway** | Protocol Integration | ⏳ **Planned** | Standardized JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`), client-side human-in-the-loop approvals, deprecation of on-server AI proposal compilers. |
| **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. |
---
## 🛠️ Detailed Milestones
### Milestone P0: Baseline Consolidation
**Status**: ✅ **Completed**
* Merged `refactor/appctl-rework` and `main` into a unified architectural baseline (commit `2297cd5`).
* Modernized metadata engine with strongly-typed models (`SitesApp`, `CoreService`, `SourceConfig`) and Docker status inspection.
* Formalized the control-plane ADR and consolidated roadmap; marked legacy roadmaps as superseded.
* Verified test suite and NixOS flake sandbox evaluation.
---
### Milestone P1: Mail Topology Realignment & Zero-Data-Loss Migration
**Status**: ✅ **Completed**
* **Objective**: Segregate platform mail routing from user-facing webmail while preserving all user data and settings.
* **Key Deliverables**:
1. *State Freeze & Verified Snapshot*: Generate timestamped, SHA256-verified backup archive of `Core/config/snappymail/data`.
2. *Workload Provisioning*: Scaffold `~/Sites/snappymail/` (Class B Image-Only workload) and provision persistent state root at `~/var/lib/homelab/snappymail/`.
3. *Zero-Data-Loss State Replication*: Copy data using `cp -a` and prove byte parity (`diff -r`).
4. *Stalwart Re-homing*: Updated Stalwart public endpoint in `Core/docker-compose.yml` to the configured `smtp.<domain>` subdomain; removed SnappyMail from Core stack.
5. *Live Verification*: Verified webmail at the configured `mail.<domain>` endpoint, user logins, address books, IMAP/SMTP routing, and Diun SMTPS delivery on port 465.
* **Exit Criteria**: 100% of user data survives cutover; mail flow and Diun alert delivery confirmed.
---
### Milestone P2: GitOps Privilege & Authority Hardening
**Status**: ✅ **Completed**
* **Objective**: Close remaining trust boundaries in the webhook continuous deployment engine.
* **Key Deliverables**:
1. *Authoritative Core Registry*: Establish `Core/config/deployments.yaml` as the sole authority for admitted deployment repositories.
2. *Decouple Data Vault from Workload GitOps*: Evict vault special-casing (`BRAIN_DIR`) from GitOps engine; continuous deployment strictly manages Sites container workloads.
3. *Compose AST Security Validator*: Pre-flight parser rejecting `privileged: true`, Docker socket bind mounts, host networking, and host mounts outside workload root or state root.
4. *Systemd Sandboxing*: Apply `ProtectSystem=strict`, `ProtectHome=read-only`, `ReadWritePaths`, `NoNewPrivileges=true`, and private temporary directories to `homelab-gitops.service`.
* **Exit Criteria**: Path traversal rejection tests pass; Compose AST security validator rejects prohibited capabilities.
---
### Milestone P3: Manifest Contract Convergence & Provenance Engine
**Status**: ✅ **Completed**
* **Objective**: Establish a single authoritative manifest schema and two-axis inspection engine across the platform.
* **Key Deliverables**:
1. *Schema v1.0 & Parser Library (`core_manifest.py`)*: Fail-closed Pydantic v2 manifest validation (`ConfigDict(extra="forbid")`), transport scheme validation (`https://`, `ssh://`, `git@`), and explicit ref semantics (moving branches vs. pinned tags vs. commit SHAs).
2. *Two-Axis Inspection*: Local deployment checkout state (`✓ Synced`, `* Dirty`) evaluated independently of upstream software provenance (resolved via `git ls-remote` bounded by a 10s timeout during `--fetch`).
3. *Engine Promotion & Cleanup*: Promoted unified engine to `scripts/appctl_engine.py`, retired `scripts/appctl_engine_v2.py` shim, and achieved zero Pyright static analysis warnings.
* **Exit Criteria**: Manifest validation active in CI; all provenance resolution tests passing.
---
### Milestone P4: Appctl Control Plane Daemon & Command-Oriented API
**Status**: ✅ **Completed**
* **Objective**: Evolve `appctl` from a collection of local shell scripts into the authoritative platform daemon while enforcing authorization gates from day one.
* **Key Deliverables**:
1. *Daemon Service (`homelab-appctl.service`)*: Systemd daemon running as dedicated user `homelab-appctl` (`Group = "homelab-operators"`), exposing one logical HTTP/1.1 API across dual transports: Unix domain socket (`/run/homelab/appctl.sock`) on host and loopback HTTP listener (`127.0.0.1:9001`).
2. *Mandatory Authorization Gate*: Enforce SOPS-projected SHA-256 Bearer tokens (`/run/secrets/appctl/tokens.json`) and 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`) for all mutations, sensitive reads (`workload.config`, `workload.logs`), and HTTP calls; restrict `SO_PEERCRED` on UDS to non-sensitive `homelab-viewer` inspection.
3. *Command-Oriented Operational Router*: Single canonical command endpoint (`POST /v1/operations` + `GET /v1/health`) invoking `core_manifest.py`, `appctl_engine.py`, `validate_compose_security()`, and pure-Python `.env` assembly with per-target `flock` serialization and revision-consistent `workload.update` execution (unifying CLI and `gitops_dispatcher.py` worker execution).
4. *Thin-Client CLI*: Re-implement `scripts/appctl` as a lightweight dispatch client communicating with the local daemon socket.
5. *Append-Only Audit Log*: Record every mutating command, sensitive read, and denied request to `/var/log/homelab/appctl/audit.jsonl` with restricted `0600` permissions (`homelab-appctl`) and a fail-closed pre-execution disk guard. Telemetry captures `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, and `result`.
* **Exit Criteria**: Hermetic API test suite passing; unauthenticated and unauthorized mutation attempts rejected across both transports; audit log capturing multi-dimensional telemetry under `homelab-appctl` isolation.
---
### Milestone P5: Identity, RBAC & SecretProvider Interface
**Status**: ⏳ **Planned**
* **Objective**: Expand the P4 authorization gate with directory-backed RBAC identity providers and dynamic secret projection.
* **Key Deliverables**:
1. *Identity Provider Integration*: Plug Traefik/Authelia trusted headers (`Remote-User`, `Remote-Groups`) for web requests, LLDAP user-scoped API token lifecycle for CLI requests, and HMAC-SHA256 verification for GitOps webhooks into the P4 authorization middleware.
2. *Role-Based Authorization Engine*: Enforce LLDAP group-based access control (`homelab-admin`, `homelab-operator`, `homelab-viewer`).
3. *SecretProvider Interface*: Control plane resolves secret references (`secretKeyRef`) at container runtime, eliminating Git history pollution for workload credentials.
* **Exit Criteria**: RBAC permission matrix verified by automated tests; secret references correctly materialized into runtime environments.
---
### 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. *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.
---
### Milestone P7: Operations UI & Dashboard Integration
**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 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.
---
## 🔒 Verification & Quality Gates
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/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.
+18 -6
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`).
--- ---
@@ -13,8 +13,8 @@ This document outlines the security controls, container isolation rules, and ope
* Traefik and Dozzle query Docker metrics and metadata via `tcp://socket-proxy:2375` rather than direct socket mounts. * Traefik and Dozzle query Docker metrics and metadata via `tcp://socket-proxy:2375` rather than direct socket mounts.
### B. Identity & Access Management (`lldap` & `authelia`) ### B. Identity & Access Management (`lldap` & `authelia`)
* **Directory Service**: User accounts and group memberships are stored in LLDAP (`users.roadtotech.me`). * **Directory Service**: User accounts and group memberships are stored in LLDAP (`users.${HOMELAB_DOMAIN}`).
* **ForwardAuth**: Traefik intercepts incoming HTTP/HTTPS requests and validates sessions with Authelia (`auth.roadtotech.me`) before routing to protected backends. * **ForwardAuth**: Traefik intercepts incoming HTTP/HTTPS requests and validates sessions with Authelia (`auth.${HOMELAB_DOMAIN}`) before routing to protected backends.
* **MFA Support**: Supports TOTP and FIDO2 authentication. * **MFA Support**: Supports TOTP and FIDO2 authentication.
### C. Network Segmentation ### C. Network Segmentation
@@ -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`). * 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. * 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 ## 2. Threat Model & Operational Considerations
@@ -51,9 +60,12 @@ This document outlines the security controls, container isolation rules, and ope
## 3. Verification Checklist ## 3. Verification Checklist
- [x] Secrets encrypted in `nixos/secrets.yaml` via Age / SOPS. - [x] Secrets encrypted in `nixos/secrets.yaml` via Age / SOPS.
- [x] User identities managed in LLDAP (`users.roadtotech.me`). - [x] User identities managed in LLDAP (`users.${HOMELAB_DOMAIN}`).
- [x] `socket-proxy` configured with `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`. - [x] `socket-proxy` configured with `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`.
- [x] Webhook HMAC signature verification active on port 9000. - [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] `config/letsencrypt/acme.json` permissions set to `0600`.
- [x] Host firewall ports restricted to declared services in `nixos/modules/homeserver.nix`. - [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' address: 'ldap://lldap:3890'
timeout: 5s timeout: 5s
start_tls: false start_tls: false
base_dn: 'dc=roadtotech,dc=me' base_dn: '{{ env "LLDAP_LDAP_BASE_DN" }}'
additional_users_dn: 'ou=people' additional_users_dn: 'ou=people'
users_filter: '(&({username_attribute}={input})(objectClass=person))' users_filter: '(&({username_attribute}={input})(objectClass=person))'
additional_groups_dn: 'ou=groups' additional_groups_dn: 'ou=groups'
@@ -24,7 +24,7 @@ authentication_backend:
display_name: 'displayName' display_name: 'displayName'
mail: 'mail' mail: 'mail'
group_name: 'cn' group_name: 'cn'
user: 'uid=admin,ou=people,dc=roadtotech,dc=me' user: 'uid=admin,ou=people,{{ env "LLDAP_LDAP_BASE_DN" }}'
access_control: access_control:
default_policy: deny default_policy: deny
+18
View File
@@ -0,0 +1,18 @@
# Example Repository Identity Registry Template
# Live production deployments are configured in ~/Workloads/deployments.yaml
# (or overridden via the HOMELAB_DEPLOYMENTS_FILE environment variable).
#
# Owns: repository identity, canonical filesystem path, and aliases.
# Enforces: strict path containment within ~/Workloads (WORKLOADS_DIR).
schemaVersion: "1.0"
repositories:
example-app:
path: "~/Workloads/example-app"
aliases:
- "example"
- "homelab-example"
example-docs:
path: "~/Workloads/example-docs"
aliases:
- "docs"
+1 -1
View File
@@ -5,7 +5,7 @@
- My Projects: - My Projects:
- Github: - Github:
- abbr: GH - abbr: GH
href: https://github.com/kiskaadee?tab=repositories href: https://github.com
- Social Media: - Social Media:
- Instagram: - Instagram:
+3 -3
View File
@@ -4,13 +4,13 @@
- Knowledge & Notes: - Knowledge & Notes:
- Docs-Viewer: - Docs-Viewer:
icon: files.png icon: files.png
href: https://docs.roadtotech.me href: https://docs.example.test
description: Reactive Obsidian & Markdown Documentation Viewer description: Reactive Obsidian & Markdown Documentation Viewer
server: my-docker server: my-docker
container: docs container: docs
- Excalidraw: - Excalidraw:
icon: excalidraw.png icon: excalidraw.png
href: https://excalidraw.roadtotech.me href: https://excalidraw.example.test
description: Collaborative Whiteboarding & Sketching Tool description: Collaborative Whiteboarding & Sketching Tool
server: my-docker server: my-docker
container: excalidraw container: excalidraw
@@ -18,7 +18,7 @@
- Media & Productivity: - Media & Productivity:
- Jellyfin: - Jellyfin:
icon: jellyfin.png icon: jellyfin.png
href: https://jellyfin.roadtotech.me href: https://jellyfin.example.test
description: Media Server & Streaming Hub description: Media Server & Streaming Hub
server: my-docker server: my-docker
container: jellyfin container: jellyfin
+18 -34
View File
@@ -3,6 +3,8 @@ services:
image: tecnativa/docker-socket-proxy image: tecnativa/docker-socket-proxy
container_name: socket-proxy container_name: socket-proxy
restart: always restart: always
ports:
- "127.0.0.1:2375:2375"
volumes: volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro - /var/run/docker.sock:/var/run/docker.sock:ro
environment: environment:
@@ -42,7 +44,7 @@ services:
- "80:80" - "80:80"
- "443:443" - "443:443"
environment: environment:
- DYNU_API_KEY=${DYNU_API_KEY} - CF_DNS_API_TOKEN=${CF_DNS_API_TOKEN}
- DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40} - DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40}
command: command:
- "--log.level=INFO" - "--log.level=INFO"
@@ -59,7 +61,7 @@ services:
- "--entrypoints.websecure.http.tls.domains[0].sans=*.${DOMAIN}" - "--entrypoints.websecure.http.tls.domains[0].sans=*.${DOMAIN}"
# SSL Setup # SSL Setup
- "--certificatesresolvers.myresolver.acme.dnschallenge=true" - "--certificatesresolvers.myresolver.acme.dnschallenge=true"
- "--certificatesresolvers.myresolver.acme.dnschallenge.provider=dynu" - "--certificatesresolvers.myresolver.acme.dnschallenge.provider=cloudflare"
- "--certificatesresolvers.myresolver.acme.email=${ACME_EMAIL}" - "--certificatesresolvers.myresolver.acme.email=${ACME_EMAIL}"
- "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json" - "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"
volumes: volumes:
@@ -79,6 +81,11 @@ services:
- "traefik.http.middlewares.authelia-auth.forwardauth.trustForwardHeader=true" - "traefik.http.middlewares.authelia-auth.forwardauth.trustForwardHeader=true"
- "traefik.http.middlewares.authelia-auth.forwardauth.authResponseHeaders=Remote-User,Remote-Groups,Remote-Email,Remote-Name" - "traefik.http.middlewares.authelia-auth.forwardauth.authResponseHeaders=Remote-User,Remote-Groups,Remote-Email,Remote-Name"
# Middleware: Public Rate Limit (mitigates scraper/crawler bursts on public routes)
- "traefik.http.middlewares.public-ratelimit.ratelimit.average=20"
- "traefik.http.middlewares.public-ratelimit.ratelimit.burst=40"
- "traefik.http.middlewares.public-ratelimit.ratelimit.period=1s"
# Dashboard - Public (HTTPS) # Dashboard - Public (HTTPS)
- "traefik.http.routers.traefik-dash.rule=Host(`traefik.${DOMAIN}`)" - "traefik.http.routers.traefik-dash.rule=Host(`traefik.${DOMAIN}`)"
- "traefik.http.routers.traefik-dash.entrypoints=websecure" - "traefik.http.routers.traefik-dash.entrypoints=websecure"
@@ -106,11 +113,11 @@ services:
environment: environment:
- TZ=America/Bogota - TZ=America/Bogota
- LLDAP_HTTP_URL=https://users.${DOMAIN} - LLDAP_HTTP_URL=https://users.${DOMAIN}
- LLDAP_LDAP_BASE_DN=dc=roadtotech,dc=me - LLDAP_LDAP_BASE_DN=${LLDAP_LDAP_BASE_DN:-dc=example,dc=test}
- LLDAP_JWT_SECRET=${LLDAP_JWT_SECRET} - LLDAP_JWT_SECRET=${LLDAP_JWT_SECRET}
- LLDAP_KEY_SEED=${LLDAP_KEY_SEED} - LLDAP_KEY_SEED=${LLDAP_KEY_SEED}
- LLDAP_LDAP_USER_PASS=${LLDAP_LDAP_USER_PASS} - LLDAP_LDAP_USER_PASS=${LLDAP_LDAP_USER_PASS}
- LLDAP_LDAP_USER_EMAIL=admin@${DOMAIN:-roadtotech.me} - LLDAP_LDAP_USER_EMAIL=${LLDAP_ADMIN_EMAIL:-admin@${DOMAIN:-example.test}}
- LLDAP_DATABASE_URL=sqlite:///data/users.db?mode=rwc - LLDAP_DATABASE_URL=sqlite:///data/users.db?mode=rwc
volumes: volumes:
- ./config/lldap/data:/data - ./config/lldap/data:/data
@@ -142,6 +149,7 @@ services:
- ./config/authelia:/config - ./config/authelia:/config
environment: environment:
- DOMAIN=${DOMAIN} - DOMAIN=${DOMAIN}
- LLDAP_LDAP_BASE_DN=${LLDAP_LDAP_BASE_DN}
- AUTHELIA_SESSION_SECRET=${AUTHELIA_SESSION_SECRET} - AUTHELIA_SESSION_SECRET=${AUTHELIA_SESSION_SECRET}
- AUTHELIA_STORAGE_ENCRYPTION_KEY=${AUTHELIA_STORAGE_ENCRYPTION_KEY} - AUTHELIA_STORAGE_ENCRYPTION_KEY=${AUTHELIA_STORAGE_ENCRYPTION_KEY}
- AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET=${AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET} - AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET=${AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET}
@@ -222,12 +230,12 @@ services:
- DIUN_PROVIDERS_DOCKER_APIVERSION=${DOCKER_API_VERSION:-1.40} - DIUN_PROVIDERS_DOCKER_APIVERSION=${DOCKER_API_VERSION:-1.40}
- DIUN_NOTIF_MAIL_HOST=stalwart - DIUN_NOTIF_MAIL_HOST=stalwart
- DIUN_NOTIF_MAIL_PORT=465 - DIUN_NOTIF_MAIL_PORT=465
- DIUN_NOTIF_MAIL_USERNAME=notifier@${DOMAIN:-roadtotech.me} - DIUN_NOTIF_MAIL_USERNAME=${DIUN_NOTIF_MAIL_USERNAME:-notifier@${DOMAIN:-example.test}}
- DIUN_NOTIF_MAIL_PASSWORD=${DIUN_SMTP_PASSWORD} - DIUN_NOTIF_MAIL_PASSWORD=${DIUN_SMTP_PASSWORD}
- DIUN_NOTIF_MAIL_SSL=true - DIUN_NOTIF_MAIL_SSL=true
- DIUN_NOTIF_MAIL_INSECURESKIPVERIFY=true - DIUN_NOTIF_MAIL_INSECURESKIPVERIFY=true
- DIUN_NOTIF_MAIL_FROM=notifier@${DOMAIN:-roadtotech.me} - DIUN_NOTIF_MAIL_FROM=${DIUN_NOTIF_MAIL_FROM:-notifier@${DOMAIN:-example.test}}
- DIUN_NOTIF_MAIL_TO=kiskaadee@${DOMAIN:-roadtotech.me} - DIUN_NOTIF_MAIL_TO=${DIUN_NOTIF_MAIL_TO:-operator@${DOMAIN:-example.test}}
volumes: volumes:
- ./config/diun:/data - ./config/diun:/data
networks: networks:
@@ -251,49 +259,25 @@ services:
- ./config/stalwart/data:/var/lib/stalwart - ./config/stalwart/data:/var/lib/stalwart
environment: environment:
- DOMAIN=${DOMAIN} - DOMAIN=${DOMAIN}
- STALWART_PUBLIC_URL=https://mail.${DOMAIN} - STALWART_PUBLIC_URL=https://smtp.${DOMAIN}
- STALWART_RECOVERY_ADMIN=admin:${LLDAP_LDAP_USER_PASS} - STALWART_RECOVERY_ADMIN=admin:${LLDAP_LDAP_USER_PASS}
networks: networks:
- proxy-net - proxy-net
labels: labels:
- "traefik.enable=true" - "traefik.enable=true"
# HTTPS WebAdmin & JMAP Router # HTTPS WebAdmin & JMAP Router
- "traefik.http.routers.stalwart.rule=Host(`mail.${DOMAIN}`)" - "traefik.http.routers.stalwart.rule=Host(`smtp.${DOMAIN}`)"
- "traefik.http.routers.stalwart.entrypoints=websecure" - "traefik.http.routers.stalwart.entrypoints=websecure"
- "traefik.http.routers.stalwart.tls=true" - "traefik.http.routers.stalwart.tls=true"
- "traefik.http.routers.stalwart.tls.certresolver=myresolver" - "traefik.http.routers.stalwart.tls.certresolver=myresolver"
- "traefik.http.routers.stalwart.service=stalwart-svc" - "traefik.http.routers.stalwart.service=stalwart-svc"
# HTTP -> HTTPS Redirect # HTTP -> HTTPS Redirect
- "traefik.http.routers.stalwart-red.rule=Host(`mail.${DOMAIN}`)" - "traefik.http.routers.stalwart-red.rule=Host(`smtp.${DOMAIN}`)"
- "traefik.http.routers.stalwart-red.entrypoints=web" - "traefik.http.routers.stalwart-red.entrypoints=web"
- "traefik.http.routers.stalwart-red.middlewares=https-redirect@docker" - "traefik.http.routers.stalwart-red.middlewares=https-redirect@docker"
# Forward to Stalwart's internal HTTP/WebAdmin port # Forward to Stalwart's internal HTTP/WebAdmin port
- "traefik.http.services.stalwart-svc.loadbalancer.server.port=8080" - "traefik.http.services.stalwart-svc.loadbalancer.server.port=8080"
snappymail:
image: ghcr.io/the-djmaze/snappymail:latest
container_name: snappymail
restart: always
depends_on:
- stalwart
volumes:
- ./config/snappymail/data:/var/lib/snappymail/_data_
networks:
- proxy-net
labels:
- "traefik.enable=true"
# Public (HTTPS)
- "traefik.http.routers.webmail.rule=Host(`webmail.${DOMAIN}`)"
- "traefik.http.routers.webmail.entrypoints=websecure"
- "traefik.http.routers.webmail.tls=true"
- "traefik.http.routers.webmail.tls.certresolver=myresolver"
- "traefik.http.routers.webmail.service=webmail-svc"
# Public (Redirect)
- "traefik.http.routers.webmail-red.rule=Host(`webmail.${DOMAIN}`)"
- "traefik.http.routers.webmail-red.entrypoints=web"
- "traefik.http.routers.webmail-red.middlewares=https-redirect@docker"
- "traefik.http.services.webmail-svc.loadbalancer.server.port=8888"
homepage: homepage:
image: ghcr.io/gethomepage/homepage:latest image: ghcr.io/gethomepage/homepage:latest
container_name: homepage container_name: homepage
+215 -95
View File
@@ -2,45 +2,143 @@
The `appctl` tool is the command-line orchestrator and metadata engine for the **Homelab Core** platform. It coordinates interactions between independent workload repositories in `~/Sites` and platform services in `~/Core`. The `appctl` tool is the command-line orchestrator and metadata engine for the **Homelab Core** platform. It coordinates interactions between independent workload repositories in `~/Sites` and platform services in `~/Core`.
> [!NOTE]
> **Implementation Reference**: This document serves as the **current implementation manual (Milestone P4)** for the `appctl` Operational Control Plane Daemon (`scripts/appctl_daemon.py`), Operational Router (`scripts/appctl_router.py`), Thin-Client CLI (`scripts/appctl`, `scripts/appctl_cli.py`), metadata/provenance engine (`scripts/appctl_engine.py`), and Pydantic v2 manifest parser (`scripts/core_manifest.py`).
> For the platform's phased engineering roadmap, see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md).
--- ---
## 1. How `appctl` Works ## 1. How `appctl` Works
`appctl` consists of two cooperating scripts: Under Milestone P4, `appctl` operates as a centralized operational control plane daemon (`homelab-appctl.service`, running as isolated user `homelab-appctl:homelab-operators`) backed by cooperating modules in `scripts/`:
1. **`scripts/appctl`** (Bash CLI wrapper): Handles command-line arguments, sources secret environment templates, dispatches `docker compose` commands, and provides shell autocompletions.
2. **`scripts/appctl_engine.py`** (Python metadata engine): Scans directories in `~/Sites`, parses `app.yaml` manifests, computes Git synchronization status against remotes, queries SSL/TLS certificate validity, and compiles the Homepage dashboard configuration.
1. **[`scripts/appctl`](../scripts/appctl) & [`scripts/appctl_cli.py`](../scripts/appctl_cli.py)** (Thin-Client CLI): Dispatches operational commands over the Unix domain socket (`/run/homelab/appctl.sock`) using HTTP/1.1 (`POST /v1/operations`), resolves operator Bearer tokens (`--token`, `APPCTL_TOKEN`, `~/.config/homelab/token`), renders human-readable tables, and fast-paths local shell autocompletions (`complete`, `completion`, `resolve`).
2. **[`scripts/appctl_daemon.py`](../scripts/appctl_daemon.py) & [`scripts/appctl_contracts.py`](../scripts/appctl_contracts.py)** (Dual-Transport Control Plane Server & Contracts): Serves a single logical HTTP/1.1 API (`POST /v1/operations` + `GET /v1/health`) identically across `/run/homelab/appctl.sock` (mode `0660`) and loopback TCP (`127.0.0.1:9001`), enforcing 64 KiB request caps and strict Pydantic v2 contracts (`ConfigDict(extra="forbid", strict=True)`).
3. **[`scripts/appctl_auth.py`](../scripts/appctl_auth.py) & [`scripts/appctl_audit.py`](../scripts/appctl_audit.py)** (Zero-Trust Auth, 3-Role RBAC & Fail-Closed Audit Guard): Verifies SHA-256 Bearer tokens against `/run/secrets/appctl/tokens.json` (mode `0400`) using `hmac.compare_digest`, maps tokenless local UDS `SO_PEERCRED` callers strictly to `homelab-viewer` (non-sensitive read-only inspection), enforces `homelab-admin` / `homelab-operator` / `homelab-viewer` RBAC, serializes mutations via per-target `fcntl.flock`, and writes append-only audit records to `/var/log/homelab/appctl/audit.jsonl` (mode `0600`) before any mutation executes.
4. **[`scripts/appctl_router.py`](../scripts/appctl_router.py)** (Operational Router & Unified Execution Engine): Enforces pre-flight path containment, `core_manifest.parse_manifest()`, and `validate_compose_security()` AST checks; assembles the 6-layer execution environment in pure Python (zero shell `source` or `eval`); and runs bounded `git` and `docker compose` subprocesses (`shell=False`, 256 KiB output cap, hard timeouts).
5. **[`scripts/appctl_engine.py`](../scripts/appctl_engine.py) & [`scripts/core_manifest.py`](../scripts/core_manifest.py)** (Discovery, Provenance & Schema v1.0 Validator): Scans `~/Sites/*`, evaluates **two-axis status** (local deployment checkout state vs. upstream software provenance), inspects live container health and TLS certificates, validates `app.yaml` manifests, and atomically compiles the Homepage dashboard configuration under `_homepage_sync.lock`.
```text
┌──────────────────────────┐ ┌──────────────────────────┐
│ appctl <cmd> (CLI) │ │ homelab-gitops.service │
└────────────┬─────────────┘ └────────────┬─────────────┘
│ UDS (/run/homelab/appctl.sock) │ Bearer Token (homelab-operator)
└─────────────────┬─────────────────┘
▼
┌────────────────────────────────────────────────┐
│ homelab-appctl.service (appctl_daemon.py) │
│ • POST /v1/operations & GET /v1/health │
│ • Auth: SHA-256 tokens.json + SO_PEERCRED │
│ • RBAC: admin / operator / viewer │
└────────────────────────┬───────────────────────┘
▼
┌────────────────────────────────────────────────┐
│ OperationalRouter (appctl_router.py) │
│ • Per-target flock + Fail-closed DISPATCHED │
│ audit write (/var/log/homelab/appctl/...) │
│ • Pre-flight: parse_manifest() + Compose AST │
│ • Pure-Python 6-layer .env assembly │
└────────────────────────┬───────────────────────┘
▼
┌────────────────────────────────────────────────┐
│ Bounded Subprocess Engine (shell=False) │
│ • git status / pull --ff-only │
│ • docker compose -f <file> <subcommand> │
└────────────────────────────────────────────────┘
``` ```
┌───────────────────────────────┐
│ appctl <command> │ ### 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.
│ setup_app_env() │
└─────────────┬─────────────┘ #### 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`
[ appctl_engine.py resolve ] [ Source Secrets ] 3. Local operator token file: `~/.config/homelab/token` (mode `0600`)
Resolves aliases, domain, /run/secrets/traefik-deployments.env 4. System service token file: `/run/secrets/appctl/token`
and manifest parameters /run/secrets/homeserver.env
│ │ 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:
│ Injected Compose Context │
│ • PROXY_NETWORK │ ```bash
│ • SERVICE_DOMAIN / DOMAIN │ python3 scripts/bootstrap_token.py
│ • CONTAINER_NAME │
│ • Custom manifest env │
└──────────────┬──────────────┘
▼
┌─────────────────────────────┐
│ docker compose <subcommand> │
└─────────────────────────────┘
``` ```
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 ## 2. CLI Command Reference
@@ -48,26 +146,27 @@ and manifest parameters /run/secrets/homeserver.en
### Status & Inspection ### Status & Inspection
#### `appctl list` / `appctl status` #### `appctl list` / `appctl status`
Lists applications discovered in `~/Sites` with container status, Git synchronization badge, routed domain, and filesystem path. Lists applications discovered in `~/Sites` using **two-axis inspection**:
- **`DEPLOYMENT` (Axis 1 — Local Checkout)**: Inspects the local `~/Sites/<app>` Git working tree (`✓ Synced`, `* Dirty`, `⬇ Behind`, `⚠️ Non-Git`).
- **`PROVENANCE` (Axis 2 — Upstream Software)**: Evaluates upstream software provenance for Class A (Source-Backed) vs. Class B (`— Image-Only`) workloads.
**Options**: **Options**:
* `--fetch` (`-f`): Runs `git fetch --quiet` across repositories before computing sync badges. * `--fetch` (`-f`): Queries upstream Git remotes (`git ls-remote` with a 10s timeout) and fetches local deployment tracking branches before computing provenance badges.
* `--core` (`-c`): Includes Core infrastructure services (`traefik`, `authelia`, `lldap`, `stalwart`, etc.) in the output. * `--core` (`-c` / `--all` / `-a`): Appends Core infrastructure services (`traefik`, `authelia`, `lldap`, `stalwart`, `homepage`, `dozzle`, `watchtower`) to the output.
* `--ssl` (`-s`): Queries SSL/TLS certificates for each domain and displays status and expiration days. * `--ssl` (`-s`): Queries SSL/TLS certificates over port 443 for each public domain and appends a `CERT` column.
* `--all` (`-a`): Equivalent to `--core`.
**Example Output**: **Example Output**:
```text ```text
SERVICE STATUS GIT SYNC DOMAIN DIRECTORY SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN
------- ------ -------- ------ --------- ------- ---------- ---------- ------ ------
docs 🟢 Running (1) ✓ Synced docs.roadtotech.me ~/Sites/homelab-docs docs ✓ Synced (main) ✓ Synced 🟢 Running (1) docs.example.com
jellyfin 🟢 Running (1) ✓ Synced jellyfin.roadtotech.me ~/Sites/homelab-jellyfin jellyfin ✓ Synced (main) — Image-Only 🟢 Running (1) jellyfin.example.com
gitea 🟢 Running (2) ⬇ 1 Behind gitea.roadtotech.me ~/Sites/homelab-gitea gitea ✓ Synced (main) ⬆ Update Available 🟢 Running (2) gitea.example.com
mongodb 🔴 Stopped ✓ Synced * mongodb.roadtotech.me ~/Sites/homelab-mongodb mongodb * Dirty (1) (main) — Image-Only 🔴 Stopped mongodb.example.com
``` ```
#### `appctl ssl [service]` #### `appctl ssl [service]`
Inspects SSL/TLS certificates over port 443. If a service is specified, shows detailed issuer, subject, and expiration data; otherwise, inspects all homelab domains. Inspects SSL/TLS certificates over port 443. If a service is specified, shows detailed issuer, subject, and expiration data; otherwise, inspects all non-internal homelab domains.
```bash ```bash
# Check all domains # Check all domains
@@ -77,14 +176,13 @@ appctl ssl
appctl ssl jellyfin appctl ssl jellyfin
``` ```
#### `appctl info <service>` #### `appctl info <service> [--ssl]`
Displays diagnostic information for a workload or Core service: Displays comprehensive two-axis diagnostics for a workload or Core service:
* Canonical name, directory, and aliases. * Canonical name, directory path, aliases, and workload class (`Class A (Source-Backed)` vs. `Class B (Image-Only)`).
* Docker container running status. * Primary routed domain, networks, and Authelia guard status.
* Primary routed domain and Authelia guard status. * **Axis 1 (Local Deployment Checkout)**: Branch, commit hash, dirty file count, and sync status.
* Git tracking details: branch, upstream remote, uncommitted file count. * **Axis 2 (Upstream Software Provenance)**: Upstream Git URL, tracked ref (`branch`, `tag`, or `commit`), resolved remote commit, and running container OCI revision label.
* Injected environment variable defaults. * Injected environment variable defaults and Homepage card metadata.
* Homepage card configuration.
* SSL certificate details (when `--ssl` is passed). * SSL certificate details (when `--ssl` is passed).
```bash ```bash
@@ -95,58 +193,73 @@ appctl info docs --ssl
### Lifecycle Management ### Lifecycle Management
#### `appctl up <service|core>` #### `appctl up <service|core> [--build] [--no-cache]`
Starts the specified service stack in detached mode (`--remove-orphans`). Starts the specified service stack in detached mode (`--remove-orphans`).
* For a workload in `~/Sites`: starts containers and calls `appctl sync`. * 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 `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. * 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>` #### `appctl down <service|core>`
Stops and removes containers defined in the target's Compose file. Stops and removes containers defined in the target's Compose file (or stops the targeted Core container).
#### `appctl restart <service|core>` #### `appctl restart <service|core>`
Restarts the target stack or individual container. Restarts the target stack or individual container:
* `appctl restart docs`: Restarts the docs workload. * `appctl restart docs`: Recreates the `docs` workload stack and syncs Homepage.
* `appctl restart core`: Restarts all Core Compose services. * `appctl restart core`: Restarts all Core Compose services.
* `appctl restart traefik`: Restarts only the Traefik container. * `appctl restart traefik`: Restarts only the Traefik container.
#### `appctl update <service|core>` #### `appctl update <service> [--branch <branch>] [--build] [--no-cache]`
Performs a sequential update workflow: Performs a sequential, revision-consistent update workflow for a Sites workload stack:
1. Checks that the local git working tree is clean (aborts if uncommitted changes exist). 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. 2. Runs `git pull --ff-only [origin <expected_branch>]` to fast-forward the current branch.
3. Runs `docker compose pull` to fetch updated container images. 3. Re-validates `app.yaml`, expected branch declaration, and Compose security rules against the newly pulled working tree.
4. Runs `docker compose up -d --remove-orphans` to recreate containers. 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. 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>` #### `appctl pull <service|core>`
Pulls latest container images and recreates the target service. Pulls latest container images and recreates the target service.
#### `appctl logs <service|core>` #### `appctl logs <service|core> [--tail N]`
Streams container logs (`docker compose logs -f`). Fetches a bounded snapshot of container logs (default: `--tail 100`). Supports passing a workload or targeted Core service container (e.g., `appctl logs traefik`).
* Supports passing container names: `appctl logs core traefik` or `appctl logs stalwart`. *(Note: As an HTTP/1.1 request-response API, log streaming `-f` is replaced by bounded snapshots).*
#### `appctl config <service|core>` #### `appctl config <service|core>`
Renders the resolved Docker Compose configuration with all injected variables. Validates the manifest and renders the resolved Docker Compose configuration with all injected variables. Fails closed if `app.yaml` is missing or invalid.
#### `appctl sync` #### `appctl sync`
Scans all `~/Sites/*/app.yaml` manifests and re-generates `config/homepage/services.yaml`. Scans all valid `~/Sites/*/app.yaml` manifests and compiles `config/homepage/services.yaml`.
#### `appctl completion [bash]` #### `appctl completion [bash]`
Outputs the bash autocompletion script. Outputs the bash autocompletion script.
--- ---
## 3. `app.yaml` Fields Consumed by `appctl` and GitOps ## 3. `app.yaml` Schema v1.0 Contract
`app.yaml` files in `~/Sites` are read by `appctl_engine.py` and `gitops_dispatcher.py` for the following fields: Workload manifests in `~/Sites/<app>/app.yaml` are validated by [`scripts/core_manifest.py`](../scripts/core_manifest.py) using strict Pydantic v2 models (`extra="forbid"`). Any unknown field, invalid transport URL, or prohibited deployment action causes validation to fail closed.
```yaml ```yaml
schema_version: "1.0" # Schema version (only "1.0" is supported)
# ── Identity & Routing ──────────────────────────────────────────────────────── # ── Identity & Routing ────────────────────────────────────────────────────────
name: "jellyfin" # Canonical service name (defaults to folder name minus homelab-) name: "jellyfin" # Canonical name: ^[a-zA-Z0-9][a-zA-Z0-9._-]*$
aliases: # Alternate CLI aliases aliases: # Optional CLI aliases
- "media" - "media"
- "movies" - "movies"
domain: "jellyfin.roadtotech.me" # Primary routed domain (defaults to <name>.roadtotech.me) domain: "jellyfin.example.com" # Primary routed domain (defaults to <name>.${HOMELAB_DOMAIN})
description: "Media Streaming Server" description: "Media Streaming Server"
# ── Platform Integration ────────────────────────────────────────────────────── # ── Platform Integration ──────────────────────────────────────────────────────
@@ -155,58 +268,65 @@ auth: false # Authelia ForwardAuth protection (default:
networks: # Docker networks to join (default: [proxy-net]) networks: # Docker networks to join (default: [proxy-net])
- proxy-net - proxy-net
# ── Upstream Software Provenance (Optional: Defines Class A vs. Class B) ─────
# Omit 'source' for Class B (Image-Only third-party workloads).
# Include 'source' for Class A (Source-Backed workloads):
source:
url: "https://github.com/example/jellyfin-app.git" # Strictly https://, ssh://, or git@host:path
ref: "main" # Branch, v* tag, or 40-char commit SHA
# ── Injected Environment Defaults ───────────────────────────────────────────── # ── Injected Environment Defaults ─────────────────────────────────────────────
# Injected into the Compose environment when appctl commands run # Keys must match ^[a-zA-Z_][a-zA-Z0-9_]*$ and cannot override reserved host keys
# (PATH, LD_PRELOAD, IFS, SHELL, USER, HOME, CORE_DIR, SITES_DIR, etc.)
env: env:
MEDIA_PATH: "/media" MEDIA_PATH: "/media"
JELLYFIN_TZ: "UTC" JELLYFIN_TZ: "UTC"
JELLYFIN_PUID: "1000"
JELLYFIN_PGID: "1000"
# ── GitOps Deployment Policy ────────────────────────────────────────────────── # ── GitOps Deployment Policy ──────────────────────────────────────────────────
# Evaluated by scripts/gitops_dispatcher.py upon webhook reception # Evaluated by scripts/gitops_dispatcher.py upon webhook admission
deployment: deployment:
branch: "main" # Target branch that triggers deployment branch: "main" # Target branch that triggers deployment
strategy: "compose" # Deployment strategy (only 'compose' is permitted) strategy: "compose" # Only 'compose' strategy is permitted
actions: # Strictly allowlisted actions actions: # Strictly allowlisted: git_pull, compose_pull,
- git_pull - git_pull # compose_up, compose_build, compose_restart
- compose_up - compose_up
# ── Homepage Dashboard Metadata ─────────────────────────────────────────────── # ── Homepage Dashboard Metadata ───────────────────────────────────────────────
homepage: homepage:
title: "Jellyfin" # Card title title: "Jellyfin" # Card title
group: "Media & Productivity" # Group name group: "Media & Productivity" # Dashboard group name
icon: "jellyfin.png" # Icon name (matched against config/homepage/icons/) icon: "jellyfin.png" # Icon name (matched against config/homepage/icons/)
container: "jellyfin" # Container name for live status widget container: "jellyfin" # Container name for live status widget
weight: 10 # Card sort weight weight: 10 # Card sort weight (lower sorts first)
``` ```
--- ---
## 4. Environment Injection & Resolution Precedence ## 4. Environment Injection & Resolution Precedence
When `appctl` executes commands against a workload, environment variables are resolved in this sequence: When `OperationalRouter` (`scripts/appctl_router.py`) executes commands against a workload or Core stack, the 6-layer execution environment is assembled in memory using a pure-Python inert `KEY=VALUE` parser (`parse_dotenv`) with zero shell `source` or variable expansion:
1. **Global Secrets & Templates**: Sourced from `/run/secrets/homeserver.env` and `/run/secrets/traefik-deployments.env` (or `/run/secrets/rendered/*` fallbacks). 1. **Base System Path & Docker Config**: `PATH` and `DOCKER_CONFIG`.
2. **Infrastructure Defaults**: 2. **Global Secrets & Templates**: Parsed inertly from `/run/secrets/rendered/homeserver.env` and `/run/secrets/rendered/traefik-deployments.env` (with `/run/secrets/*` fallbacks).
3. **Canonical Root Domain Lock**: `HOMELAB_DOMAIN` is locked using precedence `HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN` (failing closed if unset).
4. **Infrastructure Defaults & Application Identity**:
- `PROXY_NETWORK` (defaults to `proxy-net`) - `PROXY_NETWORK` (defaults to `proxy-net`)
- `CERT_RESOLVER` (defaults to `myresolver`) - `CERT_RESOLVER` (defaults to `myresolver`)
- `DOMAIN_SUFFIX` (defaults to `roadtotech.me`) - `DOMAIN_SUFFIX` (`$HOMELAB_DOMAIN`)
3. **Application Identity**:
- `SERVICE_NAME` = `<canonical-name>` - `SERVICE_NAME` = `<canonical-name>`
- `CONTAINER_NAME` = `<canonical-name>` - `CONTAINER_NAME` = `<canonical-name>`
- `SERVICE_DOMAIN` = `<resolved-domain>` - `SERVICE_DOMAIN` = `<canonical-name>.<HOMELAB_DOMAIN>`
- `DOMAIN` = `<resolved-domain>` - `DOMAIN` = `<HOMELAB_DOMAIN>`
4. **Manifest Variables**: Declared under the `env:` block in `app.yaml`. 5. **Manifest Variables**: Validated key-value pairs from the `env:` block in `app.yaml`.
5. **Local Repository Files**: Sourced from `$APP_DIR/.env` and `$APP_DIR/app.env` if present. 6. **Local Repository Files**: Parsed inertly from `$APP_DIR/.env` and `$APP_DIR/app.env` if present, rejecting any key violating `ENV_KEY_RE` or matching `RESERVED_ENV_KEYS`.
--- ---
## 5. Homepage Dashboard Compilation ## 5. Homepage Dashboard Compilation
When `appctl sync` runs: When `appctl sync` runs:
1. `appctl_engine.py` reads all `~/Sites/*/app.yaml` files. 1. `appctl_engine.py` scans all `~/Sites/*/app.yaml` manifests (skipping any workload with a `manifest_error`).
2. Core services (`traefik`, `authelia`, `lldap`, `stalwart`, `snappymail`, `dozzle`) are assigned to `Core Infrastructure`. 2. Core services (`traefik`, `authelia`, `lldap`, `stalwart`, `homepage`, `dozzle`, `watchtower`) are assigned to `Core Infrastructure`.
3. Workload applications with `visible: true` are grouped by their `homepage.group` (ordered: `Core Infrastructure`, `Knowledge & Notes`, `Media & Productivity`, `Development & AI`, `Applications`). 3. Workload applications with `visible: true` are grouped by their `homepage.group` (ordered: `Core Infrastructure`, `Knowledge & Notes`, `Media & Productivity`, `Development & AI`, `Applications`) and sorted by `(weight, title)`.
4. Custom icons matching files in `config/homepage/icons/` (SVG or PNG) are mapped to `/icons/<name>`. 4. Custom icons matching files in `config/homepage/icons/` (`.svg` or `.png`) are mapped to `/icons/<name>`.
5. The compiled configuration is written to `config/homepage/services.yaml`. 5. The compiled configuration is written to `config/homepage/services.yaml`.
+38 -33
View File
@@ -1,6 +1,10 @@
# 🏛️ Homelab Core — Architecture & System Design # 🏛️ Homelab Core — Architecture & System Design
This document details the architectural structure, component roles, networking models, and security controls of the **Homelab Core** platform for `roadtotech.me`. This document details the architectural structure, component roles, networking models, and security controls of the **Homelab Core** platform.
> [!NOTE]
> **Implementation Scope**: This document details the **current runtime architecture (Milestone P4)**, operational control plane daemon (`homelab-appctl.service`), edge routing, container topologies, and network isolation models of Homelab Core.
> For phased engineering milestones (P5–P7), see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md).
--- ---
@@ -10,12 +14,12 @@ To understand how the system is organized, three architectural dimensions are di
### A. Ownership Boundary ### A. Ownership Boundary
* **Core (`~/Core`) owns**: NixOS host configuration, shared platform services, edge ingress, identity boundaries, secrets distribution, and deployment orchestration mechanics. * **Core (`~/Core`) owns**: NixOS host configuration, shared platform services, edge ingress, identity boundaries, secrets distribution, and deployment orchestration mechanics.
* **Workload Plane (`~/Sites`) owns**: Independent application codebases, application-specific Docker Compose files, application-specific `app.yaml` metadata, and application data/state. * **Workload Plane (`~/Workloads`) owns**: Independent application deployments, workload-specific Docker Compose files, declarative `app.yaml` manifests, `~/Workloads/deployments.yaml`, and workload-scoped runtime state (`~/var/lib/homelab/<app>/`).
### B. Four Runtime Layers ### B. Four Runtime Layers
The runtime environment consists of four functional layers: The runtime environment consists of four functional layers:
``` ```text
┌────────────────────────────────────────────────────────────────────────┐ ┌────────────────────────────────────────────────────────────────────────┐
│ 1. EDGE GATEWAY & INGRESS │ │ 1. EDGE GATEWAY & INGRESS │
│ Traefik (v3.6) · Let's Encrypt Wildcard TLS · Dynu DNS-01 Provider │ │ Traefik (v3.6) · Let's Encrypt Wildcard TLS · Dynu DNS-01 Provider │
@@ -24,30 +28,31 @@ The runtime environment consists of four functional layers:
▼ ▼
┌────────────────────────────────────────────────────────────────────────┐ ┌────────────────────────────────────────────────────────────────────────┐
│ 2. CONTROL & PLATFORM SERVICES (Core Compose Stack) │ │ 2. CONTROL & PLATFORM SERVICES (Core Compose Stack) │
│ Authelia SSO · LLDAP Directory · Stalwart Mail · SnappyMail │ │ Authelia SSO · LLDAP Directory · Stalwart Mail Server │
│ Homepage Dashboard · Dozzle · Watchtower · Diun │ │ Homepage Dashboard · Dozzle · Watchtower · Diun │
│ socket-proxy (Read-Only Docker API Barrier) │ │ socket-proxy (Read-Only Docker API Barrier) │
└───────────────────────────────────┬────────────────────────────────────┘ └───────────────────────────────────┬────────────────────────────────────┘
│ │
▼ ▼
┌────────────────────────────────────────────────────────────────────────┐ ┌────────────────────────────────────────────────────────────────────────┐
│ 3. WORKLOAD PLANE (~/Sites) │ │ 3. WORKLOAD PLANE (~/Workloads) │
│ Autonomous Workload Repositories (Jellyfin, Docs, Gitea, DBs, etc.) │ │ Autonomous Workload Repositories (SnappyMail, Docs, Gitea, etc.) │
│ Declarative app.yaml Manifests & Compose Stacks │ │ Declarative app.yaml Manifests & Compose Stacks │
└───────────────────────────────────┬────────────────────────────────────┘ └───────────────────────────────────┬────────────────────────────────────┘
│ │
▼ ▼
┌────────────────────────────────────────────────────────────────────────┐ ┌────────────────────────────────────────────────────────────────────────┐
│ 4. HOST FOUNDATION │ │ 4. HOST FOUNDATION & CONTROL PLANE DAEMONS │
│ NixOS Linux · sops-nix Secrets · Docker Engine · Systemd Units │ │ NixOS Linux · sops-nix Secrets · Docker Engine · Systemd Units │
│ homelab-appctl.service (Control Plane Daemon) · homelab-gitops │
│ Smart Dynu DDNS Monitor · Host Firewall · /run Secret Projections │ │ Smart Dynu DDNS Monitor · Host Firewall · /run Secret Projections │
└────────────────────────────────────────────────────────────────────────┘ └────────────────────────────────────────────────────────────────────────┘
``` ```
### C. Cross-Cutting Orchestration ### C. Cross-Cutting Orchestration
Orchestration coordinates operations across the runtime layers without being a runtime layer itself: Orchestration coordinates operations across the runtime layers:
* **`appctl` CLI & Metadata Engine (`scripts/appctl`, `scripts/appctl_engine.py`)**: Slices across the Host Foundation (sourcing secrets from `/run/secrets/`), Workload Plane (parsing `~/Sites/*/app.yaml` and driving Docker Compose), and Platform Services (recompiling `config/homepage/services.yaml`). * **`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, enforces admission policies, and dispatches serialized deployment actions for workloads or data repositories. * **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.
--- ---
@@ -55,7 +60,7 @@ Orchestration coordinates operations across the runtime layers without being a r
### A. Edge Gateway (`traefik`) ### A. Edge Gateway (`traefik`)
* **Role**: Ingress proxy for incoming HTTP (80) and HTTPS (443) traffic. * **Role**: Ingress proxy for incoming HTTP (80) and HTTPS (443) traffic.
* **TLS Management**: Employs Traefik's native ACME resolver using the Dynu DNS-01 challenge provider (`myresolver`) to obtain and renew wildcard certificates for `*.roadtotech.me` and `roadtotech.me`. Certificate data is stored at `config/letsencrypt/acme.json` (mode `0600`). * **TLS Management**: Employs Traefik's native ACME resolver using the Dynu DNS-01 challenge provider (`myresolver`) to obtain and renew wildcard certificates for `*.${HOMELAB_DOMAIN}` and `${HOMELAB_DOMAIN}` (e.g., `*.example.com`). Certificate data is stored at `config/letsencrypt/acme.json` (mode `0600`).
* **Redirection**: Automatically upgrades HTTP traffic to HTTPS via the `https-redirect@docker` middleware. * **Redirection**: Automatically upgrades HTTP traffic to HTTPS via the `https-redirect@docker` middleware.
* **Dynamic Routing**: Discovers routers and services dynamically by reading Docker container labels via `socket-proxy` (`tcp://socket-proxy:2375`). * **Dynamic Routing**: Discovers routers and services dynamically by reading Docker container labels via `socket-proxy` (`tcp://socket-proxy:2375`).
@@ -65,36 +70,37 @@ Orchestration coordinates operations across the runtime layers without being a r
- Mounted read-only: `/var/run/docker.sock:/var/run/docker.sock:ro`. - Mounted read-only: `/var/run/docker.sock:/var/run/docker.sock:ro`.
- State-modifying and execution endpoints disabled: `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`, `COMMIT=0`, `CONFIGS=0`, `DISTRIBUTION=0`, `NODES=0`, `PLUGINS=0`, `SECRETS=0`, `SWARM=0`, `SYSTEM=0`. - State-modifying and execution endpoints disabled: `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`, `COMMIT=0`, `CONFIGS=0`, `DISTRIBUTION=0`, `NODES=0`, `PLUGINS=0`, `SECRETS=0`, `SWARM=0`, `SYSTEM=0`.
- Read-only inspection endpoints enabled: `CONTAINERS=1`, `NETWORKS=1`, `SERVICES=1`, `TASKS=1`, `IMAGES=1`, `VOLUMES=1`, `INFO=1`, `EVENTS=1`, `PING=1`, `VERSION=1`. - Read-only inspection endpoints enabled: `CONTAINERS=1`, `NETWORKS=1`, `SERVICES=1`, `TASKS=1`, `IMAGES=1`, `VOLUMES=1`, `INFO=1`, `EVENTS=1`, `PING=1`, `VERSION=1`.
* **Network**: Attached exclusively to `socket-net`. Application containers in `~/Sites` are not attached to `socket-net`. * **Network**: Attached exclusively to `socket-net`. Application containers in `~/Workloads` are never attached to `socket-net`.
### C. Identity & Directory Services (`lldap` & `authelia`) ### C. Identity & Directory Services (`lldap` & `authelia`)
* **`lldap`**: Lightweight LDAP directory service storing user accounts, password hashes, and groups. Web UI exposed at `users.roadtotech.me` (protected by Authelia). SQLite database stored in `config/lldap/data/users.db`. * **`lldap`**: Lightweight LDAP directory service storing user accounts, password hashes, and groups. Web UI exposed at `users.${HOMELAB_DOMAIN}` (protected by Authelia). SQLite database stored in `config/lldap/data/users.db`.
* **`authelia`**: Authentication and SSO gateway (`auth.roadtotech.me`). * **`authelia`**: Authentication and SSO gateway (`auth.${HOMELAB_DOMAIN}`).
- Configured with an LDAP authentication backend querying `ldap://lldap:3890`. - Configured with an LDAP authentication backend querying `ldap://lldap:3890`.
- Exposes the ForwardAuth endpoint (`/api/verify?rd=https://auth.roadtotech.me/`), registered as the `authelia-auth@docker` Traefik middleware. - Exposes the ForwardAuth endpoint (`/api/verify?rd=https://auth.${HOMELAB_DOMAIN}/`), registered as the `authelia-auth@docker` Traefik middleware.
- Passes user identity headers (`Remote-User`, `Remote-Groups`, `Remote-Email`, `Remote-Name`) upon successful session verification. - Passes user identity headers (`Remote-User`, `Remote-Groups`, `Remote-Email`, `Remote-Name`) upon successful session verification.
### D. Mail Subsystem (`stalwart` & `snappymail`) ### D. Mail Subsystem (`stalwart`)
* **`stalwart`**: All-in-one mail server handling inbound SMTP (25), SMTPS (465), SMTP Submission (587), IMAPS (993), and ManageSieve (4190). * **`stalwart`**: Core mail transport and storage server handling inbound SMTP (25), SMTPS (465), SMTP Submission (587), IMAPS (993), and ManageSieve (4190).
- WebAdmin & JMAP UI accessible at `mail.roadtotech.me` via Traefik. - WebAdmin & JMAP endpoint accessible at `smtp.${HOMELAB_DOMAIN}` via Traefik.
- Authenticates users against the LLDAP directory. - Authenticates users against the LLDAP directory.
- Outbound mail relay configured to route through an external smart host (Brevo SMTP relay via SOPS secrets). - Outbound mail relay configured to route through an external smart host (Brevo SMTP relay via SOPS secrets).
* **`snappymail`**: Webmail client accessible at `webmail.roadtotech.me` routing to Stalwart. - *(Note: User-facing webmail, such as SnappyMail, runs as an independent Class B workload in `~/Workloads/snappymail` with isolated state under `~/var/lib/homelab/snappymail/`.)*
### E. Portal & Observability (`homepage`, `dozzle`) ### E. Portal & Observability (`homepage`, `dozzle`)
* **`homepage`**: Service dashboard at `dashboard.roadtotech.me`. 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`**: Log viewing interface at `logs.roadtotech.me`, connecting through `socket-proxy`. * **`dozzle`**: Real-time container log viewer at `logs.${HOMELAB_DOMAIN}`, connecting read-only through `socket-proxy`.
### F. Host Foundation & Daemons ### F. Host Foundation & Daemons
* **`homeserver-core.service`**: Systemd unit managing the Core Docker Compose stack (`/home/kiskaadee/Core/docker-compose.yml`) using secrets projected to `/run/secrets/homeserver.env`. * **`homeserver-core.service`**: Systemd unit managing the Core Docker Compose stack (`~/Core/docker-compose.yml`) using secrets projected to `/run/secrets/homeserver.env`.
* **`homelab-gitops.service`**: Systemd unit listening on port 9000 executing `scripts/gitops_dispatcher.py`. * **`homelab-appctl.service`**: Operational control plane daemon running as dedicated user `homelab-appctl:homelab-operators` with dual listeners (`/run/homelab/appctl.sock` and `127.0.0.1:9001`), fail-closed audit logging (`/var/log/homelab/appctl/audit.jsonl`), and strict systemd sandboxing (`ProtectSystem=strict`, `ProtectHome=read-only`).
* **`homelab-gitops.service`**: Systemd unit listening on port 9000 executing `scripts/gitops_dispatcher.py` under strict systemd sandboxing (`ProtectSystem=strict`, `ProtectHome=read-only`), delegating worker deployments to `homelab-appctl.service`.
* **`dynu-monitor.service` & `dynu-monitor.timer`**: IP change monitor executing `nixos/scripts/monitor.py` every 30 minutes to detect WAN IP changes and update DNS via `ddclient`. * **`dynu-monitor.service` & `dynu-monitor.timer`**: IP change monitor executing `nixos/scripts/monitor.py` every 30 minutes to detect WAN IP changes and update DNS via `ddclient`.
--- ---
## 3. Network Segmentation ## 3. Network Segmentation
Homelab Core configures two bridge networks: Homelab Core configures two isolated Docker bridge networks:
```text ```text
┌────────────────────────────────────────────────────────────────────────┐ ┌────────────────────────────────────────────────────────────────────────┐
@@ -106,9 +112,8 @@ Homelab Core configures two bridge networks:
│ │ │ │ │ │ │ │
│ │ • traefik (router) • authelia (sso) │ │ │ │ • traefik (router) • authelia (sso) │ │
│ │ • lldap (directory) • stalwart (mail) │ │ │ │ • lldap (directory) • stalwart (mail) │ │
│ │ • snappymail (webmail) • homepage (dashboard) │ │ │ │ • homepage (dashboard) • dozzle (logs) │ │
│ │ • dozzle (logs) │ │ │ │ • All User Workloads (~/Workloads/*) │ │
│ │ • All User Workloads (~/Sites/*) │ │
│ └──────────────────────────────┬───────────────────────────────┘ │ │ └──────────────────────────────┬───────────────────────────────┘ │
│ │ │ │ │ │
│ ┌──────────────────────────────┴───────────────────────────────┐ │ │ ┌──────────────────────────────┴───────────────────────────────┐ │
@@ -124,8 +129,8 @@ Homelab Core configures two 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 container metadata join this network. 2. **`socket-net`**: Isolated Docker socket proxy network. Only Core infrastructure components needing read-only container metadata join this network.
--- ---
@@ -146,15 +151,15 @@ The host firewall is configured in `nixos/modules/homeserver.nix`:
| **993** | TCP | Stalwart | IMAPS (Secure IMAP) | Public | | **993** | TCP | Stalwart | IMAPS (Secure IMAP) | Public |
| **4190** | TCP | Stalwart | ManageSieve (Mail Filters) | Public | | **4190** | TCP | Stalwart | ManageSieve (Mail Filters) | Public |
Application containers in `~/Sites` do not bind host ports directly; they receive traffic routed by Traefik over `proxy-net`. Application containers in `~/Workloads` do not bind host ports directly; they receive traffic routed by Traefik over `proxy-net`.
--- ---
## 5. Workload Integration Model ## 5. Workload Integration Model
Workloads in `~/Sites/<app>` integrate with Core through two mechanisms: Workloads in `~/Workloads/<app>` integrate with Core through three mechanisms:
1. **Manifest Metadata (`app.yaml`)**: Declares identity, routed domain, environment variable defaults, homepage card layout, and deployment policy. 1. **Manifest Metadata (`app.yaml`)**: Validated by `scripts/core_manifest.py` (Schema v1.0). Declares canonical identity, routed domain, upstream source provenance (`source.url`, `source.ref`), environment defaults, Homepage card layout, and allowlisted GitOps deployment policy.
2. **Compose Configuration (`docker-compose.yml`)**: 2. **Compose Configuration (`docker-compose.yml`)**:
- Attaches to the external `proxy-net` network. - Attaches to the external `proxy-net` network.
- Declares Traefik routing labels: - Declares Traefik routing labels:
@@ -172,4 +177,4 @@ Workloads in `~/Sites/<app>` integrate with Core through two mechanisms:
# If auth is required: # If auth is required:
- "traefik.http.routers.${CONTAINER_NAME}.middlewares=authelia-auth@docker" - "traefik.http.routers.${CONTAINER_NAME}.middlewares=authelia-auth@docker"
``` ```
3. **Execution**: The `appctl` CLI and GitOps dispatcher supply environment variables (such as `SERVICE_DOMAIN`, `CONTAINER_NAME`, and projected secrets) when invoking Docker Compose. 3. **Execution & State Isolation**: `appctl` and `gitops_dispatcher.py` validate the manifest and Compose AST (blocking privilege escalation and out-of-bounds mounts unless explicitly authorized per workload in `homelab.workloadGrants`, projected to `/etc/homelab/grants.json` and read via `HOMELAB_GRANTS_FILE` per ADR-0005) before supplying runtime environment variables (`SERVICE_DOMAIN`, `CONTAINER_NAME`, and projected secrets). Persistent mutable workload data resides strictly under `~/var/lib/homelab/<app>/`.
@@ -0,0 +1,99 @@
---
type: decision
status: accepted
project: homelab-core
date: 2026-09-28
tags: [architecture, homelab, provenance, gitops, state, kiss]
---
# ADR 0001: Homelab 3-Tier Architecture & Deployment Provenance Model
## Context and Problem Statement
Homelab Core operates as a dedicated NixOS appliance hosting self-hosted productivity services and independent backend engineering projects. In early platform iterations (v1 through v3), several structural tensions emerged:
1. **Application & Deployment Coupling**: Custom applications co-located application source trees with host-specific Traefik labels, Docker bridge networks, and host path mounts inside individual Git repositories in `~/Sites/<app>`.
2. **Repository Inflation**: Third-party off-the-shelf applications (`jellyfin`, `stirling`, `snappymail`) required standalone Git repositories simply to store a minimal Compose file and manifest.
3. **Ambiguous Freshness**: Local Git status checks in `~/Sites/<app>` could only report whether deployment descriptors had uncommitted edits, never whether running containers matched current upstream application source code.
4. **Mutable State Entanglement**: Application databases, caches, and runtime state lived inside or adjacent to version-controlled Git working trees (`Core/config/` and `Sites/<app>/data`), risking dirty checkouts, accidental secret/state commits, or data loss during branch operations.
5. **Orchestrator Sprawl Risk**: Scaling operational scripts threatened to introduce secondary distributed infrastructure (queues, databases, message brokers) around basic single-node container deployments.
The central architectural question is: **How should Homelab Core structure application source code, deployment configuration, runtime state, and platform orchestration to maintain strict separation of concerns, verifiable provenance, and linear KISS operations?**
## Decision Drivers
* **Clean Separation of Concerns**: Application software projects must be developable, testable, and publishable independently of Homelab Core infrastructure, domains, or bridge networks.
* **Workload Simplicity**: Off-the-shelf third-party applications should not incur standalone source repository overhead.
* **Verifiable Two-Axis Provenance**: Operators must be able to independently verify local deployment configuration freshness (`~/Sites/<app>`) versus upstream software code freshness (`source.url` vs. running container image).
* **KISS Primitives & Minimal Control Paths**: Operational reconciliation must remain bounded, deterministic, and linear without distributed brokers, queues, or deployment databases.
* **Filesystem State Hygiene**: Mutable runtime data must never reside inside version-controlled Git trees.
## Considered Options
* **Option 1: Monolithic / Single-Repo Deployment (Status Quo v1–v3)**: Co-locate application source code, Dockerfiles, Compose files, and mutable runtime state inside a single Git repository per application.
* **Option 2: Miniature Cloud Platform**: Introduce message brokers (RabbitMQ/Redis), a deployment state database, multi-environment controllers, and asynchronous rollback daemons.
* **Option 3: Bounded 3-Tier Platform with OCI Provenance Labels & Linear Control Path (Adopted)**: Decouple Software, Deployment, and Platform tiers; connect them via OCI image artifacts carrying source revision labels and content-addressed digests; enforce two-axis provenance inspection, linear reconciliation, and isolated host state roots.
## Decision Outcome
Chosen option: **Option 3: Bounded 3-Tier Platform with OCI Provenance Labels & Linear Control Path**, because it resolves source-deployment coupling and provenance ambiguity while retaining a strictly bounded, single-appliance operational footprint.
### Summary of Architectural Commitments
1. **3-Tier Separation of Concerns**:
* **Tier 1 — Software Layer (Application Repositories)**: Standalone Git repositories owning application source code, tests, Dockerfiles, and CI workflows. Zero Homelab infrastructure coupling.
* **Intermediate Provenance Artifacts**: OCI container images produced by CI act as immutable provenance objects identified by their OCI digest and carrying source commit metadata via the `org.opencontainers.image.revision` label.
* **Tier 2 — Deployment Layer (`~/Sites` Workload Plane)**: Declarative catalog in `~/Sites/<app>` owning workload-specific `app.yaml` manifests and `docker-compose.yml` topologies.
* **Tier 3 — Platform Layer (Homelab Core Appliance)**: Declarative NixOS host foundation (`~/Core`) owning edge ingress (`traefik`), SSO/directory (`authelia`, `lldap`), mail (`stalwart`), monitoring (`dozzle`, `diun`), and operational controllers (`appctl`, `gitops_dispatcher`).
2. **Two Workload Deployment Classes**:
* **Class A (Source-Backed)**: Declares an explicit upstream `source:` block (`source.url`, `source.ref`) in `app.yaml`; tracks upstream Git revisions against running container OCI labels.
* **Class B (Image-Only)**: Standard third-party workloads omitting `source:`; deployment freshness relies on container registry image tags and content-addressed digests.
3. **Two Operational Inspection Axes (`scripts/provenance.py`)**:
* **Axis 1 (Local Deployment Checkout)**: Evaluates local `~/Sites/<app>` working-tree cleanliness (`✓ Synced`, `* Dirty`, `⬆ Ahead`, `⬇ Behind`).
* **Axis 2 (Upstream Software Provenance)**: Independently resolves upstream remote revisions via bounded `git ls-remote` (10-second timeout during `--fetch`) against running container revision labels.
4. **Minimal Linear Reconciliation Path**:
* The deployment lifecycle remains strictly linear:
$$\text{Source Push} \longrightarrow \text{CI Build} \longrightarrow \text{GitOps Ingress} \longrightarrow \text{appctl Reconcile} \longrightarrow \text{Compose Up}$$
* Secondary message queues, brokers, and deployment databases are rejected.
5. **Isolated Persistent State Root**:
* Mutable application runtime state (databases, caches, uploads, dynamic configs) resides strictly under `~/var/lib/homelab/<app>/`, isolated from version-controlled Git repositories.
## Pros and Cons of the Options
### Option 1: Monolithic / Single-Repo Deployment
* Good, because it requires only a single Git repository per custom application.
* Bad, because host-specific routing labels and bridge networks leak into application source repositories, preventing clean open-sourcing or reuse.
* Bad, because off-the-shelf tools require artificial wrapper repositories.
* Bad, because a single commit SHA conflates software code revisions with deployment configuration edits.
* Bad, because mutable state co-located in `Sites/<app>/data` creates dirty Git trees and risks accidental commits or data loss.
### Option 2: Miniature Cloud Platform
* Good, because it mirrors enterprise Kubernetes / ArgoCD continuous deployment pipelines.
* Bad, because running distributed brokers, queues, and state databases on a single appliance introduces disproportionate operational overhead and failure modes.
* Bad, because it violates the KISS principle.
### Option 3: Bounded 3-Tier Platform with OCI Provenance Labels (Adopted)
* Good, because custom software is completely decoupled from homelab infrastructure and remains portable and instance-agnostic.
* Good, because off-the-shelf software incurs zero source repository overhead.
* Good, because two-axis inspection resolves local configuration status and upstream code provenance unambiguously.
* Good, because runtime state is cleanly isolated under `~/var/lib/homelab/<app>/`.
* Bad, because custom applications manage source code and Sites deployment manifests as separate concerns.
* Bad, because verifying remote revisions without local clones (`git ls-remote`) evaluates commit equality (`HEAD` match) rather than full commit ancestry distance.
## Consequences
### Positive Consequences
* **Independent Software Lifecycle**: Custom applications can be developed, tested, and published without exposing homelab domains, secrets, or network topologies.
* **Precise Diagnostic Truth**: Operators and `appctl` can distinguish between uncommitted local deployment edits (`* Dirty`) and upstream software updates (`git ls-remote`).
* **Zero-Data-Loss State Isolation**: Proven during the Milestone P1 SnappyMail migration, moving persistent runtime data to `~/var/lib/homelab/<app>/` keeps Git trees pure and backups deterministic.
* **Operational Restraint**: Preserves a linear, local reconciliation path without distributed state stores.
### Negative Consequences & Accepted Trade-offs
* **Dual Repositories for Custom Workloads**: Deploying a custom application separates upstream source CI from the `~/Sites/<app>` deployment manifest.
* **Commit Equality Without Ancestry Graph**: Remote `git ls-remote` queries confirm whether the deployed revision matches upstream `HEAD`, without computing commit ahead/behind counts on uncloned source repos.
## More Information
* **Architecture Specification**: [`docs/architecture.md`](../architecture.md)
* **Secrets & State Contract**: [`docs/secrets-and-state.md`](../secrets-and-state.md)
* **Governing Roadmap**: [`ROADMAP.md`](../../ROADMAP.md) (Milestones P1 & P3)
@@ -0,0 +1,139 @@
---
type: decision
status: accepted
project: homelab-core
date: 2026-10-07
tags: [architecture, homelab, appctl, control-plane, security, rbac, audit, gitops]
---
# ADR 0002: Homelab Operational Control Plane & Deployment Model Architecture
## Context and Problem Statement
Homelab Core historically relied on `appctl` as a procedural Bash CLI wrapper (`scripts/appctl`) coupled with a Python metadata helper (`scripts/appctl_engine.py`). Operational commands (`up`, `down`, `restart`, `update`, `logs`, `config`, `sync`) executed as local subprocesses in the operator's shell session, sourcing environment files directly from `/run/secrets/` and `$APP_DIR/.env`.
As the platform matured and AI coding agents began operating inside developer SSH sessions, this script-based model exposed five architectural and security liabilities:
1. **Conflated Host & Control Plane Authority**: Entering the server via SSH granted full operational mutation authority. Any unprivileged process or AI coding agent running under the operator's UID could invoke `appctl` to mutate containers, inspect secrets, or alter routing with zero authentication.
2. **Duplicated Execution & Pre-Flight Drift**: The local CLI (`scripts/appctl`) and the GitOps webhook worker (`scripts/gitops_dispatcher.py`) maintained separate implementations of `git pull` and `docker compose`, with the CLI path bypassing Compose AST security validation and sourcing `.env` files via shell `source`.
3. **Absence of Tamper-Evident Auditability**: Operational actions produced only ephemeral terminal output with no centralized, append-only audit log recording principal identity, transport, origin, target revision, and outcome.
4. **Secret Lifecycle Coupling**: Workload secrets were broadly sourced into parent shell environments or coupled to static SOPS rebuilds rather than resolved via scoped references.
5. **Manual Workload Authoring Friction**: Onboarding workloads required handwriting boilerplate descriptors without a structured boundary separating AI-generated proposals (`DeploymentProposal`) from human-approved declarative intent (`DeploymentModel`).
The central architectural question is: **How should Homelab Core transition `appctl` into an authoritative, fail-closed operational control plane with strict privilege isolation, unified execution, mandatory token authorization, and safe deployment authoring without introducing distributed cloud complexity?**
## Decision Drivers
* **Control Plane Centralization**: Exactly one authoritative execution pipeline for all workload and platform operations across CLI, GitOps, and future web clients.
* **Host Access Does Not Confer Mutation Authority**: Entering the host via SSH must not bypass control-plane authentication. Every mutating action and sensitive read requires cryptographic token verification.
* **OS Privilege Isolation**: The control plane daemon, token store, and audit log must be isolated under a dedicated system identity (`homelab-appctl`) inaccessible to unprivileged operator shell processes and AI sessions.
* **Unified Pre-Flight & Inert Environment Assembly**: Eliminate shell `eval` and `source`; enforce Pydantic v2 schema validation ([ADR-0003](0003-pydantic-v2-runtime-validation.md)) and Compose AST security checks before every Compose invocation.
* **Declarative Git Ground Truth & AI Boundary**: Git remains the sole authoritative source of deployment state; AI agents act strictly as upstream proposal generators (`DeploymentProposal`) with zero execution authority.
* **KISS Primitives**: Preserve synchronous, linear execution using local `flock` serialization and HTTP/1.1 without external message brokers or databases.
## Considered Options
* **Option 1: Status Quo with Modernized Local CLI**: Modernize `appctl_engine.py` into a type-safe Python CLI while keeping execution in-process inside the caller's SSH session.
* **Option 2: Cloud-Native Micro-Platform (Kubernetes / Nomad / ArgoCD)**: Replace `appctl` and Docker Compose with enterprise cluster orchestration and distributed control loops.
* **Option 3: Authoritative `homelab-appctl.service` Daemon with Single Command Router & Stable Deployment Model (Adopted)**: Evolve `appctl` into an isolated systemd daemon exposing one logical HTTP/1.1 command API (`POST /v1/operations`) across Unix domain socket and TCP, backed by mandatory Bearer token auth, 3-role RBAC, fail-closed audit logging, and a 5-stage `DeploymentModel` lifecycle.
## Decision Outcome
Chosen option: **Option 3: Authoritative `homelab-appctl.service` Daemon with Single Command Router & Stable Deployment Model**, because it enforces an OS-level security boundary between operator sessions and platform execution, unifies CLI and GitOps codepaths behind a single fail-closed pipeline, and establishes a clean roadmap for directory-backed identity (P5) and human-gated AI deployment authoring (P6).
### Summary of Architectural Commitments (Reconciled with Pre-P4 Locked Decisions `DEC-01`–`DEC-05`)
```text
Clients (CLI / GitOps Worker / Future Web UI)
│
POST /v1/operations + GET /v1/health
(One Logical HTTP/1.1 Command Contract)
│
┌─────────────────────┴─────────────────────┐
▼ ▼
Unix Domain Socket (/run/homelab/appctl.sock) HTTP Listener (127.0.0.1:9001)
mode 0660 (homelab-appctl:homelab-operators) (Loopback in P4)
│ │
└─────────────────────┬─────────────────────┘
▼
┌───────────────────────────────────────────────┐
│ Unified Fail-Closed Pipeline (homelab-appctl)│
│ 1. Pydantic v2 Validator (extra="forbid", 64K)│
│ 2. Auth & 3-Role RBAC Gate (Bearer / PeerCred)│
│ 3. Per-Target flock (/var/lib/homelab/appctl) │
│ 4. Pre-Exec Audit Disk Guard (DISPATCHED) │
│ 5. Pre-Flight (Manifest + Compose AST + .env) │
│ 6. Subprocess Execution (Fixed argv, 256K cap)│
│ 7. Post-Exec Audit Record (COMPLETED / FAILED)│
└───────────────────────────────────────────────┘
```
#### 1. One Logical Command API Across Dual Transports (`DEC-01`)
* `appctl` runs as a dedicated systemd daemon (`homelab-appctl.service`) speaking standard **HTTP/1.1** over both a local Unix Domain Socket (`/run/homelab/appctl.sock`) and a TCP listener (`127.0.0.1:9001` in P4).
* All 13 canonical domain operations (`workload.list`, `workload.get`, `workload.resolve`, `platform.ssl`, `platform.health`, `workload.config`, `workload.logs`, `workload.deploy`, `workload.stop`, `workload.restart`, `workload.pull`, `workload.update`, `platform.sync_homepage`) dispatch through a **single canonical endpoint**: `POST /v1/operations` (plus `GET /v1/health` for liveness). Multi-route REST aliases are rejected.
* `scripts/appctl` acts as a thin HTTP/1.1 UDS client with zero local Docker or Git execution logic.
#### 2. Host Access Does Not Confer Mutation Authority & 3-Role RBAC (`DEC-02`)
* Entering via SSH confers zero control-plane mutation authority. Every mutating operation, every sensitive read (`workload.config`, `workload.logs`), and every HTTP request requires an explicit Bearer token validated via constant-time SHA-256 comparison (`hmac.compare_digest`) against `/run/secrets/appctl/tokens.json` (`0400`).
* **UDS `SO_PEERCRED` Viewer Fallback**: Unauthenticated local Unix socket calls extract kernel peer credentials (`SO_PEERCRED`) and fall back strictly to `homelab-viewer` privileges for non-sensitive reads (`list`, `get`, `resolve`, `ssl`, `health`), preserving zero-friction CLI inspection and shell tab-completion while blocking all mutations and secret dumps (`401`/`403`).
* **3-Role Authorization Hierarchy**:
* `homelab-admin`: Full access across `core`, `core_service`, and all valid `~/Sites/<app>` workloads.
* `homelab-operator`: Mutations and sensitive reads strictly restricted to workloads admitted in `Core/config/deployments.yaml` (used by `gitops-dispatcher`). Denied (`403`) on `core`, `core_service`, and unregistered Sites directories.
* `homelab-viewer`: Non-sensitive read-only operations only.
* *(Milestone P5 expands this gate with LLDAP directory group mapping and authenticated Traefik/Authelia ForwardAuth proxy headers).*
#### 3. Dedicated Service Identity, OS Isolation & Fail-Closed Audit Guard (`DEC-03`)
* The daemon executes as system user `homelab-appctl` (`Group = "homelab-operators"`, `SupplementaryGroups = [ "docker" ]`), with declarative recursive POSIX ACLs (`systemd.tmpfiles.rules`) granting shared read/write access on `~/Sites`, `~/var/lib/homelab`, and `~/Core/config/homepage`.
* **Append-Only Audit Telemetry (`/var/log/homelab/appctl/audit.jsonl`, mode `0600`)**: Records `DISPATCHED`, `COMPLETED`, `FAILED`, and `DENIED` lifecycle events with `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, `commit_sha`, and secret-redacted `parameters`/`result`.
* **Fail-Closed Disk Guard**: Mutating operations must write and flush a `DISPATCHED` audit record **before** invoking any Docker or Git subprocess. If the audit write fails (`OSError`), the mutation aborts immediately with `500 ERR_EXECUTION_FAILED`.
#### 4. GitOps Execution Unification (`DEC-04`)
* `scripts/gitops_dispatcher.py` retains webhook HTTP ingress (port 9000), HMAC-SHA256 verification, `config/deployments.yaml` admission, and the commit-superseding `.pending.json` queue.
* The background worker delegates deployment execution to the daemon's `workload.update` operation over `/run/homelab/appctl.sock` using its `homelab-operator` Bearer token, eliminating duplicated `git pull` and `docker compose` execution codepaths.
#### 5. Unified Pre-Flight & Pure-Python Environment Assembly (`DEC-05`)
* 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, 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.
* **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`.
## Pros and Cons of the Options
### Option 1: Status Quo with Local CLI Modernization
* Good, because it requires no background daemon or socket listener.
* Bad, because every process running under the operator's SSH UID retains full unauthenticated mutation authority over containers and secrets.
* Bad, because CLI and GitOps execution remain split across separate processes without unified lock management or tamper-evident auditing.
### Option 2: Cloud-Native Micro-Platform
* Good, because Kubernetes/ArgoCD provide built-in API servers and RBAC.
* Bad, because cluster control planes impose heavy resource and operational complexity disproportionate to a single-node NixOS appliance.
### Option 3: Authoritative `homelab-appctl.service` Daemon (Adopted)
* Good, because it isolates operational authority, secrets (`/run/secrets/appctl/tokens.json`), and audit logs (`/var/log/homelab/appctl/audit.jsonl`) under `homelab-appctl`.
* Good, because `POST /v1/operations` guarantees 100% contract parity across UDS and HTTP transports.
* Good, because `SO_PEERCRED` viewer fallback preserves ergonomic local read commands (`appctl list`, `appctl info`) while requiring tokens for mutations and secret reads.
* Bad, because it introduces a core systemd daemon and requires provisioning SOPS-managed API tokens for mutating CLI and GitOps operations.
## Consequences
### Positive Consequences
* **Defense-in-Depth Against Session Compromise**: Unprivileged scripts or AI coding agents in the operator's shell cannot mutate infrastructure, read `tokens.json`, or alter `audit.jsonl`.
* **Single Execution Truth**: Interactive CLI commands and automated GitOps webhooks execute through the exact same pre-flight validator, lock manager, and environment builder.
* **Deterministic Concurrency**: Per-target non-blocking `flock` locks (`/var/lib/homelab/appctl/locks/<target>.lock`) prevent overlapping mutations (`409 ERR_CONCURRENT_MUTATION`).
### Negative Consequences & Accepted Trade-offs
* **Daemon Dependency**: Normal operational commands depend on `homelab-appctl.service` availability (emergency host recovery remains possible for human administrators via `sudo`).
* **Token Provisioning**: Mutating CLI invocations require `APPCTL_TOKEN` / token configuration rather than relying on ambient SSH user identity.
## More Information
* **P4 Readiness & Boundary Specification**: [`docs/plans/p4-readiness-plan.md`](../plans/p4-readiness-plan.md)
* **Companion ADRs**:
* [ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model](0001-3tier-architecture-and-provenance.md)
* [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md)
* **Governing Roadmap**: [`ROADMAP.md`](../../ROADMAP.md) (Milestones P4–P7)
@@ -0,0 +1,96 @@
---
type: decision
status: accepted
project: homelab-core
date: 2026-10-15
tags: [architecture, appctl, validation, pydantic, security, api]
---
# ADR 0003: Centralized Runtime Validation & Serialization via Pydantic v2
## Context and Problem Statement
As Homelab Core transitions from decoupled CLI scripts into an authoritative operational control plane (`homelab-appctl.service`, Milestone P4), the system must process untrusted inputs across two distinct ingestion boundaries:
1. Declarative workload manifests (`app.yaml`) authored in `~/Sites` by independent workloads or external repository webhooks.
2. Command-oriented API requests sent across dual transports (host Unix Domain Socket `/run/homelab/appctl.sock` and network HTTP listener).
Previously, manifest parsing relied on Python standard library dataclasses combined with manual regex checking and dictionary traversals in `scripts/core_manifest.py`. While functional for basic validation, manual ad-hoc validation created subtle security and maintainability risks:
- Input parsing logic was duplicated across `core_manifest.py`, `appctl_engine.py`, and `gitops_dispatcher.py`.
- Validation errors varied in structure and could inadvertently reflect unvalidated raw payloads (potentially leaking secrets or host paths).
- Future daemon API endpoints would require writing independent request/response serialization, type-checking, and error-handling routines for every operation.
The central architectural question is: **How should the control plane enforce strict, fail-closed type safety and consistent serialization across workload manifests and daemon API endpoints without duplicating validation logic or leaking secrets?**
## Decision Drivers
* **Fail-Closed Type Safety**: Unrecognized fields, unexpected types, or invalid operations must be rejected immediately at the transport boundary before reaching the operational router.
* **Unified Contract Enforcement**: Workload manifests (`app.yaml`) and control plane API payloads must share a common, declarative schema definition rather than separate parser implementations.
* **Prevention of Information Disclosure**: Error payloads returned to clients or logged to audit streams must describe schema violations without echoing raw input values, environment variables, or credentials.
* **Dual-Transport Parity**: The same validated contract must govern both local Unix Domain Socket calls (CLI) and remote HTTP calls (GitOps dispatcher, Web UI).
* **Maintainability & Performance**: Minimizing bespoke parsing code while maintaining fast validation overhead suitable for daemon and CLI operations.
## Considered Options
* **Option 1: Standard Library Dataclasses with Custom Manual Validators**: Continue relying solely on Python `dataclasses` and manual validation functions (`isinstance`, regexes).
* **Option 2: JSON Schema (`jsonschema`) with Manual Object Deserialization**: Use JSON Schema definitions to validate raw dicts, then manually map validated dicts to dataclasses.
* **Option 3: Pydantic v2 with Strict Mode & Fail-Closed Configuration (Adopted)**: Introduce Pydantic v2 as the authoritative validation and serialization engine across manifests and API models.
## Decision Outcome
Chosen option: **Option 3: Pydantic v2 with Strict Mode & Fail-Closed Configuration**, because:
> *"We opted for centralizing runtime validation and serialization across workload manifest and daemon API around Pydantic models to enforce fail-closed type safety, strict schema-based contract boundaries and consistent serialization and error handling without leaking secrets."*
### Summary of Architectural Commitments
1. **Single Schema & Validation Layer**:
All domain entities—including workload manifest configurations (`SourceConfig`, `DeploymentConfig`, `HomepageConfig`, `Manifest`) and control plane API command payloads (requests, responses, errors)—are defined exclusively as Pydantic v2 models inheriting from `pydantic.BaseModel`.
2. **Fail-Closed Schema Boundaries (`extra="forbid"`)**:
Every model enforces `ConfigDict(extra="forbid")`. Any payload containing unexpected, undocumented, or extraneous fields is rejected at the transport boundary with zero execution.
3. **Strict Typing Policy (`strict=True`)**:
To prevent unexpected coercion bugs (e.g. string `"false"` coercing to boolean `True`, or floats coercing to ints), API operations, target identifiers, flags (`recreate`, `remove_orphans`, `visible`, `auth`), and tokens enforce strict types. Explicit field validators handle string trimming/normalization where intentional.
4. **Information Disclosure Prevention**:
Transport adapters intercept `pydantic.ValidationError` and map it into structured `ERR_VALIDATION_FAILED` (HTTP 400) responses. Error messages report violating field names and failure rules, but strictly sanitize and redact raw input values to prevent leaking secrets, credentials, or filesystem paths.
5. **Dual-Transport Parity**:
The identical Pydantic request and response models govern both Unix domain socket messages and HTTP API endpoints. Neither transport performs custom validation outside the shared Pydantic models.
6. **Host Runtime Alignment**:
Pydantic is packaged into the NixOS system environment (`nixos/configuration.nix`), systemd unit paths (`nixos/modules/homeserver.nix`), Nix flake development shells, and repository test dependencies (`pyproject.toml`) constrained to major version range `>=2.0,<3.0`.
## Pros and Cons of the Options
### Option 1: Standard Library Dataclasses with Custom Manual Validators
* Good, because it requires zero external dependencies and uses Python standard library modules.
* Bad, because validation code must be manually implemented for every field, nested structure, and API payload.
* Bad, because it is error-prone and historically led to parser duplication across `core_manifest.py`, `appctl_engine.py`, and `gitops_dispatcher.py`.
* Bad, because serialization and deserialization (e.g. JSON to model and back) require bespoke helper methods.
### Option 2: JSON Schema (`jsonschema`) with Manual Object Deserialization
* Good, because JSON Schema is a standardized language-agnostic specification.
* Bad, because it requires maintaining two separate artifacts for every entity: a JSON Schema document and a corresponding Python dataclass or class.
* Bad, because mapping validated JSON Schema dicts to Python typed objects adds runtime boilerplate and cognitive overhead.
* Bad, because error messages from `jsonschema` can be difficult to sanitize and format into uniform domain error structures.
### Option 3: Pydantic v2 with Strict Mode & Fail-Closed Configuration (Adopted)
* Good, because it provides declarative, unified model definitions that handle validation, type-checking, and JSON serialization in a single class.
* Good, because Pydantic v2's Rust core (`pydantic-core`) delivers high-performance validation with minimal latency impact on the daemon.
* Good, because built-in `ValidationError` metadata makes structured error mapping straightforward and consistent.
* Good, because `model_dump(mode="json")` and `model_validate_json()` provide deterministic, standardized serialization across dual transports.
* Bad, because it introduces a third-party dependency into the Core platform that must be maintained across NixOS packages, development shells, and CI pipelines (mitigated by locking `>=2.0,<3.0` in `pyproject.toml` and Nix flake checks).
## Consequences
### Positive Consequences
* Eliminates fragmented parsing code: all callers (`appctl_engine.py`, `gitops_dispatcher.py`, `homelab-appctl.service`) validate against the same authoritative schemas in `core_manifest.py`.
* Pre-P4 security posture is substantially hardened: unvalidated fields and type confusion attacks are blocked at ingestion.
* Clean separation of concerns: transport adapters focus on wire protocol handling while Pydantic guarantees valid domain objects for the operational router.
* Client error payloads are structured, actionable, and safe from secret leakage.
### Negative Consequences & Accepted Trade-offs
* Core depends on `pydantic` in host NixOS environment; all host Python environments executing `appctl` or `homelab-gitops` must have `python3Packages.pydantic` available.
* Schema evolution requires strict versioning: since `extra="forbid"` is enforced, extending manifests or API payloads with new fields requires coordinated model updates.
## More Information
* **Governing Readiness Plan**: [`docs/plans/p4-readiness-plan.md`](../plans/p4-readiness-plan.md) (Section 2.B)
* **Governing Roadmap**: [`ROADMAP.md`](../../ROADMAP.md) (Milestone P4)
* **Platform Security Invariants**: [`AGENTS.md`](../../AGENTS.md) (Invariants #1, #2, #3)
@@ -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).
+89
View File
@@ -0,0 +1,89 @@
# 🏛️ Homelab Core & Appctl Architecture Decision Index
This document serves as the authoritative repository index for Architectural Decision Records (ADRs) governing **Homelab Core** and the **`appctl` Operational Control Plane**.
Repository-level architectural decisions are recorded in `docs/decisions/` using the MADR 4.0 specification (`NNNN-slug.md`).
---
## 📋 Active Architectural Decisions
| 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 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)
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Milestone P4)
* **Core Commitments**:
1. **Single Schema & Validation Layer**: Workload manifests (`core_manifest.py`) and API command models inherit from `pydantic.BaseModel`.
2. **Fail-Closed Extra Fields (`extra="forbid"`)**: Immediate rejection of unexpected or undocumented payload properties.
3. **Strict Typing Policy (`strict=True`)**: Coercion forbidden on operations, targets, identifiers, and flags.
4. **Secret-Safe Error Transformation**: Transport-level conversion of `ValidationError` into standard `ERR_VALIDATION_FAILED` (400) with raw input values redacted.
5. **Dual-Transport Parity**: Identical validated models across Unix domain socket and HTTP transports.
### [ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture](0002-appctl-control-plane-architecture.md)
* **Canonical Document**: [`0002-appctl-control-plane-architecture.md`](0002-appctl-control-plane-architecture.md)
* **Status**: `accepted` (Active — Reconciled with Pre-P4 Locked Decisions `DEC-01`–`DEC-05`)
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v6)
* **Core Commitments**:
1. **One Logical Command API Across Dual Transports (`DEC-01`)**: `homelab-appctl.service` exposes `POST /v1/operations` (13 canonical domain operations) and `GET /v1/health` over HTTP/1.1 on `/run/homelab/appctl.sock` and `127.0.0.1:9001`.
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, 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)
* **Status**: `accepted` (Active)
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v6)
* **Core Commitments**:
1. **3-Tier Separation of Concerns**:
* *Tier 1 (Software Layer)*: Upstream application repositories owning code, tests, and CI. Zero Homelab infrastructure coupling.
* *Intermediate Provenance Artifact*: OCI container images produced by CI carrying commit provenance in metadata labels and content-addressed digests.
* *Tier 2 (Sites Deployment Layer)*: Declarative manifests (`app.yaml`) and Compose specs in `~/Sites`.
* *Tier 3 (Platform Core Appliance)*: NixOS host foundation, edge routing, SSO, and operational controllers.
2. **Two Workload Deployment Classes**:
* *Class A (Source-Backed)*: Declares upstream Git source and ref (`source.url`, `source.ref`); tracks upstream Git revisions against container labels.
* *Class B (Image-Only)*: Standard third-party tools; tracks container registry image tags and digests.
3. **Isolated Persistent State Root**: Mutable data lives strictly under `~/var/lib/homelab/<app>/`, isolated from Git repositories.
4. **Two Operational Inspection Axes**: Local deployment checkout state evaluated independently of upstream software provenance (resolved via `git ls-remote`).
---
## 📜 Superseded Historical Decisions & Lineage
The following historical plans and design iterations have been formally superseded by the active ADRs and Roadmap v6:
* **Roadmap v5 (`architecture-consolidation-roadmap-v5.md`)**: Superseded by Roadmap v6 (`DEC-01`–`DEC-05` pre-P4 boundary lock).
* **Roadmap v4, v3, v2 & v1** (`architecture-consolidation-roadmap-v4.md`): Superseded by Roadmap v5/v6.
* **appctl-v2 Modernization Plan** (`appctl-engine-v2-refactoring.md`): Scaffolded and absorbed into Roadmap Phases P0 and P3.
* **Smart Selective Deployment Pipeline Plan** (`smart-deployment-pipeline.md`): Absorbed into Phase P4 control-plane reconciliation.
* **Architecture Implementation Guide v3 & v2** (`architecture-consolidation-implementation-guide-v3.md`): Superseded by unified Roadmap v4–v6.
+29 -15
View File
@@ -1,6 +1,6 @@
# ⚡ Homelab Core — GitOps Continuous Deployment Engine # ⚡ Homelab Core — GitOps Continuous Deployment Engine
Homelab Core includes an automated GitOps deployment engine implemented in [`scripts/gitops_dispatcher.py`](../scripts/gitops_dispatcher.py). It processes Git push webhooks from Gitea (or external Git forges) and executes declared deployment actions for workloads in `~/Sites` or data vaults (such as `~/Brain`). Homelab Core includes an automated GitOps deployment engine implemented in [`scripts/gitops_dispatcher.py`](../scripts/gitops_dispatcher.py). It processes Git push webhooks from Gitea (or external Git forges) and executes declared deployment actions strictly for admitted application workloads in `~/Sites`.
--- ---
@@ -26,9 +26,9 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
│ │
▼ ▼
┌───────────────────────────────────────────────┐ ┌───────────────────────────────────────────────┐
│ 3. Canonical Repository Identity Resolution │ │ 3. Authoritative Registry Resolution │
│ Maps logical names to trusted local paths │ │ Maps names via ~/Workloads/deployments.yaml│
│ Rejects path traversal & symlink escapes │ │ Fails closed; zero dynamic discovery on host│
└───────────────────────┬───────────────────────┘ └───────────────────────┬───────────────────────┘
│ │
▼ ▼
@@ -53,7 +53,8 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
┌───────────────────────────────────────────────┐ ┌───────────────────────────────────────────────┐
│ 7. Revision-Consistent Validation & Execution │ │ 7. Revision-Consistent Validation & Execution │
│ git pull -> re-validate manifest on-tree │ │ git pull -> re-validate manifest on-tree │
│ Execute allowlisted actions -> write status│ │ Compose AST security validator (containment│
│ & privilege checks) -> compose up -> status│
└───────────────────────────────────────────────┘ └───────────────────────────────────────────────┘
``` ```
@@ -71,13 +72,13 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
* Signatures are verified using HMAC-SHA256 with `hmac.compare_digest` against the shared secret stored in `nixos/secrets.yaml` (projected to `/run/secrets/gitops/webhook_secret`). * Signatures are verified using HMAC-SHA256 with `hmac.compare_digest` against the shared secret stored in `nixos/secrets.yaml` (projected to `/run/secrets/gitops/webhook_secret`).
* Missing, empty, or mismatched signatures are rejected. * Missing, empty, or mismatched signatures are rejected.
### C. Trusted Repository Resolution ### C. Authoritative Repository Registry (`deployments.yaml`)
* Webhook payloads identify targets by logical name (e.g. `docs`, `homelab-docs`), never by raw filesystem path. * Webhook payloads identify targets strictly by logical name (e.g. `docs`, `homelab-docs`), never by raw filesystem path.
* The engine resolves names against a trusted mapping derived from: * `~/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.
1. Authoritative Data Vaults (`~/Brain` via aliases `second-brain`, `Brain`, `brain`). * **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`.
2. Workload directories in `~/Sites` by parsing `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 `..` are rejected. * **Input Validation**: Names must match `^[a-zA-Z0-9][a-zA-Z0-9._-]*$`. Slashes, backslashes, and path traversal sequences (`..`) are rejected.
* **Containment Check**: Resolved target paths must reside within `~/Sites` or `~/Brain`. Symlinks pointing outside these roots are rejected. * **Containment Check**: Declared repository paths must resolve strictly within `~/Sites`. Paths escaping `~/Sites` are rejected during registry loading.
### D. Revision-Consistent Manifest Validation ### D. Revision-Consistent Manifest Validation
* When a webhook is admitted, an initial policy check verifies that the pushed branch matches the declared `deployment.branch`. * When a webhook is admitted, an initial policy check verifies that the pushed branch matches the declared `deployment.branch`.
@@ -85,14 +86,27 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
* The engine **re-reads and re-validates `app.yaml` from the newly pulled working tree** before running subsequent container actions (`compose_up`, `compose_build`, etc.). * The engine **re-reads and re-validates `app.yaml` from the newly pulled working tree** before running subsequent container actions (`compose_up`, `compose_build`, etc.).
* If the pulled commit introduces an invalid action, unsupported strategy, or changes the target branch away from the pushed branch, deployment is aborted. * If the pulled commit introduces an invalid action, unsupported strategy, or changes the target branch away from the pushed branch, deployment is aborted.
### E. Compose AST Security Validation
Before executing `docker compose up -d`, `validate_compose_security()` parses the application's Compose file and enforces platform security invariants:
* **File Integrity**: `docker-compose.yml` and `app.yaml` must be regular files, not symlinks escaping the workload root.
* **Privilege Containment**: Rejects `privileged: true`, `cap_add` capabilities, `devices` mounts, and `security_opt: ["apparmor:unconfined"]`.
* **Namespace Isolation**: Rejects host namespaces (`network_mode: host`, `pid: host`, `ipc: host`, `uts: host`, `userns_mode: host`).
* **Docker Socket Ban**: Rejects direct bind mounts of `/var/run/docker.sock` (reserved exclusively for Core `socket-proxy:ro`).
* **Top-Level Directives**: Rejects top-level `include:` directives to prevent out-of-tree file inclusions.
* **Bind-Mount & State Isolation**:
- Resolves all bind mounts (both relative and absolute) against the authorized workload directory.
- Bind mounts are strictly restricted to **either** the workload root (`~/Sites/<app>/`) **or** the dedicated per-workload persistent state root (`~/var/lib/homelab/<app>/`).
- Cross-tenant mounts (mounting another application's directory under `~/var/lib/homelab/`) are rejected fail-closed.
--- ---
## 3. Asynchronous Queueing, Serialization & Superseding ## 3. Asynchronous Queueing, Serialization & Superseding
To avoid blocking HTTP connections and handle overlapping pushes: To avoid blocking HTTP connections and handle overlapping pushes:
1. **Immediate HTTP 200 Return**: Upon passing admission, the dispatcher writes a pending file (`~/.local/state/homelab/gitops/<target>.pending.json`), spawns a detached worker (`--worker <target>`), and returns HTTP 200. 1. **Immediate HTTP 200 Return**: Upon passing admission, the dispatcher writes a pending file (`~/.local/state/homelab/gitops/<target>.pending.json`), spawns a detached worker (`--worker <target>`), and returns HTTP 200.
2. **Per-Target `flock` Serialization**: The worker acquires an exclusive non-blocking `fcntl.flock` on `~/.local/state/homelab/gitops/<target>.lock`. If a worker is already running for this target, the second worker exits safely while the running worker continues to drain the pending file. 2. **Per-Target `flock` Serialization & Daemon Delegation**: The worker acquires an exclusive non-blocking `fcntl.flock` on `~/.local/state/homelab/gitops/<target>.lock`. When `/run/homelab/appctl.sock` is available, the worker delegates `workload.update` to `homelab-appctl.service` over UDS authenticating with `/run/secrets/gitops/appctl_token` (`homelab-operator` role), which executes `git pull --ff-only`, re-validates `app.yaml` and Compose security, runs the declared actions, logs to `/var/log/homelab/appctl/audit.jsonl`, and syncs Homepage.
3. **Commit Superseding**: 3. **Commit Superseding**:
- Commit A begins deploying. - Commit A begins deploying.
- Commit B arrives and is written to the pending file. - Commit B arrives and is written to the pending file.
@@ -161,11 +175,11 @@ The continuous deployment engine operates strictly **downstream** of CI verifica
``` ```
[Developer / PR] ──► [Gitea Actions CI] ──► [Merge to main] ──► [Gitea Webhook] ──► [homelab-gitops] ──► [Deploy] [Developer / PR] ──► [Gitea Actions CI] ──► [Merge to main] ──► [Gitea Webhook] ──► [homelab-gitops] ──► [Deploy]
(Ephemeral Container) (Host Daemon) (:host act_runner) (Host Daemon)
``` ```
1. **Pre-Merge CI Invariant (`.gitea/workflows/ci.yaml`)**: 1. **Pre-Merge CI Invariant (`.gitea/workflows/ci.yaml`)**:
- Executes inside containerized `act_runner` environments using **pre-baked toolchain images** (`container: nixery.dev/shell/coreutils/git/nix/nodejs:latest`). - Executes directly on `:host` `act_runner` instances (`ubuntu-latest:host` / `nix:host`) with a **pre-baked host toolchain** (`nix`, `node`, `git`, `coreutils`), without spawning nested `container:` jobs.
- Runs hermetic validation (`nix flake check`, `pytest`, `ruff`) with Git safe directory enforcement. - Runs hermetic validation (`nix flake check`, `pytest`, `ruff`) with Git safe directory enforcement.
- Prevents broken code, misconfigured flakes, or regression bugs from entering `main`. - Prevents broken code, misconfigured flakes, or regression bugs from entering `main`.
2. **Post-Merge CD Execution (`homelab-gitops.service`)**: 2. **Post-Merge CD Execution (`homelab-gitops.service`)**:
+368 -12
View File
@@ -16,9 +16,15 @@ After modifying any file in `nixos/` (including `configuration.nix`, `hardware-c
nix-switch nix-switch
# Or using the explicit command: # 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 ### Dry Build Validation & Rollback
```bash ```bash
# Validate build without activating (catches evaluation and syntax errors) # Validate build without activating (catches evaluation and syntax errors)
@@ -51,7 +57,7 @@ docker system prune -a --volumes --filter "until=168h"
Homelab Core runs several platform services managed by systemd: Homelab Core runs several platform services managed by systemd:
### `homeserver-core.service` (Core Compose Stack) ### `homeserver-core.service` (Core Compose Stack)
Manages the lifecycle of Traefik, Authelia, LLDAP, Stalwart, SnappyMail, Homepage, Dozzle, Watchtower, and Diun. Manages the lifecycle of Traefik, Authelia, LLDAP, Stalwart, Homepage, Dozzle, Watchtower, and Diun.
```bash ```bash
# Check service status # Check service status
@@ -103,7 +109,7 @@ tail -n 20 /var/lib/dynu/ip_history.jsonl
## 3. Workload Lifecycle Operations (`appctl`) ## 3. Workload Lifecycle Operations (`appctl`)
Applications in `~/Sites` are managed with the `appctl` CLI. Applications in `~/Workloads` are managed with the `appctl` CLI.
### Inspection & Status ### Inspection & Status
```bash ```bash
@@ -139,9 +145,8 @@ appctl restart docs
appctl restart traefik appctl restart traefik
appctl restart authelia 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 docs
appctl update core
# Stream live container logs # Stream live container logs
appctl logs docs appctl logs docs
@@ -151,6 +156,37 @@ appctl logs -f stalwart
appctl config docs 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) ## 4. User Identity & Access Management (LLDAP & Authelia)
@@ -158,7 +194,7 @@ appctl config docs
User accounts and group memberships are managed dynamically in **LLDAP** rather than static configuration files. User accounts and group memberships are managed dynamically in **LLDAP** rather than static configuration files.
### Accessing the Directory ### Accessing the Directory
1. Open `https://users.roadtotech.me` in your browser. 1. Open `https://users.${HOMELAB_DOMAIN}` (e.g., `https://users.example.com`) in your browser.
2. Authenticate using your admin credentials (`admin` / password configured in `nixos/secrets.yaml`). 2. Authenticate using your admin credentials (`admin` / password configured in `nixos/secrets.yaml`).
3. From the LLDAP UI, you can: 3. From the LLDAP UI, you can:
- Create and delete user accounts. - Create and delete user accounts.
@@ -167,7 +203,7 @@ User accounts and group memberships are managed dynamically in **LLDAP** rather
- Assign users to groups (e.g. `admin`, `users`, `media`). - Assign users to groups (e.g. `admin`, `users`, `media`).
### Authelia Session & Authentication ### Authelia Session & Authentication
* **URL**: `https://auth.roadtotech.me` * **URL**: `https://auth.${HOMELAB_DOMAIN}` (e.g., `https://auth.example.com`)
* **Session Lifetime**: 7 days maximum session, 3 days inactivity timeout. * **Session Lifetime**: 7 days maximum session, 3 days inactivity timeout.
* **ForwardAuth Guard**: Applications requiring authentication attach the `authelia-auth@docker` middleware. * **ForwardAuth Guard**: Applications requiring authentication attach the `authelia-auth@docker` middleware.
@@ -193,12 +229,12 @@ User accounts and group memberships are managed dynamically in **LLDAP** rather
``` ```
### B. Dynamic DNS (WAN IP) Drift ### B. Dynamic DNS (WAN IP) Drift
* **Symptom**: External domain `roadtotech.me` does not resolve to the current ISP WAN address. * **Symptom**: External domain (`${HOMELAB_DOMAIN}`) does not resolve to the current ISP WAN address.
* **Diagnosis**: * **Diagnosis**:
```bash ```bash
# Check current public IP vs resolved DNS IP # Check current public IP vs resolved DNS IP
curl -s https://api.ipify.org curl -s https://api.ipify.org
dig +short roadtotech.me @1.1.1.1 dig +short example.com @1.1.1.1
# Check dynu-monitor logs # Check dynu-monitor logs
systemctl status dynu-monitor systemctl status dynu-monitor
@@ -263,7 +299,7 @@ To back up the homelab, create secure snapshots of the following state directori
| **User Directory** | `~/Core/config/lldap/data/` | LLDAP SQLite database (`users.db`) | | **User Directory** | `~/Core/config/lldap/data/` | LLDAP SQLite database (`users.db`) |
| **Auth Database** | `~/Core/config/authelia/db.sqlite3` | Authelia session database | | **Auth Database** | `~/Core/config/authelia/db.sqlite3` | Authelia session database |
| **Mail Storage** | `~/Core/config/stalwart/` | Stalwart database, mailboxes, and DKIM keys | | **Mail Storage** | `~/Core/config/stalwart/` | Stalwart database, mailboxes, and DKIM keys |
| **Webmail State** | `~/Core/config/snappymail/data/` | SnappyMail configuration and sessions | | **Workload State** | `~/var/lib/homelab/<app>/` | Per-workload persistent runtime state (e.g., `snappymail`) |
| **Dashboard State** | `~/Core/config/homepage/` | Homepage configuration and custom icons | | **Dashboard State** | `~/Core/config/homepage/` | Homepage configuration and custom icons |
### Host Recovery Requirements ### Host Recovery Requirements
@@ -272,10 +308,330 @@ To bring up a replacement host from version control:
2. **Restore the host SSH private key** to `/etc/ssh/ssh_host_ed25519_key` (mode `0600`) before running `nixos-install`, as `sops-nix` requires this key during system evaluation and activation. 2. **Restore the host SSH private key** to `/etc/ssh/ssh_host_ed25519_key` (mode `0600`) before running `nixos-install`, as `sops-nix` requires this key during system evaluation and activation.
3. Install NixOS targeting the server flake: 3. Install NixOS targeting the server flake:
```bash ```bash
nixos-install --flake /mnt/home/kiskaadee/Core#server nixos-install --flake /mnt/home/<operator>/Core#server
reboot reboot
``` ```
4. Restore persistent data directories (`config/` backups) and start the Core stack: 4. Restore persistent data directories (`config/` and `~/var/lib/homelab/` backups) and start the Core stack:
```bash ```bash
sudo systemctl start homeserver-core 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/*`.
+394
View File
@@ -0,0 +1,394 @@
# 📋 Control Plane Milestone P4: Readiness Plan & Boundary Specifications
**Status**: ✅ **Approved & Locked (Pre-P4 Security Gate Complete; Ready for Daemon Implementation)**
**Target Milestone**: [Milestone P4: Appctl Control Plane Daemon & API](../../ROADMAP.md#milestone-p4-appctl-control-plane-daemon--command-oriented-api)
**Governing ADR**: [`0002-appctl-control-plane-architecture.md`](../decisions/0002-appctl-control-plane-architecture.md)
---
## 🎯 Purpose & Scope
Before initiating code implementation for `homelab-appctl.service`, this readiness plan formalizes the operational contracts, execution boundaries, and security invariants that P4 depends upon.
Milestones P0–P3 and the Pre-P4 Security Gate established the core foundation:
- **P0**: Baseline consolidation & Pytest/Nix test harness.
- **P1**: Zero-data-loss mail realignment & state isolation (`~/var/lib/homelab/snappymail`).
- **P2**: GitOps repository registry (`deployments.yaml`), AST security validation, and Systemd sandboxing.
- **P3**: Manifest Schema v1.0 ([`core_manifest.py`](../../scripts/core_manifest.py)), two-axis inspection ([`provenance.py`](../../scripts/provenance.py)), and authoritative engine ([`appctl_engine.py`](../../scripts/appctl_engine.py)).
- **Pre-P4 Security Gate (Completed)**:
- Eliminated shell `eval` and unvalidated environment injection in `scripts/appctl`.
- Enforced `Core/config/deployments.yaml` as sole GitOps registry authority, removing dynamic host discovery.
- Hardened Compose AST validator against relative traversal, cross-tenant mounts, and host capability escapes.
- Unified manifest parsing on `core_manifest.py` and enforced fail-closed `cmd_resolve` behavior.
This plan resolves the six architectural prerequisites necessary to implement P4 as a secure, fail-closed operational control plane rather than discovering boundaries ad-hoc during coding.
---
## 📑 Sequence of Deliverables
| Deliverable | Phase | Focus | Status |
| :--- | :--- | :--- | :--- |
| **1. Implementation Inventory** | P0 Verification | Baseline truth, callers, dependencies, and migration state | ✅ **Completed** |
| **2. Command & Error Contract** | P4 Prerequisite (Blocker) | Canonical domain operations, typed schemas, and error taxonomy | ✅ **Locked & Approved** |
| **3. Authorization Design** | Security Gate (Blocker) | Token lifecycle, RBAC matrix, and fail-closed evaluation | ✅ **Locked & Approved** |
| **4. Execution & Privilege Boundaries** | P4 Prerequisite | Subprocess allowlist, Docker API capabilities, and filesystem roots | ✅ **Locked & Approved** |
| **5. Audit Telemetry Semantics** | P4 Prerequisite | RFC JSONL audit schema, persistent ownership, and lifecycle | ✅ **Locked & Approved** |
| **6. P4 Acceptance Test Suite** | Verification | Concrete DoD, black-box transport parity, and security regression gates | ✅ **Locked & Approved** |
---
## 1. Reconcile the Implementation Inventory
### A. Current File & Module Roles
| File / Component | Language | Authority Status | Functional Responsibilities |
| :--- | :--- | :--- | :--- |
| [`scripts/appctl`](../../scripts/appctl) | Bash | **Active CLI Client** | CLI entry point; secret environment sourcing (`homeserver.env`, `traefik-deployments.env`); resolves metadata via engine; directly runs `docker compose` and `git pull` subprocesses. |
| [`scripts/appctl_engine.py`](../../scripts/appctl_engine.py) | Python 3 | **Authoritative Engine** | Domain models (`SitesApp`, `CoreService`); schema v1.0 parsing (`core_manifest.py`); two-axis inspection (`provenance.py`); SSL cert inspection; Homepage compilation; metadata serialization (`resolve`). |
| [`scripts/core_manifest.py`](../../scripts/core_manifest.py) | Python 3 | **Schema Library** | Authoritative Pydantic v2 models (`ConfigDict(extra="forbid")`); transport validation (`https://`, `ssh://`, `git@`); ref semantics classification (`branch`, `tag`, `commit`). |
| [`scripts/provenance.py`](../../scripts/provenance.py) | Python 3 | **Provenance Library** | Two-axis status engine; local checkout inspection (`git status`, commit SHA); bounded upstream query (`git ls-remote` with 10s timeout). |
| [`scripts/gitops_dispatcher.py`](../../scripts/gitops_dispatcher.py) | Python 3 | **Webhook Ingress & Queue** | Webhook listener (port 9000); HMAC validation; `deployments.yaml` admission; `.pending.json` commit-superseding queue; Compose AST validator (`validate_compose_security`). |
### B. Command Inventory & Implementation Division
| Command | CLI Syntax | Handled By | Operation Type | Current Behavior |
| :--- | :--- | :--- | :--- | :--- |
| `list` / `status` | `appctl list [--fetch] [--core] [--ssl]` | `appctl_engine.py` | Read-Only | Scans `~/Sites`, evaluates two-axis checkout and upstream provenance, queries container status, prints formatted table. |
| `info` | `appctl info <service> [--ssl]` | `appctl_engine.py` | Read-Only | Prints detailed metadata, two-axis local checkout vs. upstream provenance, network memberships, and TLS certificate info. |
| `ssl` | `appctl ssl [service]` | `appctl_engine.py` | Read-Only | Connects over TLS socket (port 443), extracts peer X.509 certificate, calculates days until expiration. |
| `resolve` | `appctl resolve <query>` | `appctl_engine.py` | Read-Only | Resolves canonical name / alias; emits JSON string consumed by Bash `setup_app_env`. |
| `complete` | `appctl complete` | `appctl_engine.py` | Read-Only | Emits space-separated list of known workload names, aliases, and core services for Bash shell autocompletion. |
| `sync` | `appctl sync [--homepage-dir=PATH]` | `appctl_engine.py` | Mutating (Filesystem) | Reads all `app.yaml` manifests, groups and sorts cards by weight, writes `config/homepage/services.yaml`. |
| `up` | `appctl up <service\|core>` | `scripts/appctl` (Bash) | Mutating (Containers) | Sourced environment variables $\to$ `docker compose up -d --remove-orphans` $\to$ triggers `appctl sync`. |
| `down` | `appctl down <service\|core>` | `scripts/appctl` (Bash) | Mutating (Containers) | `docker compose down` (or `stop` for Core services) $\to$ triggers `appctl sync`. |
| `restart` | `appctl restart <service\|core>` | `scripts/appctl` (Bash) | Mutating (Containers) | Sourced environment variables $\to$ `docker compose restart` (or down/up) $\to$ triggers `appctl sync`. |
| `update` | `appctl update <service\|core>` | `scripts/appctl` (Bash) | Mutating (Git + Containers) | Verifies clean git working tree $\to$ `git pull --ff-only` $\to$ `docker compose pull` $\to$ `docker compose up -d` $\to$ triggers `appctl sync`. |
| `pull` | `appctl pull <service\|core>` | `scripts/appctl` (Bash) | Mutating (Images) | `docker compose pull` $\to$ `docker compose up -d --remove-orphans`. |
| `logs` | `appctl logs <service\|core>` | `scripts/appctl` (Bash) | Read-Only (Sensitive) | Dispatches `docker compose logs`. (Bounded tail output in P4; live streaming deferred to P7.) |
| `config` | `appctl config <service\|core>` | `scripts/appctl` (Bash) | Read-Only (Sensitive) | Injects environment $\to$ executes `docker compose config` to view fully evaluated compose AST. |
### C. Active Call Sites Across the Repository
1. **System Path Integration**:
- [`nixos/configuration.nix`](../../nixos/configuration.nix#L119-L122): Installs host wrapper `/run/current-system/sw/bin/appctl` calling `${CORE_DIR:-$HOME/Core}/scripts/appctl "$@"`.
2. **Internal Script Invocation**:
- `scripts/appctl` calls `python3 "$ENGINE" resolve "$query"` to set up the Compose environment.
- `scripts/appctl` calls `python3 "$ENGINE" sync` after mutating actions (`up`, `down`, `restart`, `update`).
3. **Automated Test Coverage (124 Passing Tests)**:
- [`tests/unit/test_core_manifest.py`](../../tests/unit/test_core_manifest.py): 24 unit tests covering Pydantic v2 schema validation, extra-field rejection, and ref classification.
- [`tests/unit/test_appctl_engine.py`](../../tests/unit/test_appctl_engine.py): 20 unit tests exercising `resolve_app`, `get_docker_status`, `check_ssl_cert`, and `cmd_sync_homepage`.
- [`tests/unit/test_provenance.py`](../../tests/unit/test_provenance.py): 10 unit tests covering two-axis status inspection and timeout handling.
- [`tests/security/test_gitops_security.py`](../../tests/security/test_gitops_security.py): 60 security tests covering HMAC verification, `deployments.yaml` containment, Compose AST validation, and worker serialization.
- [`tests/security/test_security_invariants.py`](../../tests/security/test_security_invariants.py): 7 security invariant tests covering `socket-proxy`, `eval` absence, CLI env injection resilience, and platform genericism.
- [`tests/structural/test_repository_structure.py`](../../tests/structural/test_repository_structure.py): 3 structural tests asserting required paths and license preservation.
### D. Architectural Findings & Migration Deductions
1. **V1 Engine is Fully Superseded & V2 Shim Retired**: `scripts/appctl_engine.py` is the single authoritative metadata engine, and `scripts/core_manifest.py` is migrated to Pydantic v2 (`ADR-0003`).
2. **Duplicated Operational Execution in GitOps (`DEC-04`)**: `scripts/gitops_dispatcher.py` and `scripts/appctl` maintain separate implementations of `git pull` and `docker compose up`, and `gitops_dispatcher.py` currently omits workload environment injection (`SERVICE_DOMAIN`, `CONTAINER_NAME`, `app.yaml` `env:`, `traefik-deployments.env`). In P4, `gitops_dispatcher.py` retains webhook HMAC verification, `deployments.yaml` admission, and the asynchronous `.pending.json` commit-superseding queue, while its worker delegates deployment execution to the daemon's `workload.update` operation over `/run/homelab/appctl.sock` and uses `core_manifest.parse_manifest()`.
3. **Shell `.env` Sourcing & Missing Compose AST Pre-Flight on CLI Path (`DEC-05`)**: While `eval` was removed from `scripts/appctl`, the Bash CLI still runs `source "$APP_DIR/.env"` and `source "$APP_DIR/app.env"` and does not invoke `validate_compose_security()`. The P4 daemon replaces Bash `source` with an inert pure-Python key-value parser (enforcing `ENV_KEY_RE` and `RESERVED_ENV_KEYS`) and runs `validate_compose_security()` before every workload Compose operation.
---
## 2. Command and Error Contract (P4 Prerequisite — Locked via `DEC-01` & `DEC-04`)
### A. Wire Protocol, Endpoint Surface & Canonical Domain Operations (`DEC-01`)
1. **HTTP/1.1 Over Both Transports**: Both the local Unix Domain Socket (`/run/homelab/appctl.sock`) and the loopback TCP listener (`127.0.0.1:9001`) speak standard **HTTP/1.1** and traverse a single shared request pipeline (Body Size Limit $\to$ JSON Parse $\to$ Pydantic v2 Validate $\to$ Auth/RBAC Gate $\to$ Target Resolution & Lock $\to$ Pre-Execution Audit $\to$ Execution $\to$ Post-Execution Audit).
2. **Single Canonical Operation Endpoint**:
- `POST /v1/operations`: Dispatches all 13 canonical domain operations (both read-only and mutating).
- `GET /v1/health`: Convenience liveness probe that internally dispatches `platform.health`.
- No multi-route REST aliases (`GET /workloads`, `POST /operations/deploy`, etc.) are exposed in P4, eliminating URL-vs-body ambiguity.
3. **Bounded Non-Streaming Logs**: `workload.logs` is strictly non-streaming in P4 (`tail: StrictInt` bounded `1..1000`, default `100`). Live streaming (`--follow` / SSE) is deferred to Milestone P7.
4. **Payload & Output Bounds**: Maximum HTTP request body size is `64 KiB` (larger bodies are rejected with `400 ERR_VALIDATION_FAILED`). Maximum captured subprocess `stdout`/`stderr` is `256 KiB` per invocation.
```text
┌─────────────────────────┐
│ Client Request │
│ POST /v1/operations │
└────────────┬────────────┘
▼
┌───────────────────────────────────────────┐
│ Operation Dispatch Router │
└─────────────────────┬─────────────────────┘
│
┌───────────────────────────────┴───────────────────────────────┐
▼ ▼
[ Read-Only Operations ] [ Mutating Operations ]
• workload.list (viewer) • workload.deploy (operator / admin*)
• workload.get (viewer) • workload.stop (operator / admin*)
• workload.resolve (viewer) • workload.restart (operator / admin*)
• platform.ssl (viewer) • workload.update (operator / admin*)
• platform.health (viewer) • workload.pull (operator / admin*)
• workload.config (operator / admin* — sensitive read) • platform.sync_homepage (operator / admin)
• workload.logs (operator / admin* — sensitive read)
(* targeting 'core' or a 'core_service' strictly requires 'homelab-admin')
```
### B. Typed Request and Response Models (Pydantic v2 Pipeline)
All control plane API requests, responses, and error payloads are defined and validated through **Pydantic v2** (`pydantic.BaseModel`, `pydantic.Field`, `ConfigDict(extra="forbid", strict=True)`), joining the existing Pydantic v2 manifest schema in [`scripts/core_manifest.py`](../../scripts/core_manifest.py):
- **Runtime Validation Boundary**: Incoming JSON payloads over both Unix Domain Socket and HTTP endpoints are validated at the transport boundary before reaching the operational router.
- **Fail-Closed Extra Fields (`extra="forbid"`)**: Rejects any undeclared or unknown fields immediately.
- **Strict Typing vs. Coercion Rules (`strict=True`)**:
- *Strict Validation*: Operations (`operation`), target identifiers (`target`), integer bounds (`tail`), boolean flags (`recreate`, `remove_orphans`, `build`, `fetch`, `core`, `ssl`), and optional strings (`expected_branch`) enforce strict types (`StrictStr`, `StrictBool`, `StrictInt`). Implicit coercion (e.g., `"true"` or `1` to `True`, or floats to ints) is forbidden.
- *Permitted Normalization*: Only explicitly defined string whitespace trimming via field validators is permitted.
- **Operation-Specific Parameters (`DEC-04`)**:
- `workload.deploy`: `recreate: StrictBool = True`, `remove_orphans: StrictBool = True`, `build: StrictBool = False`.
- `workload.update`: `expected_branch: StrictStr | None = None`, `build: StrictBool = False`. Enforces revision-consistent post-pull validation of `app.yaml` (`deployment.branch` and `deployment.actions`, supporting `git_pull`, `compose_pull`, `compose_build`, `compose_up`, `compose_restart`).
- `workload.logs`: `tail: StrictInt = Field(default=100, ge=1, le=1000)`.
- `workload.list`: `fetch: StrictBool = False`, `core: StrictBool = False`, `ssl: StrictBool = False`.
- `workload.get`: `ssl: StrictBool = False`.
- **Information Disclosure Prevention**: Transport handlers intercept `pydantic.ValidationError`, strip raw input values (`e.errors(include_input=False, include_url=False)`), and map violations to `ERR_VALIDATION_FAILED` (`400 Bad Request`).
All requests and responses use strict JSON payloads with explicit schema versioning (`version: "1.0"`):
```json
// Example: POST /v1/operations
// Request:
{
"version": "1.0",
"operation": "workload.deploy",
"target": "jellyfin",
"parameters": {
"recreate": true,
"remove_orphans": true,
"build": false
}
}
// Response (Success):
{
"version": "1.0",
"status": "success",
"operation_id": "op_01JAX71BC98E4",
"target": "jellyfin",
"timestamp": "2026-10-16T12:00:00Z",
"duration_ms": 1420,
"result": {
"action": "deployed",
"target_type": "app",
"health": "🟢 Running (1)"
}
}
```
### C. Standardized Error Taxonomy
Failures are strongly typed and distinguished across six canonical error codes:
| Error Classification | HTTP Code | Error Code | Description / Fail-Closed Action |
| :--- | :--- | :--- | :--- |
| **Validation Error** | `400 Bad Request` | `ERR_VALIDATION_FAILED` | Request schema violation, body $>64\text{ KiB}$, invalid target format, malformed `app.yaml`, dirty git working tree on update, post-pull branch mismatch, or Compose AST security violation. |
| **Authentication Error** | `401 Unauthorized` | `ERR_AUTH_REQUIRED` | Missing, unknown, or malformed Bearer token (or unauthenticated UDS caller attempting a token-gated operation). |
| **Authorization Error** | `403 Forbidden` | `ERR_PERMISSION_DENIED` | Authenticated principal lacks required role (e.g., `homelab-viewer` attempting mutation or `config`/`logs`; `homelab-operator` targeting `core`/`core_service` or a workload not in `deployments.yaml`). |
| **Target Not Found** | `404 Not Found` | `ERR_TARGET_NOT_FOUND` | Workload target does not exist under `~/Sites` or Core services registry. |
| **State Conflict** | `409 Conflict` | `ERR_CONCURRENT_MUTATION` | Another mutating operation on the target workload is currently holding the per-target operation lock. |
| **Execution Error** | `500 Internal Error`| `ERR_EXECUTION_FAILED` | Audit log write failure, Docker/Git subprocess non-zero exit, or subprocess timeout expiration. |
---
## 3. Authorization Design (Security Gate — Locked via `DEC-02` & `DEC-05`)
### A. The Core Principle: Host Access Does Not Confer Mutation Authority
Entering the host via SSH establishes Unix access, but **zero operational control plane mutation or secret-inspection privileges**. Every mutating request—and every sensitive read (`workload.config`, `workload.logs`)—to `homelab-appctl.service` must present an authenticated Bearer token.
### B. Principal Identity, Role Mapping & Target Scope (`DEC-02`, `DEC-05`)
The platform enforces three hierarchical authorization tiers:
| Role | Permitted Operations & Target Scope | Typical Principals |
| :--- | :--- | :--- |
| `homelab-admin` | All operations across **all targets**: `core` stack, individual `core_service` containers (`traefik`, `authelia`, `stalwart`, etc.), and any valid `~/Sites/<app>` directory contained within `SITES_DIR`. | Interactive human operator token (`operator`). |
| `homelab-operator` | Workload mutations (`deploy`, `stop`, `restart`, `update`, `pull`, `sync_homepage`) and sensitive reads (`config`, `logs`) **strictly restricted to workloads registered in [`config/deployments.yaml`](../../config/deployments.yaml)**. Cannot target `core`, `core_service`, or unregistered `~/Sites` directories (`403 ERR_PERMISSION_DENIED`). | GitOps webhook worker token (`gitops-dispatcher`), scoped automation scripts. |
| `homelab-viewer` | Non-sensitive read-only operations (`workload.list`, `workload.get`, `workload.resolve`, `platform.ssl`, `platform.health`). Zero mutations permitted; `workload.config` and `workload.logs` are denied (`403 ERR_PERMISSION_DENIED`). | Local UDS `SO_PEERCRED` operator session fallback, read-only status monitors. |
### C. Transport Authentication Rules (P4 vs. P5 Boundary)
1. **SOPS-Projected Hashed Token Store (`/run/secrets/appctl/tokens.json`)**:
- Owned by `homelab-appctl` (mode `0400`).
- Stores an array of token descriptors (`token_id`, `identity`, `role`, and 64-char hex `sha256` digest of the bearer secret).
- Incoming `Authorization: Bearer <secret>` headers are hashed with SHA-256 and compared via `hmac.compare_digest`.
- Required for **all mutations**, **all `workload.config` / `workload.logs` calls**, and **all HTTP listener requests**.
2. **Unix Domain Socket (`/run/homelab/appctl.sock`) & `SO_PEERCRED`**:
- Socket ownership: `homelab-appctl:homelab-operators`, file mode `0660`.
- The UDS listener extracts kernel peer credentials (`SO_PEERCRED`: `uid`, `gid`, `pid`) on every connection and records `origin = f"peer_uid_{uid}"`.
- If no `Authorization` header is supplied over UDS and `uid` belongs to an authorized local operator, the request is authenticated as `Principal(identity=f"unix_uid_{uid}", role="homelab-viewer", token_id=None, auth_method="unix_peercred")`. This enables zero-friction local inspection (`appctl list`, `appctl info`, `appctl ssl`) and shell tab-completion (`appctl complete`) while blocking all mutations and secret dumps (`401`/`403`).
3. **HTTP Network Listener (`127.0.0.1:9001`)**:
- Bound strictly to loopback (`127.0.0.1`) in P4 (`APPCTL_HTTP_HOST=127.0.0.1`, `APPCTL_HTTP_PORT=9001`).
- Every `POST /v1/operations` call over HTTP requires a valid Bearer token (`401 ERR_AUTH_REQUIRED` if missing).
- **ForwardAuth Headers Deferred to P5**: Proxy headers (`Remote-User`, `Remote-Groups`) are **ignored and never trusted** in P4. (In P5, ForwardAuth will be introduced with dedicated proxy authentication so workload containers on `proxy-net` cannot spoof headers.)
4. **GitOps Ingress (`homelab-gitops.service` $\to$ Daemon UDS)**:
- `gitops_dispatcher.py` verifies the Gitea webhook HMAC-SHA256 signature against `/run/secrets/gitops/webhook_secret`, admits the push against `config/deployments.yaml`, and enqueues `<target>.pending.json`.
- The serialized background worker invokes `POST /v1/operations` (`operation: "workload.update"`, `parameters: {"expected_branch": branch}`) over `/run/homelab/appctl.sock` authenticating with its `homelab-operator` Bearer token.
---
## 4. Execution & Privilege Boundaries (P4 Prerequisite — Locked via `DEC-03` & `DEC-05`)
### A. Operational Capability Matrix & Timeouts
Each canonical operation is bound to minimal execution permissions, fixed argument lists (`shell=False`), hard timeouts, and role checks:
| Domain Operation | Subprocess / Tool | Allowed Arguments / API | Timeout | Required Role (`Sites` / `Core`) |
| :--- | :--- | :--- | :--- | :--- |
| `workload.list` | In-process (`appctl_engine.py`, `provenance.py`) | Scan `~/Sites/`, `git status` (`5s`), optional `git ls-remote` (`10s`), `docker compose ps` (`15s`) | `15s` / cmd | `homelab-viewer` |
| `workload.get` | In-process (`appctl_engine.py`, `core_manifest.py`) | Parse `app.yaml`, inspect git status (`5s`), `git ls-remote` (`10s`), `docker inspect` (`15s`) | `15s` / cmd | `homelab-viewer` |
| `workload.resolve` | In-process (`appctl_engine.py`) | Canonical target resolution & metadata dictionary | In-process | `homelab-viewer` |
| `platform.ssl` | In-process (`appctl_engine.py`) | TLS peer certificate check on port 443 | `3s` / host | `homelab-viewer` |
| `platform.health` | In-process | Daemon liveness, socket/lock/audit readiness check | In-process | `homelab-viewer` |
| `workload.config` | `docker` | `compose -f <compose_file> config` (with secret redaction for non-admin) | `15s` | `homelab-operator` / `homelab-admin` |
| `workload.logs` | `docker` | `compose -f <compose_file> logs --no-color --tail <1..1000>` | `15s` | `homelab-operator` / `homelab-admin` |
| `workload.deploy` | `docker` | Optional `compose -f <compose_file> build` (`if build=True`) $\to$ `compose -f <compose_file> up -d [--remove-orphans]` $\to$ Homepage sync | `300s` | `homelab-operator` / `homelab-admin` |
| `workload.stop` | `docker` | `compose -f <compose_file> down` (or `stop <container>` for `core_service`) $\to$ Homepage sync | `300s` | `homelab-operator` / `homelab-admin` |
| `workload.restart`| `docker` | `compose -f <compose_file> restart [<container>]` $\to$ Homepage sync | `300s` | `homelab-operator` / `homelab-admin` |
| `workload.pull` | `docker` | `compose -f <compose_file> pull [<container>]` $\to$ `compose -f <compose_file> up -d --remove-orphans` | `300s` | `homelab-operator` / `homelab-admin` |
| `workload.update` | `git`, `docker` | 1. Clean tree check (`git status --porcelain`, `5s`)<br>2. `git -C <dir> pull --ff-only [origin <expected_branch>]` (`60s`)<br>3. Re-validate `app.yaml` & `expected_branch` + `validate_compose_security()`<br>4. Execute declared actions (`compose_pull`, `compose_build`, `compose_up`, `compose_restart`, `300s` each) $\to$ Homepage sync | `60s` (git)<br>`300s` (docker) | `homelab-operator` / `homelab-admin` |
| `platform.sync_homepage` | In-process (`appctl_engine.py`) | Atomic compile of `Core/config/homepage/services.yaml` under `_homepage_sync.lock` | In-process | `homelab-operator` / `homelab-admin` |
### B. Unified Pre-Flight, Environment Assembly & Secret Boundary (`DEC-05`)
1. **Pre-Flight Validation Gate**: Every workload mutation and `workload.config` call executes in strict order:
- **Path Containment**: Target directory must resolve strictly inside `SITES_DIR.resolve()` (or equal `CORE_DIR.resolve()` for `homelab-admin`).
- **Registry Admission**: If `principal.role == "homelab-operator"`, target must be present in `config/deployments.yaml`.
- **Manifest Validation**: `core_manifest.parse_manifest(app_dir / "app.yaml")` must succeed with zero errors.
- **Compose AST Security Validation**: `validate_compose_security(compose_file, app_dir, app_name=manifest.name)` must pass (blocking `privileged: true`, `cap_add`, `devices`, `security_opt: unconfined`, host namespaces, `/var/run/docker.sock`, top-level `include`, escaping `env_file`, undeclared volumes, and cross-tenant bind mounts).
2. **Inert Pure-Python Environment Assembly (No Shell `source`)**:
- The daemon constructs the subprocess environment dictionary in memory:
1. Base system `PATH` and `DOCKER_CONFIG`.
2. Global secret files (`/run/secrets/rendered/homeserver.env`, `/run/secrets/rendered/traefik-deployments.env` with `/run/secrets/*` fallback) parsed via a pure-Python `KEY=VALUE` reader (no shell expansion).
3. Canonical domain lock (`HOMELAB_DOMAIN` resolved via `HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN`).
4. Infrastructure defaults (`PROXY_NETWORK=proxy-net`, `CERT_RESOLVER=myresolver`, `DOMAIN_SUFFIX=$HOMELAB_DOMAIN`) and workload identity (`SERVICE_NAME`, `CONTAINER_NAME`, `SERVICE_DOMAIN`, `DOMAIN`).
5. Validated `manifest.env` dictionary from `app.yaml`.
6. Optional `$APP_DIR/.env` and `$APP_DIR/app.env` parsed via pure-Python `KEY=VALUE` reader with every key validated against `ENV_KEY_RE` and `RESERVED_ENV_KEYS`.
3. **Secret Isolation & Redaction**:
- The daemon never accesses SOPS master keys (`/etc/ssh/ssh_host_ed25519_key`).
- Any key matching `*_KEY`, `*_SECRET`, `*_PASSWORD`, `*_TOKEN`, `*_PASS`, or `*_HASH` (and any known secret value from `/run/secrets/`) is replaced with `"[REDACTED]"` in audit logs, error responses, and diagnostic messages.
### C. Systemd Unit Sandboxing & Service Identity (`homelab-appctl.service` — `DEC-03`)
- **Dedicated Service Identity**:
- `User = "homelab-appctl"`
- `Group = "homelab-operators"`
- `SupplementaryGroups = [ "docker" ]`
- **Managed Runtime, State & Log Directories**:
- `RuntimeDirectory = "homelab"` (`RuntimeDirectoryMode = "0750"`): Hosts `/run/homelab/appctl.sock` (mode `0660`, `homelab-appctl:homelab-operators`).
- `StateDirectory = "homelab/appctl"` (`StateDirectoryMode = "0700"`): Hosts `/var/lib/homelab/appctl/locks/<target>.lock` and `_homepage_sync.lock`.
- `LogsDirectory = "homelab/appctl"` (`LogsDirectoryMode = "0700"`): Hosts `/var/log/homelab/appctl/audit.jsonl` (mode `0600`, `homelab-appctl:homelab-operators`).
- **Declarative Filesystem Access (`systemd.tmpfiles.rules` POSIX ACLs)**:
- Grants `homelab-appctl` traverse (`x`) on `/home/<operator>` and `/home/<operator>/Core`.
- Applies recursive default POSIX ACLs (`A+`) granting `d:u:homelab-appctl:rwx,u:homelab-appctl:rwx` on `/home/<operator>/Sites`, `/home/<operator>/var/lib/homelab`, and `/home/<operator>/Core/config/homepage` so both `<operator>` and `homelab-appctl` can update Git checkouts and write `services.yaml` without permission conflicts.
- **Systemd Hardening**:
- `ProtectSystem = "strict"`, `ProtectHome = "read-only"`, `PrivateTmp = true`, `NoNewPrivileges = true`, `ProtectKernelTunables = true`, `ProtectControlGroups = true`.
- `ReadWritePaths`: `/home/<operator>/Sites`, `/home/<operator>/var/lib/homelab`, `/home/<operator>/Core/config/homepage`, `/var/log/homelab/appctl`, `/var/lib/homelab/appctl`, `/run/homelab`.
### D. Platform Genericism & Domain Decoupling
Per `AGENTS.md` §3, all control-plane modules, NixOS definitions, Compose stacks, and tests must remain instance-agnostic:
- Canonical domain precedence: `HOMELAB_DOMAIN` $\to$ `DOMAIN_SUFFIX` $\to$ `DOMAIN` (fails closed if unset).
- Test fixtures and documentation examples use RFC 2606 domains (`example.com`, `example.org`, `example.test`).
---
## 5. Audit Telemetry & Operational State Semantics (`DEC-03`)
### A. Distinction Between Operation Result, Audit Event & Deployment State
1. **Operation Result (`OperationResponse`)**: Synchronous HTTP/1.1 response payload returned immediately to the caller.
2. **Audit Event (`/var/log/homelab/appctl/audit.jsonl`)**: Authoritative append-only control-plane security and mutation log. Captures pre-execution (`DISPATCHED`), post-execution (`COMPLETED` / `FAILED`), and admission rejection (`DENIED`) records correlated by `operation_id`, including pre/post `commit_sha` on `workload.update` and `workload.deploy`.
3. **GitOps Status Snapshot (`~/.local/state/homelab/gitops/<target>.status.json`)**: Lightweight latest-run status file written by `gitops_dispatcher.py` worker upon completion for backward-compatible webhook status inspection. (No separate rollback database or `appctl history` command is introduced in P4 v1.)
### B. Field Schema (RFC-Compliant JSONL)
Every audited lifecycle event is appended as a single line to `/var/log/homelab/appctl/audit.jsonl` (mode `0600`, overridable via `APPCTL_AUDIT_LOG` in hermetic tests):
```json
{
"audit_version": "1.0",
"event_id": "evt_01JAX73AB190",
"operation_id": "op_01JAX71BC98E4",
"timestamp": "2026-10-16T12:00:03.112Z",
"phase": "COMPLETED",
"principal": {
"identity": "operator",
"role": "homelab-admin",
"token_id": "tok_admin_01",
"auth_method": "bearer_token"
},
"action": "workload.update",
"target": "docs",
"transport": "unix_socket",
"origin": "peer_uid_1000",
"client": "appctl-cli/2.0",
"parameters": {
"expected_branch": null,
"build": false
},
"result": {
"status": "SUCCESS",
"exit_code": 0,
"duration_ms": 3210,
"commit_sha": "d4f8a1e",
"error_code": null,
"message": "Workload updated and reconciled successfully"
}
}
```
### C. Event Lifecycle States & Audited Scope
| Phase | Trigger & Scope |
| :--- | :--- |
| `DISPATCHED` | Written and flushed **before** any subprocess or file mutation executes for all mutating operations (`deploy`, `stop`, `restart`, `pull`, `update`, `sync_homepage`). |
| `COMPLETED` | Written when a mutating operation or sensitive read (`workload.config`, `workload.logs`) terminates cleanly (`exit_code == 0`). |
| `FAILED` | Written when a mutating operation or sensitive read fails during pre-flight validation (`400`) or execution (`500`). |
| `DENIED` | Written when authentication (`401`), RBAC authorization (`403`), or concurrency lock acquisition (`409`) rejects a request. |
*(Note: High-frequency non-sensitive viewer reads—`list`, `get`, `resolve`, `ssl`, `health`—do not emit `COMPLETED` audit records, preventing log bloat during CLI status checks and shell tab-completion.)*
### D. Failure Handling & Explicit Audit Threat Model
1. **Fail-Closed Pre-Execution Disk Guard**: If writing or flushing the `DISPATCHED` record to `audit.jsonl` fails (`OSError`), the daemon **immediately aborts the mutation and returns `500 ERR_EXECUTION_FAILED`** with zero Docker or Git invocations.
2. **Post-Execution Persistence Failure**: If writing the `COMPLETED`/`FAILED` record fails after subprocess execution, the daemon logs a critical alert to `stderr` (`journald`) and returns `500 ERR_EXECUTION_FAILED`.
3. **Explicit Threat Model**:
- **Protected Boundary**: Running the daemon as `homelab-appctl` with `/var/log/homelab/appctl/audit.jsonl` (`0600`) and `/run/secrets/appctl/tokens.json` (`0400`) enforces an OS user boundary against unprivileged processes and AI coding agents running inside the human operator's SSH session (`<operator>` UID). Session processes cannot read `tokens.json`, forge/truncate `audit.jsonl`, or signal the daemon without `sudo`.
- **Out-of-Scope Boundary**: Protection against an actor who possesses host `root` / `sudo` / `docker`-group escalation privileges is out of scope for single-node P4 (as `root` can modify any local file on the host).
---
## 6. P4 Implementation Slices (Dependency-Ordered)
1. **Slice 1 — Pydantic v2 API Contracts & Error Sanitizer (`scripts/appctl_contracts.py`)**:
- Strict request/response/error/audit models (`ConfigDict(extra="forbid", strict=True)`), operation parameter schemas, and `ValidationError` $\to$ `400 ERR_VALIDATION_FAILED` sanitizer (`include_input=False`).
- Add `"compose_pull"` to `ALLOWED_ACTIONS` in `scripts/core_manifest.py`.
2. **Slice 2 — Append-Only Audit Logger & Per-Target Lock Manager**:
- `AuditLogger` (`DISPATCHED`, `COMPLETED`, `FAILED`, `DENIED`, `0600` enforcement, secret redaction, fail-closed disk guard) and non-blocking `fcntl.flock` manager (`/var/lib/homelab/appctl/locks/<target>.lock` + `_homepage_sync.lock`).
3. **Slice 3 — Authentication & 3-Role RBAC Gate**:
- SOPS `tokens.json` SHA-256 authenticator (`hmac.compare_digest`), UDS `SO_PEERCRED` extractor (`unix_peercred` viewer fallback for non-sensitive reads), and role-scoped authorization policy (`homelab-admin` vs `homelab-operator` `deployments.yaml` restriction vs `homelab-viewer`).
4. **Slice 4 — Operational Router & Unified Execution Engine**:
- Pure-Python `.env` parser (no shell `source`), mandatory `parse_manifest()` + `validate_compose_security()` pre-flight, revision-consistent `workload.update` (`expected_branch`, dynamic action adoption, `build`), bounded `workload.logs` (`tail`), and atomic Homepage sync.
5. **Slice 5 — Dual-Transport HTTP/1.1 Daemon (`scripts/appctl_daemon.py`) & GitOps Cutover**:
- HTTP/1.1 server over UDS (`/run/homelab/appctl.sock`) and TCP (`127.0.0.1:9001`), graceful `SIGTERM`/`SIGINT` cleanup, and rewiring `scripts/gitops_dispatcher.py` to parse manifests via `core_manifest.parse_manifest()` and execute worker deployments through the daemon.
6. **Slice 6 — Thin-Client CLI (`scripts/appctl`), NixOS Service & Platform Genericism Cleanup**:
- Re-implement `scripts/appctl` as a thin UDS HTTP client, declare `homelab-appctl.service` (`homelab-appctl:homelab-operators` + POSIX ACLs) in `nixos/modules/homeserver.nix`, scrub remaining hardcoded domain/username literals across `nixos/`, `config/deployments.yaml`, and `docker-compose.yml`, and add `pyright` to `flake.nix` checks and `.githooks/pre-commit`.
---
## 7. P4 Definition of Done & Acceptance Test Matrix
Before marking Milestone P4 complete, the following automated regression suite must pass:
| Test Suite / Area | Assertion / Invariant Verified | Failure Action |
| :--- | :--- | :--- |
| **Transport Parity** | `test_transport_dual_equivalence`: Compare responses of `POST /v1/operations` (`workload.list`, `workload.get`, errors) over Unix socket vs HTTP `127.0.0.1`. Assert 100% schema and status parity. | Reject PR |
| **Unauthenticated Rejection** | `test_auth_missing_token_fails_closed`: Mutating operations and `workload.config`/`workload.logs` without `Authorization: Bearer` return `401 ERR_AUTH_REQUIRED` on both UDS and HTTP and execute zero subprocesses. | Block Release |
| **UDS Peercred Viewer Scope** | `test_uds_peercred_viewer_boundary`: Tokenless UDS call from operator UID succeeds for `workload.list` (`auth_method: "unix_peercred"`), but fails with `401`/`403` on any mutation or `workload.config`. | Block Release |
| **RBAC & Role-Scoped Resolution**| `test_rbac_role_matrix`: `homelab-viewer` denied (`403`) on all mutations; `homelab-operator` allowed on `deployments.yaml` workloads but denied (`403`) on `core`, `core_service`, and unregistered `~/Sites` dirs; `homelab-admin` allowed on all valid targets. | Block Release |
| **Pre-Flight & `.env` Safety** | `test_daemon_preflight_and_dotenv_safety`: Workload with malicious `.env` (`$(touch ...)`) or prohibited Compose directive (`privileged: true`, `/var/run/docker.sock`) is blocked / parsed inertly with zero shell execution. | Block Release |
| **Concurrency Lock (`409`)** | `test_concurrent_mutation_conflict`: Second concurrent mutation on the same target immediately returns `409 ERR_CONCURRENT_MUTATION` and logs `DENIED`. | Block Release |
| **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/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.
+27 -10
View File
@@ -29,21 +29,27 @@ This document explains the secrets distribution architecture, runtime projection
│ 3. /run/secrets/gitops/webhook_secret │ │ 3. /run/secrets/gitops/webhook_secret │
│ -> Consumed by homelab-gitops.service for HMAC verification │ │ -> Consumed by homelab-gitops.service for HMAC verification │
│ │ │ │
│ 4. /run/credentials/ddclient.service/ddclient.conf │ │ 4. /run/secrets/appctl/tokens.json (mode 0400, homelab-appctl) │
│ -> Consumed by homelab-appctl.service for SHA-256 Bearer auth │
│ │
│ 5. /run/secrets/gitops/appctl_token (mode 0400, operatorUser) │
│ -> Consumed by homelab-gitops.service worker for UDS daemon auth │
│ │
│ 6. /run/credentials/ddclient.service/ddclient.conf │
│ -> Consumed by systemd ddclient service │ │ -> Consumed by systemd ddclient service │
│ │ │ │
│ 5. /run/secrets/pdf_decrypt_password │ │ 7. /run/secrets/pdf_decrypt_password │
│ -> Consumed by shell pdf_dc utility │ │ -> Consumed by shell pdf_dc utility │
└────────────────────────────────────────────────────────────────────────┘ └────────────────────────────────────────────────────────────────────────┘
``` ```
--- ---
## 3. Projected Secret Templates ## 3. Projected Secret Templates & Token Store
### A. Core Platform Environment (`/run/secrets/homeserver.env`) ### A. Core Platform Environment (`/run/secrets/homeserver.env`)
Generated by `nixos/modules/homeserver.nix`. Supplies credentials to the Core Compose stack: Generated by `nixos/modules/homeserver.nix`. Supplies credentials to the Core Compose stack:
* `DOMAIN`: Apex domain (`roadtotech.me`). * `DOMAIN`: Apex domain (e.g., `example.com`).
* `DYNU_API_KEY`: API key for Dynu DNS-01 ACME Let's Encrypt validation. * `DYNU_API_KEY`: API key for Dynu DNS-01 ACME Let's Encrypt validation.
* `ACME_EMAIL`: Account email for Let's Encrypt certificates. * `ACME_EMAIL`: Account email for Let's Encrypt certificates.
* `AUTHELIA_SESSION_SECRET`: Authelia cookie encryption secret. * `AUTHELIA_SESSION_SECRET`: Authelia cookie encryption secret.
@@ -54,7 +60,13 @@ Generated by `nixos/modules/homeserver.nix`. Supplies credentials to the Core Co
* `SMTP_SERVER`, `SMTP_PORT`, `SMTP_LOGIN`, `SMTP_KEY`: Outbound relay credentials (Brevo) for Stalwart mail transport. * `SMTP_SERVER`, `SMTP_PORT`, `SMTP_LOGIN`, `SMTP_KEY`: Outbound relay credentials (Brevo) for Stalwart mail transport.
### B. Workload Deployments Environment (`/run/secrets/traefik-deployments.env`) ### B. Workload Deployments Environment (`/run/secrets/traefik-deployments.env`)
Generated by `nixos/modules/traefik-deployments.nix`. Projects shared infrastructure secrets and workload credentials that `appctl` sources when orchestrating stacks in `~/Sites` (such as database passwords, API keys, and runner tokens). Generated by `nixos/modules/traefik-deployments.nix`. Projects shared infrastructure secrets and workload credentials that `appctl` parses inertly in pure Python when orchestrating stacks in `~/Sites` (such as database passwords, API keys, and runner tokens).
### 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()`, 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 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.
--- ---
@@ -80,6 +92,9 @@ lldap:
admin_password: "..." admin_password: "..."
gitops: gitops:
webhook_secret: "..." webhook_secret: "..."
appctl_token: "..."
appctl:
tokens_json: "[...]"
brevo: brevo:
smtp_login: "..." smtp_login: "..."
smtp_key: "..." smtp_key: "..."
@@ -88,7 +103,7 @@ brevo:
### 3. Save and Apply Changes ### 3. Save and Apply Changes
Saving the file in your editor automatically re-encrypts it with Age. Apply the updated templates to running services: Saving the file in your editor automatically re-encrypts it with Age. Apply the updated templates to running services:
```bash ```bash
sudo nixos-rebuild switch --flake ~/Core#server sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
``` ```
--- ---
@@ -97,8 +112,8 @@ sudo nixos-rebuild switch --flake ~/Core#server
Homelab Core separates **user identity** from **static platform secrets**: Homelab Core separates **user identity** from **static platform secrets**:
* **Static Secrets**: Stored in `nixos/secrets.yaml` (system API keys, JWT secrets, database passwords). * **Static Secrets**: Stored in `nixos/secrets.yaml` (system API keys, JWT secrets, database passwords, control-plane token hashes).
* **Dynamic User Directory**: User accounts, credentials, and group memberships are managed live in **LLDAP** (`https://users.roadtotech.me`). User account updates do not require editing `secrets.yaml` or rebuilding NixOS. * **Dynamic User Directory**: User accounts, credentials, and group memberships are managed live in **LLDAP** (`https://users.${HOMELAB_DOMAIN}`). User account updates do not require editing `secrets.yaml` or rebuilding NixOS.
* **Authelia Integration**: Authelia queries LLDAP over LDAP (`ldap://lldap:3890`) at runtime using credentials projected from `/run/secrets/homeserver.env`. * **Authelia Integration**: Authelia queries LLDAP over LDAP (`ldap://lldap:3890`) at runtime using credentials projected from `/run/secrets/homeserver.env`.
--- ---
@@ -109,12 +124,14 @@ Homelab Core separates **user identity** from **static platform secrets**:
| :--- | :--- | :--- | :--- | | :--- | :--- | :--- | :--- |
| **Declarative Config** | `~/Core/nixos/*.nix`, `docker-compose.yml` | ✅ Yes | System and container definitions | | **Declarative Config** | `~/Core/nixos/*.nix`, `docker-compose.yml` | ✅ Yes | System and container definitions |
| **Encrypted Secrets** | `~/Core/nixos/secrets.yaml` | ✅ Yes (Encrypted) | SOPS Age-encrypted secret source | | **Encrypted Secrets** | `~/Core/nixos/secrets.yaml` | ✅ Yes (Encrypted) | SOPS Age-encrypted secret source |
| **Runtime Secrets** | `/run/secrets/*` | ❌ No (RAM tmpfs) | Ephemeral decrypted environment files | | **Runtime Secrets** | `/run/secrets/*` | ❌ No (RAM tmpfs) | Ephemeral decrypted environment & token files |
| **Control Plane Audit** | `/var/log/homelab/appctl/audit.jsonl` | ❌ No | Append-only JSONL security & mutation log (`0600`) |
| **Control Plane Locks** | `/var/lib/homelab/appctl/locks/` | ❌ No | Per-target `flock` files & `_homepage_sync.lock` |
| **SSL Certificates** | `~/Core/config/letsencrypt/acme.json` | ❌ No | Active Let's Encrypt certificates (mode 0600) | | **SSL Certificates** | `~/Core/config/letsencrypt/acme.json` | ❌ No | Active Let's Encrypt certificates (mode 0600) |
| **User Directory** | `~/Core/config/lldap/data/` | ❌ No | LLDAP SQLite database (`users.db`) | | **User Directory** | `~/Core/config/lldap/data/` | ❌ No | LLDAP SQLite database (`users.db`) |
| **Auth Database** | `~/Core/config/authelia/db.sqlite3` | ❌ No | Authelia session database | | **Auth Database** | `~/Core/config/authelia/db.sqlite3` | ❌ No | Authelia session database |
| **Mail Data & Keys** | `~/Core/config/stalwart/` | ❌ No | Stalwart mail storage, DKIM keys, mailboxes | | **Mail Data & Keys** | `~/Core/config/stalwart/` | ❌ No | Stalwart mail storage, DKIM keys, mailboxes |
| **Webmail Storage** | `~/Core/config/snappymail/data/` | ❌ No | SnappyMail configuration and sessions | | **Workload State Root** | `~/var/lib/homelab/<app>/` | ❌ No | Per-workload persistent runtime state (e.g., `snappymail`) |
| **Container Volumes** | Docker volume `dozzle_data` | ❌ No | Dozzle UI preferences and state | | **Container Volumes** | Docker volume `dozzle_data` | ❌ No | Dozzle UI preferences and state |
| **DDNS History** | `/var/lib/dynu/ip_history.jsonl` | ❌ No | Historical WAN IP transitions log | | **DDNS History** | `/var/lib/dynu/ip_history.jsonl` | ❌ No | Historical WAN IP transitions log |
| **GitOps State** | `~/.local/state/homelab/gitops/` | ❌ No | Deployment locks, pending JSONs, status logs | | **GitOps State** | `~/.local/state/homelab/gitops/` | ❌ No | Deployment locks, pending JSONs, status logs |
+82 -12
View File
@@ -12,10 +12,10 @@ When provisioning bare-metal hardware or a virtual machine from a NixOS Minimal
1. Partition and format disks according to `nixos/hardware-configuration.nix` (e.g. boot EFI partition and root filesystem). 1. Partition and format disks according to `nixos/hardware-configuration.nix` (e.g. boot EFI partition and root filesystem).
2. Mount partitions under `/mnt`. 2. Mount partitions under `/mnt`.
3. **Restore Host Secrets Key**: Copy the host SSH private key to `/mnt/etc/ssh/ssh_host_ed25519_key` (mode `0600`). This is required because `sops-nix` decrypts `nixos/secrets.yaml` during system activation. 3. **Restore Host Secrets Key**: Copy the host SSH private key to `/mnt/etc/ssh/ssh_host_ed25519_key` (mode `0600`). This is required because `sops-nix` decrypts `nixos/secrets.yaml` during system activation.
4. Clone the Core repository to `/mnt/home/kiskaadee/Core`. 4. Clone the Core repository to `/mnt/home/<operator>/Core`.
5. Run the NixOS installer: 5. Run the NixOS installer:
```bash ```bash
nixos-install --flake /mnt/home/kiskaadee/Core#server nixos-install --flake /mnt/home/<operator>/Core#server
reboot reboot
``` ```
@@ -32,24 +32,64 @@ sudo ls -l /etc/ssh/ssh_host_ed25519_key
sudo chmod 600 /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 ```bash
cd ~/Core cd ~/Core
sudo nixos-rebuild switch --flake ~/Core#server sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
``` ```
This configures: This configures:
* Docker daemon, host firewall rules, and system packages. * Docker daemon, host firewall rules, and system packages.
* Decrypted secret files in `/run/secrets/homeserver.env` and `/run/secrets/traefik-deployments.env`. * 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: The Core Compose stack and workloads require the `proxy-net` and `socket-net` bridge networks:
```bash ```bash
docker network create proxy-net 2>/dev/null || true docker network create proxy-net 2>/dev/null || true
docker network create socket-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 ```bash
sudo systemctl start homeserver-core sudo systemctl start homeserver-core
``` ```
@@ -58,7 +98,7 @@ Check running containers:
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" 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: 1. Trigger an immediate DDNS update:
```bash ```bash
sudo systemctl start dynu-monitor sudo systemctl start dynu-monitor
@@ -68,11 +108,39 @@ docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
appctl ssl traefik appctl ssl traefik
``` ```
### Step 6: Initialize LLDAP Directory ### Step 7: Initialize LLDAP Directory
1. Navigate to `https://users.roadtotech.me`. 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`). 2. Authenticate using `admin` and the password configured in `nixos/secrets.yaml` (`lldap/admin_password`).
3. Create standard user accounts and assign them to required groups. 3. Create standard user accounts and assign them to required groups.
### Step 8: Provision Read-Only Agent SSH Access (`agents`)
The `agents` user provides a restricted, read-only SSH identity for automated or agentic diagnostics without granting `sudo`, `docker` group membership, or write access to host state.
1. **Generate a dedicated Ed25519 SSH keypair** on your workstation:
```bash
ssh-keygen -t ed25519 -f ~/.ssh/canopy_agents -C "canopy-agents"
```
2. **Wire the public key into NixOS**:
Add the contents of `~/.ssh/canopy_agents.pub` to `users.users.agents.openssh.authorizedKeys.keys` in `nixos/configuration.nix` and apply the configuration on the server:
```bash
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
```
`nixos/configuration.nix` assigns `agents` only to `homelab-operators` (for read-only `appctl` socket queries) and `systemd-journal` (for `journalctl`), and enforces `Match User agents` with `ForceCommand` (`nixos/scripts/agents-force-command.sh`), `PermitTTY no`, `PasswordAuthentication no`, and forwarding disabled.
3. **Configure workstation `~/.ssh/config`** (replace `<server-host>` with your host or `server.example.test`):
```sshconfig
Host server-agents
HostName <server-host>
User agents
IdentityFile ~/.ssh/canopy_agents
IdentitiesOnly yes
```
4. **Verify read-only inspection** from the workstation:
```bash
ssh server-agents "docker ps"
ssh server-agents "appctl list --core"
ssh server-agents "journalctl -u homelab-appctl -n 5"
```
--- ---
## 3. Onboarding a New Application Workload ## 3. Onboarding a New Application Workload
@@ -89,10 +157,11 @@ git init
### Step 2: Create `app.yaml` Manifest ### Step 2: Create `app.yaml` Manifest
Create `~/Sites/homelab-myapp/app.yaml`: Create `~/Sites/homelab-myapp/app.yaml`:
```yaml ```yaml
schema_version: "1.0"
name: "myapp" name: "myapp"
aliases: aliases:
- "app" - "app"
domain: "myapp.roadtotech.me" domain: "myapp.example.com"
description: "My New Application Service" description: "My New Application Service"
visible: true visible: true
auth: false auth: false
@@ -104,6 +173,7 @@ env:
deployment: deployment:
branch: "main" branch: "main"
strategy: "compose"
actions: actions:
- git_pull - git_pull
- compose_up - compose_up
@@ -165,7 +235,7 @@ Before committing changes to Homelab Core, run the repository test runner:
```bash ```bash
cd ~/Core cd ~/Core
./scripts/test ./scripts/run-tests
``` ```
This runs: This runs:
* Code formatting and lint checks (`ruff`). * Code formatting and lint checks (`ruff`).
Generated
+7 -7
View File
@@ -2,11 +2,11 @@
"nodes": { "nodes": {
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1790463110, "lastModified": 1795234589,
"narHash": "sha256-VZHcT2wKLkApBCACQ2SH4P1jVZUbbOA7jWAGi1MIViw=", "narHash": "sha256-pAEASBc6wof0S58XcSEdZoQ2iFQDkCnZwH+wFLrkd1Q=",
"rev": "e158d9ed9b51c98974c5e66e1ba1c9e0255fecaa", "rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f",
"type": "tarball", "type": "tarball",
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1080189.e158d9ed9b51/nixexprs.tar.zst" "url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1125864.2786a2a72088/nixexprs.tar.zst"
}, },
"original": { "original": {
"type": "tarball", "type": "tarball",
@@ -26,11 +26,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1790498116, "lastModified": 1794866654,
"narHash": "sha256-rs9meAYxW3zzrh43yaW7htrqCD+X9+pupDPHN86fumI=", "narHash": "sha256-Y28AMB8lyKjASdJ0BVsR2AqR1cUsVuo8RVVpzHoECho=",
"owner": "Mic92", "owner": "Mic92",
"repo": "sops-nix", "repo": "sops-nix",
"rev": "5efb5a6f4f5ab192817d28557dd4d650fa14d866", "rev": "7c637afdccdf9bcf35c4a2d67b58a77c1fd843a4",
"type": "github" "type": "github"
}, },
"original": { "original": {
+16 -9
View File
@@ -1,5 +1,5 @@
{ {
description = "Homelab Core — Turnkey Declarative NixOS Appliance for roadtotech.me"; description = "Homelab Core — Turnkey Declarative NixOS Appliance";
inputs = { inputs = {
nixpkgs.url = "https://channels.nixos.org/nixos-unstable/nixexprs.tar.zst"; nixpkgs.url = "https://channels.nixos.org/nixos-unstable/nixexprs.tar.zst";
@@ -14,6 +14,12 @@
let let
system = "x86_64-linux"; system = "x86_64-linux";
pkgs = nixpkgs.legacyPackages.${system}; pkgs = nixpkgs.legacyPackages.${system};
pythonEnv = pkgs.python3.withPackages (ps: with ps; [
pyyaml
types-pyyaml
pytest
pydantic
]);
in in
{ {
nixosConfigurations.server = nixpkgs.lib.nixosSystem { nixosConfigurations.server = nixpkgs.lib.nixosSystem {
@@ -27,26 +33,26 @@
devShells.${system}.default = pkgs.mkShell { devShells.${system}.default = pkgs.mkShell {
buildInputs = with pkgs; [ buildInputs = with pkgs; [
(python3.withPackages (ps: with ps; [ pythonEnv
pyyaml
types-pyyaml
pytest
]))
pyright pyright
ruff ruff
]; ];
shellHook = '' shellHook = ''
git config core.hooksPath .githooks 2>/dev/null || true git config core.hooksPath .githooks 2>/dev/null || true
if [ -d .venv ] && [ ! -L .venv ]; then
rm -rf .venv
fi
ln -sfn ${pythonEnv} .venv
''; '';
}; };
checks.${system} = { checks.${system} = {
test-suite = pkgs.runCommand "core-tests" { test-suite = pkgs.runCommand "core-tests" {
nativeBuildInputs = with pkgs; [ nativeBuildInputs = with pkgs; [
python3 git
python3Packages.pytest pythonEnv
python3Packages.pyyaml
ruff ruff
pyright
]; ];
} '' } ''
mkdir -p $out mkdir -p $out
@@ -54,6 +60,7 @@
chmod -R u+w source chmod -R u+w source
cd source cd source
HOME=/tmp ruff check --no-cache . HOME=/tmp ruff check --no-cache .
HOME=/tmp pyright
HOME=/tmp pytest -o cache_dir=/tmp/.pytest_cache tests/ HOME=/tmp pytest -o cache_dir=/tmp/.pytest_cache tests/
''; '';
}; };
+62 -9
View File
@@ -1,5 +1,5 @@
# 🌐 Server NixOS Configuration — Turnkey Headless Homelab Appliance # 🌐 Server NixOS Configuration — Turnkey Headless Homelab Appliance
# Standalone declarative configuration for the roadtotech.me homelab server. # Standalone declarative configuration for the homelab server.
# No Home Manager. No shared desktop modules. # No Home Manager. No shared desktop modules.
# Goal: wipe & restore from any NixOS installation via `nixos-install --flake ~/Core#server` # Goal: wipe & restore from any NixOS installation via `nixos-install --flake ~/Core#server`
@@ -10,21 +10,43 @@
./hardware-configuration.nix # Server-specific disk and CPU configuration ./hardware-configuration.nix # Server-specific disk and CPU configuration
./modules/homeserver.nix # Core services: systemd units, Authelia, SOPS secrets ./modules/homeserver.nix # Core services: systemd units, Authelia, SOPS secrets
./modules/traefik-deployments.nix # Traefik deployment secrets and env templates ./modules/traefik-deployments.nix # Traefik deployment secrets and env templates
./modules/dynu.nix # Dynu DDNS smart IP monitor service
./modules/shell.nix # Declarative bash environment for the server ./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 = "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 ────────────────────────────────────────────── # ── SOPS secrets configuration ──────────────────────────────────────────────
# Set once here to avoid duplicate-option conflicts across submodules # Set once here to avoid duplicate-option conflicts across submodules
sops.defaultSopsFile = ./secrets.yaml; sops.defaultSopsFile = ./secrets.yaml;
sops.defaultSopsFormat = "yaml"; sops.defaultSopsFormat = "yaml";
# ── Nix settings ───────────────────────────────────────────────────────────── # ── Nix settings & maintenance ───────────────────────────────────────────────
nix.settings.experimental-features = [ "nix-command" "flakes" ]; nix.settings.experimental-features = [ "nix-command" "flakes" ];
# Pin nixpkgs registry to the flake input (avoids GitHub API calls from the CLI) # Pin nixpkgs registry to the flake input (avoids GitHub API calls from the CLI)
nix.registry.nixpkgs.flake = inputs.nixpkgs; nix.registry.nixpkgs.flake = inputs.nixpkgs;
# Automated garbage collection and store hardlink deduplication
nix.gc = {
automatic = true;
dates = "weekly";
options = "--delete-older-than 14d";
};
nix.optimise.automatic = true;
nixpkgs.config.allowUnfree = true; nixpkgs.config.allowUnfree = true;
# ── Regional & locale settings ─────────────────────────────────────────────── # ── Regional & locale settings ───────────────────────────────────────────────
@@ -45,24 +67,54 @@
networking.hostName = "server"; networking.hostName = "server";
networking.networkmanager.enable = true; networking.networkmanager.enable = true;
# ── User account ───────────────────────────────────────────────────────────── # ── User accounts ────────────────────────────────────────────────────────────
users.users.kiskaadee = { users.users.${config.homelab.operatorUser} = {
isNormalUser = true; isNormalUser = true;
description = "Primary server administrator";
openssh.authorizedKeys.keys = [ openssh.authorizedKeys.keys = [
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICAVPPMk+WApUd/fo78+lsRGnLKSlY4GDZiNGKwBAifD" "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICAVPPMk+WApUd/fo78+lsRGnLKSlY4GDZiNGKwBAifD"
]; ];
extraGroups = [ extraGroups = [
"wheel" # sudo access "wheel" # sudo access
"docker" # run docker without sudo "docker" # run docker without sudo
"homelab-operators" # access /run/homelab/appctl.sock
"networkmanager" # modify network settings "networkmanager" # modify network settings
]; ];
}; };
users.users.agents = {
isNormalUser = true;
description = "Read-only agent inspection user";
openssh.authorizedKeys.keys = [
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIE1pxTdygG5696q0jT7clfJZWtx48ugfUjpzvkHzovVd canopy-agents"
];
extraGroups = [
"homelab-operators" # read-only access via /run/homelab/appctl.sock
"systemd-journal" # read-only access to journalctl
];
};
# ── SSH ────────────────────────────────────────────────────────────────────── # ── SSH ──────────────────────────────────────────────────────────────────────
services.openssh = { services.openssh = let
agentsForceCommand = pkgs.writeShellScriptBin "agents-force-command" ''
export CORE_DIR="''${CORE_DIR:-/home/${config.homelab.operatorUser}/Core}"
export WORKLOADS_DIR="''${WORKLOADS_DIR:-/home/${config.homelab.operatorUser}/Workloads}"
export DOCKER_HOST="''${DOCKER_HOST:-tcp://127.0.0.1:2375}"
exec ${pkgs.bash}/bin/bash ${./scripts/agents-force-command.sh} "$@"
'';
in {
enable = true; enable = true;
ports = [ 22 ]; ports = [ 22 ];
settings.PermitRootLogin = "no"; settings.PermitRootLogin = "no";
extraConfig = ''
Match User agents
ForceCommand ${agentsForceCommand}/bin/agents-force-command
AllowTcpForwarding no
X11Forwarding no
AllowAgentForwarding no
PermitTTY no
PasswordAuthentication no
'';
}; };
# ── Virtualisation ─────────────────────────────────────────────────────────── # ── Virtualisation ───────────────────────────────────────────────────────────
@@ -119,10 +171,11 @@
# Secrets tooling (required for sops-nix secret decryption and manual re-encryption) # Secrets tooling (required for sops-nix secret decryption and manual re-encryption)
sops sops
age age
# Python runtime (hard requirement for appctl and gitops_dispatcher.py) # Python runtime (hard requirement for appctl, core_manifest, and gitops_dispatcher.py)
python3.withPackages(ps: with ps; [ (python3.withPackages (ps: with ps; [
pyyaml pyyaml
]) pydantic
]))
# Modern shell utilities # Modern shell utilities
eza # ls replacement eza # ls replacement
ripgrep # rg — fast grep ripgrep # rg — fast grep
+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" ];
# };
};
}
-88
View File
@@ -1,88 +0,0 @@
# 🌐 Dynu DDNS IP Monitor & Updater Service
# This NixOS module configures a smart, local-first IP change detector.
# It queries public IP providers, maintains a history log of WAN IP rotations,
# and triggers ddclient only when an actual change is detected to prevent API rate limits.
{ config, lib, pkgs, ... }:
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);
in
{
# Define the keys to decrypt
sops.secrets."dynu/user" = { };
sops.secrets."dynu/domain" = { };
sops.secrets."dynu/password" = { };
sops.secrets."system/pdf_decrypt_password" = {
owner = "kiskaadee";
};
# Assemble the ddclient config file securely at boot time in /run/secrets/
# Defaults to owner root:root (which avoids dynamic user evaluation issues)
sops.templates."ddclient.conf" = {
content = builtins.replaceStrings
[ "@dynu_user@" "@dynu_password@" "@dynu_domain@" ]
[
config.sops.placeholder."dynu/user"
config.sops.placeholder."dynu/password"
config.sops.placeholder."dynu/domain"
]
(builtins.readFile ../scripts/ddclient.conf);
};
# Enable ddclient and feed it the decrypted configuration template via systemd credentials
services.ddclient = {
enable = true;
configFile = "/run/credentials/ddclient.service/ddclient.conf";
};
systemd.services.ddclient = {
serviceConfig = {
# Securely load the root-owned secret file into the dynamic ddclient service
LoadCredential = [ "ddclient.conf:${config.sops.templates."ddclient.conf".path}" ];
};
};
# Disable ddclient's automatic timer.
# This stops ddclient from polling every 10 minutes on its own.
systemd.timers.ddclient.enable = false;
# Define the smart IP change detector service
systemd.services.dynu-monitor = {
description = "Dynu DDNS Smart IP Change Monitor";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
path = with pkgs; [
systemd # Required for systemctl
];
serviceConfig = {
Type = "oneshot";
User = "root";
Group = "root";
StateDirectory = "dynu";
Environment = "HISTORY_FILE=/var/lib/dynu/ip_history.jsonl";
ExecStart = "${ipMonitorScript}/bin/dynu-ip-monitor";
TimeoutSec = 30;
# Hardening
NoNewPrivileges = true;
PrivateTmp = true;
ProtectSystem = "strict";
ProtectHome = true;
ReadWritePaths = "/var/lib/dynu";
};
};
# Run the smart IP change monitor periodically (every 30 minutes)
systemd.timers.dynu-monitor = {
description = "Run Dynu IP monitor periodically";
timerConfig = {
OnBootSec = "5min";
OnUnitActiveSec = "30min";
AccuracySec = "1min";
Persistent = true;
};
wantedBy = [ "timers.target" ];
};
}
+258 -18
View File
@@ -4,9 +4,113 @@
{ config, lib, pkgs, ... }: { config, lib, pkgs, ... }:
{ {
# Declarative configuration options for Homelab Core
options.homelab = {
domain = lib.mkOption {
type = lib.types.str;
default = "example.test";
description = "Canonical domain for homelab services";
};
operatorUser = lib.mkOption {
type = lib.types.str;
default = "operator";
description = "Primary operator user identity";
};
coreDir = lib.mkOption {
type = lib.types.str;
default = "/home/${config.homelab.operatorUser}/Core";
description = "Path to Homelab Core repository";
};
sitesDir = lib.mkOption {
type = lib.types.str;
default = "/home/${config.homelab.operatorUser}/Workloads";
description = "Path to Workloads directory (legacy option name: sitesDir)";
};
workloadGrants = lib.mkOption {
type = lib.types.attrsOf (lib.types.submodule {
options = {
devices = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
description = "Host device paths permitted for this workload (prefer specific nodes such as /dev/dri/renderD128).";
};
groups = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
description = "Host group names or numeric GIDs permitted in group_add and user: primary GID.";
};
readOnlyPaths = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
description = "Host directories permitted for read-only (:ro) bind mounts.";
};
};
});
default = {};
description = "Host-granted hardware devices, groups, and read-only storage paths keyed by workload name.";
};
};
config = let
domainParts = lib.splitString "." config.homelab.domain;
ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts);
in {
# ── Workload Capability Grant Invariants (ADR-0005) ─────────────────────────
assertions = let
grantsList = lib.mapAttrsToList (app: grant: { inherit app grant; }) config.homelab.workloadGrants;
privilegedGroups = [ "0" "root" "wheel" "docker" ];
hasInvalidPath = p:
!(lib.hasPrefix "/" p)
|| (lib.hasInfix "/../" p)
|| (lib.hasSuffix "/.." p)
|| (p == "..");
in
(map ({ app, grant }: {
assertion = lib.all (g: !(lib.elem (lib.toLower (lib.strings.trim g)) privilegedGroups)) grant.groups;
message = "homelab.workloadGrants.${app}.groups must not contain privileged groups (0, root, wheel, docker).";
}) grantsList)
++ (map ({ app, grant }: {
assertion = lib.all (p: !(hasInvalidPath p)) grant.devices;
message = "homelab.workloadGrants.${app}.devices must contain absolute paths without '..' traversal.";
}) grantsList)
++ (map ({ app, grant }: {
assertion = lib.all (p: !(hasInvalidPath p)) grant.readOnlyPaths;
message = "homelab.workloadGrants.${app}.readOnlyPaths must contain absolute paths without '..' traversal.";
}) grantsList);
# ── Host Capability Grants Projection (/etc/homelab/grants.json) ─────────────
environment.etc."homelab/grants.json" = {
user = "root";
group = "homelab-operators";
mode = "0640";
text = builtins.toJSON {
schemaVersion = "1.0";
workloads = config.homelab.workloadGrants;
};
};
# ── Host Activation Guard ────────────────────────────────────────────────────
# Prevents activating on a live host if homelab.domain defaulted to example.test (e.g. forgot --impure)
system.activationScripts.checkHomelabDomain = {
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 # Define the keys to decrypt from secrets.yaml
sops.secrets = lib.genAttrs [ sops.secrets = (lib.genAttrs [
"dynu/api_key" "cloudflare/dns_api_token"
"traefik/acme_email" "traefik/acme_email"
"authelia/session_secret" "authelia/session_secret"
"authelia/storage_encryption_key" "authelia/storage_encryption_key"
@@ -18,15 +122,30 @@
"brevo/smtp_login" "brevo/smtp_login"
"brevo/smtp_key" "brevo/smtp_key"
"diun/smtp_password" "diun/smtp_password"
] (name: { owner = "kiskaadee"; }); ] (name: { owner = config.homelab.operatorUser; })) // {
"appctl/tokens_json" = {
owner = "homelab-appctl";
group = "homelab-operators";
mode = "0400";
path = "/run/secrets/appctl/tokens.json";
};
"gitops/appctl_token" = {
owner = config.homelab.operatorUser;
group = "homelab-operators";
mode = "0400";
};
};
# Generate the unified environment file at runtime in /run/secrets/homeserver.env # Generate the unified environment file at runtime in /run/secrets/homeserver.env
sops.templates."homeserver.env" = { sops.templates."homeserver.env" = {
owner = "kiskaadee"; owner = config.homelab.operatorUser;
group = "homelab-operators";
mode = "0440";
content = lib.generators.toKeyValue {} { content = lib.generators.toKeyValue {} {
DOMAIN = "roadtotech.me"; DOMAIN = config.homelab.domain;
LLDAP_LDAP_BASE_DN = ldapBaseDn;
DOCKER_API_VERSION = "1.40"; DOCKER_API_VERSION = "1.40";
DYNU_API_KEY = config.sops.placeholder."dynu/api_key"; CF_DNS_API_TOKEN = config.sops.placeholder."cloudflare/dns_api_token";
ACME_EMAIL = config.sops.placeholder."traefik/acme_email"; ACME_EMAIL = config.sops.placeholder."traefik/acme_email";
AUTHELIA_SESSION_SECRET = config.sops.placeholder."authelia/session_secret"; AUTHELIA_SESSION_SECRET = config.sops.placeholder."authelia/session_secret";
AUTHELIA_STORAGE_ENCRYPTION_KEY = config.sops.placeholder."authelia/storage_encryption_key"; AUTHELIA_STORAGE_ENCRYPTION_KEY = config.sops.placeholder."authelia/storage_encryption_key";
@@ -53,7 +172,7 @@
serviceConfig = { serviceConfig = {
Type = "oneshot"; Type = "oneshot";
RemainAfterExit = true; RemainAfterExit = true;
WorkingDirectory = "/home/kiskaadee/Core"; WorkingDirectory = config.homelab.coreDir;
ExecStart = "${pkgs.docker-compose}/bin/docker-compose --env-file ${config.sops.templates."homeserver.env".path} up -d --remove-orphans"; ExecStart = "${pkgs.docker-compose}/bin/docker-compose --env-file ${config.sops.templates."homeserver.env".path} up -d --remove-orphans";
ExecStop = "${pkgs.docker-compose}/bin/docker-compose down"; ExecStop = "${pkgs.docker-compose}/bin/docker-compose down";
}; };
@@ -62,45 +181,166 @@
# Declarative Dynamic GitOps Webhook Service (Internal Port 9000) # Declarative Dynamic GitOps Webhook Service (Internal Port 9000)
systemd.services.homelab-gitops = { systemd.services.homelab-gitops = {
description = "Dynamic Homelab GitOps Webhook Dispatcher"; description = "Dynamic Homelab GitOps Webhook Dispatcher";
after = [ "network-online.target" "docker.service" ]; after = [ "network-online.target" "docker.service" "homelab-appctl.service" ];
wants = [ "network-online.target" ]; wants = [ "network-online.target" "homelab-appctl.service" ];
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
path = with pkgs; [ git docker docker-compose python3 coreutils bash openssh ]; path = with pkgs; [
git
docker
docker-compose
(python3.withPackages (ps: with ps; [ pyyaml pydantic ]))
coreutils
bash
openssh
];
environment = { environment = {
GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path; 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 = { serviceConfig = {
Type = "simple"; Type = "simple";
User = "kiskaadee"; User = config.homelab.operatorUser;
WorkingDirectory = "/home/kiskaadee/Core"; SupplementaryGroups = [ "docker" "homelab-operators" ];
WorkingDirectory = config.homelab.coreDir;
ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [ ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [
{ {
id = "deploy"; id = "deploy";
execute-command = "/home/kiskaadee/Core/scripts/gitops_dispatcher.py"; execute-command = "${config.homelab.coreDir}/scripts/gitops_dispatcher.py";
pass-arguments-to-command = [ pass-arguments-to-command = [
{ source = "raw-request-body"; } { source = "raw-request-body"; }
{ source = "header"; name = "X-Gitea-Signature"; } { source = "header"; name = "X-Gitea-Signature"; }
{ source = "header"; name = "X-Gitea-Event"; } { source = "header"; name = "X-Gitea-Event"; }
]; ];
command-working-directory = "/home/kiskaadee/Core"; command-working-directory = config.homelab.coreDir;
response-message = "Deployment payload dispatched successfully."; response-message = "Deployment payload dispatched successfully.";
} }
])} -port 9000 -verbose"; ])} -port 9000 -verbose";
Restart = "on-failure"; Restart = "on-failure";
RestartSec = "5s"; RestartSec = "5s";
# Privilege separation & Systemd sandboxing
NoNewPrivileges = true;
PrivateTmp = true;
ProtectSystem = "strict";
ProtectHome = "read-only";
ProtectKernelTunables = true;
ProtectControlGroups = true;
ReadWritePaths = [
config.homelab.sitesDir
"/home/${config.homelab.operatorUser}/.local/state/homelab"
"-/run/homelab"
];
}; };
}; };
# Ensure persistent directories have proper permissions for container runtimes (e.g. Stalwart UID 2000, SnappyMail) # Declarative Users and Groups for Control Plane Service Identity
users.groups.homelab-operators.members = [ config.homelab.operatorUser ];
users.users.homelab-appctl = {
isSystemUser = true;
group = "homelab-operators";
extraGroups = [ "docker" ];
description = "Homelab appctl control plane daemon service user";
};
# Declarative appctl Control Plane Daemon (Internal HTTP 9001 + UDS /run/homelab/appctl.sock)
systemd.services.homelab-appctl = {
description = "Homelab appctl Control Plane Daemon";
after = [ "network-online.target" "docker.service" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
path = with pkgs; [
git
docker
docker-compose
(python3.withPackages (ps: with ps; [ pyyaml pydantic ]))
coreutils
bash
openssh
];
environment = {
HOME = "/var/lib/homelab/appctl";
DOCKER_CONFIG = "/var/lib/homelab/appctl/.docker";
HOMELAB_DOMAIN = config.homelab.domain;
APPCTL_SOCKET_PATH = "/run/homelab/appctl.sock";
APPCTL_HTTP_HOST = "127.0.0.1";
APPCTL_HTTP_PORT = "9001";
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.sitesDir}/deployments.yaml";
HOMELAB_GRANTS_FILE = "/etc/homelab/grants.json";
};
serviceConfig = {
Type = "simple";
User = "homelab-appctl";
Group = "homelab-operators";
SupplementaryGroups = [ "docker" ];
WorkingDirectory = config.homelab.coreDir;
ExecStart = "${(pkgs.python3.withPackages (ps: with ps; [ pyyaml pydantic ]))}/bin/python3 ${config.homelab.coreDir}/scripts/appctl_daemon.py";
Restart = "always";
RestartSec = "5s";
RuntimeDirectory = "homelab";
RuntimeDirectoryMode = "0750";
StateDirectory = "homelab/appctl";
StateDirectoryMode = "0700";
LogsDirectory = "homelab/appctl";
LogsDirectoryMode = "0700";
NoNewPrivileges = true;
PrivateTmp = true;
ProtectSystem = "strict";
ProtectHome = "read-only";
ProtectKernelTunables = true;
ProtectControlGroups = true;
ReadWritePaths = [
config.homelab.sitesDir
"-/home/${config.homelab.operatorUser}/var/lib/homelab"
"-${config.homelab.coreDir}/config/homepage"
"/var/log/homelab/appctl"
"-/var/lib/homelab/appctl"
"-/run/homelab"
];
};
};
# Ensure persistent directories have proper permissions for container runtimes
systemd.tmpfiles.rules = [ systemd.tmpfiles.rules = [
"d /home/kiskaadee/Core/config/stalwart/data 0777 kiskaadee users -" "d ${config.homelab.coreDir}/config/stalwart/data 0777 ${config.homelab.operatorUser} users -"
"d /home/kiskaadee/Core/config/stalwart/etc 0777 kiskaadee users -" "d ${config.homelab.coreDir}/config/stalwart/etc 0777 ${config.homelab.operatorUser} users -"
"d /home/kiskaadee/Core/config/snappymail/data 0777 kiskaadee 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 -"
"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) # Open ports in the firewall for Traefik, Gitea SSH, GitOps Webhook Receiver, and Mail (SMTP, Submission, SMTPS, IMAPS, ManageSieve)
networking.firewall.allowedTCPPorts = [ 80 443 2223 9000 25 465 587 993 4190 ]; networking.firewall.allowedTCPPorts = [ 80 443 2223 9000 25 465 587 993 4190 ];
};
} }
+6 -3
View File
@@ -3,9 +3,12 @@
# This replaces the laptop-inherited ~/.bashrc with a clean, server-appropriate profile. # This replaces the laptop-inherited ~/.bashrc with a clean, server-appropriate profile.
# Delivered via /etc/bashrc — no Home Manager required. # Delivered via /etc/bashrc — no Home Manager required.
{ pkgs, ... }: { config, pkgs, ... }:
{ {
sops.secrets."system/pdf_decrypt_password" = {
owner = config.homelab.operatorUser;
};
# ── Shell-integrated programs ───────────────────────────────────────────────── # ── Shell-integrated programs ─────────────────────────────────────────────────
# These handle both installation and bash hook injection automatically # These handle both installation and bash hook injection automatically
programs.zoxide.enable = true; # smart cd with bash init wired into /etc/bashrc programs.zoxide.enable = true; # smart cd with bash init wired into /etc/bashrc
@@ -62,8 +65,8 @@
reload = "exec bash"; reload = "exec bash";
pgoog = "ping google.com -c 3"; pgoog = "ping google.com -c 3";
wifi = "nmtui"; wifi = "nmtui";
# NixOS rebuild targeting this flake # NixOS rebuild targeting this flake (path scheme + impure required for instance.nix)
nix-switch = "sudo nixos-rebuild switch --flake ~/Core#server"; nix-switch = "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure";
}; };
interactiveShellInit = '' interactiveShellInit = ''
+19 -17
View File
@@ -15,31 +15,33 @@
"postgres/password" "postgres/password"
"postgres/db" "postgres/db"
"gitea/runner_token" "gitea/runner_token"
] (name: { owner = "kiskaadee"; }); ] (name: { owner = config.homelab.operatorUser; });
# Generate the unified environment file at runtime in /run/secrets/traefik-deployments.env # Generate the unified environment file at runtime in /run/secrets/traefik-deployments.env
sops.templates."traefik-deployments.env" = { sops.templates."traefik-deployments.env" = {
owner = "kiskaadee"; owner = config.homelab.operatorUser;
group = "homelab-operators";
mode = "0440";
content = lib.generators.toKeyValue {} { content = lib.generators.toKeyValue {} {
# --- Core / Infrastructure Settings --- # --- Core / Infrastructure Settings ---
PROXY_NETWORK = "proxy-net"; PROXY_NETWORK = "proxy-net";
CERT_RESOLVER = "myresolver"; CERT_RESOLVER = "myresolver";
DOMAIN_SUFFIX = "roadtotech.me"; DOMAIN_SUFFIX = config.homelab.domain;
# --- Dashboard & Landing --- # --- Dashboard & Landing ---
DASHBOARD_DOMAIN = "dashboard.roadtotech.me"; DASHBOARD_DOMAIN = "dashboard.${config.homelab.domain}";
LANDING_DOMAIN = "roadtotech.me"; LANDING_DOMAIN = config.homelab.domain;
# --- Docs --- # --- Docs ---
DOCS_DOMAIN = "docs.roadtotech.me"; DOCS_DOMAIN = "docs.${config.homelab.domain}";
DOCS_PROJECT_PATH = "/home/kiskaadee/Brain"; DOCS_PROJECT_PATH = "/home/${config.homelab.operatorUser}/Brain";
# --- Excalidraw --- # --- Excalidraw ---
EXCALIDRAW_DOMAIN = "excalidraw.roadtotech.me"; EXCALIDRAW_DOMAIN = "excalidraw.${config.homelab.domain}";
# --- Gitea --- # --- Gitea ---
GITEA_DOMAIN = "gitea.roadtotech.me"; GITEA_DOMAIN = "gitea.${config.homelab.domain}";
GITEA_SSH_DOMAIN = "gitea.roadtotech.me"; GITEA_SSH_DOMAIN = "gitea.${config.homelab.domain}";
GITEA_SSH_PORT = "2223"; GITEA_SSH_PORT = "2223";
GITEA_AUTH_MIDDLEWARE = "https-redirect@docker"; GITEA_AUTH_MIDDLEWARE = "https-redirect@docker";
GITEA_RUNNER_TOKEN = config.sops.placeholder."gitea/runner_token"; GITEA_RUNNER_TOKEN = config.sops.placeholder."gitea/runner_token";
@@ -48,7 +50,7 @@
JELLYFIN_SERVICE_NAME = "jellyfin"; JELLYFIN_SERVICE_NAME = "jellyfin";
JELLYFIN_CONTAINER_NAME = "jellyfin"; JELLYFIN_CONTAINER_NAME = "jellyfin";
JELLYFIN_IMAGE_TAG = "latest"; JELLYFIN_IMAGE_TAG = "latest";
JELLYFIN_DOMAIN = "jellyfin.roadtotech.me"; JELLYFIN_DOMAIN = "jellyfin.${config.homelab.domain}";
JELLYFIN_TZ = "UTC"; JELLYFIN_TZ = "UTC";
JELLYFIN_PUID = "1000"; JELLYFIN_PUID = "1000";
JELLYFIN_PGID = "1000"; JELLYFIN_PGID = "1000";
@@ -60,7 +62,7 @@
# --- Learning Dashboard --- # --- Learning Dashboard ---
LEARNING_SERVICE_NAME = "learning-hub"; LEARNING_SERVICE_NAME = "learning-hub";
LEARNING_DOMAIN = "learning.roadtotech.me"; LEARNING_DOMAIN = "learning.${config.homelab.domain}";
LEARNING_APP_PORT = "8000"; LEARNING_APP_PORT = "8000";
LEARNING_SOCKET_PROXY_NETWORK = "socket-net"; LEARNING_SOCKET_PROXY_NETWORK = "socket-net";
LEARNING_DOCKER_HOST = "tcp://socket-proxy:2375"; LEARNING_DOCKER_HOST = "tcp://socket-proxy:2375";
@@ -68,25 +70,25 @@
TURSO_AUTH_TOKEN = config.sops.placeholder."learning/turso_auth_token"; TURSO_AUTH_TOKEN = config.sops.placeholder."learning/turso_auth_token";
# --- Mermaid --- # --- Mermaid ---
MERMAID_DOMAIN = "mermaid.roadtotech.me"; MERMAID_DOMAIN = "mermaid.${config.homelab.domain}";
MERMAID_SERVICE_NAME = "mermaid"; MERMAID_SERVICE_NAME = "mermaid";
# --- Minecraft --- # --- Minecraft ---
MINECRAFT_DOMAIN = "minecraft.roadtotech.me"; MINECRAFT_DOMAIN = "minecraft.${config.homelab.domain}";
# --- MongoDB --- # --- MongoDB ---
MONGO_ROOT_USERNAME = config.sops.placeholder."mongo/root_username"; MONGO_ROOT_USERNAME = config.sops.placeholder."mongo/root_username";
MONGO_ROOT_PASSWORD = config.sops.placeholder."mongo/root_password"; MONGO_ROOT_PASSWORD = config.sops.placeholder."mongo/root_password";
MONGO_DOMAIN = "mongodb.roadtotech.me"; MONGO_DOMAIN = "mongodb.${config.homelab.domain}";
# --- PostgreSQL --- # --- PostgreSQL ---
POSTGRES_USER = config.sops.placeholder."postgres/user"; POSTGRES_USER = config.sops.placeholder."postgres/user";
POSTGRES_PASSWORD = config.sops.placeholder."postgres/password"; POSTGRES_PASSWORD = config.sops.placeholder."postgres/password";
POSTGRES_DB = config.sops.placeholder."postgres/db"; POSTGRES_DB = config.sops.placeholder."postgres/db";
POSTGRES_DOMAIN = "pgsql.roadtotech.me"; POSTGRES_DOMAIN = "pgsql.${config.homelab.domain}";
# --- Ollama --- # --- Ollama ---
OLLAMA_DOMAIN = "ollama.roadtotech.me"; OLLAMA_DOMAIN = "ollama.${config.homelab.domain}";
OLLAMA_API_KEY = config.sops.placeholder."ollama/api_key"; OLLAMA_API_KEY = config.sops.placeholder."ollama/api_key";
OLLAMA_REPLICAS = "1"; OLLAMA_REPLICAS = "1";
OLLAMA_DATA_VOLUME = "ollama_data"; OLLAMA_DATA_VOLUME = "ollama_data";
+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
View File
@@ -1,12 +0,0 @@
# General configuration
syslog=no
pid=/run/ddclient/ddclient.pid
cache=/var/lib/ddclient/ddclient.cache
usev4=webv4
# Provider definition using credentials decrypted at runtime
protocol=dyndns2
server=api.dynu.com
login=@dynu_user@
password=@dynu_password@
@dynu_domain@
-204
View File
@@ -1,204 +0,0 @@
"""
Dynu DDNS Smart IP Change Monitor and Updater.
This script determines the current public IPv4 address by querying multiple
external resolvers sequentially. It compares the discovered IP against the last
recorded successful IP in a local history log. If a change is detected, it
triggers the `ddclient.service` on-demand to perform the DNS record update.
This local-first state verification prevents making redundant API requests to
the DNS provider, avoiding rate-limiting, IP bans, or API abuse flags.
"""
import json
import os
import re
import subprocess
import sys
import urllib.error
import urllib.request
from datetime import datetime, timezone
# History file location storing the transition log of public IP states.
# Defaults to a state directory managed securely by the systemd service unit.
HISTORY_FILE = os.environ.get("HISTORY_FILE", "/var/lib/dynu/ip_history.jsonl")
# Fallback sequence of external services to discover the public WAN IP.
PROVIDERS = [
"https://api.ipify.org",
"https://ifconfig.me/ip",
"https://icanhazip.com",
"https://wtfismyip.com/text"
]
def is_valid_public_ipv4(ip):
"""
Validates that a string is a properly formatted public IPv4 address.
This function excludes standard private, loopback, link-local, and CGNAT
blocks to avoid recording temporary, local, or invalid network states.
"""
match = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
if not match:
return False
octets = [int(x) for x in match.groups()]
if any(x > 255 for x in octets):
return False
a, b, _c, _d = octets
# RFC 1918 Private ranges: 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12
if a == 10:
return False
if a == 192 and b == 168:
return False
if a == 172 and 16 <= b <= 31:
return False
# Carrier-Grade NAT (CGNAT) RFC 6598: 100.64.0.0/10
if a == 100 and 64 <= b <= 127:
return False
# Loopback address range: 127.0.0.0/8
if a == 127:
return False
# Link-local addresses: 169.254.0.0/16
return not (a == 169 and b == 254)
def get_public_ip():
"""
Queries public IP providers until a valid public IPv4 is returned.
Returns:
str: The validated public IP string, or None if all providers fail.
"""
errors = []
for provider in PROVIDERS:
try:
req = urllib.request.Request(
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:
ip = response.read().decode('utf-8').strip()
if is_valid_public_ipv4(ip):
return ip
else:
errors.append(f"{provider}: invalid public IPv4 '{ip}'")
except (urllib.error.URLError, OSError, ValueError) as e:
errors.append(f"{provider}: {e!s}")
print(
f"Error: All IP discovery providers failed. Details: {errors}",
file=sys.stderr
)
return None
def get_last_recorded_ip():
"""
Reads the history log to locate the last successful IP address.
Returns:
str: The last successfully updated IP, or None if no log exists yet.
"""
if not os.path.exists(HISTORY_FILE):
return None
try:
with open(HISTORY_FILE, "r") as f:
lines = f.readlines()
if not lines:
return None
# Search backwards to find the most recent successful transition
for line in reversed(lines):
try:
entry = json.loads(line)
if entry.get("status") == "success":
return entry.get("ip")
except json.JSONDecodeError:
continue
except OSError as e:
print(f"Warning: Failed to read history file: {e}", file=sys.stderr)
return None
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=timezone.utc).isoformat(),
"ip": ip,
"status": status
}
if details:
entry["details"] = details
try:
with open(HISTORY_FILE, "a") as f:
f.write(json.dumps(entry) + "\n")
except OSError as e:
print(f"Error: Failed to write to history file: {e}", file=sys.stderr)
def trigger_ddclient():
"""
Invokes the systemd service unit for `ddclient` on-demand.
Returns:
tuple: (bool, str) representing (success_boolean, error_details_string)
"""
try:
# Run ddclient as a one-shot activation via systemd to perform API call
res = subprocess.run(
["systemctl", "start", "ddclient.service"],
capture_output=True,
text=True,
check=False,
)
if res.returncode == 0:
return True, None
else:
err_msg = (
f"systemctl exited with {res.returncode}: "
f"{res.stderr.strip()}"
)
return False, err_msg
except (OSError, subprocess.SubprocessError) as e:
return False, str(e)
def main():
"""
Orchestrator logic for DDNS state management.
"""
current_ip = get_public_ip()
if not current_ip:
sys.exit(1)
last_ip = get_last_recorded_ip()
if current_ip == last_ip:
# IP matches last recorded working IP; do nothing to conserve quota
sys.exit(0)
print(f"IP rotation detected! Old: {last_ip}, New: {current_ip}")
# Trigger ddclient to perform the DNS record update
success, error_msg = trigger_ddclient()
if success:
print("Dynu DDNS update via ddclient triggered successfully.")
record_ip(current_ip, "success")
else:
err_msg = f"Error: Failed to trigger ddclient update: {error_msg}"
print(err_msg, file=sys.stderr)
record_ip(current_ip, "failed_update", details=error_msg)
sys.exit(1)
if __name__ == "__main__":
main()
+10 -2
View File
@@ -30,6 +30,7 @@ system:
pdf_decrypt_password: ENC[AES256_GCM,data:n3XTANd+PbejUw==,iv:y2VIabyv/DfTgztbjS6M/xIfRNKOL+U+r3eXsal32OQ=,tag:oFpXg2E9dDM5dwkjSZkLgw==,type:str] pdf_decrypt_password: ENC[AES256_GCM,data:n3XTANd+PbejUw==,iv:y2VIabyv/DfTgztbjS6M/xIfRNKOL+U+r3eXsal32OQ=,tag:oFpXg2E9dDM5dwkjSZkLgw==,type:str]
gitops: gitops:
webhook_secret: ENC[AES256_GCM,data:Kj3d0Repa3OOvjCkW6+kakQEfsCdpdVJQd71Am6zQHBt7QkLtxlnovUmmS+zJ+jChQBbCc9/7LunFvFT2pL36w==,iv:qh1pEIVtvB/fxbMv+a9pworhbXsIpfF5gKWS22Zn0GU=,tag:D4RNXkWhg9l3BJFp7MMloA==,type:str] webhook_secret: ENC[AES256_GCM,data:Kj3d0Repa3OOvjCkW6+kakQEfsCdpdVJQd71Am6zQHBt7QkLtxlnovUmmS+zJ+jChQBbCc9/7LunFvFT2pL36w==,iv:qh1pEIVtvB/fxbMv+a9pworhbXsIpfF5gKWS22Zn0GU=,tag:D4RNXkWhg9l3BJFp7MMloA==,type:str]
appctl_token: ENC[AES256_GCM,data:+2BK6LejtvIj68+88zrjzgod8tXXVSRH+WpmIIHCbGU7aKbdTK20JlIIKb2u+2w/fHVrTwxUkX+dp5/AHsU+ZvVWh7tUsEo=,iv:tX5+bTfFFil46o7ZXa3dLIQH5+ET2e+75qRvjSJrhwU=,tag:mVGkDADx8RqaSi3AnDyPEw==,type:str]
lldap: lldap:
jwt_secret: ENC[AES256_GCM,data:RHtVgZJzNK7PFFvYO4jSsv+3928PYG2RdajG3ETEfN5eh0FwAmqcC98X2scT8H2JAeDV+bRI6QMZ3FoNRNcOHw==,iv:YGYImZJQzf1ONkc9lq2bEV/eWKIPfTyH+2hKzObaY08=,tag:jcUYKHrYSPYvHjQ86hLl0g==,type:str] jwt_secret: ENC[AES256_GCM,data:RHtVgZJzNK7PFFvYO4jSsv+3928PYG2RdajG3ETEfN5eh0FwAmqcC98X2scT8H2JAeDV+bRI6QMZ3FoNRNcOHw==,iv:YGYImZJQzf1ONkc9lq2bEV/eWKIPfTyH+2hKzObaY08=,tag:jcUYKHrYSPYvHjQ86hLl0g==,type:str]
key_seed: ENC[AES256_GCM,data:8Jf/xyMMXQFYxSO9RezTQRcS+Amm9hYOf97K03H/8cI=,iv:D5BJ4I12cMp2HAdCJC8MD/LnrBskbX7X/a6TnyisuMk=,tag:fhxge0iBSPllyrGQfCkw7w==,type:str] key_seed: ENC[AES256_GCM,data:8Jf/xyMMXQFYxSO9RezTQRcS+Amm9hYOf97K03H/8cI=,iv:D5BJ4I12cMp2HAdCJC8MD/LnrBskbX7X/a6TnyisuMk=,tag:fhxge0iBSPllyrGQfCkw7w==,type:str]
@@ -37,6 +38,13 @@ lldap:
brevo: brevo:
smtp_login: ENC[AES256_GCM,data:zfqKsAtoAOWCrSqx38sknwcJZT2m8W2J,iv:tMwTNDf+2CE3/8rKqWTWLl5Zp4LUVNSFV90QN94VXxo=,tag:XYXz9w3oIa0qkcfjCcgcYg==,type:str] smtp_login: ENC[AES256_GCM,data:zfqKsAtoAOWCrSqx38sknwcJZT2m8W2J,iv:tMwTNDf+2CE3/8rKqWTWLl5Zp4LUVNSFV90QN94VXxo=,tag:XYXz9w3oIa0qkcfjCcgcYg==,type:str]
smtp_key: ENC[AES256_GCM,data:YulXyaVF/sLWE9x12yxdBAj9KMbfP/CK/7FS3XkYO8sCj3GWgPbNoSaUT/9quLWHPtCsBxxdLeLoDNa1jE2WRyHP1W+Ioyyx5sAzdzevzHIBmfP+fdw0rKhe,iv:QT0HfzNPsTqXlN3IC/+bBzJfUzN9YkXYiv/3uqkXHBw=,tag:vBetkZPDYoh0Yy3BpMT9BQ==,type:str] smtp_key: ENC[AES256_GCM,data:YulXyaVF/sLWE9x12yxdBAj9KMbfP/CK/7FS3XkYO8sCj3GWgPbNoSaUT/9quLWHPtCsBxxdLeLoDNa1jE2WRyHP1W+Ioyyx5sAzdzevzHIBmfP+fdw0rKhe,iv:QT0HfzNPsTqXlN3IC/+bBzJfUzN9YkXYiv/3uqkXHBw=,tag:vBetkZPDYoh0Yy3BpMT9BQ==,type:str]
cloudflare:
account_name: ENC[AES256_GCM,data:fIuzvJbLoz/w,iv:tT3rCldA9hqHzKjJa4gENTk/XprzS5X6Wm/rqkb6jow=,tag:p0aEezfUFlJn25PdW/DAOA==,type:str]
global_api_key: ENC[AES256_GCM,data:IDFHetxM2LE1/cytHo2Jn16piLeIvM27ui3Qld4Z5hwWauDRaY05nZH6+V6ic9dYFfagvA==,iv:9q3cosnJ+eC1BLmQ1Hx1y3Dksyc5k4UMQPZ6Or9vWFE=,tag:k/RilX02EJzMWZcfzBtu4A==,type:str]
account_id: ENC[AES256_GCM,data:/IyUXySFGQSGs16Kv6yZajMiGTxwOuxILvcFZ/6YROo=,iv:TdMwtzs/LMnbhpsEbqunj4n+P+JxcscYGKaM42fYQ20=,tag:HHmIq03Jc4g8fBvuaWevAA==,type:str]
dns_api_token: ENC[AES256_GCM,data:lTByYg0BM+mloaHDb2WkN7LY9twnVzKn6NO8W1rTH5FXyWaNlEovLxCPT2sG+JuRfqGJ52w=,iv:nBX3rUSdf1wFSTz0sY/ApNKVaYkCPJAJPhmMu+abzhE=,tag:LK8qyYap/T1HZb+jWnHyuA==,type:str]
appctl:
tokens_json: ENC[AES256_GCM,data:O2vsiMMcZjsduFSRen1MnnckdRYK45aPH40EhX42h1WUwf62Nm58PV5BQJOgJ97AH3hOH97mzg1tjL0C1oV/epXMaypRWY9AGLS00CfzD2sgdM5Wx7VKbfGggFnGqgd7veaCA+pxUC0uTk/Dq2Cz/uhXhLX1wVjafX0OAqS6fxO+L9Oza3+RBtKgx2xX0AKW+KSZQUM1nvNW8R/Eyvnqvw2OSb2FdKN1CKhlVWhCZiaxTe8617BqGhJDL9pu4lfn0m+tdIwvluI3h8cmKuT6dzd01Jxr0EHBY/+mZZ/WQoNhIy4QulFpKiMudiT+WGzUm+UT4mYBoGwzQCVV8MD7W1r84mkbCkLc/HpWG08TqK4tpAdtLgYK3Zslr1+lmboWyJ6WcinmxkhUexhj+gTyfXYmVSB3fF8PIeyQINGB3rLvmpZ7DDMzYa1ICgFbJ6zmYa54TXRDLGzLD09koeDp9FhXNKPvuwz2x4uwWDDUfU8wwTkGbw==,iv:FJpB+WZiE4PKUhIuwBWIB/TLtifwCzGRMtbMx7x6ly8=,tag:NZQXYFnVBqbOONl+Yh3tuA==,type:str]
sops: sops:
age: age:
- enc: | - enc: |
@@ -57,7 +65,7 @@ sops:
yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A== yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A==
-----END AGE ENCRYPTED FILE----- -----END AGE ENCRYPTED FILE-----
recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg
lastmodified: "2026-09-25T00:49:38Z" lastmodified: "2026-11-23T20:45:18Z"
mac: ENC[AES256_GCM,data:EyJ9V0aYo7isyqnW6HWBz4hD2X6xa+VRNg3TaK88gkX6YCG/H0htBfMf/VYl/hOA/eEZW+uMVys8Ocula9zpY1Pd1gUbWt5FrXQvooYNhtCFCFUAJdsrmif8Ru7AXazFbyhhaeBSBjSQURM0qi69XqllVvfmiSz32WlX/QIOZ/c=,iv:znmm8JuFKSFl2IGGhRG77SE9kqy3uFWUK8VjocJ18n4=,tag:tG000kt5a6W1fa0IEfvLLQ==,type:str] mac: ENC[AES256_GCM,data:3Rm8olJtCErH+KGisvQENqwFhMF3Y9acXjrBHC7ot3ThRzT8Yo3X1RyxKXzyYzB6Yy2G3ua9yUtgQjydXgjQR1b6KY6ERmyu6H2S1IF/Ps4grYVZ6xEhJMDtjNKDvhtjhRM61eFByeYzJeHWD6K8dsxDcWUI2GKRRH7U8iG95Fo=,iv:/IY6iKamEEoi5vVLRGOmmPpyJte3amLfjVhYIDbMdBE=,tag:gT3RSrnwl0TH14LJvbiPlg==,type:str]
unencrypted_suffix: _unencrypted unencrypted_suffix: _unencrypted
version: 3.13.3 version: 3.13.3
+22
View File
@@ -1,2 +1,24 @@
[project]
name = "homelab-core"
version = "0.1.0"
description = "Homelab Core platform and orchestration"
requires-python = ">=3.13"
dependencies = [
"pyyaml>=6.0",
"pydantic>=2.0,<3.0",
]
[tool.pyright] [tool.pyright]
include = ["scripts"]
extraPaths = ["scripts"] extraPaths = ["scripts"]
venvPath = "."
venv = ".venv"
[tool.pytest.ini_options]
# Automatically adds app modules and script hooks to the sys.venvPath
pythonpath = [
".",
"scripts"
]
+35 -278
View File
@@ -1,162 +1,26 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# appctl - Unified, Manifest-Driven Container Orchestrator # appctl - Unified, Manifest-Driven Container Orchestrator
# Discovers individual application repositories located in ~/Sites/*/ # Thin CLI wrapper delegating operational commands to homelab-appctl.service over UDS
# Injects global homelab secrets, per-app metadata from app.yaml, and monitors Git sync
set -e set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENGINE="$SCRIPT_DIR/appctl_engine.py" ENGINE="$SCRIPT_DIR/appctl_engine.py"
ENV_FILE="/run/secrets/rendered/traefik-deployments.env" if [ -z "$PYTHON_BIN" ]; then
if [ ! -f "$ENV_FILE" ] && [ -f "/run/secrets/traefik-deployments.env" ]; then if [ -x "$SCRIPT_DIR/../.venv/bin/python3" ]; then
ENV_FILE="/run/secrets/traefik-deployments.env" PYTHON_BIN="$SCRIPT_DIR/../.venv/bin/python3"
else
PYTHON_BIN="python3"
fi 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 fi
SOCKET_PATH="${APPCTL_SOCKET_PATH:-/run/homelab/appctl.sock}"
CLI_CLIENT="$SCRIPT_DIR/appctl_cli.py"
if [ -f "$ENV_FILE" ]; then # Fast-path local shell completion helpers
set -a case "${1:-}" in
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a
fi
# 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=$(python3 "$ENGINE" resolve "$query" 2>/dev/null || 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=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('type', 'app'))" "$resolved_json")
APP_DIR=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d['dir_path'])" "$resolved_json")
CANONICAL_NAME=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d['name'])" "$resolved_json")
TARGET_CONTAINER=$(python3 -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=$(python3 -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:-roadtotech.me}"
# 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.)
eval "$(python3 -c "
import json, sys
d = json.loads(sys.argv[1])
env_dict = d.get('env', {})
for k, v in env_dict.items():
if v != '' and v is not None:
print(f'export {k}=\"{v}\"')
" "$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)
python3 "$ENGINE" list "${@:2}"
;;
ssl)
python3 "$ENGINE" ssl "${@:2}"
;;
info)
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
python3 "$ENGINE" info "${@:2}"
;;
sync)
python3 "$ENGINE" sync "${@:2}"
;;
complete) complete)
python3 "$ENGINE" complete "${@:2}" exec "$PYTHON_BIN" "$ENGINE" complete "${@:2}"
;;
resolve)
python3 "$ENGINE" resolve "${@:2}"
;; ;;
completion) completion)
cat <<'EOF' cat <<'EOF'
@@ -172,7 +36,7 @@ _appctl_completions() {
cword=$COMP_CWORD cword=$COMP_CWORD
fi 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 if [ "$cword" -eq 1 ]; then
COMPREPLY=( $(compgen -W "$commands" -- "$cur") ) COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
@@ -206,7 +70,25 @@ _appctl_completions() {
COMPREPLY=( $(compgen -W "$services" -- "$cur") ) COMPREPLY=( $(compgen -W "$services" -- "$cur") )
fi 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 local services
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true) services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
COMPREPLY=( $(compgen -W "$services" -- "$cur") ) COMPREPLY=( $(compgen -W "$services" -- "$cur") )
@@ -218,138 +100,13 @@ _appctl_completions() {
} }
complete -F _appctl_completions appctl complete -F _appctl_completions appctl
EOF 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}"
python3 "$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}"
python3 "$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}"
python3 "$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 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}"
python3 "$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 exit 1
fi
exec "$PYTHON_BIN" "$CLI_CLIENT" "$@"
;; ;;
esac esac
+406
View File
@@ -0,0 +1,406 @@
"""
appctl_audit.py — Append-Only Audit Logger & Per-Target Lock Manager (P4 Slice 2)
Governs the audit telemetry and concurrency control for homelab-appctl.service:
- Append-only JSONL audit writer adhering to RFC-compliant schema (mode 0600)
- Pre-execution DISPATCHED fail-closed disk guard
- Sensitive parameter and error redaction (*_KEY, *_SECRET, *_PASSWORD, etc.)
- Non-blocking per-target flock context manager raising ConcurrentMutationError (409)
"""
from __future__ import annotations
import fcntl
import os
import re
import secrets
import threading
from datetime import UTC, datetime
from enum import StrEnum
from pathlib import Path
from types import TracebackType
from typing import Annotated, Any, Literal, Self
from appctl_contracts import StrictModel
from pydantic import BeforeValidator, ConfigDict, Field, StrictInt, StrictStr
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
)
class AuditPhase(StrEnum):
"""Lifecycle phases for control plane audit events."""
DISPATCHED = "DISPATCHED"
COMPLETED = "COMPLETED"
FAILED = "FAILED"
DENIED = "DENIED"
def _coerce_phase(v: Any) -> Any:
if isinstance(v, str):
try:
return AuditPhase(v)
except ValueError:
return v
return v
FlexibleAuditPhase = Annotated[
AuditPhase,
BeforeValidator(_coerce_phase),
]
class PrincipalAudit(StrictModel):
"""Authenticated principal details captured in audit records."""
identity: StrictStr
role: StrictStr
token_id: StrictStr | None = None
auth_method: StrictStr
class AuditResult(StrictModel):
"""Execution outcome details captured in audit records."""
status: Literal["SUCCESS", "FAILED", "DENIED", "IN_PROGRESS"]
exit_code: StrictInt | None = None
duration_ms: StrictInt | None = None
commit_sha: StrictStr | None = None
error_code: StrictStr | None = None
message: StrictStr | None = None
class AuditEvent(StrictModel):
"""RFC-compliant single-line JSONL audit event model (ADR-0002 / DEC-03)."""
model_config = ConfigDict(extra="forbid", strict=True)
audit_version: Literal["1.0"] = "1.0"
event_id: StrictStr
operation_id: StrictStr
timestamp: StrictStr
phase: FlexibleAuditPhase
principal: PrincipalAudit
action: StrictStr
target: StrictStr | None = None
transport: StrictStr
origin: StrictStr
client: StrictStr
parameters: dict[str, Any] = Field(default_factory=dict)
result: AuditResult | None = None
class AuditPersistenceError(Exception):
"""Raised when an audit record cannot be persisted or flushed to disk."""
class ConcurrentMutationError(Exception):
"""Raised when a per-target operation lock cannot be acquired (409 Conflict)."""
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."
)
super().__init__(msg)
def redact_sensitive_data(val: Any) -> Any:
"""
Recursively redact values whose dictionary keys match sensitive patterns
(*_KEY, *_SECRET, *_PASSWORD, *_TOKEN, *_PASS, *_HASH).
"""
if isinstance(val, dict):
return {
k: "[REDACTED]"
if REDACT_KEY_PATTERNS.match(str(k))
else redact_sensitive_data(v)
for k, v in val.items()
}
if isinstance(val, list):
return [redact_sensitive_data(v) for v in val]
return val
def generate_event_id() -> str:
"""Generate a unique event identifier."""
return f"evt_{secrets.token_hex(6)}"
def generate_operation_id() -> str:
"""Generate a unique operation identifier."""
return f"op_{secrets.token_hex(6)}"
def current_iso_timestamp() -> str:
"""Current UTC timestamp formatted as ISO 8601 with millisecond precision."""
now = datetime.now(UTC)
return now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
class AuditLogger:
"""
Append-only thread-safe audit logger writing single-line JSONL records.
Enforces mode 0600 on the log file and provides a fail-closed pre-execution
DISPATCHED disk guard.
"""
def __init__(self, log_path: Path | str | None = None) -> None:
if log_path is not None:
self.log_path = Path(log_path)
elif "APPCTL_AUDIT_LOG" in os.environ:
self.log_path = Path(os.environ["APPCTL_AUDIT_LOG"])
else:
self.log_path = DEFAULT_AUDIT_LOG
self._lock = threading.Lock()
def _ensure_log_file(self) -> None:
"""Ensure parent directories exist and file is initialized with mode 0600."""
self.log_path.parent.mkdir(parents=True, exist_ok=True)
if not self.log_path.exists():
fd = os.open(
self.log_path,
os.O_WRONLY | os.O_CREAT | os.O_APPEND,
0o600,
)
os.close(fd)
def emit_event(self, event: AuditEvent) -> None:
"""
Append an audit event as a single JSON line to the audit log.
Flushes and fsyncs to ensure durability. Raises AuditPersistenceError on failure.
"""
with self._lock:
try:
self._ensure_log_file()
line = event.model_dump_json() + "\n"
fd = os.open(
self.log_path,
os.O_WRONLY | os.O_APPEND,
0o600,
)
try:
os.write(fd, line.encode("utf-8"))
os.fsync(fd)
finally:
os.close(fd)
except OSError as err:
raise AuditPersistenceError(
f"Failed to persist audit event '{event.event_id}': {err}"
) from err
def log_dispatched(
self,
operation_id: str,
principal: PrincipalAudit,
action: str,
target: str | None,
transport: str,
origin: str,
client: str,
parameters: dict[str, Any],
) -> AuditEvent:
"""
Fail-closed pre-execution disk guard: logs DISPATCHED phase before any
subprocess or filesystem mutation begins. Raises AuditPersistenceError if disk write fails.
"""
clean_params = redact_sensitive_data(parameters)
event = AuditEvent(
event_id=generate_event_id(),
operation_id=operation_id,
timestamp=current_iso_timestamp(),
phase=AuditPhase.DISPATCHED,
principal=principal,
action=action,
target=target,
transport=transport,
origin=origin,
client=client,
parameters=clean_params,
result=AuditResult(status="IN_PROGRESS"),
)
self.emit_event(event)
return event
def log_completed(
self,
operation_id: str,
principal: PrincipalAudit,
action: str,
target: str | None,
transport: str,
origin: str,
client: str,
parameters: dict[str, Any],
duration_ms: int,
commit_sha: str | None = None,
message: str | None = None,
) -> AuditEvent:
"""Log COMPLETED phase upon clean operation termination."""
clean_params = redact_sensitive_data(parameters)
event = AuditEvent(
event_id=generate_event_id(),
operation_id=operation_id,
timestamp=current_iso_timestamp(),
phase=AuditPhase.COMPLETED,
principal=principal,
action=action,
target=target,
transport=transport,
origin=origin,
client=client,
parameters=clean_params,
result=AuditResult(
status="SUCCESS",
exit_code=0,
duration_ms=duration_ms,
commit_sha=commit_sha,
error_code=None,
message=message or "Operation completed successfully",
),
)
self.emit_event(event)
return event
def log_failed(
self,
operation_id: str,
principal: PrincipalAudit,
action: str,
target: str | None,
transport: str,
origin: str,
client: str,
parameters: dict[str, Any],
duration_ms: int | None = None,
exit_code: int | None = None,
error_code: str | None = None,
message: str | None = None,
) -> AuditEvent:
"""Log FAILED phase when validation or execution fails."""
clean_params = redact_sensitive_data(parameters)
clean_msg = redact_sensitive_data(message) if message else None
event = AuditEvent(
event_id=generate_event_id(),
operation_id=operation_id,
timestamp=current_iso_timestamp(),
phase=AuditPhase.FAILED,
principal=principal,
action=action,
target=target,
transport=transport,
origin=origin,
client=client,
parameters=clean_params,
result=AuditResult(
status="FAILED",
exit_code=exit_code,
duration_ms=duration_ms,
error_code=error_code,
message=clean_msg,
),
)
self.emit_event(event)
return event
def log_denied(
self,
operation_id: str,
principal: PrincipalAudit,
action: str,
target: str | None,
transport: str,
origin: str,
client: str,
parameters: dict[str, Any],
error_code: str,
message: str,
) -> AuditEvent:
"""Log DENIED phase when authentication, RBAC, or concurrency lock rejects request."""
clean_params = redact_sensitive_data(parameters)
event = AuditEvent(
event_id=generate_event_id(),
operation_id=operation_id,
timestamp=current_iso_timestamp(),
phase=AuditPhase.DENIED,
principal=principal,
action=action,
target=target,
transport=transport,
origin=origin,
client=client,
parameters=clean_params,
result=AuditResult(
status="DENIED",
error_code=error_code,
message=message,
),
)
self.emit_event(event)
return event
class TargetLock:
"""Context manager acquiring a non-blocking per-target flock."""
def __init__(self, lock_path: Path, target: str) -> None:
self.lock_path = lock_path
self.target = target
self._fd: int | None = None
def __enter__(self) -> Self:
self.lock_path.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(
self.lock_path,
os.O_RDWR | os.O_CREAT,
0o600,
)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (BlockingIOError, OSError) as err:
os.close(fd)
raise ConcurrentMutationError(self.target) from err
self._fd = fd
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
if self._fd is not None:
try:
fcntl.flock(self._fd, fcntl.LOCK_UN)
finally:
os.close(self._fd)
self._fd = None
class TargetLockManager:
"""Manages operational per-target locks under /var/lib/homelab/appctl/locks."""
def __init__(self, lock_dir: Path | str | None = None) -> None:
if lock_dir is not None:
self.lock_dir = Path(lock_dir)
elif "APPCTL_LOCK_DIR" in os.environ:
self.lock_dir = Path(os.environ["APPCTL_LOCK_DIR"])
else:
self.lock_dir = DEFAULT_LOCK_DIR
def lock_target(self, target: str) -> TargetLock:
"""Return a non-blocking flock context manager for a workload target."""
clean_target = re.sub(r"[^a-zA-Z0-9._-]", "_", target)
lock_path = self.lock_dir / f"{clean_target}.lock"
return TargetLock(lock_path, target)
def homepage_sync_lock(self) -> TargetLock:
"""Return a non-blocking flock context manager for homepage compilation."""
lock_path = self.lock_dir / "_homepage_sync.lock"
return TargetLock(lock_path, "_homepage_sync")
+398
View File
@@ -0,0 +1,398 @@
"""
appctl_auth.py — Authentication & 3-Role RBAC Policy Enforcement (P4 Slice 3)
Implements the zero-trust authorization pipeline for homelab-appctl.service:
- SOPS-managed SHA-256 Bearer token store loader (mode 0400 check, constant-time compare)
- 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 ~/Workloads/deployments.yaml (or HOMELAB_DEPLOYMENTS_FILE / WORKLOADS_DIR override) for homelab-operator
"""
from __future__ import annotations
import hashlib
import hmac
import json
import os
import stat
from enum import StrEnum
from pathlib import Path
from typing import Annotated, Any, Literal
from appctl_contracts import (
ErrorCode,
OperationType,
StrictModel,
)
from pydantic import BeforeValidator, ConfigDict, Field, StrictStr
try:
import yaml
except ImportError:
yaml = None # type: ignore[assignment]
DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json")
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",
"traefik",
"authelia",
"lldap",
"stalwart",
"dozzle",
"socket-proxy",
"homepage",
"diun",
"watchtower",
}
)
SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset(
{
OperationType.WORKLOAD_CONFIG,
OperationType.WORKLOAD_LOGS,
}
)
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(
{
OperationType.WORKLOAD_LIST,
OperationType.WORKLOAD_GET,
OperationType.WORKLOAD_RESOLVE,
OperationType.PLATFORM_SSL,
OperationType.PLATFORM_HEALTH,
}
)
class Role(StrEnum):
"""Hierarchical authorization roles for homelab-appctl.service."""
ADMIN = "homelab-admin"
OPERATOR = "homelab-operator"
VIEWER = "homelab-viewer"
def _coerce_role(v: Any) -> Any:
if isinstance(v, str):
try:
return Role(v)
except ValueError:
return v
return v
FlexibleRole = Annotated[
Role,
BeforeValidator(_coerce_role),
]
class Principal(StrictModel):
"""Authenticated caller identity and operational role."""
model_config = ConfigDict(extra="forbid", strict=True)
identity: StrictStr
role: FlexibleRole
token_id: StrictStr | None = None
auth_method: Literal["bearer_token", "unix_peercred"]
class TokenDescriptor(StrictModel):
"""Internal model for token entries in SOPS tokens.json store."""
model_config = ConfigDict(extra="forbid", strict=True)
token_id: StrictStr
identity: StrictStr
role: FlexibleRole
sha256: Annotated[StrictStr, Field(pattern=r"^[0-9a-fA-F]{64}$")]
class AuthenticationError(Exception):
"""Raised when authentication fails (401 Unauthorized)."""
def __init__(
self,
message: str = "Authentication required",
code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED,
) -> None:
super().__init__(message)
self.code = code
self.http_status = 401
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:
super().__init__(message)
self.code = code
self.http_status = 403
class TokenStore:
"""Loads and validates SHA-256 Bearer tokens from a mode 0400 store."""
def __init__(self, tokens_path: Path | str | None = None) -> None:
if tokens_path is not None:
self.tokens_path = Path(tokens_path)
elif "APPCTL_TOKENS_FILE" in os.environ:
self.tokens_path = Path(os.environ["APPCTL_TOKENS_FILE"])
else:
self.tokens_path = DEFAULT_TOKENS_FILE
def _verify_permissions(self) -> None:
"""Enforce strict 0400 file mode: readable only by owner, no write/exec, no group/world."""
if not self.tokens_path.is_file():
raise AuthenticationError(
f"Token store '{self.tokens_path}' not found",
code=ErrorCode.ERR_AUTH_REQUIRED,
)
# Check permissions: reject if group/world readable or writable (must be 0400)
mode = stat.S_IMODE(self.tokens_path.stat().st_mode)
if (mode & 0o077) != 0 or (mode & 0o200) != 0:
raise AuthenticationError(
f"Token store '{self.tokens_path}' has insecure mode {oct(mode)}; mode 0400 required",
code=ErrorCode.ERR_AUTH_REQUIRED,
)
def load_tokens(self) -> list[TokenDescriptor]:
"""Load and parse token descriptors from the token store."""
self._verify_permissions()
try:
content = self.tokens_path.read_text(encoding="utf-8")
data = json.loads(content)
if not isinstance(data, list):
raise TypeError("Tokens payload must be an array of token descriptors")
return [TokenDescriptor.model_validate(item) for item in data]
except (OSError, json.JSONDecodeError, ValueError, TypeError) as err:
raise AuthenticationError(
f"Failed to load token store '{self.tokens_path}': {err}",
code=ErrorCode.ERR_AUTH_REQUIRED,
) from err
def authenticate_bearer(self, secret: str) -> Principal:
"""
Hash secret with SHA-256 and look up against stored token descriptors using
constant-time hmac.compare_digest.
"""
if not secret:
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.lower()):
return Principal(
identity=token.identity,
role=token.role,
token_id=token.token_id,
auth_method="bearer_token",
)
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 ~/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 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
if not reg_file.is_file():
return set()
yaml_errors = (yaml.YAMLError,) if yaml is not None else ()
try:
content = reg_file.read_text(encoding="utf-8")
if yaml is not None:
data = yaml.safe_load(content)
else:
data = json.loads(content)
if not isinstance(data, dict):
return set()
admitted: set[str] = set()
repos = data.get("repositories", {})
if isinstance(repos, dict):
for name, entry in repos.items():
admitted.add(name)
if isinstance(entry, dict):
aliases = entry.get("aliases", [])
if isinstance(aliases, list):
for alias in aliases:
if isinstance(alias, str) and alias.strip():
admitted.add(alias.strip())
return admitted
except (
OSError,
UnicodeDecodeError,
ValueError,
json.JSONDecodeError,
*yaml_errors,
):
return set()
def authenticate_request(
transport: Literal["unix_socket", "http"],
auth_header: str | None,
peer_uid: int | None = None,
token_store: TokenStore | None = None,
) -> Principal:
"""
Authenticate an incoming request across transports:
- If Authorization header present: parses Bearer secret and verifies against TokenStore.
- If Authorization header missing over HTTP: fails closed with 401 ERR_AUTH_REQUIRED.
- If Authorization header missing over Unix socket: falls back to homelab-viewer with peer_uid.
"""
store = token_store or TokenStore()
if auth_header is not None:
header_val = auth_header.strip()
if not header_val.startswith("Bearer "):
raise AuthenticationError(
"Malformed Authorization header: must start with 'Bearer '",
code=ErrorCode.ERR_AUTH_REQUIRED,
)
secret = header_val[7:].strip()
if not secret:
raise AuthenticationError(
"Missing token secret in Authorization header",
code=ErrorCode.ERR_AUTH_REQUIRED,
)
return store.authenticate_bearer(secret)
# Missing Authorization header
if transport == "unix_socket":
if peer_uid is not None:
return Principal(
identity=f"unix_uid_{peer_uid}",
role=Role.VIEWER,
token_id=None,
auth_method="unix_peercred",
)
raise AuthenticationError(
"Missing peer credentials over Unix socket",
code=ErrorCode.ERR_AUTH_REQUIRED,
)
# HTTP transport requires Bearer token strictly
raise AuthenticationError(
"Bearer token required over network transport",
code=ErrorCode.ERR_AUTH_REQUIRED,
)
def enforce_rbac(
principal: Principal,
operation: OperationType,
target: str | None = None,
admitted_workloads: set[str] | None = None,
) -> None:
"""
Enforce 3-role RBAC policy (homelab-admin, homelab-operator, homelab-viewer).
Raises AuthorizationError (403) on violation.
"""
# 1. homelab-admin has unrestricted access across all operations and targets
if principal.role == Role.ADMIN:
return
# 2. homelab-operator:
if principal.role == Role.OPERATOR:
# Platform homepage sync allowed
if operation == OperationType.PLATFORM_SYNC_HOMEPAGE:
return
# Target checks for operations targeting infrastructure
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,
)
# Non-sensitive reads are permitted
if operation in READ_ONLY_OPERATIONS:
return
# Sensitive reads and mutations must target an admitted workload from deployments.yaml
if operation in SENSITIVE_OPERATIONS or operation in MUTATING_OPERATIONS:
if not target:
raise AuthorizationError(
f"Operation '{operation.value}' requires an explicit workload target",
code=ErrorCode.ERR_PERMISSION_DENIED,
)
registry = (
admitted_workloads
if admitted_workloads is not None
else load_admitted_workloads()
)
if target not in registry:
raise AuthorizationError(
f"Target '{target}' is not registered in deployments.yaml for role 'homelab-operator'",
code=ErrorCode.ERR_PERMISSION_DENIED,
)
return
# 3. homelab-viewer:
if principal.role == Role.VIEWER:
if operation in MUTATING_OPERATIONS:
raise AuthorizationError(
f"Role 'homelab-viewer' is not permitted to execute mutating operation '{operation.value}'",
code=ErrorCode.ERR_PERMISSION_DENIED,
)
if operation in SENSITIVE_OPERATIONS:
raise AuthorizationError(
f"Role 'homelab-viewer' is not permitted to access sensitive operation '{operation.value}'",
code=ErrorCode.ERR_PERMISSION_DENIED,
)
if operation in READ_ONLY_OPERATIONS:
return
raise AuthorizationError(
f"Operation '{operation.value}' denied for role '{principal.role.value}'",
code=ErrorCode.ERR_PERMISSION_DENIED,
)
+412
View File
@@ -0,0 +1,412 @@
#!/usr/bin/env python3
"""
appctl_cli.py — Thin HTTP/1.1 Unix Domain Socket Client for homelab-appctl
Dispatches CLI commands to the control plane daemon over /run/homelab/appctl.sock.
Supports local peercred viewer fallback, Bearer token authentication, and formatted output.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from pathlib import Path
from typing import Any
from appctl_contracts import (
OperationRequest,
OperationResponse,
OperationType,
)
from appctl_daemon import (
DEFAULT_SOCKET_PATH,
send_daemon_request,
)
def resolve_token(cli_token: str | None = None) -> str | None:
"""Resolve Bearer token from CLI flag, environment, or user token files."""
if cli_token:
return cli_token.strip()
if "APPCTL_TOKEN" in os.environ:
return os.environ["APPCTL_TOKEN"].strip()
token_candidates = [
Path.home() / ".config/homelab/token",
Path("/run/secrets/appctl/token"),
]
for path in token_candidates:
if path.is_file():
try:
return path.read_text(encoding="utf-8").strip()
except OSError:
continue
return None
def _format_workload_table(workloads: list[dict[str, Any]]) -> str:
"""Format a list of workload dictionaries into a human-readable tabular display."""
if not workloads:
return "ℹ️ No workloads found."
has_ssl = any("ssl" in w and isinstance(w["ssl"], dict) for w in workloads)
lines: list[str] = []
if has_ssl:
lines.append(
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
)
lines.append(
f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
)
else:
lines.append(
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN'}"
)
lines.append(
f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------'}"
)
for w in workloads:
name = str(w.get("name") or "-")
domain = str(w.get("domain") or "-")
status = str(w.get("status") or "-")
if w.get("manifest_error"):
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")
cert_status = (
str(ssl_info.get("status", "-"))
if isinstance(ssl_info, dict)
else "-"
)
lines.append(
f"{name:<16} {dep:<22} {prov:<22} {status:<15} {domain:<28} {cert_status}"
)
else:
lines.append(
f"{name:<16} {dep:<22} {prov:<24} {status:<15} {domain}"
)
return "\n".join(lines)
def _format_workload_info(workload: dict[str, Any]) -> str:
"""Format a single workload metadata dictionary for `appctl info`."""
name = workload.get("name", "unknown")
w_type = workload.get("type", workload.get("app_type", "app"))
header = (
f"ℹ️ Core Infrastructure Service: {name}"
if w_type in ("core", "core_service")
else f"ℹ️ Workload Overview: {name}"
)
lines = [
header,
"-" * 50,
f"Directory: {workload.get('dir_path', '-')}",
f"Domain: {workload.get('domain', '-')}",
f"Type: {w_type}",
f"Description: {workload.get('description', '-')}",
]
if workload.get("container"):
lines.append(f"Container: {workload['container']}")
aliases = workload.get("aliases")
if isinstance(aliases, list) and aliases:
lines.append(f"Aliases: {', '.join(str(a) for a in aliases)}")
networks = workload.get("networks")
if isinstance(networks, list) and networks:
lines.append(f"Networks: {', '.join(str(n) for n in networks)}")
if "auth" in workload:
lines.append(f"Auth Protected: {workload['auth']}")
if "visible" in workload:
lines.append(f"Dashboard: {'Visible' if workload['visible'] else 'Hidden'}")
source = workload.get("source")
if isinstance(source, dict):
lines.append(f"Source URL: {source.get('url', '-')}")
lines.append(f"Target Ref: {source.get('ref', '-')}")
if workload.get("manifest_error"):
lines.append(f"\n⚠️ Manifest Validation Error:\n {workload['manifest_error']}")
ssl_info = workload.get("ssl")
if isinstance(ssl_info, dict):
lines.append("\n🔒 SSL/TLS Certificate:")
lines.append(f" Status: {ssl_info.get('status', '-')}")
lines.append(f" Issuer: {ssl_info.get('issuer', '-')}")
lines.append(f" Expiration: {ssl_info.get('formatted_expiry', '-')}")
return "\n".join(lines)
def _format_ssl_info(ssl_info: dict[str, Any]) -> str:
"""Format SSL certificate details for `appctl ssl`."""
domain = ssl_info.get("domain", "-")
lines = [
f"🔒 SSL/TLS Certificate: {domain}",
"-" * 50,
f"Domain: {domain}",
f"Status: {ssl_info.get('status', '-')}",
f"Issuer: {ssl_info.get('issuer', '-')}",
f"Subject: {ssl_info.get('subject', '-')}",
f"Expiration: {ssl_info.get('not_after', '-')}",
]
if ssl_info.get("days_remaining") is not None:
lines.append(
f"Days Remaining: {ssl_info['days_remaining']} days ({ssl_info.get('formatted_expiry', '-')})"
)
if ssl_info.get("error"):
lines.append(f"Details/Error: {ssl_info['error']}")
return "\n".join(lines)
def format_response(resp: OperationResponse, raw_json: bool = False) -> str:
"""Format an OperationResponse for human-friendly terminal display or JSON output."""
if raw_json:
return resp.model_dump_json(indent=2, exclude_none=True)
if not resp.success:
err_msg = resp.error.message if resp.error else "Unknown error"
code = f" [{resp.error.code.value}]" if resp.error else ""
return f"❌ Error{code}: {err_msg}"
# If the engine produced terminal output (e.g. logs, compose config, status table), show it
if resp.output:
return resp.output
if resp.result:
if "workloads" in resp.result and isinstance(resp.result["workloads"], list):
return _format_workload_table(resp.result["workloads"])
if resp.operation == OperationType.WORKLOAD_RESOLVE and "workload" in resp.result:
return json.dumps(resp.result["workload"])
if "workload" in resp.result and isinstance(resp.result["workload"], dict):
return _format_workload_info(resp.result["workload"])
if "ssl" in resp.result and isinstance(resp.result["ssl"], dict):
return _format_ssl_info(resp.result["ssl"])
if "message" in resp.result and len(resp.result) <= 3:
return f"✨ {resp.result['message']}"
return json.dumps(resp.result, indent=2)
return f"✨ Operation '{resp.operation}' succeeded."
def run_cli(argv: list[str] | None = None) -> int:
"""Main CLI command parser and dispatcher."""
common_parser = argparse.ArgumentParser(add_help=False)
common_parser.add_argument(
"--socket",
type=Path,
default=None,
help="Path to appctl Unix domain socket",
)
common_parser.add_argument(
"--token",
type=str,
default=None,
help="Bearer token secret (overrides APPCTL_TOKEN and token files)",
)
common_parser.add_argument(
"--json",
action="store_true",
help="Output raw JSON response",
)
parser = argparse.ArgumentParser(
prog="appctl",
description="Homelab Unified Control Plane Client",
parents=[common_parser],
)
subparsers = parser.add_subparsers(dest="command", help="Operational commands")
# list / status
list_p = subparsers.add_parser("list", aliases=["status"], parents=[common_parser], help="List workloads")
list_p.add_argument("--core", "-c", "--all", "-a", action="store_true", dest="core", help="Include core platform services")
list_p.add_argument("--fetch", "-f", action="store_true", help="Fetch remote git revisions")
list_p.add_argument("--ssl", "-s", action="store_true", help="Check SSL certificate status")
# info
info_p = subparsers.add_parser("info", parents=[common_parser], help="Get workload metadata")
info_p.add_argument("target", help="Workload name")
info_p.add_argument("--ssl", "-s", action="store_true", help="Check SSL certificate status")
# resolve
resolve_p = subparsers.add_parser("resolve", parents=[common_parser], help="Resolve target metadata")
resolve_p.add_argument("target", help="Workload or core target")
# ssl
ssl_p = subparsers.add_parser("ssl", parents=[common_parser], help="Inspect platform SSL certificates")
ssl_p.add_argument("target", nargs="?", default=None, help="Target workload or platform")
# health
subparsers.add_parser("health", parents=[common_parser], help="Check control plane daemon health")
# up / deploy
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")
down_p.add_argument("target", help="Workload or core target")
# restart
restart_p = subparsers.add_parser("restart", parents=[common_parser], help="Restart workload")
restart_p.add_argument("target", help="Workload or core target")
# update
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")
pull_p.add_argument("target", help="Workload target")
# logs
logs_p = subparsers.add_parser("logs", parents=[common_parser], help="View workload logs")
logs_p.add_argument("target", help="Workload target")
logs_p.add_argument("--tail", type=int, default=100, help="Number of log lines")
# config
config_p = subparsers.add_parser("config", parents=[common_parser], help="View workload compose config")
config_p.add_argument("target", help="Workload target")
# sync
subparsers.add_parser("sync", parents=[common_parser], help="Synchronize Homepage services.yaml")
parsed, _ = parser.parse_known_args(argv)
if not parsed.command:
parser.print_help()
return 1
token = resolve_token(parsed.token)
socket_path = parsed.socket or Path(os.environ.get("APPCTL_SOCKET_PATH", DEFAULT_SOCKET_PATH))
# Map command to OperationRequest
op_req: OperationRequest
cmd = parsed.command
if cmd in ("list", "status"):
params: dict[str, Any] = {
"core": getattr(parsed, "core", False),
"fetch": getattr(parsed, "fetch", False),
"ssl": getattr(parsed, "ssl", False),
}
op_req = OperationRequest(operation=OperationType.WORKLOAD_LIST, parameters=params)
elif cmd == "info":
op_req = OperationRequest(
operation=OperationType.WORKLOAD_GET,
target=parsed.target,
parameters={"ssl": getattr(parsed, "ssl", False)},
)
elif cmd == "resolve":
op_req = OperationRequest(
operation=OperationType.WORKLOAD_RESOLVE,
target=parsed.target,
)
elif cmd == "ssl":
op_req = OperationRequest(
operation=OperationType.PLATFORM_SSL,
target=parsed.target,
)
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": build_flag or no_cache_flag,
"no_cache": no_cache_flag,
},
)
elif cmd in ("down", "stop"):
op_req = OperationRequest(
operation=OperationType.WORKLOAD_STOP,
target=parsed.target,
)
elif cmd == "restart":
op_req = OperationRequest(
operation=OperationType.WORKLOAD_RESTART,
target=parsed.target,
)
elif cmd == "update":
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,
parameters=params,
)
elif cmd == "pull":
op_req = OperationRequest(
operation=OperationType.WORKLOAD_PULL,
target=parsed.target,
)
elif cmd == "logs":
op_req = OperationRequest(
operation=OperationType.WORKLOAD_LOGS,
target=parsed.target,
parameters={"tail": getattr(parsed, "tail", 100)},
)
elif cmd == "config":
op_req = OperationRequest(
operation=OperationType.WORKLOAD_CONFIG,
target=parsed.target,
)
elif cmd == "sync":
op_req = OperationRequest(operation=OperationType.PLATFORM_SYNC_HOMEPAGE)
else:
print(f"❌ Unknown command '{cmd}'", file=sys.stderr)
return 1
try:
resp = send_daemon_request(
endpoint=socket_path,
operation_request=op_req,
token=token,
timeout=330.0,
)
print(format_response(resp, raw_json=parsed.json))
return 0 if resp.success else 1
except FileNotFoundError:
print(f"❌ Error: appctl daemon socket not found at {socket_path}", file=sys.stderr)
return 1
except ConnectionRefusedError:
print(f"❌ Error: appctl daemon is not accepting connections at {socket_path}", file=sys.stderr)
return 1
except (
OSError,
json.JSONDecodeError,
TimeoutError,
ValueError,
) as e:
print(f"❌ Error: Failed to communicate with appctl daemon: {e}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(run_cli())
+352
View File
@@ -0,0 +1,352 @@
"""
appctl_contracts.py — Authoritative Control Plane API Contracts & Schema Validation
Defines the wire protocol and Pydantic v2 domain schemas for homelab-appctl.service:
- Canonical 13 domain operations (workload.*, platform.*)
- Fail-closed strict typing (ConfigDict(extra="forbid", strict=True))
- Operation-specific parameter models (DeployParams, UpdateParams, LogsParams, ListParams, GetParams)
- Closed 6-code error taxonomy mapped to HTTP/1.1 semantics
- Information-disclosure-preventing error sanitizer (stripping input and url)
- Dual-transport request/response models
"""
from __future__ import annotations
from enum import StrEnum
from typing import Annotated, Any, Literal
from pydantic import (
AliasChoices,
BaseModel,
BeforeValidator,
ConfigDict,
Field,
StrictBool,
StrictInt,
StrictStr,
ValidationError,
field_validator,
model_validator,
)
class StrictModel(BaseModel):
"""Base model propagating strict validation across all control plane models — ADR-0003."""
model_config = ConfigDict(extra="forbid", strict=True, ignored_types=(dict,))
class OperationType(StrEnum):
"""The 13 canonical domain operations exposed by homelab-appctl.service."""
# Read-Only Operations
WORKLOAD_LIST = "workload.list"
WORKLOAD_GET = "workload.get"
WORKLOAD_RESOLVE = "workload.resolve"
PLATFORM_SSL = "platform.ssl"
PLATFORM_HEALTH = "platform.health"
WORKLOAD_CONFIG = "workload.config"
WORKLOAD_LOGS = "workload.logs"
# Mutating Operations
WORKLOAD_DEPLOY = "workload.deploy"
WORKLOAD_STOP = "workload.stop"
WORKLOAD_RESTART = "workload.restart"
WORKLOAD_UPDATE = "workload.update"
WORKLOAD_PULL = "workload.pull"
PLATFORM_SYNC_HOMEPAGE = "platform.sync_homepage"
# Backward-compatibility alias
WorkloadAction = OperationType
CanonicalOperation = OperationType
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({
OperationType.WORKLOAD_LIST,
OperationType.WORKLOAD_GET,
OperationType.WORKLOAD_RESOLVE,
OperationType.PLATFORM_SSL,
OperationType.PLATFORM_HEALTH,
OperationType.WORKLOAD_CONFIG,
OperationType.WORKLOAD_LOGS,
})
SENSITIVE_READ_OPERATIONS: frozenset[OperationType] = frozenset({
OperationType.WORKLOAD_CONFIG,
OperationType.WORKLOAD_LOGS,
})
TARGET_REQUIRED_OPERATIONS: frozenset[OperationType] = frozenset({
OperationType.WORKLOAD_GET,
OperationType.WORKLOAD_RESOLVE,
OperationType.WORKLOAD_CONFIG,
OperationType.WORKLOAD_LOGS,
OperationType.WORKLOAD_DEPLOY,
OperationType.WORKLOAD_STOP,
OperationType.WORKLOAD_RESTART,
OperationType.WORKLOAD_UPDATE,
OperationType.WORKLOAD_PULL,
})
def _coerce_operation(v: Any) -> Any:
if isinstance(v, str):
try:
return OperationType(v)
except ValueError:
return v
return v
FlexibleOperationType = Annotated[
OperationType,
BeforeValidator(_coerce_operation),
]
FlexibleWorkloadAction = FlexibleOperationType
class ErrorCode(StrEnum):
"""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"
@property
def http_status(self) -> int:
return ERROR_HTTP_STATUS[self]
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,
}
def _coerce_error_code(v: Any) -> Any:
if isinstance(v, str):
try:
return ErrorCode(v)
except ValueError:
return v
return v
FlexibleErrorCode = Annotated[
ErrorCode,
BeforeValidator(_coerce_error_code),
]
class DeployParams(StrictModel):
"""Parameters for workload.deploy."""
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):
"""Parameters for workload.update."""
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):
"""Parameters for workload.logs."""
tail: StrictInt = Field(default=100, ge=1, le=1000)
class ListParams(StrictModel):
"""Parameters for workload.list."""
fetch: StrictBool = False
core: StrictBool = False
ssl: StrictBool = False
class GetParams(StrictModel):
"""Parameters for workload.get."""
ssl: StrictBool = False
class EmptyParams(StrictModel):
"""Parameters model for operations that accept no arguments."""
OPERATION_PARAMS_MAP: dict[OperationType, type[StrictModel]] = {
OperationType.WORKLOAD_DEPLOY: DeployParams,
OperationType.WORKLOAD_UPDATE: UpdateParams,
OperationType.WORKLOAD_LOGS: LogsParams,
OperationType.WORKLOAD_LIST: ListParams,
OperationType.WORKLOAD_GET: GetParams,
OperationType.WORKLOAD_STOP: EmptyParams,
OperationType.WORKLOAD_RESTART: EmptyParams,
OperationType.WORKLOAD_PULL: EmptyParams,
OperationType.WORKLOAD_RESOLVE: EmptyParams,
OperationType.PLATFORM_SSL: EmptyParams,
OperationType.PLATFORM_HEALTH: EmptyParams,
OperationType.WORKLOAD_CONFIG: EmptyParams,
OperationType.PLATFORM_SYNC_HOMEPAGE: EmptyParams,
}
class OperationError(StrictModel):
"""Standardized error payload returned in failed OperationResponse payloads."""
code: FlexibleErrorCode
message: StrictStr
details: list[dict[str, Any]] | None = None
def sanitize_validation_error(exc: ValidationError) -> OperationError:
"""
Format and sanitize a Pydantic ValidationError into an OperationError with ERR_VALIDATION_FAILED,
stripping raw user input and documentation URLs to prevent information disclosure.
"""
raw_details = exc.errors(include_input=False, include_url=False)
clean_details: list[dict[str, Any]] = []
for d in raw_details:
clean_details.append({
"type": d.get("type"),
"loc": list(d.get("loc", ())),
"msg": d.get("msg"),
})
return OperationError(
code=ErrorCode.ERR_VALIDATION_FAILED,
message="Request payload validation failed",
details=clean_details,
)
class OperationRequest(StrictModel):
"""Defines the body requirements of an HTTP/1.1 operation request."""
model_config = ConfigDict(
extra="forbid",
strict=True,
populate_by_name=True,
ignored_types=(dict,),
)
version: Literal["1.0"] = "1.0"
operation: FlexibleOperationType = Field(
validation_alias=AliasChoices("operation", "action")
)
target: Annotated[StrictStr, Field(min_length=1)] | None = None
parameters: dict[str, Any] = Field(
default_factory=dict,
validation_alias=AliasChoices("parameters", "params"),
)
@property
def action(self) -> OperationType:
return self.operation
@property
def params(self) -> dict[str, Any]:
return self.parameters
@field_validator("parameters", mode="before")
@classmethod
def _coerce_parameters(cls, v: Any) -> Any:
if isinstance(v, BaseModel):
return v.model_dump()
return v
@model_validator(mode="after")
def validate_request(self) -> OperationRequest:
if self.operation in TARGET_REQUIRED_OPERATIONS and not self.target:
raise ValueError(f"Operation '{self.operation.value}' requires a non-empty target")
param_model = OPERATION_PARAMS_MAP[self.operation]
param_model.model_validate(self.parameters)
return self
def parse_parameters(self) -> StrictModel:
"""Parse and return the typed parameter model for this operation."""
param_model = OPERATION_PARAMS_MAP[self.operation]
return param_model.model_validate(self.parameters)
class OperationResponse(StrictModel):
"""Defines the standard response payload for control plane operations."""
model_config = ConfigDict(extra="forbid", strict=True, populate_by_name=True)
version: Literal["1.0"] = "1.0"
success: StrictBool | None = None
status: Literal["success", "error"] | None = None
operation_id: StrictStr = Field(min_length=1)
operation: FlexibleOperationType | StrictStr | None = Field(
default=None,
validation_alias=AliasChoices("operation", "action"),
)
target: StrictStr | None = None
output: StrictStr = ""
result: dict[str, Any] | None = None
error: OperationError | None = None
timestamp: StrictStr | None = None
duration_ms: StrictInt | None = None
@property
def action(self) -> OperationType | str | None:
return self.operation
@model_validator(mode="after")
def check_consistency(self) -> OperationResponse:
if self.success is None and self.status is None:
raise ValueError("Either 'success' or 'status' must be provided")
if self.success is None and self.status is not None:
self.success = self.status == "success"
elif self.status is None and self.success is not None:
self.status = "success" if self.success else "error"
elif (
self.success is not None
and self.status is not None
and (self.status == "success") != self.success
):
raise ValueError("'status' and 'success' must agree")
if self.success and self.error is not None:
raise ValueError("Successful operation cannot contain an error")
if not self.success and self.error is None:
raise ValueError("Failed operation must contain an error")
return self
+604
View File
@@ -0,0 +1,604 @@
#!/usr/bin/env python3
"""
appctl_daemon.py — Dual-Transport HTTP/1.1 Control Plane Daemon for Homelab
Implements Milestone P4 Control Plane Daemon:
- Multi-threaded Unix domain socket listener (/run/homelab/appctl.sock, mode 0660)
- Multi-threaded loopback HTTP listener (127.0.0.1:9001)
- Bounded 64 KiB request body enforcement
- Endpoints: GET /v1/health, POST /v1/operations
- Linux SO_PEERCRED credential extraction on UDS transport
- Bearer token authentication + RBAC gating + append-only audit logging
- Pure-Python Unix domain socket HTTP client helper
- Graceful SIGINT and SIGTERM shutdown unlinking socket file
"""
from __future__ import annotations
import http.client
import http.server
import json
import logging
import os
import signal
import socket
import socketserver
import struct
import sys
import threading
import time
from pathlib import Path
from typing import Any, cast
from urllib.parse import urlparse
from appctl_audit import (
AuditLogger,
PrincipalAudit,
TargetLockManager,
current_iso_timestamp,
generate_operation_id,
)
from appctl_auth import (
AuthenticationError,
TokenStore,
authenticate_request,
)
from appctl_contracts import (
ErrorCode,
OperationError,
OperationRequest,
OperationResponse,
OperationType,
sanitize_validation_error,
)
from appctl_router import OperationalRouter
from pydantic import ValidationError
logger = logging.getLogger("appctl_daemon")
CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent))
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") or (WORKLOADS_DIR / "deployments.yaml")
)
DEFAULT_SOCKET_PATH = Path(
os.environ.get("APPCTL_SOCKET_PATH", "/run/homelab/appctl.sock")
)
DEFAULT_HTTP_HOST = os.environ.get("APPCTL_HTTP_HOST", "127.0.0.1")
DEFAULT_HTTP_PORT = int(os.environ.get("APPCTL_HTTP_PORT", "9001"))
MAX_REQUEST_BODY = 64 * 1024 # 64 KiB
def extract_peer_credentials(sock: socket.socket) -> tuple[int, int, int] | None:
"""
Extract (pid, uid, gid) from a connected Unix domain socket on Linux via SO_PEERCRED.
Returns None if unsupported or on error.
"""
try:
so_peercred = getattr(socket, "SO_PEERCRED", 17)
creds = sock.getsockopt(socket.SOL_SOCKET, so_peercred, struct.calcsize("3i"))
pid, uid, gid = struct.unpack("3i", creds)
return pid, uid, gid
except (OSError, struct.error, AttributeError):
return None
class UnixHTTPConnection(http.client.HTTPConnection):
"""HTTP client connection over a local Unix domain socket."""
def __init__(self, socket_path: str, timeout: float = 30.0) -> None:
super().__init__("localhost", timeout=timeout)
self.socket_path = socket_path
def connect(self) -> None:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if self.timeout is not None:
sock.settimeout(self.timeout)
sock.connect(self.socket_path)
self.sock = sock
def send_daemon_request(
endpoint: str | Path,
operation_request: OperationRequest | dict[str, Any],
token: str | None = None,
timeout: float = 30.0,
) -> OperationResponse:
"""
Client helper to send an OperationRequest over UDS or HTTP to the daemon.
Accepts:
- Path object or path ending in .sock -> UnixHTTPConnection
- URL starting with http:// or host:port -> standard HTTPConnection
"""
if isinstance(operation_request, OperationRequest):
req_body = operation_request.model_dump_json(exclude_none=True)
elif isinstance(operation_request, dict):
req_body = json.dumps(operation_request)
else:
raise TypeError("operation_request must be OperationRequest or dict")
headers = {
"Content-Type": "application/json",
"Host": "localhost",
}
if token:
headers["Authorization"] = f"Bearer {token}"
is_unix = False
endpoint_str = str(endpoint)
if (
isinstance(endpoint, Path)
or endpoint_str.endswith(".sock")
or ("/" in endpoint_str and not endpoint_str.startswith("http"))
):
is_unix = True
if is_unix:
conn = UnixHTTPConnection(endpoint_str, timeout=timeout)
else:
if endpoint_str.startswith(("http://", "https://")):
parsed = urlparse(endpoint_str)
host = parsed.hostname or "127.0.0.1"
port = parsed.port or (443 if parsed.scheme == "https" else 80)
elif ":" in endpoint_str:
host, port_str = endpoint_str.split(":", 1)
port = int(port_str)
else:
host = endpoint_str
port = DEFAULT_HTTP_PORT
conn = http.client.HTTPConnection(host, port, timeout=timeout)
try:
conn.request("POST", "/v1/operations", body=req_body.encode("utf-8"), headers=headers)
res = conn.getresponse()
resp_data = res.read().decode("utf-8")
parsed_json = json.loads(resp_data)
return OperationResponse.model_validate(parsed_json)
finally:
conn.close()
class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
"""
HTTP/1.1 request handler for appctl control plane operations.
Supports both UDS and loopback TCP listeners.
"""
server_version = "AppctlDaemon/1.0"
protocol_version = "HTTP/1.1"
@property
def appctl_server(self) -> ThreadingUnixStreamServer | ThreadingHTTPServer:
return cast("ThreadingUnixStreamServer | ThreadingHTTPServer", self.server)
def address_string(self) -> str:
"""Safely format client address avoiding slow DNS lookups or UDS unpack errors."""
client_addr = self.client_address
if isinstance(client_addr, tuple) and len(client_addr) >= 2:
return f"{client_addr[0]}:{client_addr[1]}"
if isinstance(client_addr, str) and client_addr:
return client_addr
return "unix_socket"
def log_message(self, format: str, *args: Any) -> None:
"""Forward access logs to Python standard logger."""
logger.info("%s - %s", self.address_string(), format % args)
def _send_json(self, status_code: int, data: dict[str, Any] | str) -> None:
"""Send formatted JSON HTTP response."""
body_bytes = data.encode("utf-8") if isinstance(data, str) else json.dumps(data, indent=2).encode("utf-8")
self.send_response(status_code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body_bytes)))
self.send_header("Connection", "close")
self.end_headers()
self.wfile.write(body_bytes)
def _send_operation_response(self, status_code: int, response: OperationResponse) -> None:
"""Serialize and send an OperationResponse payload."""
payload_str = response.model_dump_json(exclude_none=True)
self._send_json(status_code, payload_str)
def _send_operation_error(
self,
status_code: int,
error: OperationError,
operation: Any = None,
target: str | None = None,
op_id: str | None = None,
) -> None:
"""Send standardized OperationResponse representing a failure."""
resp = OperationResponse(
version="1.0",
success=False,
status="error",
operation_id=op_id or generate_operation_id(),
operation=operation if isinstance(operation, (OperationType, str)) else None,
target=target if isinstance(target, str) else None,
error=error,
timestamp=current_iso_timestamp(),
)
self._send_operation_response(status_code, resp)
def _send_error_response(
self,
status_code: int,
code: ErrorCode,
message: str,
details: list[dict[str, Any]] | None = None,
op_id: str | None = None,
operation: Any = None,
target: str | None = None,
) -> None:
"""Send structured error response with canonical error code."""
error = OperationError(code=code, message=message, details=details)
self._send_operation_error(
status_code=status_code,
error=error,
operation=operation,
target=target,
op_id=op_id,
)
def do_GET(self) -> None:
"""Handle health check endpoint."""
if self.path in ("/v1/health", "/health"):
health = self.appctl_server.daemon_instance.get_health_status()
self._send_json(200, health)
return
self._send_error_response(
status_code=404,
code=ErrorCode.ERR_TARGET_NOT_FOUND,
message=f"Endpoint '{self.path}' not found",
)
def do_POST(self) -> None:
"""Handle operational dispatch requests."""
if self.path != "/v1/operations":
self._send_error_response(
status_code=404,
code=ErrorCode.ERR_TARGET_NOT_FOUND,
message=f"Endpoint '{self.path}' not found. Supported endpoint: POST /v1/operations",
)
return
cl_header = self.headers.get("Content-Length")
if cl_header is None:
self._send_error_response(
status_code=400,
code=ErrorCode.ERR_VALIDATION_FAILED,
message="Missing Content-Length header",
)
return
try:
content_length = int(cl_header.strip())
except ValueError:
self._send_error_response(
status_code=400,
code=ErrorCode.ERR_VALIDATION_FAILED,
message="Malformed Content-Length header",
)
return
if content_length < 0:
self._send_error_response(
status_code=400,
code=ErrorCode.ERR_VALIDATION_FAILED,
message="Content-Length cannot be negative",
)
return
if content_length > MAX_REQUEST_BODY:
self._send_error_response(
status_code=400,
code=ErrorCode.ERR_VALIDATION_FAILED,
message=f"Request body ({content_length} bytes) exceeds limit of {MAX_REQUEST_BODY} bytes",
)
return
raw_body = self.rfile.read(content_length)
try:
body_dict = json.loads(raw_body.decode("utf-8"))
except (json.JSONDecodeError, UnicodeDecodeError) as e:
self._send_error_response(
status_code=400,
code=ErrorCode.ERR_VALIDATION_FAILED,
message=f"Invalid JSON payload: {e}",
)
return
if not isinstance(body_dict, dict):
self._send_error_response(
status_code=400,
code=ErrorCode.ERR_VALIDATION_FAILED,
message="Payload root must be a JSON object mapping",
)
return
try:
req = OperationRequest.model_validate(body_dict)
except ValidationError as exc:
sanitized = sanitize_validation_error(exc)
self._send_operation_error(
status_code=400,
error=sanitized,
operation=body_dict.get("operation") or body_dict.get("action"),
target=body_dict.get("target"),
)
return
# Determine transport scheme and peer credentials
is_unix = getattr(self.connection, "family", None) == socket.AF_UNIX
transport = "unix_socket" if is_unix else "http"
peer_uid: int | None = None
if is_unix:
creds = extract_peer_credentials(self.connection)
if creds is not None:
_, peer_uid, _ = creds
origin = f"peer_uid_{peer_uid}" if peer_uid is not None else "unix_socket"
else:
origin = self.address_string()
client_header = self.headers.get("User-Agent", "appctl-client/1.0")
auth_header = self.headers.get("Authorization")
# Authenticate principal
try:
principal = authenticate_request(
auth_header=auth_header,
transport=transport,
peer_uid=peer_uid,
token_store=self.appctl_server.token_store,
)
except AuthenticationError as auth_err:
op_id = generate_operation_id()
auth_msg = str(auth_err)
self.appctl_server.audit_logger.log_denied(
operation_id=op_id,
principal=PrincipalAudit(
identity=f"peer_uid_{peer_uid}" if peer_uid is not None else "unknown",
role="homelab-viewer" if is_unix else "unknown",
token_id=None,
auth_method="unix_peercred" if is_unix and auth_header is None else "bearer_token",
),
action=req.operation.value,
target=req.target,
transport=transport,
origin=origin,
client=client_header,
parameters=req.parameters,
error_code=auth_err.code.value,
message=auth_msg,
)
self._send_operation_error(
status_code=auth_err.code.http_status,
error=OperationError(code=auth_err.code, message=auth_msg),
operation=req.operation,
target=req.target,
op_id=op_id,
)
return
# Dispatch operation to OperationalRouter
try:
resp = self.appctl_server.router.dispatch(
request=req,
principal=principal,
transport=transport,
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)
class ThreadingUnixStreamServer(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
"""Multi-threaded Unix Domain Socket HTTP server."""
daemon_threads = True
allow_reuse_address = True
router: OperationalRouter
token_store: TokenStore
audit_logger: AuditLogger
daemon_instance: AppctlDaemon
class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
"""Multi-threaded TCP Loopback HTTP server."""
daemon_threads = True
allow_reuse_address = True
router: OperationalRouter
token_store: TokenStore
audit_logger: AuditLogger
daemon_instance: AppctlDaemon
class AppctlDaemon:
"""
Control Plane Daemon managing dual-transport operational listeners (UDS + TCP).
"""
def __init__(
self,
router: OperationalRouter | None = None,
token_store: TokenStore | None = None,
audit_logger: AuditLogger | None = None,
lock_manager: TargetLockManager | None = None,
socket_path: Path | str | None = None,
http_host: str | None = None,
http_port: int | None = None,
sites_dir: Path | str | None = None,
core_dir: Path | str | None = None,
deployments_file: Path | str | None = None,
) -> None:
self.socket_path = Path(socket_path or os.environ.get("APPCTL_SOCKET_PATH", DEFAULT_SOCKET_PATH))
self.http_host = str(http_host or os.environ.get("APPCTL_HTTP_HOST", DEFAULT_HTTP_HOST))
self.http_port = int(http_port or os.environ.get("APPCTL_HTTP_PORT", str(DEFAULT_HTTP_PORT)))
self.audit_logger = audit_logger or AuditLogger()
self.token_store = token_store or TokenStore()
self.lock_manager = lock_manager or TargetLockManager()
self.router = router or OperationalRouter(
audit_logger=self.audit_logger,
lock_manager=self.lock_manager,
sites_dir=sites_dir or SITES_DIR,
core_dir=core_dir or CORE_DIR,
)
self.uds_server: ThreadingUnixStreamServer | None = None
self.tcp_server: ThreadingHTTPServer | None = None
self.uds_thread: threading.Thread | None = None
self.tcp_thread: threading.Thread | None = None
self.running = False
self.start_time: float = 0.0
def start(self) -> None:
"""Bind both transports and start listener worker threads."""
if self.running:
return
self.start_time = time.time()
# 1. Prepare and bind UDS listener
self.socket_path.parent.mkdir(parents=True, exist_ok=True)
if self.socket_path.exists() or self.socket_path.is_socket():
self.socket_path.unlink(missing_ok=True)
self.uds_server = ThreadingUnixStreamServer(str(self.socket_path), AppctlHTTPHandler)
self.uds_server.router = self.router
self.uds_server.token_store = self.token_store
self.uds_server.audit_logger = self.audit_logger
self.uds_server.daemon_instance = self
try:
os.chmod(self.socket_path, 0o660)
except OSError as e:
logger.warning("Could not set mode 0660 on socket %s: %s", self.socket_path, e)
# 2. Prepare and bind TCP listener
self.tcp_server = ThreadingHTTPServer((self.http_host, self.http_port), AppctlHTTPHandler)
self.tcp_server.router = self.router
self.tcp_server.token_store = self.token_store
self.tcp_server.audit_logger = self.audit_logger
self.tcp_server.daemon_instance = self
# 3. Start listener threads
self.uds_thread = threading.Thread(target=self.uds_server.serve_forever, daemon=True, name="uds-listener")
self.uds_thread.start()
self.tcp_thread = threading.Thread(target=self.tcp_server.serve_forever, daemon=True, name="tcp-listener")
self.tcp_thread.start()
self.running = True
logger.info(
"appctl daemon started: UDS=%s, HTTP=%s:%d",
self.socket_path,
self.http_host,
self.http_port,
)
def stop(self) -> None:
"""Gracefully shut down both transport servers and unlink socket."""
if not self.running:
return
self.running = False
logger.info("Shutting down appctl daemon...")
if self.uds_server:
self.uds_server.shutdown()
self.uds_server.server_close()
self.uds_server = None
if self.socket_path.exists() or self.socket_path.is_socket():
self.socket_path.unlink(missing_ok=True)
if self.tcp_server:
self.tcp_server.shutdown()
self.tcp_server.server_close()
self.tcp_server = None
if self.uds_thread and self.uds_thread.is_alive():
self.uds_thread.join(timeout=2.0)
self.uds_thread = None
if self.tcp_thread and self.tcp_thread.is_alive():
self.tcp_thread.join(timeout=2.0)
self.tcp_thread = None
logger.info("appctl daemon shut down successfully.")
def get_health_status(self) -> dict[str, Any]:
"""Produce non-sensitive health metadata."""
uptime = round(time.time() - self.start_time, 2) if self.running else 0.0
return {
"status": "healthy" if self.running else "stopped",
"version": "1.0",
"uptime_seconds": uptime,
"transports": {
"unix_socket": str(self.socket_path),
"http_loopback": f"{self.http_host}:{self.http_port}",
},
"timestamp": current_iso_timestamp(),
}
def main() -> None:
"""CLI entrypoint for running the daemon."""
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] [appctl-daemon] %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
daemon = AppctlDaemon()
def handle_signal(sig: int, _frame: Any) -> None:
logger.info("Received signal %d, stopping daemon...", sig)
daemon.stop()
sys.exit(0)
signal.signal(signal.SIGINT, handle_signal)
signal.signal(signal.SIGTERM, handle_signal)
daemon.start()
try:
while daemon.running:
time.sleep(1.0)
except KeyboardInterrupt:
daemon.stop()
if __name__ == "__main__":
main()
+791 -616
View File
File diff suppressed because it is too large. Load diff
-372
View File
@@ -1,372 +0,0 @@
import os
import sys
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
import yaml
# Dynamic Environment Paths
CORE_DIR = os.environ.get(
"CORE_DIR", 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"),
)
HOMELAB_DOMAIN = os.environ.get("HOMELAB_DOMAIN") or os.environ.get("DOMAIN", "")
def validate_environment() -> None:
"""Ensure mandatory environment configuration is valid before CLI execution."""
errors: list[str] = []
if not HOMELAB_DOMAIN:
errors.append(
"• Missing 'HOMELAB_DOMAIN' (or 'DOMAIN') environment variable.\n"
" Please export it (e.g. export HOMELAB_DOMAIN='roadtotech.me') or set it in your environment file."
)
if not os.path.isdir(CORE_DIR):
errors.append(f"• Core directory not found at: {CORE_DIR}")
if errors:
print("❌ Environment Validation Failed:\n", file=sys.stderr)
for err in errors:
print(f" {err}", file=sys.stderr)
sys.exit(1)
class ManifestError(Exception):
pass
@dataclass
class HomepageConfig:
title: str
group: str = "Applications"
icon: str = "default.png"
container: str = ""
weight: int = 50
@dataclass
class SourceConfig:
"""Upstream source provenance descriptor."""
type: str = "git" # "git"
url: str = "" # e.g., "https://git.roadtotech.me/kiskaadee/bitetrack.git"
ref: str = "main" # Branch (e.g. "main"), tag (e.g. "v1.0.0"), or commit SHA
@dataclass
class App:
name: str # Canonical identified (e.g., "traefik", "jellyfin")
description: str # Human-readable summary for dashboards and CLI info
domain: str # Routing FQDN (e.g., "auth.roadtotech.me") or "internal".
dir_path: str # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
@property
def is_internal(self) -> bool:
"""Returns True if the service does not expose a public TLS endpoint."""
return not self.domain or self.domain == "internal" or self.domain.endswith(".local") or ":" in self.domain
def to_dict(self) -> dict[str, Any]:
"""Serialize for JSON consumption by scripts/appctl"""
data = asdict(self)
data["type"] = getattr(self, "app_type", "app")
return data
@dataclass
class CoreService(App):
container: str = "" # Target container name inside Core's root docker-compose.yml (e.g., "authelia", "stalwart")
weight: int = 50 # Homepage ordering weight (optional, for dashboard synchronization)
icon: str = "default.png" # Dashboard icon filename
app_type: str = "core_service"
dir_path: str = CORE_DIR
@dataclass
class SitesApp(App):
dir_name: str = "" # directory name in ~/Sites (e.g., "homelab-vaultwarden")
source: SourceConfig | None = None # Upstream source provenance (optional; None indicates Image-Only workload)
aliases: list[str] = field(default_factory=list) # CLI resolution aliases (e.g., "vw", "vaultwarden")
visible: bool = True # Defines whether the icon is visible in the Homepage Dashboard
auth: bool = True # Authelia protection guard indicator; Defaulting to True is safer
has_compose: bool = False # Whether a docker-compose.yaml exists at ~/Sites/dir_name.
networks: list[str] = field(default_factory=lambda: ["proxy-net"]) # Docker network attachments (def ["proxy-net"])
env: dict[str, Any] = field(default_factory=dict) # Dynamic environment variable overrides
homepage: HomepageConfig | None = None # Dashboard Card Configuration
manifest_error: str | None = None # Captured syntax/loading errors if app.yaml was malformed/absent
app_type: str = "app"
def load_manifest(manifest_path: str) -> dict[str, Any]:
"""Load and parese the app manifest file
Raises:
FileNotFoundError: if the manifest file does not exist.
ValueError: if YAML object is malformed.
TypeError: If root is not a directory
"""
if not os.path.isfile(manifest_path):
raise FileNotFoundError(f"Manifest file not found at {manifest_path}")
try:
with open(manifest_path, "r", encoding="utf-8") as file:
manifest_data = yaml.safe_load(file) or {}
except (yaml.YAMLError, OSError) as err:
raise ManifestError(f"YAML parsing failed: {err}") from err
if not isinstance(manifest_data, dict):
raise ManifestError(f"Invalid manifest root: expected `dict`, got `{type(manifest_data).__name__}`")
return manifest_data
def sites_app_from_manifest(
app_dir: str,
manifest: dict[str, Any],
manifest_error: str | None = None
) -> SitesApp:
"""Construct and normalize a SitesApp domain model from raw manifest data."""
raw_dir_name = os.path.basename(app_dir)
canonical_name = str(manifest.get("name") or raw_dir_name.replace("homelab-", ""))
# Normalize aliases into list[str]
raw_aliases = manifest.get("aliases") or []
if isinstance(raw_aliases, str):
aliases = [raw_aliases]
elif isinstance(raw_aliases, list):
aliases = [str(alias) for alias in raw_aliases]
else:
aliases = []
# Homepage card normalization
homepage_config: HomepageConfig | None = None
raw_hp = manifest.get("homepage")
if isinstance(raw_hp, dict):
homepage_config = HomepageConfig(
title=str(raw_hp.get("title") or canonical_name),
group=str(raw_hp.get("group") or "Applications"),
icon=str(raw_hp.get("icon") or "default.png"),
container=str(raw_hp.get("container") or canonical_name),
weight=int(raw_hp.get("weight", 50))
)
has_compose = (
os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or
os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
)
# Manifest Data parsing
raw_desc = manifest.get("description")
app_desc: str = str(raw_desc) if raw_desc is not None else ""
raw_dom = manifest.get("domain")
app_dom = str(raw_dom) if raw_dom is not None else f"{canonical_name}.{HOMELAB_DOMAIN}"
app_net = manifest.get("networks")
if not isinstance(app_net, list):
app_net = ["proxy-net"]
app_env = manifest.get("env")
if not isinstance(app_env, dict):
app_env = {}
def _as_bool(value: Any, default: bool) -> bool:
if isinstance(value, bool):
return value
return default
app_vis = _as_bool(manifest.get("visible"), True)
app_auth = _as_bool(manifest.get("auth"), True)
# Source provenance normalization
source_config: SourceConfig | None = None
raw_source = manifest.get("source")
if isinstance(raw_source, dict):
source_url = str(raw_source.get("url") or "")
allowed_schemes = ("https://", "ssh://", "git@")
if source_url:
if not any(source_url.startswith(s) for s in allowed_schemes):
err = f"Invalid source.url scheme: must start with {', '.join(allowed_schemes)}"
manifest_error = f"{manifest_error}; {err}" if manifest_error else err
else:
source_config = SourceConfig(
type=str(raw_source.get("type") or "git"),
url=source_url,
ref=str(raw_source.get("ref") or "main"),
)
return SitesApp(
name=canonical_name,
dir_name=raw_dir_name,
source=source_config,
description=app_desc,
domain=app_dom,
dir_path=app_dir,
has_compose=has_compose,
aliases=aliases,
visible=app_vis,
auth=app_auth,
networks=app_net,
env=app_env,
homepage=homepage_config,
manifest_error=manifest_error,
)
def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]:
"""
Scan the given sites directory (defaulting to SITES_DIR) for application.
"""
target_dir = sites_dir or SITES_DIR
apps: list[SitesApp] = []
if not os.path.isdir(target_dir):
return apps
for entry in sorted(os.listdir(target_dir)):
app_dir = os.path.join(target_dir, entry)
# skip hidden or null directories
if entry.startswith(".") or not os.path.isdir(app_dir):
continue
manifest_path = os.path.join(app_dir, "app.yaml")
manifest: dict[str, Any] = {}
manifest_error: str | None = None
if os.path.isfile(manifest_path):
try:
manifest = load_manifest(manifest_path=manifest_path)
except ManifestError as err:
manifest_error = str(err)
apps.append(sites_app_from_manifest(app_dir, manifest, manifest_error))
return apps
def resolve_app(
query: str,
apps: list[SitesApp] | None = None,
sites_dir: str | None = None
) -> SitesApp | None:
if apps is None:
apps = get_sites_apps(sites_dir= sites_dir if sites_dir is not None else SITES_DIR)
query_clean = query.strip().lower()
# 1. Extract match on canonical name
for app in apps:
if app.name.lower() == query_clean:
return app
# 2. Match on alias
for app in apps:
if any(alias.lower() == query_clean for alias in app.aliases):
return app
# 3. Match directory name
for app in apps:
if app.dir_name.lower() == query_clean:
return app
# 4. Match stripped 'homelab-' prefix
for app in apps:
if app.dir_name.lower() == f"homelab-{query_clean}":
return app
return None
def get_core_services(core_dir: str | None = None) -> list[CoreService]:
"""Return the strongly-typed registry of Core platform services."""
return [
CoreService(
name="traefik",
domain=f"traefik.{HOMELAB_DOMAIN}",
container="traefik",
description="Edge Reverse Proxy & ACME TLS",
icon="traefik.png",
weight=10,
),
CoreService(
name="authelia",
domain=f"auth.{HOMELAB_DOMAIN}",
container="authelia",
description="Identity & SSO Access Control",
icon="authelia.png",
weight=20,
),
CoreService(
name="lldap",
domain=f"users.{HOMELAB_DOMAIN}",
container="lldap",
description="Lightweight LDAP User Directory",
icon="lldap.png",
weight=25,
),
CoreService(
name="stalwart",
domain=f"mail.{HOMELAB_DOMAIN}",
container="stalwart",
description="All-in-one Mail Server",
icon="email.png",
weight=26,
),
CoreService(
name="portainer",
domain=f"portainer.{HOMELAB_DOMAIN}",
container="portainer",
description="Container Management GUI",
icon="portainer.png",
weight=30,
),
CoreService(
name="dozzle",
domain=f"logs.{HOMELAB_DOMAIN}",
container="dozzle",
description="Real-time Log Viewer",
icon="dozzle.png",
weight=40,
),
CoreService(
name="socket-proxy",
domain="internal",
container="socket-proxy",
description="Docker Socket Security Proxy",
),
CoreService(
name="homepage",
domain=f"dashboard.{HOMELAB_DOMAIN}",
container="homepage",
description="Application Dashboard & System Portal",
icon="homepage.png",
weight=5,
),
CoreService(
name="diun",
domain="internal",
container="diun",
description="Docker Image Update Notifier",
),
CoreService(
name="watchtower",
domain="internal",
container="watchtower",
description="Automated Container Updates",
),
]
def get_docker_status(
dir_path: str | Path,
container_name: str | None = None
) -> str:
path: Path = Path(dir_path)
def _do_something(path: Path = path):
return ""
return _do_something()
def cmd_sync_homepage(args) -> None:
pass
File diff suppressed because it is too large. Load diff
+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())
+519
View File
@@ -0,0 +1,519 @@
"""
core_manifest.py — Authoritative Workload Manifest Schema (v1.0) & Parser Library
Governs the contract for all ~/Sites workloads:
- Strongly-typed Pydantic v2 representations (Manifest, SourceConfig, DeploymentConfig, HomepageConfig)
- Strict source transport scheme validation (https://, ssh://, git@)
- Explicit ref classification (moving branches vs. pinned tags vs. commit SHAs)
- Workload classification: Class A (Source-Backed) vs. Class B (Image-Only)
- Fail-closed schema enforcement with ConfigDict(extra="forbid")
"""
from __future__ import annotations
import re
from enum import Enum
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
from pydantic import (
BaseModel,
ConfigDict,
Field,
ValidationError,
field_validator,
model_validator,
)
try:
import yaml
except ImportError:
yaml = None # type: ignore[assignment]
class ManifestValidationError(Exception):
"""Raised when an application manifest violates schema or security constraints."""
class RefType(str, Enum):
"""Semantic classification of an upstream git reference."""
BRANCH = "branch" # Moving branch (e.g. main, master, develop, release/v1)
TAG = "tag" # Pinned release tag (e.g. v1.0.0, 2.3.1)
COMMIT = "commit" # Immutable commit SHA (40-character hex)
UNKNOWN = "unknown"
class TransportScheme(str, Enum):
"""Supported secure git network transports."""
HTTPS = "https"
SSH = "ssh"
GIT_SCP = "git_scp"
# Security regexes
NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]*$")
COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$")
SHORT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,12}$")
SEMVER_TAG_RE = re.compile(r"^v?[0-9]+(\.[0-9]+)+([a-zA-Z0-9._-]*)$")
SCP_URL_RE = re.compile(
r"^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:([0-9]+/)?([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+(\.git)?$"
)
ENV_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
RESERVED_ENV_KEYS = {
"PATH",
"LD_PRELOAD",
"IFS",
"SHELL",
"USER",
"CORE_DIR",
"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",
}
def validate_transport(url: str) -> tuple[TransportScheme, str]:
"""
Validate that an upstream source URL uses an approved secure transport.
Rejects raw host paths, traversal attempts, and insecure protocols (e.g. http://, file://).
"""
if not isinstance(url, str) or not url.strip():
raise ManifestValidationError("Source URL cannot be empty.")
clean_url = url.strip()
# Reject path traversal / directory escapes
if ".." in clean_url or "\\" in clean_url or clean_url.startswith(("/", "~")):
raise ManifestValidationError(
f"Prohibited filesystem path or traversal in source URL: '{clean_url}'"
)
# 1. HTTPS transport
if clean_url.startswith("https://"):
parsed = urlparse(clean_url)
if not parsed.netloc:
raise ManifestValidationError(
f"Malformed HTTPS source URL (missing host): '{clean_url}'"
)
if not parsed.path or parsed.path == "/":
raise ManifestValidationError(
f"Malformed HTTPS source URL (missing repository path): '{clean_url}'"
)
return TransportScheme.HTTPS, clean_url
# 2. Standard SSH transport (ssh://[user@]host[:port]/path)
if clean_url.startswith("ssh://"):
parsed = urlparse(clean_url)
if not parsed.netloc:
raise ManifestValidationError(
f"Malformed SSH source URL (missing host): '{clean_url}'"
)
if not parsed.path or parsed.path == "/":
raise ManifestValidationError(
f"Malformed SSH source URL (missing repository path): '{clean_url}'"
)
return TransportScheme.SSH, clean_url
# 3. SCP-style SSH transport (git@host:owner/repo.git)
if clean_url.startswith("git@") or (
"@" in clean_url and ":" in clean_url and not clean_url.startswith("http")
):
if SCP_URL_RE.match(clean_url):
return TransportScheme.GIT_SCP, clean_url
raise ManifestValidationError(f"Malformed SCP-style source URL: '{clean_url}'")
# Reject plaintext HTTP or unsupported schemes
if clean_url.startswith("http://"):
raise ManifestValidationError(
f"Insecure HTTP source URL rejected (HTTPS or SSH required): '{clean_url}'"
)
raise ManifestValidationError(
f"Invalid source.url scheme: '{clean_url}'. "
"Allowed transports are https://, ssh://, or git@<host>:<path>."
)
def classify_ref(ref_str: str) -> tuple[RefType, str]:
"""
Classify a git ref into semantic categories (BRANCH, TAG, COMMIT)
and return the normalized identifier.
"""
if not isinstance(ref_str, str) or not ref_str.strip():
return RefType.BRANCH, "main"
ref = ref_str.strip()
# Explicit git ref namespace
if ref.startswith("refs/heads/"):
return RefType.BRANCH, ref.removeprefix("refs/heads/")
if ref.startswith("refs/tags/"):
return RefType.TAG, ref.removeprefix("refs/tags/")
# Full 40-character commit SHA
if COMMIT_SHA_RE.match(ref):
return RefType.COMMIT, ref
# Version tags (e.g. v1.0.0, 2.4.1, v0.2-alpha)
if SEMVER_TAG_RE.match(ref):
return RefType.TAG, ref
# Non-versioned arbitrary string treated as branch
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"
ref_type: RefType = RefType.BRANCH
transport: TransportScheme = TransportScheme.HTTPS
@model_validator(mode="before")
@classmethod
def validate_source(cls, data: Any) -> Any:
if isinstance(data, dict):
src_type = str(data.get("type", "git")).strip().lower()
if src_type != "git":
raise ManifestValidationError(
f"Unsupported source type '{src_type}'. Only 'git' is supported."
)
data["type"] = src_type
raw_url = data.get("url")
if raw_url is not None:
transport, validated_url = validate_transport(str(raw_url))
data["url"] = validated_url
if "transport" not in data or data["transport"] is None:
data["transport"] = transport
raw_ref = data.get("ref", "main")
if raw_ref is not None:
ref_type, clean_ref = classify_ref(str(raw_ref))
data["ref"] = clean_ref
if "ref_type" not in data or data["ref_type"] is None:
data["ref_type"] = ref_type
return data
def to_dict(self) -> dict[str, Any]:
return {
"type": self.type,
"url": self.url,
"ref": self.ref,
"ref_type": self.ref_type.value,
"transport": self.transport.value,
}
class DeploymentConfig(BaseModel):
"""Continuous deployment strategy and action policy."""
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"])
@field_validator("strategy", mode="before")
@classmethod
def validate_strategy(cls, v: Any) -> str:
clean = str(v).strip().lower()
if clean not in ALLOWED_STRATEGIES:
raise ManifestValidationError(
f"Unsupported deployment strategy '{clean}'. Allowed: {sorted(ALLOWED_STRATEGIES)}"
)
return clean
@field_validator("actions", mode="before")
@classmethod
def validate_actions(cls, v: Any) -> list[str]:
if isinstance(v, list):
actions: list[str] = []
for act in v:
act_str = str(act).strip().lower()
if act_str not in ALLOWED_ACTIONS:
raise ManifestValidationError(
f"Unsupported deployment action '{act_str}' (Prohibited deployment action '{act_str}'). Allowed: {sorted(ALLOWED_ACTIONS)}"
)
actions.append(act_str)
if not actions:
return ["compose_up"]
return actions
return ["compose_up"]
def to_dict(self) -> dict[str, Any]:
return self.model_dump(mode="python")
class HomepageConfig(BaseModel):
"""Dashboard card metadata for Homepage."""
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
title: str
group: str = "Applications"
icon: str = "default.png"
container: str = ""
weight: int = 50
@field_validator("weight", mode="before")
@classmethod
def normalize_weight(cls, v: Any) -> int:
try:
return int(v)
except (ValueError, TypeError):
return 50
def to_dict(self) -> dict[str, Any]:
return self.model_dump(mode="python")
class Manifest(BaseModel):
"""
Authoritative Workload Manifest Model (Schema v1.0).
Represents the full contract declared in a workload's app.yaml.
"""
model_config = ConfigDict(
extra="forbid",
populate_by_name=True,
ignored_types=(dict,),
)
name: str
schema_version: str = Field(default="1.0", alias="schemaVersion")
domain: str = ""
description: str = ""
aliases: list[str] = Field(default_factory=list)
visible: bool = True
auth: bool = True
networks: list[str] = Field(default_factory=lambda: ["proxy-net"])
env: dict[str, str] = Field(default_factory=dict)
deployment: DeploymentConfig = Field(default_factory=DeploymentConfig)
source: SourceConfig | None = None
homepage: HomepageConfig | None = None
@model_validator(mode="before")
@classmethod
def prepare_manifest(cls, data: Any) -> Any:
if isinstance(data, dict):
raw_name = data.get("name")
if (
raw_name is None
or not isinstance(raw_name, str)
or not raw_name.strip()
):
raise ManifestValidationError(
"Manifest is missing mandatory string field 'name'."
)
clean_name = raw_name.strip()
if not NAME_RE.match(clean_name):
raise ManifestValidationError(
f"Invalid workload name '{clean_name}'. Must be alphanumeric with optional '.' '_' '-', starting with alphanumeric."
)
data["name"] = clean_name
# Source: treat empty dict or missing url as None
src = data.get("source")
if isinstance(src, dict) and not src.get("url"):
data["source"] = None
# Homepage default propagation
hp = data.get("homepage")
if isinstance(hp, dict):
hp.setdefault("title", clean_name)
hp.setdefault("container", clean_name)
return data
@field_validator("visible", "auth", mode="before")
@classmethod
def cast_bool(cls, v: Any) -> bool:
if v is None:
return True
return bool(v)
@field_validator("aliases", mode="before")
@classmethod
def normalize_aliases(cls, v: Any) -> list[str]:
if isinstance(v, str):
return [v.strip()] if v.strip() else []
if isinstance(v, list):
return [str(a).strip() for a in v if isinstance(a, str) and str(a).strip()]
return []
@field_validator("networks", mode="before")
@classmethod
def normalize_networks(cls, v: Any) -> list[str]:
if isinstance(v, list):
clean = [str(n).strip() for n in v if str(n).strip()]
if clean:
return clean
return ["proxy-net"]
@field_validator("env", mode="before")
@classmethod
def validate_env(cls, v: Any) -> dict[str, str]:
if not isinstance(v, dict):
return {}
env: dict[str, str] = {}
for raw_k, raw_v in v.items():
k_str = str(raw_k).strip()
if not ENV_KEY_RE.match(k_str) or k_str in RESERVED_ENV_KEYS:
raise ManifestValidationError(
f"Invalid or reserved environment variable key '{k_str}'. "
f"Keys must match ^[a-zA-Z_][a-zA-Z0-9_]*$ and cannot be reserved."
)
env[k_str] = str(raw_v) if raw_v is not None else ""
return env
@property
def is_class_a(self) -> bool:
"""Class A: Source-backed workload requiring upstream repository checkout & build."""
return self.source is not None
@property
def is_class_b(self) -> bool:
"""Class B: Image-only workload deploying directly from container registries."""
return self.source is None
@property
def is_internal(self) -> bool:
"""True if the workload does not expose a public TLS endpoint."""
return (
not self.domain
or self.domain == "internal"
or self.domain.endswith(".local")
or ":" in self.domain
)
def to_dict(self) -> dict[str, Any]:
data: dict[str, Any] = {
"schemaVersion": self.schema_version,
"name": self.name,
"domain": self.domain,
"description": self.description,
"aliases": list(self.aliases),
"visible": self.visible,
"auth": self.auth,
"networks": list(self.networks),
"env": dict(self.env),
"deployment": self.deployment.to_dict(),
"is_class_a": self.is_class_a,
"is_class_b": self.is_class_b,
"is_internal": self.is_internal,
}
if self.source:
data["source"] = self.source.to_dict()
if self.homepage:
data["homepage"] = self.homepage.to_dict()
return data
def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest:
"""
Parse and strictly validate an app.yaml manifest into an authoritative Manifest object.
Accepts:
- Path object pointing to an app.yaml
- Raw YAML string content
- Pre-parsed dictionary
"""
data: dict[str, Any] = {}
if isinstance(raw_input, Path):
if not raw_input.is_file():
raise ManifestValidationError(f"Manifest file not found: {raw_input}")
try:
content = raw_input.read_text(encoding="utf-8")
except OSError as e:
raise ManifestValidationError(
f"Failed to read manifest {raw_input}: {e}"
) from e
try:
data = (
yaml.safe_load(content) if yaml else _parse_yaml_basic(content)
) or {}
except Exception as e:
raise ManifestValidationError(
f"YAML parsing error in {raw_input}: {e}"
) from e
elif isinstance(raw_input, str):
try:
data = (
yaml.safe_load(raw_input) if yaml else _parse_yaml_basic(raw_input)
) or {}
except Exception as e:
raise ManifestValidationError(f"YAML parsing error: {e}") from e
elif isinstance(raw_input, dict):
data = raw_input
else:
raise ManifestValidationError(
f"Invalid input type for manifest parsing: {type(raw_input)}"
)
if not isinstance(data, dict):
raise ManifestValidationError(
"Manifest root must be a YAML dictionary mapping."
)
try:
return Manifest.model_validate(data)
except ValidationError as e:
for err in e.errors():
ctx = err.get("ctx", {})
orig_err = ctx.get("error")
if isinstance(orig_err, ManifestValidationError):
raise orig_err from e
first_error = e.errors()[0]
msg = first_error.get("msg", str(e))
if msg.startswith("Value error, "):
msg = msg.removeprefix("Value error, ")
loc = ".".join(str(p) for p in first_error.get("loc", []))
if loc and first_error.get("type") == "extra_forbidden":
raise ManifestValidationError(
f"Manifest contains unrecognized or forbidden field '{loc}'."
) from e
raise ManifestValidationError(msg) from e
def _parse_yaml_basic(content: str) -> dict[str, Any]:
"""Lightweight fallback parser when PyYAML is unavailable."""
result: dict[str, Any] = {}
for line in content.splitlines():
trimmed = line.strip()
if not trimmed or trimmed.startswith("#") or ":" not in trimmed:
continue
k, v = trimmed.split(":", 1)
k = k.strip()
v = v.strip().strip("\"'")
result[k] = v
return result
+1364 -157
View File
File diff suppressed because it is too large. Load diff
+354
View File
@@ -0,0 +1,354 @@
"""
provenance.py — Two-Axis Inspection & Upstream Provenance Resolver
Evaluates workload health along two independent axes:
1. Local Deployment Axis: Local checkout cleanliness (* Dirty vs. ✓ Clean), branch, commit, and container runtime state.
2. Upstream Provenance Axis: Upstream git repository state resolved via bounded `git ls-remote` (10s timeout).
"""
from __future__ import annotations
import os
import subprocess
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from core_manifest import Manifest, RefType, SourceConfig
class ProvenanceStatus(str, Enum):
"""Evaluation result of local state vs. upstream software provenance."""
SYNCED = "✓ Synced"
UPDATE_AVAILABLE = "↓ Update Available"
IMAGE_ONLY = "— Image-Only (Class B)"
DIRTY = "* Dirty"
UNREACHABLE = "⚠ Unreachable"
TIMEOUT = "⏱ Timed Out (10s)"
UNKNOWN = "— Not Checked"
NOT_CLONED = "✕ Missing Checkout"
@dataclass
class CheckoutStatus:
"""Axis 1: Local deployment checkout state."""
is_git: bool
is_dirty: bool
branch: str
commit_sha: str
status_label: str
def to_dict(self) -> dict[str, str | bool]:
return {
"is_git": self.is_git,
"is_dirty": self.is_dirty,
"branch": self.branch,
"commit_sha": self.commit_sha,
"status_label": self.status_label,
}
@dataclass
class UpstreamProvenance:
"""Axis 2: Upstream software provenance state."""
status: ProvenanceStatus
remote_sha: str = ""
target_ref: str = ""
message: str = ""
def to_dict(self) -> dict[str, str]:
return {
"status": self.status.value,
"remote_sha": self.remote_sha,
"target_ref": self.target_ref,
"message": self.message,
}
@dataclass
class TwoAxisStatus:
"""Unified inspection combining local deployment and upstream provenance."""
app_name: str
checkout: CheckoutStatus
provenance: UpstreamProvenance
docker_status: str
image_revision: str | None = None
def to_dict(self) -> dict[str, object]:
return {
"app_name": self.app_name,
"checkout": self.checkout.to_dict(),
"provenance": self.provenance.to_dict(),
"docker_status": self.docker_status,
"image_revision": self.image_revision,
}
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)
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,
branch="",
commit_sha="",
status_label="— No Git Repo",
)
# 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 (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(
status_cmd,
capture_output=True,
text=True,
check=False,
timeout=5.0,
env=git_env,
)
if status_res.returncode == 0:
if status_res.stdout.strip():
is_dirty = True
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(git_root), "rev-parse", "--abbrev-ref", "HEAD"],
capture_output=True,
text=True,
check=False,
timeout=5.0,
env=git_env,
)
if branch_res.returncode == 0:
branch = branch_res.stdout.strip()
if branch == "HEAD":
# Detached HEAD, check describe
desc_res = subprocess.run(
["git", "-C", str(git_root), "describe", "--tags", "--exact-match"],
capture_output=True,
text=True,
check=False,
timeout=5.0,
env=git_env,
)
if desc_res.returncode == 0 and desc_res.stdout.strip():
branch = desc_res.stdout.strip()
except (subprocess.SubprocessError, OSError):
branch = "unknown"
# 3. Get commit SHA
commit_sha = ""
try:
sha_res = subprocess.run(
["git", "-C", str(git_root), "rev-parse", "--short", "HEAD"],
capture_output=True,
text=True,
check=False,
timeout=5.0,
env=git_env,
)
if sha_res.returncode == 0:
commit_sha = sha_res.stdout.strip()
except (subprocess.SubprocessError, OSError):
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
return CheckoutStatus(
is_git=True,
is_dirty=is_dirty,
branch=branch,
commit_sha=commit_sha,
status_label=status_label,
)
def resolve_upstream_provenance(
source: SourceConfig | None,
local_commit: str = "",
timeout: float = 10.0,
) -> UpstreamProvenance:
"""
Resolve upstream provenance via bounded `git ls-remote`.
Compares the declared upstream ref with the deployed local commit.
Bounded by a 10-second timeout to prevent hanging on unresponsive remotes.
"""
if source is None:
return UpstreamProvenance(
status=ProvenanceStatus.IMAGE_ONLY,
message="Class B workload deploys prebuilt container images directly",
)
target_ref = source.ref
remote_url = source.url
# Commits pinned directly in manifest cannot be checked via ls-remote ref matching
if source.ref_type == RefType.COMMIT:
is_match = local_commit and (
source.ref.startswith(local_commit) or local_commit.startswith(source.ref)
)
status = (
ProvenanceStatus.SYNCED if is_match else ProvenanceStatus.UPDATE_AVAILABLE
)
return UpstreamProvenance(
status=status,
remote_sha=source.ref,
target_ref=source.ref[:7],
message="Pinned immutable commit SHA",
)
cmd = ["git", "ls-remote", "--exit-code", remote_url, target_ref]
try:
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
check=False,
timeout=timeout,
)
except subprocess.TimeoutExpired:
return UpstreamProvenance(
status=ProvenanceStatus.TIMEOUT,
target_ref=target_ref,
message=f"Upstream check timed out after {int(timeout)}s ({remote_url})",
)
except (subprocess.SubprocessError, OSError) as e:
return UpstreamProvenance(
status=ProvenanceStatus.UNREACHABLE,
target_ref=target_ref,
message=f"Network error querying upstream: {e}",
)
if proc.returncode != 0:
# Check if ref was not found on remote (exit code 2 for git ls-remote)
err_msg = proc.stderr.strip() or f"Ref '{target_ref}' not found on remote."
return UpstreamProvenance(
status=ProvenanceStatus.UNREACHABLE,
target_ref=target_ref,
message=f"Failed to query remote ({remote_url}): {err_msg}",
)
# Parse remote SHA from ls-remote output (Format: <SHA>\t<ref_name>)
remote_sha = ""
for line in proc.stdout.splitlines():
parts = line.strip().split()
if len(parts) >= 2 and (
parts[1] == target_ref
or parts[1] == f"refs/heads/{target_ref}"
or parts[1] == f"refs/tags/{target_ref}"
or parts[1] == f"refs/tags/{target_ref}^{{}}"
):
remote_sha = parts[0]
# Peaked tags (^{}) take precedence over lightweight tag refs
if parts[1].endswith("^{}"):
break
if not remote_sha and proc.stdout.strip():
# Fallback: take first match SHA
remote_sha = proc.stdout.strip().split()[0]
if not remote_sha:
return UpstreamProvenance(
status=ProvenanceStatus.UNREACHABLE,
target_ref=target_ref,
message=f"No matching ref found for '{target_ref}' at {remote_url}",
)
# Compare local commit with remote SHA
is_synced = False
if local_commit and (
remote_sha.startswith(local_commit) or local_commit.startswith(remote_sha[:7])
):
is_synced = True
status = ProvenanceStatus.SYNCED if is_synced else ProvenanceStatus.UPDATE_AVAILABLE
short_remote = remote_sha[:7]
msg = f"Upstream at {short_remote}" if not is_synced else "Up to date with upstream"
return UpstreamProvenance(
status=status,
remote_sha=remote_sha,
target_ref=target_ref,
message=msg,
)
def inspect_workload_two_axis(
app_dir: Path | str,
manifest: Manifest,
fetch_upstream: bool = False,
docker_status: str = "⚪ Not Stack",
image_revision: str | None = None,
timeout: float = 10.0,
) -> TwoAxisStatus:
"""
Perform two-axis status inspection of a single workload.
"""
path = Path(app_dir)
# Axis 1: Local Deployment Checkout
checkout = get_local_checkout_status(path)
# Axis 2: Upstream Provenance
if manifest.is_class_b:
provenance = UpstreamProvenance(
status=ProvenanceStatus.IMAGE_ONLY,
message="Class B (Image-Only)",
)
elif not fetch_upstream:
provenance = UpstreamProvenance(
status=ProvenanceStatus.UNKNOWN,
target_ref=manifest.source.ref if manifest.source else "",
message="Pass --fetch to query upstream repository",
)
else:
provenance = resolve_upstream_provenance(
manifest.source,
local_commit=checkout.commit_sha,
timeout=timeout,
)
return TwoAxisStatus(
app_name=manifest.name,
checkout=checkout,
provenance=provenance,
docker_status=docker_status,
image_revision=image_revision,
)
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
# scripts/run-tests - Automated test & invariant verification runner for Homelab Core
set -euo pipefail
cd "$(dirname "$0")/.."
echo "🔍 Running code linters (ruff)..."
if command -v ruff &>/dev/null; then
ruff check .
else
nix develop --command ruff check .
fi
echo "🔎 Running static type analysis (pyright)..."
if command -v pyright &>/dev/null; then
pyright
else
nix develop --command pyright
fi
echo "🧪 Running architecture & security test suite (pytest)..."
if [ -x ".venv/bin/pytest" ]; then
.venv/bin/pytest tests/
elif command -v pytest &>/dev/null; then
pytest tests/
else
nix develop --command pytest tests/
fi
echo "❄️ Verifying NixOS flake & sandbox checks..."
nix flake check
nix eval .#nixosConfigurations.server.config.system.build.toplevel.drvPath --json >/dev/null
echo "✨ All tests and architectural invariants passed successfully!"
-24
View File
@@ -1,24 +0,0 @@
#!/usr/bin/env bash
# scripts/test - Automated test & invariant verification runner for Homelab Core
set -euo pipefail
cd "$(dirname "$0")/.."
echo "🔍 Running code linters (ruff)..."
if command -v ruff &>/dev/null; then
ruff check .
else
nix-shell -p ruff --run "ruff check ."
fi
echo "🧪 Running architecture & security test suite (pytest)..."
if command -v pytest &>/dev/null; then
pytest tests/
else
nix-shell -p python3Packages.pytest python3Packages.pyyaml --run "pytest tests/"
fi
echo "❄️ Verifying NixOS flake & sandbox checks..."
nix flake check
echo "✨ All tests and architectural invariants passed successfully!"
+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
+6
View File
@@ -0,0 +1,6 @@
[mutmut]
also_copy=
pyproject.toml
docker-compose.yml
config
scripts
+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}"
)
File diff suppressed because it is too large. Load diff
+499 -5
View File
@@ -2,10 +2,20 @@
Security invariant tests for Docker Compose and container isolation. Security invariant tests for Docker Compose and container isolation.
""" """
import json
import os
import shutil
import subprocess
from pathlib import Path from pathlib import Path
import yaml 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 CORE_ROOT = Path(__file__).resolve().parent.parent.parent
@@ -42,8 +52,12 @@ def test_no_direct_docker_sock_mounts_except_socket_proxy():
volumes = svc.get("volumes", []) volumes = svc.get("volumes", [])
for vol in volumes: for vol in volumes:
if isinstance(vol, str) and "/var/run/docker.sock" in vol: if isinstance(vol, str) and "/var/run/docker.sock" in vol:
assert name == "socket-proxy", f"Service '{name}' directly mounts docker.sock!" assert name == "socket-proxy", (
assert vol.endswith(":ro"), "socket-proxy docker.sock mount must be read-only (:ro)" f"Service '{name}' directly mounts docker.sock!"
)
assert vol.endswith(":ro"), (
"socket-proxy docker.sock mount must be read-only (:ro)"
)
def test_no_privileged_containers(): def test_no_privileged_containers():
@@ -55,7 +69,9 @@ def test_no_privileged_containers():
services = compose.get("services", {}) services = compose.get("services", {})
for name, svc in services.items(): for name, svc in services.items():
privileged = svc.get("privileged", False) privileged = svc.get("privileged", False)
assert privileged is not True, f"Service '{name}' is configured as privileged: true!" assert privileged is not True, (
f"Service '{name}' is configured as privileged: true!"
)
def test_no_shell_true_in_core_scripts(): def test_no_shell_true_in_core_scripts():
@@ -73,7 +89,485 @@ def test_portainer_is_deprecated_and_absent():
compose = yaml.safe_load(f) compose = yaml.safe_load(f)
services = compose.get("services", {}) services = compose.get("services", {})
assert "portainer" not in services, "Deprecated service 'portainer' must not exist in docker-compose.yml" assert "portainer" not in services, (
"Deprecated service 'portainer' must not exist in docker-compose.yml"
)
volumes = compose.get("volumes", {}) or {} volumes = compose.get("volumes", {}) or {}
assert "portainer_data" not in volumes, "Deprecated volume 'portainer_data' must not exist in docker-compose.yml" assert "portainer_data" not in volumes, (
"Deprecated volume 'portainer_data' must not exist in docker-compose.yml"
)
def test_no_eval_in_appctl_script():
"""Ensure scripts/appctl never uses eval on dynamic environment or manifest payloads."""
appctl_path = CORE_ROOT / "scripts" / "appctl"
content = appctl_path.read_text(encoding="utf-8")
assert "eval " not in content, "Dangerous 'eval' detected in scripts/appctl!"
def test_appctl_env_injection_resilience(tmp_path: Path, monkeypatch):
"""Ensure environment values from app.yaml cannot execute shell commands via command substitution
during P4 production environment assembly and router dispatch. Executes OperationalRouter with a mock docker binary.
"""
canary = tmp_path / "pwned.txt"
payload = f"$(touch {canary})"
# 1. Setup mock Sites directory with vulnerable app.yaml and docker-compose.yml
sites_dir = tmp_path / "Sites"
app_dir = sites_dir / "vuln-app"
app_dir.mkdir(parents=True)
app_yaml = f"""
name: vuln-app
domain: vuln.example.test
env:
INJECTION_TEST: '{payload}'
NORMAL_VAR: 'safe_value'
"""
(app_dir / "app.yaml").write_text(app_yaml.strip(), encoding="utf-8")
(app_dir / "docker-compose.yml").write_text(
"services:\n web:\n image: nginx\n", encoding="utf-8"
)
# 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" ] && [ "$4" = "config" ]; then
echo "MOCK_DOCKER_COMPOSE_CONFIG"
echo "CAPTURED_INJECTION=$INJECTION_TEST"
echo "CAPTURED_NORMAL=$NORMAL_VAR"
exit 0
fi
exit 0
"""
mock_docker.write_text(mock_docker_script, encoding="utf-8")
mock_docker.chmod(0o755)
# 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",
)
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 resp.success is True, (
f"OperationalRouter dispatch failed: {resp.error}"
)
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():
"""Ensure personal domains and operator usernames are absent from scripts, tests, and documentation."""
forbidden = ["roadtotech.me", "kiskaadee"]
root_dirs = [
CORE_ROOT / "scripts",
CORE_ROOT / "tests",
CORE_ROOT / "docs",
CORE_ROOT / "nixos" / "modules",
CORE_ROOT / "config",
]
root_files = [
CORE_ROOT / "README.md",
CORE_ROOT / "ROADMAP.md",
CORE_ROOT / "AGENTS.md",
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 = []
candidate_files = list(root_files)
for root_dir in root_dirs:
candidate_files.extend(root_dir.rglob("*"))
for file_path in candidate_files:
if (
file_path.is_file()
and file_path.suffix
in (".py", ".sh", ".bash", ".yml", ".yaml", ".md", ".nix", "")
and file_path.name != "test_security_invariants.py"
):
content = file_path.read_text(encoding="utf-8", errors="ignore")
for term in forbidden:
if term in content:
violations.append(
f"{file_path.relative_to(CORE_ROOT)}: contains prohibited literal '{term}'"
)
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", "SECURITY.md",
"nixos", "nixos",
"nixos/configuration.nix", "nixos/configuration.nix",
"nixos/instance.example.nix",
"nixos/modules/homeserver.nix", "nixos/modules/homeserver.nix",
"nixos/secrets.yaml", "nixos/secrets.yaml",
"scripts/gitops_dispatcher.py", "scripts/gitops_dispatcher.py",
@@ -36,7 +37,9 @@ def test_required_architectural_paths_exist():
pre_commit = CORE_ROOT / ".githooks" / "pre-commit" pre_commit = CORE_ROOT / ".githooks" / "pre-commit"
assert pre_commit.is_file(), ".githooks/pre-commit must be a regular file" assert pre_commit.is_file(), ".githooks/pre-commit must be a regular file"
assert os.access(pre_commit, os.X_OK), ".githooks/pre-commit must be marked executable" assert os.access(pre_commit, os.X_OK), (
".githooks/pre-commit must be marked executable"
)
def test_deprecated_legacy_structures_are_absent(): def test_deprecated_legacy_structures_are_absent():
@@ -61,4 +64,7 @@ def test_unlicense_preserved():
unlicense = CORE_ROOT / "UNLICENSE" unlicense = CORE_ROOT / "UNLICENSE"
assert unlicense.is_file(), "UNLICENSE file must be present" assert unlicense.is_file(), "UNLICENSE file must be present"
content = unlicense.read_text(encoding="utf-8") content = unlicense.read_text(encoding="utf-8")
assert "This is free and unencumbered software released into the public domain." in content assert (
"This is free and unencumbered software released into the public domain."
in content
)
+373
View File
@@ -0,0 +1,373 @@
"""
tests/unit/test_appctl_audit.py — Unit Tests for Audit Logger & Concurrency Lock (P4 Slice 2)
Behavior-driven test naming convention:
test_<subject>_<accepts|rejects|enforces>_<condition>
"""
from __future__ import annotations
import json
import stat
from pathlib import Path
import pytest
from appctl_audit import (
AuditEvent,
AuditLogger,
AuditPersistenceError,
AuditPhase,
ConcurrentMutationError,
PrincipalAudit,
TargetLockManager,
redact_sensitive_data,
)
@pytest.fixture
def temp_audit_file(tmp_path: Path) -> Path:
return tmp_path / "audit" / "audit.jsonl"
@pytest.fixture
def temp_lock_dir(tmp_path: Path) -> Path:
lock_dir = tmp_path / "locks"
lock_dir.mkdir(parents=True, exist_ok=True)
return lock_dir
@pytest.fixture
def sample_principal() -> PrincipalAudit:
return PrincipalAudit(
identity="operator",
role="homelab-admin",
token_id="tok_admin_01",
auth_method="bearer_token",
)
# ---------------------------------------------------------------------------
# File Permissions & Initialization
# ---------------------------------------------------------------------------
def test_audit_logger_enforces_0600_permissions_on_creation(
temp_audit_file: Path, sample_principal: PrincipalAudit
):
logger = AuditLogger(temp_audit_file)
logger.log_dispatched(
operation_id="op_100",
principal=sample_principal,
action="workload.deploy",
target="snappymail",
transport="unix_socket",
origin="peer_uid_1000",
client="appctl-cli/2.0",
parameters={"recreate": True},
)
assert temp_audit_file.exists()
mode = stat.S_IMODE(temp_audit_file.stat().st_mode)
assert mode == 0o600
# ---------------------------------------------------------------------------
# Audit Phases & RFC JSONL Schema
# ---------------------------------------------------------------------------
def test_audit_logger_writes_valid_jsonl_lifecycle(
temp_audit_file: Path, sample_principal: PrincipalAudit
):
logger = AuditLogger(temp_audit_file)
# 1. DISPATCHED
evt_disp = logger.log_dispatched(
operation_id="op_101",
principal=sample_principal,
action="workload.update",
target="jellyfin",
transport="http",
origin="127.0.0.1:48291",
client="gitops-dispatcher/1.0",
parameters={"expected_branch": "main", "build": False},
)
assert evt_disp.phase == AuditPhase.DISPATCHED
assert evt_disp.result is not None
assert evt_disp.result.status == "IN_PROGRESS"
# 2. COMPLETED
evt_comp = logger.log_completed(
operation_id="op_101",
principal=sample_principal,
action="workload.update",
target="jellyfin",
transport="http",
origin="127.0.0.1:48291",
client="gitops-dispatcher/1.0",
parameters={"expected_branch": "main", "build": False},
duration_ms=1450,
commit_sha="a1b2c3d",
message="Workload updated and reconciled successfully",
)
assert evt_comp.phase == AuditPhase.COMPLETED
assert evt_comp.target == "jellyfin"
assert evt_comp.parameters == {"expected_branch": "main", "build": False}
assert evt_comp.result is not None
assert evt_comp.result.status == "SUCCESS"
assert evt_comp.result.exit_code == 0
assert evt_comp.result.duration_ms == 1450
assert evt_comp.result.message == "Workload updated and reconciled successfully"
assert evt_comp.result.commit_sha == "a1b2c3d"
# Read and validate JSONL file contents
lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 2
parsed_disp = AuditEvent.model_validate(json.loads(lines[0]))
assert parsed_disp.phase == AuditPhase.DISPATCHED
assert parsed_disp.operation_id == "op_101"
parsed_comp = AuditEvent.model_validate(json.loads(lines[1]))
assert parsed_comp.phase == AuditPhase.COMPLETED
assert parsed_comp.operation_id == "op_101"
def test_audit_logger_writes_failed_event(
temp_audit_file: Path, sample_principal: PrincipalAudit
):
logger = AuditLogger(temp_audit_file)
logger.log_failed(
operation_id="op_102",
principal=sample_principal,
action="workload.deploy",
target="jellyfin",
transport="unix_socket",
origin="peer_uid_1000",
client="appctl-cli/2.0",
parameters={"recreate": True},
duration_ms=320,
exit_code=1,
error_code="ERR_EXECUTION_FAILED",
message="Docker compose failed with exit code 1",
)
lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 1
event = AuditEvent.model_validate(json.loads(lines[0]))
assert event.phase == AuditPhase.FAILED
assert event.target == "jellyfin"
assert event.parameters == {"recreate": True}
assert event.result is not None
assert event.result.status == "FAILED"
assert event.result.exit_code == 1
assert event.result.error_code == "ERR_EXECUTION_FAILED"
assert event.result.duration_ms == 320
assert event.result.message == "Docker compose failed with exit code 1"
def test_audit_logger_writes_denied_event(
temp_audit_file: Path, sample_principal: PrincipalAudit
):
logger = AuditLogger(temp_audit_file)
logger.log_denied(
operation_id="op_103",
principal=sample_principal,
action="workload.config",
target="core",
transport="http",
origin="127.0.0.1:49000",
client="curl/8.1",
parameters={},
error_code="ERR_PERMISSION_DENIED",
message="Role homelab-operator cannot target core stack",
)
lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 1
event = AuditEvent.model_validate(json.loads(lines[0]))
assert event.phase == AuditPhase.DENIED
assert event.result is not None
assert event.result.status == "DENIED"
assert event.result.error_code == "ERR_PERMISSION_DENIED"
# ---------------------------------------------------------------------------
# Secret Redaction
# ---------------------------------------------------------------------------
def test_redact_sensitive_data_masks_secret_keys():
raw_params = {
"API_KEY": "supersecretkey123",
"WEBHOOK_SECRET": "whsec_9999",
"db_password": "mypassword",
"AUTH_TOKEN": "tok_12345",
"SSH_KEY": "ssh-ed25519 AAA...",
"PASSWORD_HASH": "$2b$12$...",
"recreate": True,
"nested": {
"SECRET_PASS": "pass123",
"normal_config": "enabled",
"list_items": [
{"ITEM_SECRET": "leak", "id": 1},
"safe_string",
],
},
}
redacted = redact_sensitive_data(raw_params)
assert redacted["API_KEY"] == "[REDACTED]"
assert redacted["WEBHOOK_SECRET"] == "[REDACTED]"
assert redacted["db_password"] == "[REDACTED]"
assert redacted["AUTH_TOKEN"] == "[REDACTED]"
assert redacted["SSH_KEY"] == "[REDACTED]"
assert redacted["PASSWORD_HASH"] == "[REDACTED]"
assert redacted["recreate"] is True
assert redacted["nested"]["SECRET_PASS"] == "[REDACTED]"
assert redacted["nested"]["normal_config"] == "enabled"
assert redacted["nested"]["list_items"][0]["ITEM_SECRET"] == "[REDACTED]"
assert redacted["nested"]["list_items"][0]["id"] == 1
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
):
logger = AuditLogger(temp_audit_file)
logger.log_dispatched(
operation_id="op_104",
principal=sample_principal,
action="workload.deploy",
target="vaultwarden",
transport="unix_socket",
origin="peer_uid_1000",
client="appctl-cli/2.0",
parameters={"ADMIN_TOKEN": "super_token_leak", "recreate": True},
)
content = temp_audit_file.read_text(encoding="utf-8")
assert "super_token_leak" not in content
assert "[REDACTED]" in content
# ---------------------------------------------------------------------------
# Pre-Execution Fail-Closed Disk Guard
# ---------------------------------------------------------------------------
def test_audit_logger_fails_closed_when_audit_log_unwritable(
tmp_path: Path, sample_principal: PrincipalAudit
):
# 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)
logger = AuditLogger(unwritable_target)
with pytest.raises(AuditPersistenceError) as exc_info:
logger.log_dispatched(
operation_id="op_105",
principal=sample_principal,
action="workload.deploy",
target="jellyfin",
transport="unix_socket",
origin="peer_uid_1000",
client="appctl-cli/2.0",
parameters={"recreate": True},
)
assert "Failed to persist audit event" in str(exc_info.value)
# ---------------------------------------------------------------------------
# Concurrency & Non-Blocking Flock Manager
# ---------------------------------------------------------------------------
def test_target_lock_manager_acquires_and_releases_lock(temp_lock_dir: Path):
manager = TargetLockManager(temp_lock_dir)
with manager.lock_target("snappymail") as lock:
assert lock.target == "snappymail"
assert lock.lock_path.exists()
# Verify mode 0600 on lock file
assert stat.S_IMODE(lock.lock_path.stat().st_mode) == 0o600
# Lock can be re-acquired immediately after release
with manager.lock_target("snappymail"):
pass
def test_target_lock_manager_rejects_concurrent_mutation(temp_lock_dir: Path):
manager = TargetLockManager(temp_lock_dir)
with (
manager.lock_target("jellyfin"),
pytest.raises(ConcurrentMutationError) as exc_info,
manager.lock_target("jellyfin"),
):
pass
assert exc_info.value.target == "jellyfin"
assert "locked by a concurrent task" in str(exc_info.value)
def test_target_lock_manager_permits_independent_targets_concurrently(
temp_lock_dir: Path,
):
manager = TargetLockManager(temp_lock_dir)
with manager.lock_target("app1"), manager.lock_target("app2"):
pass
def test_homepage_sync_lock_acquires_designated_file(temp_lock_dir: Path):
manager = TargetLockManager(temp_lock_dir)
with (
manager.homepage_sync_lock() as lock,
pytest.raises(ConcurrentMutationError) as exc_info,
manager.homepage_sync_lock(),
):
pass
assert lock.lock_path.name == "_homepage_sync.lock"
assert exc_info.value.target == "_homepage_sync"
def test_target_lock_manager_sanitizes_special_characters_and_supports_env(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
custom_lock_dir = tmp_path / "custom_locks"
monkeypatch.setenv("APPCTL_LOCK_DIR", str(custom_lock_dir))
manager = TargetLockManager()
assert manager.lock_dir == custom_lock_dir
with manager.lock_target("special/tenant:workload@v1!#$") as lock:
assert lock.lock_path.name == "special_tenant_workload_v1___.lock"
assert lock.lock_path.exists()
+536
View File
@@ -0,0 +1,536 @@
"""
tests/unit/test_appctl_auth.py — Unit Tests for Authentication & 3-Role RBAC (P4 Slice 3)
Behavior-driven test naming convention:
test_<subject>_<accepts|rejects|enforces>_<condition>
"""
from __future__ import annotations
import hashlib
import json
import os
from pathlib import Path
import pytest
from appctl_auth import (
AuthenticationError,
AuthorizationError,
Principal,
Role,
TokenStore,
authenticate_request,
enforce_rbac,
load_admitted_workloads,
)
from appctl_contracts import ErrorCode, OperationType
@pytest.fixture
def secret_tokens() -> dict[str, str]:
return {
"admin_secret": "sec_admin_9876543210abcdef",
"operator_secret": "sec_operator_1234567890abcdef",
}
@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()
data = [
{
"token_id": "tok_admin_01",
"identity": "operator",
"role": "homelab-admin",
"sha256": admin_hash,
},
{
"token_id": "tok_gitops_01",
"identity": "gitops-dispatcher",
"role": "homelab-operator",
"sha256": op_hash,
},
]
tokens_path.write_text(json.dumps(data), encoding="utf-8")
os.chmod(tokens_path, 0o400)
return tokens_path
@pytest.fixture
def admitted_workloads() -> set[str]:
return {"snappymail", "mail", "webmail", "jellyfin", "media", "docs"}
# ---------------------------------------------------------------------------
# TokenStore & Strict Permissions (0400)
# ---------------------------------------------------------------------------
def test_token_store_accepts_valid_0400_store(temp_tokens_file: Path):
store = TokenStore(temp_tokens_file)
tokens = store.load_tokens()
assert len(tokens) == 2
assert tokens[0].role == Role.ADMIN
assert tokens[1].role == Role.OPERATOR
def test_token_store_rejects_insecure_file_permissions(tmp_path: Path):
bad_tokens_file = tmp_path / "insecure_tokens.json"
bad_tokens_file.write_text("[]", encoding="utf-8")
# Insecure modes: 0644, 0600, 0777
for insecure_mode in [0o644, 0o600, 0o777, 0o444]:
os.chmod(bad_tokens_file, insecure_mode)
store = TokenStore(bad_tokens_file)
with pytest.raises(AuthenticationError) as exc_info:
store.load_tokens()
assert "mode 0400 required" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED
def test_token_store_rejects_missing_file(tmp_path: Path):
missing_file = tmp_path / "nonexistent.json"
store = TokenStore(missing_file)
with pytest.raises(AuthenticationError) as exc_info:
store.load_tokens()
assert "not found" in str(exc_info.value)
# ---------------------------------------------------------------------------
# Bearer Token Authentication
# ---------------------------------------------------------------------------
def test_token_store_authenticates_valid_bearer_secrets(
temp_tokens_file: Path, secret_tokens: dict[str, str]
):
store = TokenStore(temp_tokens_file)
p_admin = store.authenticate_bearer(secret_tokens["admin_secret"])
assert p_admin.identity == "operator"
assert p_admin.role == Role.ADMIN
assert p_admin.token_id == "tok_admin_01"
assert p_admin.auth_method == "bearer_token"
p_op = store.authenticate_bearer(secret_tokens["operator_secret"])
assert p_op.identity == "gitops-dispatcher"
assert p_op.role == Role.OPERATOR
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)
with pytest.raises(AuthenticationError) as exc_info:
store.authenticate_bearer("wrong_secret_token_123")
assert "Invalid or unknown Bearer token" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED
def test_token_store_rejects_empty_bearer_secret(temp_tokens_file: Path):
store = TokenStore(temp_tokens_file)
with pytest.raises(AuthenticationError) as exc_info:
store.authenticate_bearer("")
assert "Empty Bearer token provided" in str(exc_info.value)
# ---------------------------------------------------------------------------
# Transport Authentication Rules (HTTP vs. Unix Domain Socket)
# ---------------------------------------------------------------------------
def test_authenticate_request_over_http_requires_valid_bearer(
temp_tokens_file: Path, secret_tokens: dict[str, str]
):
store = TokenStore(temp_tokens_file)
# Valid Bearer token
auth_header = f"Bearer {secret_tokens['admin_secret']}"
p = authenticate_request("http", auth_header, token_store=store)
assert p.role == Role.ADMIN
# Missing Authorization header -> 401
with pytest.raises(AuthenticationError) as exc_info:
authenticate_request("http", None, token_store=store)
assert "Bearer token required over network transport" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED
# Malformed Authorization header -> 401
with pytest.raises(AuthenticationError):
authenticate_request("http", "Basic dXNlcjpwYXNz", token_store=store)
def test_authenticate_request_over_uds_falls_back_to_viewer(
temp_tokens_file: Path, secret_tokens: dict[str, str]
):
store = TokenStore(temp_tokens_file)
# Missing Authorization header over UDS with peer_uid=1000
p = authenticate_request("unix_socket", None, peer_uid=1000, token_store=store)
assert p.identity == "unix_uid_1000"
assert p.role == Role.VIEWER
assert p.token_id is None
assert p.auth_method == "unix_peercred"
# 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
)
assert p_admin.role == Role.ADMIN
assert p_admin.auth_method == "bearer_token"
def test_authenticate_request_over_uds_rejects_missing_peer_uid():
with pytest.raises(AuthenticationError) as exc_info:
authenticate_request("unix_socket", None, peer_uid=None)
assert "Missing peer credentials" in str(exc_info.value)
# ---------------------------------------------------------------------------
# Deployments Registry Scope Loader
# ---------------------------------------------------------------------------
def test_load_admitted_workloads_parses_names_and_aliases(tmp_path: Path):
deploy_file = tmp_path / "deployments.yaml"
deploy_file.write_text(
"""
schemaVersion: "1.0"
repositories:
snappymail:
path: "/home/operator/Sites/snappymail"
aliases:
- "mail"
- "webmail"
jellyfin:
path: "/home/operator/Sites/homelab-jellyfin"
aliases:
- "media"
""",
encoding="utf-8",
)
admitted = load_admitted_workloads(deploy_file)
assert "snappymail" in admitted
assert "mail" in admitted
assert "webmail" in admitted
assert "jellyfin" in admitted
assert "media" in admitted
assert "unknown_app" not in admitted
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(
{
"repositories": {
"app1": {
"path": "/home/operator/Sites/app1",
"aliases": [123, None, " ", "valid_alias"],
}
}
}
),
encoding="utf-8",
)
admitted = load_admitted_workloads(deploy_file)
assert "app1" in admitted
assert "valid_alias" in admitted
assert 123 not in admitted
assert None not in admitted
assert "" not in admitted
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"
)
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deploy_file))
admitted_env = load_admitted_workloads(None)
assert "env_app" in admitted_env
# ---------------------------------------------------------------------------
# RBAC Policy Matrix Enforcement
# ---------------------------------------------------------------------------
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"
)
# 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_CONFIG, "core", admitted_workloads)
enforce_rbac(admin, OperationType.WORKLOAD_LOGS, "traefik", admitted_workloads)
enforce_rbac(admin, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads)
enforce_rbac(admin, OperationType.WORKLOAD_LIST, None, admitted_workloads)
def test_rbac_operator_permitted_on_admitted_workloads(
admitted_workloads: set[str],
):
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_UPDATE, "mail", 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.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"
)
# Targeting "core" stack
with pytest.raises(AuthorizationError) as exc_info:
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
)
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"
)
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 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 exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
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"
)
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
)
with pytest.raises(AuthorizationError) as exc_info:
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"
)
with pytest.raises(AuthorizationError) as exc_info:
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"
)
# Permitted reads
enforce_rbac(viewer, OperationType.WORKLOAD_LIST, None)
enforce_rbac(viewer, OperationType.WORKLOAD_GET, "snappymail")
enforce_rbac(viewer, OperationType.WORKLOAD_RESOLVE, "snappymail")
enforce_rbac(viewer, OperationType.PLATFORM_SSL, "snappymail")
enforce_rbac(viewer, OperationType.PLATFORM_HEALTH, None)
def test_rbac_viewer_denied_on_mutations():
viewer = Principal(
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
)
mutations = [
OperationType.WORKLOAD_DEPLOY,
OperationType.WORKLOAD_STOP,
OperationType.WORKLOAD_RESTART,
OperationType.WORKLOAD_UPDATE,
OperationType.WORKLOAD_PULL,
OperationType.PLATFORM_SYNC_HOMEPAGE,
]
for mut in mutations:
with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(viewer, mut, "snappymail")
assert "not permitted to execute mutating operation" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_viewer_denied_on_sensitive_reads():
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"}
+596
View File
@@ -0,0 +1,596 @@
"""
test_appctl_cli.py — Unit Tests for Thin UDS Client (scripts/appctl_cli.py)
"""
from __future__ import annotations
import io
from pathlib import Path
from unittest.mock import patch
from appctl_cli import format_response, resolve_token, run_cli
from appctl_contracts import (
ErrorCode,
OperationError,
OperationRequest,
OperationResponse,
OperationType,
)
def test_cli_token_resolution(tmp_path: Path, monkeypatch):
"""Ensure token resolution checks CLI flag, environment, and config file."""
# 1. Direct CLI argument precedence
assert resolve_token("explicit-secret") == "explicit-secret"
# 2. Environment variable precedence
monkeypatch.setenv("APPCTL_TOKEN", "env-secret")
assert resolve_token(None) == "env-secret"
# 3. File fallback
monkeypatch.delenv("APPCTL_TOKEN", raising=False)
cfg_token = tmp_path / "token"
cfg_token.write_text("file-secret\n", encoding="utf-8")
with patch("pathlib.Path.home", return_value=tmp_path):
dot_config = tmp_path / ".config" / "homelab"
dot_config.mkdir(parents=True)
(dot_config / "token").write_text("user-file-secret\n", encoding="utf-8")
assert resolve_token(None) == "user-file-secret"
def test_cli_format_response_success_and_error():
"""Ensure response formatter produces human-friendly strings and JSON."""
success_resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_123",
operation=OperationType.WORKLOAD_DEPLOY,
output="Container started successfully",
)
formatted = format_response(success_resp, raw_json=False)
assert "Container started successfully" in formatted
raw_json = format_response(success_resp, raw_json=True)
assert '"operation": "workload.deploy"' in raw_json
assert '"success": true' in raw_json
error_resp = OperationResponse(
version="1.0",
success=False,
operation_id="op_456",
operation=OperationType.WORKLOAD_DEPLOY,
error=OperationError(code=ErrorCode.ERR_PERMISSION_DENIED, message="Forbidden"),
)
formatted_err = format_response(error_resp, raw_json=False)
assert "❌ Error [ERR_PERMISSION_DENIED]: Forbidden" in formatted_err
def test_cli_dispatches_list_command():
"""Ensure appctl list dispatches OperationRequest(workload.list)."""
mock_resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_001",
operation=OperationType.WORKLOAD_LIST,
output="NAME STATUS\ndocs running\n",
)
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
ret = run_cli(["list", "--core"])
assert ret == 0
assert mock_send.call_count == 1
req: OperationRequest = mock_send.call_args[1]["operation_request"]
assert req.operation == OperationType.WORKLOAD_LIST
assert req.parameters["core"] is True
assert "NAME STATUS" in mock_stdout.getvalue()
def test_cli_dispatches_mutation_command():
"""Ensure appctl up <target> dispatches OperationRequest(workload.deploy)."""
mock_resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_002",
operation=OperationType.WORKLOAD_DEPLOY,
target="jellyfin",
result={"action": "deployed", "message": "Workload deployed"},
)
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
ret = run_cli(["up", "jellyfin", "--token", "tok_secret"])
assert ret == 0
assert mock_send.call_count == 1
assert mock_send.call_args[1]["token"] == "tok_secret"
req: OperationRequest = mock_send.call_args[1]["operation_request"]
assert req.operation == OperationType.WORKLOAD_DEPLOY
assert req.target == "jellyfin"
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:
ret = run_cli(["list", "--socket", "/nonexistent/appctl.sock"])
assert ret == 1
assert "socket not found" in mock_stderr.getvalue()
def test_cli_format_response_renders_workload_list_table():
"""Ensure workload.list renders the canonical 5-column layout matching docs/appctl.md."""
resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_list_01",
operation=OperationType.WORKLOAD_LIST,
result={
"total": 2,
"workloads": [
{
"name": "snappymail",
"type": "app",
"domain": "mail.example.test",
"deployment_status": "✓ Synced (main)",
"provenance_status": "✓ Synced",
"status": "🟢 Running (1)",
},
{
"name": "traefik",
"type": "core_service",
"domain": "traefik.example.test",
"deployment_status": "",
"provenance_status": "— Core Platform",
"status": "🟢 Running (1)",
},
],
"message": "Found 2 workloads",
},
output="",
)
rendered = format_response(resp, raw_json=False)
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(
version="1.0",
success=True,
operation_id="op_get_01",
operation=OperationType.WORKLOAD_GET,
target="snappymail",
result={
"workload": {
"name": "snappymail",
"type": "app",
"dir_path": "/home/operator/Sites/snappymail",
"domain": "mail.example.test",
"description": "Lightweight Webmail",
"aliases": ["webmail", "mail"],
"networks": ["proxy-net"],
"auth": True,
"visible": True,
},
"message": "Retrieved metadata for snappymail",
},
output="",
)
rendered = format_response(resp, raw_json=False)
assert "Workload Overview: snappymail" in rendered
assert "/home/operator/Sites/snappymail" in rendered
assert "mail.example.test" in rendered
assert "webmail, mail" in rendered
assert "✨ Retrieved metadata" not in rendered
def test_cli_format_response_renders_empty_workload_list():
resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_list_empty",
operation=OperationType.WORKLOAD_LIST,
result={"total": 0, "workloads": []},
output="",
)
rendered = format_response(resp, raw_json=False)
assert rendered == "ℹ️ No workloads found."
def test_cli_format_response_renders_core_service_and_rich_metadata():
resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_get_core",
operation=OperationType.WORKLOAD_GET,
target="traefik",
result={
"workload": {
"name": "traefik",
"type": "core_service",
"dir_path": "/home/operator/Core",
"domain": "traefik.example.test",
"container": "traefik-proxy",
"description": "Edge Ingress",
"aliases": ["edge"],
"networks": ["proxy-net", "internal"],
"auth": False,
"visible": False,
"source": {
"url": "https://git.example.com/repo.git",
"ref": "main",
},
"manifest_error": "Syntax error in app.yaml",
"ssl": {
"status": "valid",
"issuer": "Let's Encrypt",
"formatted_expiry": "2027-01-01",
},
},
},
output="",
)
rendered = format_response(resp, raw_json=False)
assert "ℹ️ Core Infrastructure Service: traefik" in rendered
assert "Container: traefik-proxy" in rendered
assert "Aliases: edge" in rendered
assert "Networks: proxy-net, internal" in rendered
assert "Auth Protected: False" in rendered
assert "Dashboard: Hidden" in rendered
assert "Source URL: https://git.example.com/repo.git" in rendered
assert "Target Ref: main" in rendered
assert "⚠️ Manifest Validation Error:" in rendered
assert "Syntax error in app.yaml" in rendered
assert "🔒 SSL/TLS Certificate:" in rendered
assert "Status: valid" in rendered
def test_cli_format_response_renders_ssl_info():
resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_ssl_01",
operation=OperationType.PLATFORM_SSL,
result={
"ssl": {
"domain": "app.example.test",
"status": "valid",
"issuer": "Let's Encrypt Authority X3",
"subject": "CN=app.example.test",
"not_after": "2027-01-01 00:00:00 GMT",
"days_remaining": 75,
"formatted_expiry": "in 75 days",
"error": "Near expiration warning",
}
},
output="",
)
rendered = format_response(resp, raw_json=False)
assert "🔒 SSL/TLS Certificate: app.example.test" in rendered
assert "Domain: app.example.test" in rendered
assert "Status: valid" in rendered
assert "Issuer: Let's Encrypt Authority X3" in rendered
assert "Subject: CN=app.example.test" in rendered
assert "Expiration: 2027-01-01 00:00:00 GMT" in rendered
assert "Days Remaining: 75 days (in 75 days)" in rendered
assert "Details/Error: Near expiration warning" in rendered
def test_cli_format_response_renders_workload_resolve_json():
import json
workload_data = {"name": "app1", "dir": "/sites/app1"}
resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_resolve_01",
operation=OperationType.WORKLOAD_RESOLVE,
result={"workload": workload_data},
output="",
)
rendered = format_response(resp, raw_json=False)
assert json.loads(rendered) == workload_data
def test_cli_format_response_error_without_error_payload():
from unittest.mock import MagicMock
resp = MagicMock(spec=OperationResponse)
resp.success = False
resp.error = None
rendered = format_response(resp, raw_json=False)
assert rendered == "❌ Error: Unknown error"
def test_cli_format_response_default_success_message():
resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_succ",
operation=OperationType.PLATFORM_HEALTH,
)
rendered = format_response(resp, raw_json=False)
assert rendered == "✨ Operation 'platform.health' succeeded."
def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path, monkeypatch):
"""Ensure scripts/appctl executes `complete` and `completion` via appctl_engine.py even when socket exists."""
import os
import shutil
import socket as std_socket
import subprocess
import sys
import tempfile
bash_bin = shutil.which("bash") or "bash"
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:
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(sock_path),
"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
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
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
+695
View File
@@ -0,0 +1,695 @@
"""
tests/unit/test_appctl_contracts.py — Unit Tests for Control Plane API Contracts (P4 Slice 1)
Behavior-driven test naming convention:
test_<subject>_<accepts|rejects>_<condition>
"""
from __future__ import annotations
import pytest
from appctl_contracts import (
MUTATING_OPERATIONS,
READ_ONLY_OPERATIONS,
TARGET_REQUIRED_OPERATIONS,
DeployParams,
EmptyParams,
ErrorCode,
GetParams,
ListParams,
LogsParams,
OperationError,
OperationRequest,
OperationResponse,
OperationType,
UpdateParams,
sanitize_validation_error,
)
from core_manifest import ALLOWED_ACTIONS, Manifest
from pydantic import BaseModel, ValidationError
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def get_validation_error_locs(data: dict) -> list[str | int]:
with pytest.raises(ValidationError) as exc_info:
OperationRequest.model_validate(data)
return [err["loc"][0] for err in exc_info.value.errors()]
# ---------------------------------------------------------------------------
# Canonical 13 Operations
# ---------------------------------------------------------------------------
def test_operation_type_contains_exactly_13_canonical_operations():
assert len(OperationType) == 13
expected = {
"workload.list",
"workload.get",
"workload.resolve",
"platform.ssl",
"platform.health",
"workload.config",
"workload.logs",
"workload.deploy",
"workload.stop",
"workload.restart",
"workload.update",
"workload.pull",
"platform.sync_homepage",
}
assert {op.value for op in OperationType} == expected
def test_operation_sets_partition_canonical_operations():
assert MUTATING_OPERATIONS | READ_ONLY_OPERATIONS == set(OperationType)
assert MUTATING_OPERATIONS.isdisjoint(READ_ONLY_OPERATIONS)
@pytest.mark.parametrize("op", list(OperationType))
def test_operation_request_accepts_all_canonical_operations(op: OperationType):
target = "jellyfin" if op in TARGET_REQUIRED_OPERATIONS else None
request = {
"version": "1.0",
"operation": op.value,
"target": target,
"parameters": {},
}
validated = OperationRequest.model_validate(request)
assert validated.operation == op
assert validated.action == op
def test_operation_request_rejects_unknown_operation():
request = {
"version": "1.0",
"operation": "workload.unknown_action",
"target": "jellyfin",
"parameters": {},
}
locs = get_validation_error_locs(request)
assert "operation" in locs
def test_operation_request_rejects_empty_operation():
request = {
"version": "1.0",
"operation": "",
"target": "jellyfin",
"parameters": {},
}
locs = get_validation_error_locs(request)
assert "operation" in locs
def test_operation_request_rejects_non_string_operation():
request = {
"version": "1.0",
"operation": 12345,
"target": "jellyfin",
"parameters": {},
}
locs = get_validation_error_locs(request)
assert "operation" in locs
# ---------------------------------------------------------------------------
# Version "1.0"
# ---------------------------------------------------------------------------
def test_operation_request_accepts_default_and_explicit_version_1_0():
# Explicit "1.0"
r1 = OperationRequest.model_validate({
"version": "1.0",
"operation": "platform.health",
})
assert r1.version == "1.0"
# Default "1.0"
r2 = OperationRequest.model_validate({
"operation": "platform.health",
})
assert r2.version == "1.0"
def test_operation_request_rejects_non_1_0_version():
for bad_ver in ["2.0", "0.9", "1.1", ""]:
request = {
"version": bad_ver,
"operation": "platform.health",
}
locs = get_validation_error_locs(request)
assert "version" in locs
def test_operation_request_rejects_numeric_version():
request = {
"version": 1.0,
"operation": "platform.health",
}
locs = get_validation_error_locs(request)
assert "version" in locs
# ---------------------------------------------------------------------------
# Target Validation
# ---------------------------------------------------------------------------
def test_operation_request_rejects_empty_target():
request = {
"version": "1.0",
"operation": "workload.deploy",
"target": "",
"parameters": {},
}
locs = get_validation_error_locs(request)
assert "target" in locs
@pytest.mark.parametrize("op", list(TARGET_REQUIRED_OPERATIONS))
def test_operation_request_rejects_missing_target_when_required(op: OperationType):
request = {
"version": "1.0",
"operation": op.value,
"target": None,
"parameters": {},
}
with pytest.raises(ValidationError) as exc_info:
OperationRequest.model_validate(request)
assert "requires a non-empty target" in str(exc_info.value)
@pytest.mark.parametrize("op", [
OperationType.WORKLOAD_LIST,
OperationType.PLATFORM_HEALTH,
OperationType.PLATFORM_SYNC_HOMEPAGE,
])
def test_operation_request_accepts_missing_target_when_optional(op: OperationType):
request = {
"version": "1.0",
"operation": op.value,
"parameters": {},
}
validated = OperationRequest.model_validate(request)
assert validated.target is None
# ---------------------------------------------------------------------------
# Parameter Models & Bounds Validation
# ---------------------------------------------------------------------------
def test_deploy_params_defaults_and_explicit_bounds():
# Defaults
p_default = DeployParams()
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, 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():
for bad_bool in ["true", "false", 1, 0, None, [True]]:
with pytest.raises(ValidationError):
DeployParams(recreate=bad_bool) # type: ignore[arg-type]
with pytest.raises(ValidationError):
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():
with pytest.raises(ValidationError):
DeployParams.model_validate({"recreate": True, "unexpected": "extra"})
def test_update_params_defaults_and_explicit():
# Defaults
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, 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.model_validate({"build": False, "extra": "prohibited"})
def test_logs_params_defaults_and_bounds():
# Default
p_default = LogsParams()
assert p_default.tail == 100
# Bounds
assert LogsParams(tail=1).tail == 1
assert LogsParams(tail=1000).tail == 1000
assert LogsParams(tail=500).tail == 500
# Below minimum
with pytest.raises(ValidationError):
LogsParams(tail=0)
# Above maximum
with pytest.raises(ValidationError):
LogsParams(tail=1001)
# Non-strict integer (string / float)
with pytest.raises(ValidationError):
LogsParams(tail="100") # type: ignore[arg-type]
with pytest.raises(ValidationError):
LogsParams(tail=100.5) # type: ignore[arg-type]
with pytest.raises(ValidationError):
LogsParams.model_validate({"tail": 50, "follow": True})
def test_list_params_defaults_and_explicit():
p_default = ListParams()
assert p_default.fetch is False
assert p_default.core is False
assert p_default.ssl is False
p_custom = ListParams(fetch=True, core=True, ssl=True)
assert p_custom.fetch is True
assert p_custom.core is True
assert p_custom.ssl is True
with pytest.raises(ValidationError):
ListParams(fetch="yes") # type: ignore[arg-type]
with pytest.raises(ValidationError):
ListParams.model_validate({"fetch": False, "extra": 1})
def test_get_params_defaults_and_explicit():
p_default = GetParams()
assert p_default.ssl is False
p_custom = GetParams(ssl=True)
assert p_custom.ssl is True
with pytest.raises(ValidationError):
GetParams(ssl="true") # type: ignore[arg-type]
def test_empty_params_rejects_extra_fields():
p = EmptyParams()
assert p.model_dump() == {}
with pytest.raises(ValidationError):
EmptyParams.model_validate({"any_field": "disallowed"})
def test_operation_request_validates_and_parses_operation_specific_params():
# Deploy
req_deploy = OperationRequest.model_validate({
"version": "1.0",
"operation": "workload.deploy",
"target": "snappymail",
"parameters": {"recreate": True, "build": True},
})
params = req_deploy.parse_parameters()
assert isinstance(params, DeployParams)
assert params.build is True
# Logs
req_logs = OperationRequest.model_validate({
"version": "1.0",
"operation": "workload.logs",
"target": "snappymail",
"parameters": {"tail": 250},
})
log_params = req_logs.parse_parameters()
assert isinstance(log_params, LogsParams)
assert log_params.tail == 250
# Stop (accepts EmptyParams)
req_stop = OperationRequest.model_validate({
"version": "1.0",
"operation": "workload.stop",
"target": "snappymail",
"parameters": {},
})
assert isinstance(req_stop.parse_parameters(), EmptyParams)
def test_operation_request_rejects_invalid_params_for_operation():
# Deploy with bad tail
with pytest.raises(ValidationError):
OperationRequest.model_validate({
"version": "1.0",
"operation": "workload.deploy",
"target": "snappymail",
"parameters": {"tail": 50}, # Deploy does not accept tail
})
# Logs with out-of-bounds tail
with pytest.raises(ValidationError):
OperationRequest.model_validate({
"version": "1.0",
"operation": "workload.logs",
"target": "snappymail",
"parameters": {"tail": 9999},
})
# Stop with extra params
with pytest.raises(ValidationError):
OperationRequest.model_validate({
"version": "1.0",
"operation": "workload.stop",
"target": "snappymail",
"parameters": {"force": True},
})
def test_operation_request_rejects_extra_top_level_fields():
request = {
"version": "1.0",
"operation": "platform.health",
"prohibited_extra": "attack",
}
with pytest.raises(ValidationError) as exc_info:
OperationRequest.model_validate(request)
assert "extra_forbidden" in [e["type"] for e in exc_info.value.errors()]
def test_operation_request_backward_compatibility_aliases():
# Accepts 'action' alias for 'operation', and 'params' alias for 'parameters'
request = {
"action": "workload.deploy",
"target": "jellyfin",
"params": {"recreate": True},
}
validated = OperationRequest.model_validate(request)
assert validated.operation == OperationType.WORKLOAD_DEPLOY
assert validated.action == OperationType.WORKLOAD_DEPLOY
assert validated.parameters == {"recreate": True}
assert validated.params == {"recreate": True}
# ---------------------------------------------------------------------------
# Closed 6-Code Error Taxonomy
# ---------------------------------------------------------------------------
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",
}
assert {code.value for code in ErrorCode} == expected_codes
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
def test_operation_error_accepts_valid_error_code():
err = OperationError(
code=ErrorCode.ERR_AUTH_REQUIRED,
message="Bearer token required",
)
assert err.code == ErrorCode.ERR_AUTH_REQUIRED
assert err.message == "Bearer token required"
assert err.details is None
def test_operation_error_accepts_string_error_code_coercion():
err = OperationError.model_validate({
"code": "ERR_CONCURRENT_MUTATION",
"message": "Operation locked by concurrent task",
})
assert err.code == ErrorCode.ERR_CONCURRENT_MUTATION
def test_operation_error_rejects_invalid_error_code():
with pytest.raises(ValidationError):
OperationError.model_validate({
"code": "ERR_CUSTOM_CODE",
"message": "Invalid code",
})
def test_operation_error_rejects_extra_fields():
with pytest.raises(ValidationError):
OperationError.model_validate({
"code": "ERR_VALIDATION_FAILED",
"message": "Failed",
"secret_leak": "value",
})
# ---------------------------------------------------------------------------
# Error Sanitizer (Information Disclosure Prevention)
# ---------------------------------------------------------------------------
def test_sanitize_validation_error_strips_input_and_url():
# Create a model with secret value that fails validation
class SecretPayload(BaseModel):
token: str = "default"
try:
LogsParams.model_validate({
"tail": "SUPER_SECRET_TOKEN_DO_NOT_LEAK",
})
except ValidationError as exc:
op_err = sanitize_validation_error(exc)
assert op_err.code == ErrorCode.ERR_VALIDATION_FAILED
assert op_err.message == "Request payload validation failed"
assert op_err.details is not None
assert len(op_err.details) == 1
detail = op_err.details[0]
# Ensure neither input nor url appears in any details dictionary
assert "input" not in detail
assert "url" not in detail
assert "SUPER_SECRET_TOKEN_DO_NOT_LEAK" not in str(detail)
assert detail["loc"] == ["tail"]
assert detail["type"] == "int_type"
assert "Input should be a valid integer" in detail["msg"]
# Verify defense-in-depth: exc.errors called with include_input=False and include_url=False
from unittest.mock import MagicMock
mock_exc = MagicMock(spec=ValidationError)
mock_exc.errors.return_value = [{"loc": ("field",), "type": "value_error", "msg": "Invalid"}]
sanitize_validation_error(mock_exc)
mock_exc.errors.assert_called_once_with(include_input=False, include_url=False)
# ---------------------------------------------------------------------------
# OperationResponse Consistency & Edge Cases
# ---------------------------------------------------------------------------
def test_operation_response_accepts_success_without_error():
response_data = {
"version": "1.0",
"success": True,
"operation_id": "op_123",
"operation": "workload.deploy",
"target": "snappymail",
"output": "Snappymail deployment complete",
}
validated = OperationResponse.model_validate(response_data)
assert validated.success is True
assert validated.status == "success"
assert validated.error is None
assert validated.operation == OperationType.WORKLOAD_DEPLOY
assert validated.action == OperationType.WORKLOAD_DEPLOY
assert validated.operation_id == "op_123"
def test_operation_response_accepts_status_field_reconciliation():
# Pass 'status': 'success' without 'success'
r1 = OperationResponse.model_validate({
"version": "1.0",
"status": "success",
"operation_id": "op_123",
"operation": "platform.health",
})
assert r1.success is True
assert r1.status == "success"
# Pass 'status': 'error' without 'success'
r2 = OperationResponse.model_validate({
"version": "1.0",
"status": "error",
"operation_id": "op_124",
"operation": "platform.health",
"error": {
"code": "ERR_EXECUTION_FAILED",
"message": "Health probe failed",
},
})
assert r2.success is False
assert r2.status == "error"
def test_operation_response_accepts_failure_with_nested_error():
response_data = {
"version": "1.0",
"success": False,
"operation_id": "op_456",
"operation": "workload.deploy",
"target": "capybara",
"error": {
"code": "ERR_TARGET_NOT_FOUND",
"message": "Workload `capybara` does not exist",
},
}
validated = OperationResponse.model_validate(response_data)
assert validated.success is False
assert validated.target == "capybara"
assert validated.operation_id == "op_456"
assert validated.operation == OperationType.WORKLOAD_DEPLOY
assert isinstance(validated.error, OperationError)
assert validated.error.code == ErrorCode.ERR_TARGET_NOT_FOUND
assert validated.error.message == "Workload `capybara` does not exist"
def test_operation_response_rejects_success_with_error():
response_data = {
"version": "1.0",
"success": True,
"operation": "workload.deploy",
"target": "microservice1",
"operation_id": "op_124",
"error": {
"code": "ERR_VALIDATION_FAILED",
"message": "This error should not appear on success response",
},
}
with pytest.raises(ValidationError) as exc_info:
OperationResponse.model_validate(response_data)
assert "cannot contain an error" in str(exc_info.value)
def test_operation_response_rejects_failure_without_error():
response_data = {
"version": "1.0",
"success": False,
"operation": "workload.deploy",
"target": "microservice2",
"operation_id": "op_125",
}
with pytest.raises(ValidationError) as exc_info:
OperationResponse.model_validate(response_data)
assert "must contain an error" in str(exc_info.value)
def test_operation_response_rejects_inconsistent_status_and_success():
response_data = {
"version": "1.0",
"success": True,
"status": "error",
"operation": "platform.health",
"operation_id": "op_126",
}
with pytest.raises(ValidationError) as exc_info:
OperationResponse.model_validate(response_data)
assert "'status' and 'success' must agree" in str(exc_info.value)
def test_operation_response_rejects_extra_fields():
response_data = {
"version": "1.0",
"success": True,
"operation": "platform.health",
"operation_id": "op_127",
"unauthorized_field": "data",
}
with pytest.raises(ValidationError) as exc_info:
OperationResponse.model_validate(response_data)
assert "extra_forbidden" in [e["type"] for e in exc_info.value.errors()]
# ---------------------------------------------------------------------------
# Core Manifest compose_pull Action
# ---------------------------------------------------------------------------
def test_core_manifest_allows_compose_pull_action():
assert "compose_pull" in ALLOWED_ACTIONS
valid_manifest = {
"schema_version": "1.0",
"name": "snappymail",
"source": {
"type": "git",
"url": "https://github.com/example/snappymail.git",
"ref": "main",
},
"deployment": {
"strategy": "compose",
"actions": ["git_pull", "compose_pull", "compose_up"],
},
}
parsed = Manifest.model_validate(valid_manifest)
assert parsed.deployment.actions == ["git_pull", "compose_pull", "compose_up"]
+645
View File
@@ -0,0 +1,645 @@
"""
test_appctl_daemon.py — Unit and Integration Test Suite for Milestone P4 Daemon
Asserts:
- Dual-transport equivalence between UDS (/run/homelab/appctl.sock) and TCP (127.0.0.1:9001)
- 64 KiB request body limit enforcement (400 ERR_VALIDATION_FAILED)
- Health check route GET /v1/health
- Unauthenticated rejection fails closed (401 ERR_AUTH_REQUIRED)
- UDS SO_PEERCRED viewer fallback boundary
- 3-role RBAC enforcement across daemon transports
- Pre-flight and inert dotenv safety through daemon
- Concurrency conflict (409 ERR_CONCURRENT_MUTATION)
- Truthful execution failure reporting (500 ERR_EXECUTION_FAILED)
- Fail-closed pre-execution audit guard
- Daemon restart socket unlinking and clean rebinding
- gitops_dispatcher delegation to daemon UDS
"""
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, AuditPersistenceError, TargetLockManager
from appctl_auth import Role, TokenDescriptor, TokenStore
from appctl_contracts import ErrorCode, OperationRequest, OperationType
from appctl_daemon import (
AppctlDaemon,
UnixHTTPConnection,
send_daemon_request,
)
from appctl_router import OperationalRouter
ADMIN_SECRET = "secret-admin-key-789"
OPERATOR_SECRET = "secret-operator-key-456"
ADMIN_HASH = hashlib.sha256(ADMIN_SECRET.encode()).hexdigest()
OPERATOR_HASH = hashlib.sha256(OPERATOR_SECRET.encode()).hexdigest()
def get_free_port() -> int:
"""Find an available TCP port on loopback."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
@pytest.fixture
def daemon_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
"""
Spins up an isolated AppctlDaemon instance with:
- Dedicated UDS socket in tmp_path
- Dynamic loopback TCP port
- Mock Sites directory with admitted 'docs' and unregistered 'rogue' workloads
- Valid 0400 tokens store with admin and operator tokens
- Valid 0600 audit log file
"""
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
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"
# Tokens store
tokens_file = tmp_path / "tokens.json"
tokens_data = [
TokenDescriptor(
token_id="tok_admin",
identity="operator",
role=Role.ADMIN,
sha256=ADMIN_HASH,
).model_dump(),
TokenDescriptor(
token_id="tok_gitops",
identity="gitops-dispatcher",
role=Role.OPERATOR,
sha256=OPERATOR_HASH,
).model_dump(),
]
tokens_file.write_text(json.dumps(tokens_data), encoding="utf-8")
tokens_file.chmod(0o400)
token_store = TokenStore(tokens_file)
# Audit log
audit_file = tmp_path / "audit.jsonl"
audit_file.touch()
audit_file.chmod(0o600)
audit_logger = AuditLogger(audit_file)
# Locks
lock_dir = tmp_path / "locks"
lock_dir.mkdir()
lock_manager = TargetLockManager(lock_dir)
# Workloads
sites_dir = tmp_path / "Sites"
sites_dir.mkdir()
core_dir = tmp_path / "Core"
core_dir.mkdir()
# Admitted workload: docs
docs_dir = sites_dir / "docs"
docs_dir.mkdir()
(docs_dir / "app.yaml").write_text(
"name: docs\n"
"domain: docs\n"
"deployment:\n"
" branch: main\n"
" actions:\n"
" - compose_up\n",
encoding="utf-8",
)
(docs_dir / "docker-compose.yml").write_text(
"services:\n"
" web:\n"
" image: nginx:alpine\n",
encoding="utf-8",
)
# Unregistered workload: rogue
rogue_dir = sites_dir / "rogue"
rogue_dir.mkdir()
(rogue_dir / "app.yaml").write_text(
"name: rogue\n"
"deployment:\n"
" branch: main\n"
" actions:\n"
" - compose_up\n",
encoding="utf-8",
)
(rogue_dir / "docker-compose.yml").write_text(
"services:\n"
" web:\n"
" image: alpine:latest\n",
encoding="utf-8",
)
# deployments.yaml
deployments_file = tmp_path / "deployments.yaml"
deployments_file.write_text(
'schemaVersion: "1.0"\n'
"repositories:\n"
" docs:\n"
f' path: "{docs_dir}"\n',
encoding="utf-8",
)
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file))
router = OperationalRouter(
audit_logger=audit_logger,
lock_manager=lock_manager,
sites_dir=sites_dir,
core_dir=core_dir,
)
daemon = AppctlDaemon(
router=router,
token_store=token_store,
audit_logger=audit_logger,
lock_manager=lock_manager,
socket_path=socket_path,
http_host=http_host,
http_port=http_port,
sites_dir=sites_dir,
core_dir=core_dir,
deployments_file=deployments_file,
)
daemon.start()
class Context:
def __init__(self):
self.daemon = daemon
self.socket_path = socket_path
self.http_url = f"http://{http_host}:{http_port}"
self.sites_dir = sites_dir
self.core_dir = core_dir
self.audit_file = audit_file
self.deployments_file = deployments_file
self.docs_dir = docs_dir
self.rogue_dir = rogue_dir
ctx = Context()
try:
yield ctx
finally:
daemon.stop()
sock_dir.cleanup()
def test_health_endpoint(daemon_env):
"""GET /v1/health returns HTTP 200 with health metadata over UDS and TCP."""
# Over UDS
conn_uds = UnixHTTPConnection(str(daemon_env.socket_path))
conn_uds.request("GET", "/v1/health")
res_uds = conn_uds.getresponse()
assert res_uds.status == 200
data_uds = json.loads(res_uds.read().decode())
assert data_uds["status"] == "healthy"
assert data_uds["version"] == "1.0"
assert "uptime_seconds" in data_uds
conn_uds.close()
# Over TCP
import http.client
conn_tcp = http.client.HTTPConnection("127.0.0.1", daemon_env.daemon.http_port)
conn_tcp.request("GET", "/v1/health")
res_tcp = conn_tcp.getresponse()
assert res_tcp.status == 200
data_tcp = json.loads(res_tcp.read().decode())
assert data_tcp["status"] == "healthy"
assert data_tcp["version"] == "1.0"
conn_tcp.close()
def test_transport_dual_equivalence(daemon_env):
"""
Compare responses of POST /v1/operations over Unix socket vs HTTP 127.0.0.1.
Asserts 100% schema and status parity.
"""
list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST)
# 1. Successful query with admin token
resp_uds = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=list_req,
token=ADMIN_SECRET,
)
resp_http = send_daemon_request(
endpoint=daemon_env.http_url,
operation_request=list_req,
token=ADMIN_SECRET,
)
assert resp_uds.success is True
assert resp_http.success is True
assert resp_uds.status == resp_http.status
assert resp_uds.operation == resp_http.operation
assert resp_uds.version == resp_http.version
assert resp_uds.result == resp_http.result
# 2. Error case parity (404 target not found)
get_req = OperationRequest(operation=OperationType.WORKLOAD_GET, target="nonexistent")
err_uds = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=get_req,
token=ADMIN_SECRET,
)
err_http = send_daemon_request(
endpoint=daemon_env.http_url,
operation_request=get_req,
token=ADMIN_SECRET,
)
assert err_uds.success is False
assert err_http.success is False
assert err_uds.error is not None and err_http.error is not None
assert err_uds.error.code == ErrorCode.ERR_TARGET_NOT_FOUND
assert err_http.error.code == ErrorCode.ERR_TARGET_NOT_FOUND
assert err_uds.error.code.http_status == 404
assert err_http.error.code.http_status == 404
def test_request_body_size_limit(daemon_env):
"""Requests exceeding 64 KiB are rejected with 400 ERR_VALIDATION_FAILED."""
oversized_data = {"version": "1.0", "operation": "workload.list", "padding": "x" * (65 * 1024)}
body_str = json.dumps(oversized_data)
conn = UnixHTTPConnection(str(daemon_env.socket_path))
headers = {"Content-Type": "application/json", "Host": "localhost"}
conn.request("POST", "/v1/operations", body=body_str, headers=headers)
res = conn.getresponse()
assert res.status == 400
data = json.loads(res.read().decode())
assert data["status"] == "error"
assert data["error"]["code"] == ErrorCode.ERR_VALIDATION_FAILED.value
assert "exceeds limit" in data["error"]["message"]
conn.close()
def test_auth_missing_token_fails_closed(daemon_env):
"""
Mutating operations and sensitive reads without Bearer token return 401 ERR_AUTH_REQUIRED
and execute zero subprocesses.
"""
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
with patch("appctl_router.run_bounded_subprocess") as mock_subproc:
# Over HTTP without token
resp_http = send_daemon_request(
endpoint=daemon_env.http_url,
operation_request=deploy_req,
token=None,
)
assert resp_http.success is False
assert resp_http.error is not None
assert resp_http.error.code == ErrorCode.ERR_AUTH_REQUIRED
assert resp_http.error.code.http_status == 401
assert mock_subproc.call_count == 0
# Over UDS without token (deploy is mutating, peercred viewer fallback must be rejected)
resp_uds = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=deploy_req,
token=None,
)
assert resp_uds.success is False
assert resp_uds.error is not None
assert resp_uds.error.code == ErrorCode.ERR_PERMISSION_DENIED
assert resp_uds.error.code.http_status == 403
assert mock_subproc.call_count == 0
def test_uds_peercred_viewer_boundary(daemon_env):
"""
Tokenless UDS call from operator UID succeeds for workload.list (auth_method: unix_peercred),
but fails with 403 on mutation or sensitive reads.
"""
# Read-only query over UDS without token succeeds as viewer
list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST)
resp = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=list_req,
token=None,
)
assert resp.success is True
assert resp.result is not None
assert "workloads" in resp.result
# Sensitive read (workload.config) without token fails
config_req = OperationRequest(operation=OperationType.WORKLOAD_CONFIG, target="docs")
resp_cfg = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=config_req,
token=None,
)
assert resp_cfg.success is False
assert resp_cfg.error is not None
assert resp_cfg.error.code == ErrorCode.ERR_PERMISSION_DENIED
assert resp_cfg.error.code.http_status == 403
def test_rbac_role_matrix(daemon_env):
"""
homelab-operator allowed on deployments.yaml workloads but denied on unregistered workloads;
homelab-admin allowed on all valid targets.
"""
deploy_registered = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
deploy_unregistered = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="rogue")
with patch("appctl_router.run_bounded_subprocess") as mock_subproc, patch("appctl_router.OperationalRouter._trigger_homepage_sync"):
mock_subproc.return_value = (0, "Container docs created", "")
# Operator on registered target -> SUCCESS
resp_op_reg = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=deploy_registered,
token=OPERATOR_SECRET,
)
assert resp_op_reg.success is True
assert resp_op_reg.result is not None
assert resp_op_reg.result["action"] == "deployed"
# Operator on unregistered target -> 403 ERR_PERMISSION_DENIED
resp_op_unreg = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=deploy_unregistered,
token=OPERATOR_SECRET,
)
assert resp_op_unreg.success is False
assert resp_op_unreg.error is not None
assert resp_op_unreg.error.code == ErrorCode.ERR_PERMISSION_DENIED
assert resp_op_unreg.error.code.http_status == 403
# Admin on unregistered target -> SUCCESS
resp_adm_unreg = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=deploy_unregistered,
token=ADMIN_SECRET,
)
assert resp_adm_unreg.success is True
assert resp_adm_unreg.result is not None
assert resp_adm_unreg.result["action"] == "deployed"
def test_daemon_preflight_and_dotenv_safety(daemon_env):
"""
Workload with prohibited Compose directive (privileged: true) is blocked by Compose AST
pre-flight before any subprocess runs.
"""
bad_compose = daemon_env.docs_dir / "docker-compose.yml"
bad_compose.write_text(
"services:\n"
" web:\n"
" image: nginx\n"
" privileged: true\n",
encoding="utf-8",
)
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
with patch("appctl_router.run_bounded_subprocess") as mock_subproc:
resp = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=deploy_req,
token=ADMIN_SECRET,
)
assert resp.success is False
assert resp.error is not None
assert resp.error.code == ErrorCode.ERR_VALIDATION_FAILED
assert resp.error.code.http_status == 400
assert "privileged: true" in resp.error.message
assert mock_subproc.call_count == 0
def test_concurrent_mutation_conflict(daemon_env):
"""
Second concurrent mutation on the same target returns 409 ERR_CONCURRENT_MUTATION.
"""
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
# Manually hold lock on target
lock_ctx = daemon_env.daemon.lock_manager.lock_target("docs")
with lock_ctx:
resp = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=deploy_req,
token=ADMIN_SECRET,
)
assert resp.success is False
assert resp.error is not None
assert resp.error.code == ErrorCode.ERR_CONCURRENT_MUTATION
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.
"""
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
with patch("appctl_router.run_bounded_subprocess") as mock_subproc:
mock_subproc.return_value = (1, "", "Error: docker daemon not reachable")
resp = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=deploy_req,
token=ADMIN_SECRET,
)
assert resp.success is False
assert resp.error is not None
assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED
assert resp.error.code.http_status == 500
# Verify audit.jsonl contains FAILED event
lines = [json.loads(line) for line in daemon_env.audit_file.read_text().splitlines() if line.strip()]
failed_events = [ev for ev in lines if ev.get("phase") == "FAILED"]
assert len(failed_events) >= 1
assert failed_events[-1]["target"] == "docs"
assert failed_events[-1]["result"]["error_code"] == ErrorCode.ERR_EXECUTION_FAILED.value
def test_audit_failure_blocks_mutation(daemon_env):
"""
Unwritable audit.jsonl aborts mutating command with 500 ERR_EXECUTION_FAILED
and zero Docker invocations.
"""
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
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,
token=ADMIN_SECRET,
)
assert resp.success is False
assert resp.error is not None
assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED
assert resp.error.code.http_status == 500
assert mock_subproc.call_count == 0
def test_daemon_restart_preserves_state(daemon_env):
"""
Clean stop and restart of daemon unlinks and rebinds socket cleanly.
"""
daemon_env.daemon.stop()
assert not daemon_env.socket_path.exists()
# Restart
daemon_env.daemon.start()
assert daemon_env.socket_path.is_socket()
# Re-verify communication
list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST)
resp = send_daemon_request(
endpoint=daemon_env.socket_path,
operation_request=list_req,
token=ADMIN_SECRET,
)
assert resp.success is True
def test_gitops_dispatcher_delegates_to_daemon(daemon_env, monkeypatch):
"""
When daemon socket is active, gitops_dispatcher calls daemon over UDS with Bearer token.
"""
monkeypatch.setattr(gitops_dispatcher, "DEFAULT_APPCTL_SOCKET_PATH", daemon_env.socket_path)
monkeypatch.setenv("GITOPS_APPCTL_TOKEN", OPERATOR_SECRET)
monkeypatch.setenv("APPCTL_SOCKET_PATH", str(daemon_env.socket_path))
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_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
+609
View File
@@ -0,0 +1,609 @@
from dataclasses import dataclass
from pathlib import Path
from unittest.mock import MagicMock
import appctl_engine as engine
import pytest
# Import appctl engine
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
@dataclass
class AppFactory:
"""Helper class to generate mock app directories and configurations"""
sites_dir: Path
def create(
self,
dir_name: str,
manifest_yaml: str = "",
has_compose: bool = True,
) -> Path:
app_dir: Path = self.sites_dir / dir_name
app_dir.mkdir(parents=True, exist_ok=True)
if manifest_yaml:
(app_dir / "app.yaml").write_text(manifest_yaml, encoding="utf-8")
if has_compose:
(app_dir / "docker-compose.yml").write_text(
"services: {}\n", encoding="utf-8"
)
return app_dir
@pytest.fixture
def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""Fixture that creates an isolated Sites directory and points engine.SITES_DIR to it"""
sites = tmp_path / "Sites"
monkeypatch.setattr(engine, "SITES_DIR", str(sites))
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "mydomain.test")
return sites
@pytest.fixture
def app_factory(mock_sites_dir: Path) -> AppFactory:
"""Fixture that provides the AppFactory instance to test"""
return AppFactory(mock_sites_dir)
@pytest.fixture
def mock_core_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""Fixture that creates an isolated Core directory and points engine.CORE_DIR to it"""
core = tmp_path / "CORE"
core.mkdir(parents=True, exist_ok=True)
return core
## GREEN TEST: Existing implementation should not break
def test_resolve_app_hierarchy(app_factory: AppFactory):
"""Ensure resolution follows: Canonical Name > Alias > Dir Name > Prefix"""
app_factory.create(
dir_name="homelab-jellyfin",
manifest_yaml="""
name: media-server
aliases:
- movies
""",
)
apps = engine.get_sites_apps()
assert engine.resolve_app("media-server", apps) is not None
assert engine.resolve_app("movies", apps) is not None
assert engine.resolve_app("homelab-jellyfin", apps) is not None
assert engine.resolve_app("unknown", apps) is None
def test_manifest_data_overrides_default_values(app_factory: AppFactory):
"""Ensure app.yaml values successfully override the system defaults"""
app_factory.create(
dir_name="homelab-custom",
manifest_yaml="""
name: custom-app
domain: custom.example.test
auth: false
visible: false
networks:
- custom-net
""",
)
apps = engine.get_sites_apps()
app = engine.resolve_app("custom-app", apps)
assert app is not None
assert app.domain == "custom.example.test"
assert app.auth is False
assert app.networks == ["custom-net"]
def test_sites_app_normalization(app_factory: AppFactory):
"""Ensure missing or badly typed manifest fields are safely normalized"""
app_factory.create(
dir_name="homelab-custom",
manifest_yaml="""
name: testapp
# Missing domain - should fallback to <name>.<HOMELAB_DOMAIN>
aliases: single-string-alias # should become a list[str]
auth: "False" # should evaluate based on boolean casting
homepage:
weight: "99" # this should be casted as an int
""",
)
apps = engine.get_sites_apps()
app = engine.resolve_app("testapp", apps)
assert app is not None
assert app.name == "testapp"
assert app.domain == "testapp.mydomain.test"
assert app.aliases == ["single-string-alias"]
assert app.auth is True
assert app.homepage is not None
assert app.homepage.weight == 99
def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
"""Ensure source provenance block is correctly parsed into SourceConfig"""
# 1. Source-backed app with explicit ref
app_factory.create(
dir_name="homelab-bitetrack",
manifest_yaml="""
name: bitetrack
source:
type: git
url: https://git.example.com/operator/bitetrack.git
ref: v1.2.0
""",
)
# 2. Source-backed app with default ref (main)
app_factory.create(
dir_name="homelab-doc2site",
manifest_yaml="""
name: doc2site
source:
url: https://git.example.com/operator/doc2site.git
""",
)
# 3. Image-only app (no source block)
app_factory.create(
dir_name="homelab-jellyfin",
manifest_yaml="""
name: jellyfin
""",
)
apps = engine.get_sites_apps()
bitetrack = engine.resolve_app("bitetrack", apps)
assert bitetrack is not None
assert bitetrack.source is not None
assert bitetrack.source.type == "git"
assert bitetrack.source.url == "https://git.example.com/operator/bitetrack.git"
assert bitetrack.source.ref == "v1.2.0"
assert bitetrack.to_dict()["source"]["ref"] == "v1.2.0"
doc2site = engine.resolve_app("doc2site", apps)
assert doc2site is not None
assert doc2site.source is not None
assert doc2site.source.ref == "main"
jellyfin = engine.resolve_app("jellyfin", apps)
assert jellyfin is not None
assert jellyfin.source is None
assert jellyfin.to_dict()["source"] is None
# 4. App with illegal source transport (e.g. file://)
app_factory.create(
dir_name="homelab-malformed",
manifest_yaml="""
name: malformed
source:
url: file:///etc/passwd
""",
)
apps_updated = engine.get_sites_apps()
malformed = engine.resolve_app("malformed", apps_updated)
assert malformed is not None
assert malformed.source is None
assert malformed.manifest_error is not None
assert "Invalid source.url scheme" in malformed.manifest_error
## RED TESTS: TDD Goals for next implementation
def test_docker_status_parser_running(monkeypatch):
"""Ensure get_docker_status reports running compose stack when all containers are running."""
def mock_run(args, **kwargs):
mock = MagicMock()
mock.returncode = 0
if "ps" in args:
mock.stdout = "container123\n"
if "inspect" in args:
mock.stdout = "true\n"
return mock
monkeypatch.setattr("subprocess.run", mock_run)
status = engine.get_docker_status("/fake/dir")
assert status == "🟢 Running (1)"
def test_docker_status_parser_stopped(monkeypatch):
"""Ensure get_docker_status reports stopped when no containers exist."""
def mock_run(args, **kwargs):
mock = MagicMock()
mock.returncode = 0
if "ps" in args:
mock.stdout = ""
return mock
monkeypatch.setattr("subprocess.run", mock_run)
status = engine.get_docker_status("/fake/dir")
assert status == "🔴 Stopped"
def test_docker_status_parser_degraded(monkeypatch):
"""Ensure get_docker_status reports degraded when partial containers are running."""
def mock_run(args, **kwargs):
mock = MagicMock()
mock.returncode = 0
if "ps" in args:
mock.stdout = "c1\nc2\n"
if "inspect" in args:
mock.stdout = "true\nfalse\n"
return mock
monkeypatch.setattr("subprocess.run", mock_run)
status = engine.get_docker_status("/fake/dir")
assert status == "🟡 Degraded (1/2)"
def test_docker_status_parser_not_stack(tmp_path: Path):
"""Ensure get_docker_status reports Not Stack for real directory without compose file."""
empty_dir = tmp_path / "empty_service"
empty_dir.mkdir()
assert engine.get_docker_status(empty_dir) == "⚪ Not Stack"
def test_docker_status_single_container(monkeypatch):
"""Ensure get_docker_status inspects single Core container by name."""
def mock_run(args, **kwargs):
mock = MagicMock()
mock.returncode = 0
if "authelia" in args:
mock.stdout = "true\n"
else:
mock.stdout = "false\n"
return mock
monkeypatch.setattr("subprocess.run", mock_run)
assert engine.get_docker_status("", container_name="authelia") == "🟢 Running (1)"
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."""
def mock_err(*args, **kwargs):
raise OSError("Docker socket unreachable")
monkeypatch.setattr("subprocess.run", mock_err)
assert engine.get_docker_status("/fake/dir") == "❓ Unknown"
def test_docker_image_revision_extraction(monkeypatch):
"""Ensure get_docker_image_revision extracts org.opencontainers.image.revision."""
def mock_run(args, **kwargs):
mock = MagicMock()
if "ps" in args:
mock.stdout = "container123\n"
if "inspect" in args:
mock.stdout = "9d82577f489f0d478e465a36077538d0ded16ba5\n"
return mock
monkeypatch.setattr("subprocess.run", mock_run)
assert (
engine.get_docker_image_revision("/fake/dir")
== "9d82577f489f0d478e465a36077538d0ded16ba5"
)
def mock_run_empty(args, **kwargs):
mock = MagicMock()
if "ps" in args:
mock.stdout = "container123\n"
if "inspect" in args:
mock.stdout = "<no value>\n"
return mock
monkeypatch.setattr("subprocess.run", mock_run_empty)
assert engine.get_docker_image_revision("/fake/dir") is None
def test_homepage_sync_groups_and_sorts_correctly(
mock_core_dir: Path, app_factory: AppFactory, monkeypatch
):
"""
TDD Goal: Port `cmd_sync_homepage` to V2 using the new Dataclass structure.
It must group by `homepage.group` and sort by `homepage.weight`.
"""
hp_config_dir = mock_core_dir / "config" / "homepage"
hp_config_dir.mkdir(parents=True, exist_ok=True)
app_factory.create(
dir_name="homelab-app1",
manifest_yaml="""
name: App1
domain: app1.local.test
homepage:
title: App1
group: Group B
weight: 20
""",
)
app_factory.create(
dir_name="homelab-app2",
manifest_yaml="""
name: App2
domain: app2.local.test
homepage:
title: App2
group: Group A
weight: 10
""",
)
monkeypatch.setattr(engine, "get_core_services", list)
engine.cmd_sync_homepage(["--homepage-dir=" + str(hp_config_dir)])
output_file = hp_config_dir / "services.yaml"
assert output_file.exists(), "The services.yaml file must be generated"
content = output_file.read_text()
assert content.find("- Group A") < content.find(
"- Group B"
) # Group A should appear before Group B
assert "App2" in content # App 2 is in the file
def test_homepage_sync_core_services_domain_isolation(
mock_core_dir: Path,
monkeypatch,
):
"""
Ensure Core Infrastructure services use HOMELAB_DOMAIN and do not leak
an application's domain if DOMAIN is overridden by appctl.
"""
hp_config_dir = mock_core_dir / "config" / "homepage"
hp_config_dir.mkdir(parents=True, exist_ok=True)
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "example.com")
monkeypatch.setenv("DOMAIN", "mermaid.example.com")
engine.cmd_sync_homepage(["--homepage-dir=" + str(hp_config_dir)])
output_file = hp_config_dir / "services.yaml"
assert output_file.exists()
content = output_file.read_text()
assert "https://dashboard.example.com" in content
assert "https://traefik.example.com" in content
assert "https://auth.example.com" in content
assert "mermaid.example.com" not in content
def test_resolve_core_stack_type():
"""
Ensure resolving 'core' returns app_type='core' (entire stack),
while individual core services return app_type='core_service'.
"""
core = engine.resolve_app("core")
assert core is not None
assert core.to_dict()["type"] == "core"
assert core.container == ""
traefik = engine.resolve_app("traefik")
assert traefik is not None
assert traefik.to_dict()["type"] == "core_service"
assert traefik.container == "traefik"
def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(
app_factory: AppFactory,
):
"""Ensure manifest parsing uses core_manifest and catches invalid env keys."""
app_factory.create(
dir_name="homelab-badenv",
manifest_yaml="""
name: badenv
env:
PATH: /override/bin
""",
)
apps = engine.get_sites_apps()
app = engine.resolve_app("badenv", apps)
assert app is not None
assert app.manifest_error is not None
assert "Invalid or reserved environment variable key" in app.manifest_error
def test_cmd_resolve_fails_closed_on_manifest_error(
app_factory: AppFactory, capsys: pytest.CaptureFixture
):
"""Ensure cmd_resolve exits with non-zero on workload with manifest errors."""
app_factory.create(
dir_name="homelab-corrupt",
manifest_yaml="""
name: corrupt
env:
ILLEGAL-KEY: forbidden
""",
)
with pytest.raises(SystemExit) as exc_info:
engine.cmd_resolve(["corrupt"])
assert exc_info.value.code != 0
captured = capsys.readouterr()
assert "invalid manifest" in captured.err.lower() or "error" in captured.err.lower()
def test_cmd_resolve_fails_closed_on_missing_app_yaml(mock_sites_dir: Path):
"""Ensure cmd_resolve exits with non-zero if workload has no app.yaml."""
no_manifest_dir = mock_sites_dir / "homelab-nomanifest"
no_manifest_dir.mkdir(parents=True, exist_ok=True)
with pytest.raises(SystemExit) as exc_info:
engine.cmd_resolve(["nomanifest"])
assert exc_info.value.code != 0
def test_unification_uses_core_manifest_dataclasses(app_factory: AppFactory):
"""Ensure SitesApp uses core_manifest SourceConfig and HomepageConfig."""
import core_manifest
app_factory.create(
dir_name="homelab-unified",
manifest_yaml="""
name: unified
source:
url: https://git.example.com/operator/unified.git
ref: v1.0.0
homepage:
title: Unified App
weight: 30
""",
)
apps = engine.get_sites_apps()
app = engine.resolve_app("unified", apps)
assert app is not None
assert isinstance(app.source, core_manifest.SourceConfig)
assert isinstance(app.homepage, core_manifest.HomepageConfig)
assert app.source.ref_type == core_manifest.RefType.TAG
assert app.source.transport == core_manifest.TransportScheme.HTTPS
def test_cmd_list_flags_manifest_error(
app_factory: AppFactory, capsys: pytest.CaptureFixture
):
"""Ensure cmd_list flags workloads with manifest errors instead of swallowing them."""
app_factory.create(
dir_name="homelab-broken",
manifest_yaml="""
name: broken
env:
SHELL: /bin/sh
""",
)
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)
-257
View File
@@ -1,257 +0,0 @@
import sys
from dataclasses import dataclass
from pathlib import Path
from unittest.mock import MagicMock
import pytest
# Import appctl engine v2
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(CORE_ROOT / "scripts"))
import appctl_engine_v2 as engine
@dataclass
class AppFactory:
"""Helper class to generate mock app directories and configurations"""
sites_dir: Path
def create(
self,
dir_name: str,
manifest_yaml: str = "",
has_compose: bool = True,
) -> Path:
app_dir: Path = self.sites_dir / dir_name
app_dir.mkdir(parents=True, exist_ok=True)
if manifest_yaml:
(app_dir / "app.yaml").write_text(manifest_yaml, encoding="utf-8")
if has_compose:
(app_dir / "docker-compose.yml").write_text("services: {}\n", encoding="utf-8")
return app_dir
@pytest.fixture
def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""Fixture that creates an isolated Sites directory and points engine.SITES_DIR to it"""
sites = tmp_path / "Sites"
monkeypatch.setattr(engine, "SITES_DIR", str(sites))
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "mydomain.test")
return sites
@pytest.fixture
def app_factory(mock_sites_dir: Path) -> AppFactory:
"""Fixture that provides the AppFactory instance to test"""
return AppFactory(mock_sites_dir)
@pytest.fixture
def mock_core_dir(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch
) -> Path:
"""Fixture that creates an isolated Core directory and points engine.CORE_DIR to it"""
core = tmp_path / "CORE"
core.mkdir(parents=True, exist_ok=True)
return core
## GREEN TEST: Existing implementation should not break
def test_resolve_app_hierarchy(app_factory: AppFactory):
"""Ensure resolution follows: Canonical Name > Alias > Dir Name > Prefix"""
app_factory.create(
dir_name="homelab-jellyfin",
manifest_yaml="""
name: media-server
aliases:
- movies
""",
)
apps = engine.get_sites_apps()
assert engine.resolve_app("media-server", apps) is not None
assert engine.resolve_app("movies", apps) is not None
assert engine.resolve_app("homelab-jellyfin", apps) is not None
assert engine.resolve_app("unknown", apps) is None
def test_manifest_data_overrides_default_values(app_factory: AppFactory):
"""Ensure app.yaml values successfully override the system defaults"""
app_factory.create(
dir_name="homelab-custom",
manifest_yaml="""
name: custom-app
domain: custom.roadtotech.local
auth: false
visible: false
networks:
- custom-net
"""
)
apps = engine.get_sites_apps()
app = engine.resolve_app("custom-app", apps)
assert app is not None
assert app.domain == "custom.roadtotech.local"
assert app.auth is False
assert app.networks == ["custom-net"]
def test_sites_app_normalization(app_factory: AppFactory):
"""Ensure missing or badly typed manifest fields are safely normalized"""
app_factory.create(
dir_name="homelab-custom",
manifest_yaml="""
name: testapp
# Missing domain - should fallback to <name>.roadtotech.me
aliases: single-string-alias # should become a list[str]
auth: "False" # should evaluate based on boolean casting
homepage:
weight: "99" # this should be casted as an int
"""
)
apps = engine.get_sites_apps()
app = engine.resolve_app("testapp", apps)
assert app is not None
assert app.name == "testapp"
assert app.domain == "testapp.mydomain.test"
assert app.aliases == ["single-string-alias"]
assert app.auth is True
assert app.homepage is not None
assert app.homepage.weight == 99
def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
"""Ensure source provenance block is correctly parsed into SourceConfig"""
# 1. Source-backed app with explicit ref
app_factory.create(
dir_name="homelab-bitetrack",
manifest_yaml="""
name: bitetrack
source:
type: git
url: https://git.roadtotech.me/kiskaadee/bitetrack.git
ref: v1.2.0
"""
)
# 2. Source-backed app with default ref (main)
app_factory.create(
dir_name="homelab-doc2site",
manifest_yaml="""
name: doc2site
source:
url: https://git.roadtotech.me/kiskaadee/doc2site.git
"""
)
# 3. Image-only app (no source block)
app_factory.create(
dir_name="homelab-jellyfin",
manifest_yaml="""
name: jellyfin
"""
)
apps = engine.get_sites_apps()
bitetrack = engine.resolve_app("bitetrack", apps)
assert bitetrack is not None
assert bitetrack.source is not None
assert bitetrack.source.type == "git"
assert bitetrack.source.url == "https://git.roadtotech.me/kiskaadee/bitetrack.git"
assert bitetrack.source.ref == "v1.2.0"
assert bitetrack.to_dict()["source"]["ref"] == "v1.2.0"
doc2site = engine.resolve_app("doc2site", apps)
assert doc2site is not None
assert doc2site.source is not None
assert doc2site.source.ref == "main"
jellyfin = engine.resolve_app("jellyfin", apps)
assert jellyfin is not None
assert jellyfin.source is None
assert jellyfin.to_dict()["source"] is None
# 4. App with illegal source transport (e.g. file://)
app_factory.create(
dir_name="homelab-malformed",
manifest_yaml="""
name: malformed
source:
url: file:///etc/passwd
"""
)
apps_updated = engine.get_sites_apps()
malformed = engine.resolve_app("malformed", apps_updated)
assert malformed is not None
assert malformed.source is None
assert malformed.manifest_error is not None
assert "Invalid source.url scheme" in malformed.manifest_error
## RED TESTS: TDD Goals for next implementation
@pytest.mark.xfail(reason="TDD in progress: get_docker_status not yet implemented")
def test_docker_status_parser_running(monkeypatch):
"""
TDD Goal: Port `get_docker_status` to V2
It must shell out to `docker-compse ps` and `docker inspect`
then return the correct UI badge
"""
def mock_run(args, **kwargs):
"""Mocking a running"""
mock = MagicMock()
if "ps" in args:
mock.stdout = "container123\n"
if "inspect" in args:
mock.stdout = "true\n"
return mock
monkeypatch.setattr("subprocess.run", mock_run)
status = engine.get_docker_status("/fake/dir")
assert status == "🟢 Running (1)"
@pytest.mark.xfail(reason="TDD in progress: cmd_sync_homepage not yet implemented")
def test_homepage_sync_groups_and_sorts_correctly(
mock_core_dir: Path,
app_factory: AppFactory,
monkeypatch):
"""
TDD Goal: Port `cmd_sync_homepage` to V2 using the new Dataclass structure.
It must group by `homepage.group` and sort by `homepage.weight`.
"""
hp_config_dir = mock_core_dir / "config" / "homepage"
hp_config_dir.mkdir(parents=True, exist_ok=True)
app_factory.create(
dir_name="homelab-app1",
manifest_yaml="""
name: App1
domain: app1.local.test
homepage:
title: App1
group: Group B
weight: 20
"""
)
app_factory.create(
dir_name="homelab-app2",
manifest_yaml="""
name: App2
domain: app2.local.test
homepage:
title: App2
group: Group A
weight: 10
"""
)
monkeypatch.setattr(engine, "get_core_services", list)
engine.cmd_sync_homepage(["--homepage-dir=" + str(hp_config_dir)])
output_file = hp_config_dir / "services.yaml"
assert output_file.exists(), "The services.yaml file must be generated"
content = output_file.read_text()
assert content.find("- Group A") < content.find("- Group B") # Group A should appear before Group B
assert "App2" in content # App 2 is in the file
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
+369
View File
@@ -0,0 +1,369 @@
"""
Unit test suite for scripts/core_manifest.py (Schema v1.0 & Parser Library).
"""
from pathlib import Path
import pytest
# # Add scripts directory to path
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
from core_manifest import (
Manifest,
ManifestValidationError,
RefType,
TransportScheme,
classify_ref,
parse_manifest,
validate_transport,
)
def test_validate_transport_https():
scheme, url = validate_transport(
"https://git.example.com/operator/homelab-snappymail.git"
)
assert scheme == TransportScheme.HTTPS
assert url == "https://git.example.com/operator/homelab-snappymail.git"
def test_validate_transport_ssh():
scheme, url = validate_transport(
"ssh://git@git.example.com:2223/operator/homelab-docs.git"
)
assert scheme == TransportScheme.SSH
assert url == "ssh://git@git.example.com:2223/operator/homelab-docs.git"
def test_validate_transport_git_scp():
scheme, url = validate_transport("git@github.com:operator/custom-workload.git")
assert scheme == TransportScheme.GIT_SCP
assert url == "git@github.com:operator/custom-workload.git"
@pytest.mark.parametrize(
"insecure_url",
[
"http://insecure.example.com/repo.git",
"http://github.com/repo.git",
],
)
def test_validate_transport_rejects_http(insecure_url: str):
with pytest.raises(
ManifestValidationError, match="Insecure HTTP source URL rejected"
):
validate_transport(insecure_url)
@pytest.mark.parametrize(
"empty_or_invalid_url",
[
"",
" ",
None,
],
)
def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url):
with pytest.raises(
ManifestValidationError, match=r"^Source URL cannot be empty\.$"
):
validate_transport(empty_or_invalid_url) # type: ignore[arg-type]
@pytest.mark.parametrize(
("root_path_url", "scheme"),
[
("https://git.example.com/", "HTTPS"),
("ssh://git.example.com/", "SSH"),
],
)
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\)",
):
validate_transport(root_path_url)
@pytest.mark.parametrize(
"traversal_url",
[
"../../etc/shadow",
"/home/operator/secret",
"~/vault",
r"repo\windows\payload",
r"..\traversal",
],
)
def test_validate_transport_rejects_paths_and_traversal(traversal_url: str):
with pytest.raises(
ManifestValidationError,
match="Prohibited filesystem path or traversal in source URL",
):
validate_transport(traversal_url)
def test_validate_transport_rejects_file_scheme():
with pytest.raises(
ManifestValidationError,
match="Invalid source.url scheme: 'file:///etc/passwd'",
):
validate_transport("file:///etc/passwd")
@pytest.mark.parametrize(
"empty_ref",
[
"",
" ",
None,
12345,
],
)
def test_classify_ref_empty_or_invalid_defaults_to_main(empty_ref):
assert classify_ref(empty_ref) == (RefType.BRANCH, "main") # type: ignore[arg-type]
def test_classify_ref_branches():
assert classify_ref("main") == (RefType.BRANCH, "main")
assert classify_ref("refs/heads/develop") == (RefType.BRANCH, "develop")
assert classify_ref("feat/manifest-engine") == (
RefType.BRANCH,
"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",
)
def test_classify_ref_tags():
assert classify_ref("v1.0.0") == (RefType.TAG, "v1.0.0")
assert classify_ref("refs/tags/2.4.1") == (RefType.TAG, "2.4.1")
assert classify_ref("v0.1.0-alpha") == (RefType.TAG, "v0.1.0-alpha")
def test_classify_ref_commit_sha():
sha = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
assert classify_ref(sha) == (RefType.COMMIT, sha)
def test_parse_manifest_class_a_source_backed():
raw_yaml = """
schemaVersion: "1.0"
name: "bitetrack"
aliases:
- "bt"
domain: "bitetrack.example.com"
description: "Nutrition and macro tracking application"
visible: true
auth: true
networks:
- proxy-net
env:
PORT: 8080
source:
type: git
url: "https://git.example.com/operator/bitetrack.git"
ref: "v1.2.0"
deployment:
strategy: compose
branch: main
actions:
- git_pull
- compose_build
- compose_up
homepage:
title: "BiteTrack"
group: "Productivity"
icon: "food.png"
weight: 25
"""
manifest = parse_manifest(raw_yaml)
assert manifest.name == "bitetrack"
assert manifest.schema_version == "1.0"
assert manifest.aliases == ["bt"]
assert manifest.is_class_a is True
assert manifest.is_class_b is False
assert manifest.is_internal is False
assert manifest.source is not None
assert manifest.source.url == "https://git.example.com/operator/bitetrack.git"
assert manifest.source.ref == "v1.2.0"
assert manifest.source.ref_type == RefType.TAG
assert manifest.source.transport == TransportScheme.HTTPS
assert manifest.deployment.actions == ["git_pull", "compose_build", "compose_up"]
assert manifest.homepage is not None
assert manifest.homepage.weight == 25
def test_parse_manifest_class_b_image_only():
raw_yaml = """
name: "snappymail"
domain: "mail.example.com"
description: "Webmail Client"
deployment:
actions:
- compose_up
"""
manifest = parse_manifest(raw_yaml)
assert manifest.name == "snappymail"
assert manifest.is_class_a is False
assert manifest.is_class_b is True
assert manifest.source is None
assert manifest.deployment.actions == ["compose_up"]
def test_parse_manifest_rejects_missing_name():
with pytest.raises(
ManifestValidationError, match="missing mandatory string field 'name'"
):
parse_manifest("domain: test.example.com\n")
def test_parse_manifest_rejects_invalid_name():
with pytest.raises(ManifestValidationError, match="Invalid workload name"):
parse_manifest("name: 'invalid/name'\n")
def test_parse_manifest_rejects_prohibited_deployment_actions():
raw_yaml = """
name: "app"
deployment:
actions:
- compose_up
- rm_rf_root
"""
with pytest.raises(
ManifestValidationError, match="Prohibited deployment action 'rm_rf_root'"
):
parse_manifest(raw_yaml)
def test_parse_manifest_rejects_prohibited_strategy():
raw_yaml = """
name: "app"
deployment:
strategy: "swarm"
"""
with pytest.raises(
ManifestValidationError, match="Unsupported deployment strategy 'swarm'"
):
parse_manifest(raw_yaml)
def test_parse_manifest_from_path(tmp_path: Path):
manifest_file = tmp_path / "app.yaml"
manifest_file.write_text("name: file-app\ndomain: internal\n", encoding="utf-8")
manifest = parse_manifest(manifest_file)
assert manifest.name == "file-app"
assert manifest.is_internal is True
@pytest.mark.parametrize(
"invalid_key",
[
"123_BAD",
"INVALID-KEY",
"FOO;BAR",
"KEY WITH SPACE",
"PATH",
"LD_PRELOAD",
"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):
raw_yaml = f"""
name: "app"
env:
"{invalid_key}": "some_value"
"""
with pytest.raises(
ManifestValidationError, match="Invalid or reserved environment variable key"
):
parse_manifest(raw_yaml)
def test_parse_manifest_accepts_valid_env_keys():
raw_yaml = """
name: "app"
env:
PROJECT_PATH: "/mnt/data"
CUSTOM_PORT_1: "8080"
_INTERNAL_FLAG: "true"
"""
manifest = parse_manifest(raw_yaml)
assert manifest.env["PROJECT_PATH"] == "/mnt/data"
assert manifest.env["CUSTOM_PORT_1"] == "8080"
assert manifest.env["_INTERNAL_FLAG"] == "true"
def test_parse_manifest_rejects_extra_fields():
"""Ensure extra='forbid' rejects unrecognized top-level manifest keys."""
raw_yaml = """
name: "app"
unrecognized_field: "should_fail"
"""
with pytest.raises(
ManifestValidationError, match="unrecognized or forbidden field"
):
parse_manifest(raw_yaml)
def test_parse_manifest_rejects_extra_fields_in_nested_blocks():
"""Ensure extra='forbid' rejects unrecognized keys in nested configuration blocks."""
raw_yaml = """
name: "app"
deployment:
strategy: compose
unknown_deploy_option: "forbidden"
"""
with pytest.raises(ManifestValidationError):
parse_manifest(raw_yaml)
def test_manifest_pydantic_serialization():
"""Ensure Manifest operates as a Pydantic v2 model with correct serialization."""
from pydantic import BaseModel
raw_yaml = """
name: "serialized-app"
domain: "app.example.test"
description: "Pydantic serialization test"
"""
manifest = parse_manifest(raw_yaml)
assert isinstance(manifest, Manifest)
assert isinstance(manifest, BaseModel)
dumped = manifest.model_dump(by_alias=True)
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)
+365
View File
@@ -0,0 +1,365 @@
"""
Unit test suite for scripts/provenance.py (Two-Axis Inspection & Provenance Resolver).
"""
import os
import subprocess
from pathlib import Path
from unittest.mock import MagicMock, patch
# # Add scripts directory to path
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
from core_manifest import Manifest, RefType, SourceConfig, TransportScheme
from provenance import (
ProvenanceStatus,
get_local_checkout_status,
inspect_workload_two_axis,
resolve_upstream_provenance,
)
def _clean_git_env() -> dict[str, str]:
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
env["GIT_AUTHOR_NAME"] = "Test"
env["GIT_AUTHOR_EMAIL"] = "test@example.com"
env["GIT_COMMITTER_NAME"] = "Test"
env["GIT_COMMITTER_EMAIL"] = "test@example.com"
return env
def test_get_local_checkout_status_non_git(tmp_path: Path):
non_git = tmp_path / "app"
non_git.mkdir()
status = get_local_checkout_status(non_git)
assert status.is_git is False
assert status.is_dirty is False
assert "No Git Repo" in status.status_label
def test_get_local_checkout_status_clean_repo(tmp_path: Path):
app_dir = tmp_path / "git_app"
app_dir.mkdir()
env = _clean_git_env()
subprocess.run(
["git", "-C", str(app_dir), "init", "-b", "main"],
check=True,
capture_output=True,
env=env,
)
subprocess.run(
["git", "-C", str(app_dir), "config", "user.email", "test@example.com"],
check=True,
env=env,
)
subprocess.run(
["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env
)
(app_dir / "file.txt").write_text("hello", encoding="utf-8")
subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env)
subprocess.run(
["git", "-C", str(app_dir), "commit", "-m", "init"],
check=True,
capture_output=True,
env=env,
)
status = get_local_checkout_status(app_dir)
assert status.is_git is True
assert status.is_dirty is False
assert status.branch == "main"
assert status.commit_sha != ""
assert "✓ Clean" in status.status_label
def test_get_local_checkout_status_dirty_repo(tmp_path: Path):
app_dir = tmp_path / "git_dirty_app"
app_dir.mkdir()
env = _clean_git_env()
subprocess.run(
["git", "-C", str(app_dir), "init", "-b", "main"],
check=True,
capture_output=True,
env=env,
)
subprocess.run(
["git", "-C", str(app_dir), "config", "user.email", "test@example.com"],
check=True,
env=env,
)
subprocess.run(
["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env
)
(app_dir / "file.txt").write_text("hello", encoding="utf-8")
subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env)
subprocess.run(
["git", "-C", str(app_dir), "commit", "-m", "init"],
check=True,
capture_output=True,
env=env,
)
# Modify file to create dirty state
(app_dir / "file.txt").write_text("modified", encoding="utf-8")
status = get_local_checkout_status(app_dir)
assert status.is_git is True
assert status.is_dirty is True
assert "* Dirty" in status.status_label
def test_resolve_upstream_provenance_image_only():
prov = resolve_upstream_provenance(None)
assert prov.status == ProvenanceStatus.IMAGE_ONLY
def test_resolve_upstream_provenance_synced():
source = SourceConfig(
url="https://git.example.com/operator/app.git",
ref="main",
ref_type=RefType.BRANCH,
transport=TransportScheme.HTTPS,
)
mock_sha = "abc1234567890abcdef1234567890abcdef12345"
mock_output = f"{mock_sha}\trefs/heads/main\n"
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0, stdout=mock_output)
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
assert prov.status == ProvenanceStatus.SYNCED
assert prov.remote_sha == mock_sha
assert "Up to date" in prov.message
# Verify 10s timeout was passed to subprocess.run
assert mock_run.call_args[1]["timeout"] == 10.0
def test_resolve_upstream_provenance_update_available():
source = SourceConfig(
url="https://git.example.com/operator/app.git",
ref="main",
ref_type=RefType.BRANCH,
transport=TransportScheme.HTTPS,
)
mock_sha = "fff9999999990abcdef1234567890abcdef12345"
mock_output = f"{mock_sha}\trefs/heads/main\n"
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0, stdout=mock_output)
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
assert prov.status == ProvenanceStatus.UPDATE_AVAILABLE
assert prov.remote_sha == mock_sha
assert "Upstream at fff9999" in prov.message
def test_resolve_upstream_provenance_timeout():
source = SourceConfig(
url="https://slow-remote.test/repo.git",
ref="main",
ref_type=RefType.BRANCH,
transport=TransportScheme.HTTPS,
)
with patch(
"subprocess.run",
side_effect=subprocess.TimeoutExpired(cmd=["git"], timeout=10.0),
):
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
assert prov.status == ProvenanceStatus.TIMEOUT
assert "timed out after 10s" in prov.message
def test_resolve_upstream_provenance_unreachable():
source = SourceConfig(
url="https://bad-remote.test/repo.git",
ref="main",
ref_type=RefType.BRANCH,
transport=TransportScheme.HTTPS,
)
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=128, stderr="fatal: remote error")
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
assert prov.status == ProvenanceStatus.UNREACHABLE
assert "Failed to query remote" in prov.message
def test_resolve_upstream_provenance_pinned_commit():
sha = "1234567890abcdef1234567890abcdef12345678"
source = SourceConfig(
url="https://git.example.com/app.git",
ref=sha,
ref_type=RefType.COMMIT,
transport=TransportScheme.HTTPS,
)
# Matched local commit
prov = resolve_upstream_provenance(source, local_commit="1234567")
assert prov.status == ProvenanceStatus.SYNCED
# Differing local commit
prov_diff = resolve_upstream_provenance(source, local_commit="9999999")
assert prov_diff.status == ProvenanceStatus.UPDATE_AVAILABLE
def test_inspect_workload_two_axis(tmp_path: Path):
manifest = Manifest(
name="test-app",
source=SourceConfig(
url="https://git.test/app.git",
ref="main",
ref_type=RefType.BRANCH,
transport=TransportScheme.HTTPS,
),
)
# Without fetch_upstream: Axis 2 returns UNKNOWN
status_no_fetch = inspect_workload_two_axis(
tmp_path, manifest, fetch_upstream=False
)
assert status_no_fetch.provenance.status == ProvenanceStatus.UNKNOWN
assert "Pass --fetch" in status_no_fetch.provenance.message
# With fetch_upstream: Axis 2 queries remote
with patch("provenance.resolve_upstream_provenance") as mock_resolve:
mock_resolve.return_value = MagicMock(status=ProvenanceStatus.SYNCED)
status_fetch = inspect_workload_two_axis(
tmp_path, manifest, fetch_upstream=True
)
assert status_fetch.provenance.status == ProvenanceStatus.SYNCED
mock_resolve.assert_called_once()
def test_resolve_upstream_provenance_class_b_and_default_timeout():
# 1. Class B workload (source is None)
prov_class_b = resolve_upstream_provenance(None)
assert prov_class_b.status == ProvenanceStatus.IMAGE_ONLY
assert prov_class_b.message == "Class B workload deploys prebuilt container images directly"
# 2. Default timeout (10.0s) verification
source = SourceConfig(
url="https://git.example.com/operator/app.git",
ref="main",
ref_type=RefType.BRANCH,
transport=TransportScheme.HTTPS,
)
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0, stdout="abc1234567890abcdef1234567890abcdef12345\trefs/heads/main\n")
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) == {}
+47
View File
@@ -0,0 +1,47 @@
x 2026-10-13 (A) Create core_manifest.py schema and parser with strict transport validation (https, ssh, git) and ref classification in scripts/core_manifest.py +manifest @core
x 2026-10-13 (A) Implement unit tests for core_manifest.py covering valid manifests, invalid URLs, and ref types in tests/unit/test_core_manifest.py +test @core
x 2026-10-13 (B) Implement two-axis inspection engine in appctl evaluating local checkout state independently from upstream provenance +provenance @appctl
x 2026-10-13 (B) Implement bounded git ls-remote provenance resolver with 10s timeout for appctl status --fetch +provenance @appctl
x 2026-10-13 (B) Add unit tests for provenance resolution and timeout handling with mocked network fixtures in tests/unit/test_provenance.py +test @appctl
x 2026-10-13 (C) Promote scripts/appctl_engine_v2.py to authoritative scripts/appctl_engine.py +engine @appctl
x 2026-10-13 (C) Verify full test suite and update CLI wrappers for appctl v2 engine promotion +test @appctl
x 2026-10-13 (A) Reconcile appctl implementation inventory and document caller/dependency map in docs/plans/p4-readiness-plan.md +inventory @p4-gate
x 2026-10-13 (A) Define canonical command and error contract across dual transports in docs/plans/p4-readiness-plan.md +contract @p4-gate
x 2026-10-13 (A) Close authorization design enforcing token-everywhere policy in docs/plans/p4-readiness-plan.md +auth @p4-gate
x 2026-10-13 (B) Specify daemon execution and privilege boundaries for Docker, subprocesses, and filesystem roots in docs/plans/p4-readiness-plan.md +security @p4-gate
x 2026-10-13 (B) Define append-only audit telemetry schema, lifecycle, and failure handling semantics in docs/plans/p4-readiness-plan.md +audit @p4-gate
x 2026-10-13 (C) Establish P4 acceptance test matrix and definition of done before daemon implementation in docs/plans/p4-readiness-plan.md +test @p4-gate
x 2026-10-14 (A) Eliminate eval in scripts/appctl and enforce strict env key validation in scripts/core_manifest.py +security @appctl
x 2026-10-15 (A) Enforce deployments.yaml as sole registry and remove dynamic discovery fallback in scripts/gitops_dispatcher.py +registry @gitops
x 2026-10-15 (A) Harden validate_compose_security in scripts/gitops_dispatcher.py blocking relative traversal, cross-tenant mounts, and privilege escalation +compose @gitops
x 2026-10-15 (A) Unify manifest parsing on core_manifest.py and eliminate duplicate parsers in scripts/appctl_engine.py +manifest @engine
x 2026-10-15 (A) Codify Platform Genericism invariant in AGENTS.md and add Pydantic to flake.nix, pyproject.toml, and scripts/test +invariant @core
x 2026-10-15 (A) Add pydantic to host NixOS runtime and constrain dependency range in flake.nix and nixos/configuration.nix +nixos @core
x 2026-10-15 (A) Wire app_name and harden compose validator for env_file and undeclared volumes in scripts/gitops_dispatcher.py +compose @gitops
x 2026-10-15 (B) Scrub hardcoded domain defaults across scripts and tests enforcing instance-agnostic parameterization +generic @core
x 2026-10-15 (A) De-tautologize appctl env injection test to execute scripts/appctl directly with mock docker in tests/security/test_security_invariants.py +test @security
x 2026-10-15 (A) Clarify Pydantic v2 target architecture, strict typing rules, and domain precedence in docs/plans/p4-readiness-plan.md +docs @p4-gate
x 2026-10-15 (A) Migrate core_manifest.py to Pydantic v2 models for strict type validation and serialization +manifest @schema
x 2026-10-19 (A) Implement strict Pydantic v2 API contracts, error sanitizer, and compose_pull action in scripts/appctl_contracts.py and scripts/core_manifest.py +contracts @p4
x 2026-10-19 (A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4
x 2026-10-19 (A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4
x 2026-10-19 (B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4
x 2026-10-19 (B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) and wire gitops_dispatcher.py worker to daemon in scripts/appctl_daemon.py +daemon @p4
x 2026-10-19 (B) Add comprehensive unit and security test suite for P4 contracts, RBAC, audit guard, concurrency, and dual-transport parity in tests/unit/test_appctl_daemon.py +test @p4
x 2026-10-19 (C) Re-implement scripts/appctl as a thin UDS HTTP client and declare homelab-appctl.service with POSIX ACLs in nixos/modules/homeserver.nix +cli @p4
x 2026-10-19 (C) Scrub remaining hardcoded domain and username literals across NixOS modules, Compose stack, and config/deployments.yaml and add pyright to flake.nix checks +generic @core
x 2026-10-19 (A) Enable Core platform stack and core_service container-scoped dispatch in OperationalRouter in scripts/appctl_router.py +router @p4
x 2026-10-19 (A) Restore human-readable tabular output, list filter parameters, and bash autocompletion fast-path in scripts/appctl_cli.py and scripts/appctl +cli @p4
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
Generated
+185 -2
View File
@@ -1,3 +1,186 @@
version = 1 version = 1
revision = 3 revision = 5
requires-python = ">=3.11" requires-python = ">=3.13"
[[package]]
name = "annotated-types"
version = "0.8.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" },
]
[[package]]
name = "homelab-core"
version = "0.1.0"
source = { virtual = "." }
dependencies = [
{ name = "pydantic" },
{ name = "pyyaml" },
]
[package.metadata]
requires-dist = [
{ name = "pydantic", specifier = ">=2.0,<3.0" },
{ name = "pyyaml", specifier = ">=6.0" },
]
[[package]]
name = "pydantic"
version = "2.14.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "annotated-types" },
{ name = "pydantic-core" },
{ name = "typing-extensions" },
{ name = "typing-inspection" },
]
sdist = { url = "https://files.pythonhosted.org/packages/7c/0b/8e10b2e693af8ec54346a14caf36221334775975a747c9ceaa3f8371d96d/pydantic-2.14.1.tar.gz", hash = "sha256:94f478203dd03404682a1ada216965651dd74b1d2d5ffd62e00e0837caab5c26", size = 900362, upload-time = "2026-10-11T18:37:55.396Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/35/ea/a56b9fe5066f3537b7882f77e9c5dfb26d8c2eefdaed9b5fc73d57b4dc22/pydantic-2.14.1-py3-none-any.whl", hash = "sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454", size = 488106, upload-time = "2026-10-11T18:37:53.437Z" },
]
[[package]]
name = "pydantic-core"
version = "2.50.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a6/24/af4ec4be49fbc810f35b0bdcacc3d433b56bbfa469fd3bfd4ae116cd9bf1/pydantic_core-2.50.1.tar.gz", hash = "sha256:e50d7b94baac6c7d09927fa5ca5800a0c7ee5015c7fcff65beb3a1931b5a6e09", size = 513515, upload-time = "2026-10-11T18:35:44.82Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ae/57/0e237d7091d2cd44a35d243b7344227f90440166860469cd036afc23a04d/pydantic_core-2.50.1-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:d5e062c01286d861fd6a1c4ff6e063547b3e713067f2df033c0ff97ac2ca006b", size = 2222774, upload-time = "2026-10-11T18:32:43.103Z" },
{ url = "https://files.pythonhosted.org/packages/f7/b9/c720e56858d4e1539503297ed37063e0c08e0f3541c41b777f6a800f75fa/pydantic_core-2.50.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0c003c3b7f49debb893d2d85ae099ac5959c9839e2f330fadb1fcdf7a6594482", size = 2024738, upload-time = "2026-10-11T18:32:44.587Z" },
{ url = "https://files.pythonhosted.org/packages/4d/b8/fbfc25875219cc060e613170ff10e850c6d8924beb4910da57c2ee3ba1d2/pydantic_core-2.50.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:409e0ea40ec30d9158f33574fd758e689f6045a0f2596701828c27816ca9687d", size = 2047049, upload-time = "2026-10-11T18:32:46.164Z" },
{ url = "https://files.pythonhosted.org/packages/d7/43/34210124d504c553688f2f04b48500b131237528ac545b445e0d6d30e0d5/pydantic_core-2.50.1-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:131059670f1d2444269b8585cb888963994871932447c08b39ac6a51fcfef658", size = 2173415, upload-time = "2026-10-11T18:32:47.722Z" },
{ url = "https://files.pythonhosted.org/packages/65/cf/6e178e8fdc11da5965bef980983bf46326a42f436871dd51ba0a57f39df1/pydantic_core-2.50.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6dbcbee53bf17196a7f745aa9bf5a9603953a1e365b1f020be3207c676a3e7c4", size = 2361719, upload-time = "2026-10-11T18:32:49.217Z" },
{ url = "https://files.pythonhosted.org/packages/11/14/bd5169d356aa91bf777e28ba0b281c192d286d03c2812c9c9db023a2f00e/pydantic_core-2.50.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:325c23f3e35cfbf0fe3486fa5f7260d1e45885173002d30a28ca019994124255", size = 2439803, upload-time = "2026-10-11T18:32:51.025Z" },
{ url = "https://files.pythonhosted.org/packages/1c/bc/d79d000e5203ebef39af839f2ce77a777fcad6e08ad26af9a2fcd114ffc8/pydantic_core-2.50.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:17e722e156d0444ecaefbe640bdb60928752bf2013e2b7a11cdb099aaae19bec", size = 2158402, upload-time = "2026-10-11T18:32:52.714Z" },
{ url = "https://files.pythonhosted.org/packages/1b/a5/4902cb5fd599422c130bd3124ab31ee8b771199bd56662702eed07d3fec7/pydantic_core-2.50.1-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:aa8224f10880d9bf1b5993988ba153d42a8b4f3f4f511f93b1f09c93ff613c72", size = 2229755, upload-time = "2026-10-11T18:32:54.126Z" },
{ url = "https://files.pythonhosted.org/packages/1a/f5/c1481f8669f6060d89110c9b1374173fc8767ca276b84f4870bd8acd5e3f/pydantic_core-2.50.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:41bc8237121bd8dc8d888dfd6279fc166ffc88c1f1bf3a8bf00869680533ca4c", size = 2242303, upload-time = "2026-10-11T18:32:55.641Z" },
{ url = "https://files.pythonhosted.org/packages/04/f9/77fc3c7653ba9b6e42049e17e96b25388187d4a7c274ab1cb07f58ac8419/pydantic_core-2.50.1-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:45c6266d071c241f2a168d45bf8c54344f0effce35e7e6b73afdec11f3687568", size = 2278345, upload-time = "2026-10-11T18:32:57.38Z" },
{ url = "https://files.pythonhosted.org/packages/95/9b/0579c5d12e7f2b16b27e6782427987341fcce07b0725e02ddb0b74add0c4/pydantic_core-2.50.1-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:1deeacb112d14d3f4fcb16b165f7dbaf76c70ba6e82f37ba042bdab51970a0b8", size = 2449947, upload-time = "2026-10-11T18:32:58.896Z" },
{ url = "https://files.pythonhosted.org/packages/a8/ac/1b677db91eba54cc5922f4de6edc46ba45c2bd712dfdc0130382d158e214/pydantic_core-2.50.1-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:1c96fd793b73d1b92e65570132505498fe7b21eaef73cdf74e67e5dfba7ac9e4", size = 2476889, upload-time = "2026-10-11T18:33:00.665Z" },
{ url = "https://files.pythonhosted.org/packages/4d/2a/3a9f6624ee3ea9ccba5249dde11418bb4c35780a7a92608f8768bd3fea39/pydantic_core-2.50.1-cp313-cp313-win32.whl", hash = "sha256:06ead20d39ffd6f2f6f2a8f8a6de67ff8bb1b4f14a8a30e058502514ee2ac685", size = 2101118, upload-time = "2026-10-11T18:33:02.329Z" },
{ url = "https://files.pythonhosted.org/packages/2d/1f/323f78ddd9d9938aac420c1abb4e8ba799fc8bdab0acc67c0593b837c979/pydantic_core-2.50.1-cp313-cp313-win_amd64.whl", hash = "sha256:7816e98acc08119dc0f340ab167048ecc54126316330c1f0caf7c6756c88e28f", size = 2170840, upload-time = "2026-10-11T18:33:03.919Z" },
{ url = "https://files.pythonhosted.org/packages/cb/09/8497c52a739ae425c3ac2f7f56414cbc711c67d374346174f40fe2062644/pydantic_core-2.50.1-cp313-cp313-win_arm64.whl", hash = "sha256:c17799a62c142d61b8a3c51752a7cbc87fe2ad4ccfab10e628a77b405075c662", size = 2161633, upload-time = "2026-10-11T18:33:05.518Z" },
{ url = "https://files.pythonhosted.org/packages/49/33/28b96e81677153715e3eafb9f26663a80841e859fde282a380359b0d3fa1/pydantic_core-2.50.1-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:1cf41f1ae3fa155cf167a72689ad044bcc1e3c97e064123677149bdfb5dafc4a", size = 2224428, upload-time = "2026-10-11T18:33:07.153Z" },
{ url = "https://files.pythonhosted.org/packages/94/40/15c06410c9b7b8da5805d27b64e09bd3f900e986728106db2689dbc51513/pydantic_core-2.50.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4df197990c15b5a37c5a277d131d9f2c67de6133f2e5dafd80d9bba4b99f46f9", size = 2023740, upload-time = "2026-10-11T18:33:08.763Z" },
{ url = "https://files.pythonhosted.org/packages/a1/4e/5eb629f6efc2a27e421d789dd4bfacbb5f6d09c80c28b13d1e87d73163d5/pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0036473f5583e6a60e50b8b21651511564277a3f05cc5dab8cf579f552cd5f6c", size = 2049435, upload-time = "2026-10-11T18:33:10.366Z" },
{ url = "https://files.pythonhosted.org/packages/ba/8e/f195aebec49ad12318876ac2368c197a7939f5d52f8e156d2238ef8a4588/pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:992c3514ec891fa7858099183e4d64e6bd5a5d4ff452fae29df22faa77a006bb", size = 2172975, upload-time = "2026-10-11T18:33:12.368Z" },
{ url = "https://files.pythonhosted.org/packages/e0/f5/7ad9fb83010cd5ea0948409db105676ed779c4e709e2d3d89b9fe2558794/pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:739dc730e6be3bd5ec2f4ab5cfc7eb047cc45fc1497b3bafec74ff2ed07df597", size = 2364197, upload-time = "2026-10-11T18:33:14.244Z" },
{ url = "https://files.pythonhosted.org/packages/ca/fb/bf0aab3e78301d202b82a0322ec968cd703b11fc0623fde9a28708936f62/pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:32fad3a91e51b6d2039c572db04a5a873260b399f6bd62c3552671fa7a4a2899", size = 2444259, upload-time = "2026-10-11T18:33:15.79Z" },
{ url = "https://files.pythonhosted.org/packages/45/35/38f6d6564fae57d9b12e5676dfa947e0e7d5c46dbeaa7eb3352261d6d299/pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:42b54c2c90ad348b5e3a85e03e715d572c1fde357ef104cdfe3b03b697a404ea", size = 2159857, upload-time = "2026-10-11T18:33:17.51Z" },
{ url = "https://files.pythonhosted.org/packages/65/a0/fb0a3ca10f139dcf765b2d312d10cf0f65c57c59993229d00ad12b14ceff/pydantic_core-2.50.1-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:2df1ff41884de2bc4b307bafd7c40a691094fad2ff8e767e5b45a319257bcf4e", size = 2233954, upload-time = "2026-10-11T18:33:19.591Z" },
{ url = "https://files.pythonhosted.org/packages/8c/6a/e63842252702aa4ec6e6b7178ca85e541a77459076592c23ebe2d9840b33/pydantic_core-2.50.1-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:fe90228920fd8ff2be62622b6bb8a2b11acd65046d50c6b130614b5879605a20", size = 2243876, upload-time = "2026-10-11T18:33:21.393Z" },
{ url = "https://files.pythonhosted.org/packages/39/25/5991cf8318b37e0dfab47b87541619a1df8501a793cba0d978846cba37a7/pydantic_core-2.50.1-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:844b869f118e22a41a091bdcedda8a71bc1b0f62c38d1a0c3211cece47e1d8fc", size = 2277908, upload-time = "2026-10-11T18:33:23.324Z" },
{ url = "https://files.pythonhosted.org/packages/a7/3e/3ee8baaa6cc25a6961c69168cf9ff0f002d56f4e0d541ad6724c18fb61f3/pydantic_core-2.50.1-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:2eb75304506894a281d346220a4f7481a1b8729577c5ed2a05395991966a8396", size = 2449285, upload-time = "2026-10-11T18:33:24.942Z" },
{ url = "https://files.pythonhosted.org/packages/c0/c7/acbec6deac13fe697a80c275a9b6661db62c4d323bac8a47347b1f39c7cd/pydantic_core-2.50.1-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:6b20a4bffabdad0db2927ac034ae3b8a681b1f7a0182f3e60b479ad2fde21ebb", size = 2479013, upload-time = "2026-10-11T18:33:26.925Z" },
{ url = "https://files.pythonhosted.org/packages/10/08/21a3f237b264389f6219d053ee78fc1b5c2fd402c1b1cb2b6cb8b85f9834/pydantic_core-2.50.1-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:99ba9bc2b8062ea0c326a990f7f00e6530c23579de66dd246e72c4cafef950a5", size = 1484400, upload-time = "2026-10-11T18:33:28.693Z" },
{ url = "https://files.pythonhosted.org/packages/09/ce/077a6d262d12ef09108377ac0717f029f420d773ace63cafd6143af75568/pydantic_core-2.50.1-cp314-cp314-win32.whl", hash = "sha256:cf356f70551d40374eaffb1aa63f1eb6d2006681cbd7a9faea173ce0f4dd7cd2", size = 2103222, upload-time = "2026-10-11T18:33:30.326Z" },
{ url = "https://files.pythonhosted.org/packages/14/4c/350a2415209c43d670eb71d3c040f332c04a30583d39e311b05c7ac15762/pydantic_core-2.50.1-cp314-cp314-win_amd64.whl", hash = "sha256:d32f3acc081cc3923386d88f422cde8892335e95f034e0104bb4cf9310d9915f", size = 2171586, upload-time = "2026-10-11T18:33:32.139Z" },
{ url = "https://files.pythonhosted.org/packages/bf/92/9bea6ca96580a0902fed366f064f0829e404f41889b34543279a1162b888/pydantic_core-2.50.1-cp314-cp314-win_arm64.whl", hash = "sha256:bed5163e03b98bc1fa2eb05d74c63d9c5c95d8ed6254985481640fbf5e237dea", size = 2155773, upload-time = "2026-10-11T18:33:33.896Z" },
{ url = "https://files.pythonhosted.org/packages/86/8c/f121f073cf32bdd5cba7e6230b1ce0ac845b0cf43e44dd597d95af272db2/pydantic_core-2.50.1-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:9572c1369e9c9da2d64a7b7992c786d90ff295abc93964cfe3125e4290768070", size = 2234017, upload-time = "2026-10-11T18:33:35.588Z" },
{ url = "https://files.pythonhosted.org/packages/a4/69/2bb2bcd6146cffe98d760a46c42ae71efd5151d9b2f9c9bf6619a3b32083/pydantic_core-2.50.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2005207aafe1231315718bf6ed5d064a7300fb4772754af35ee72fc68159492e", size = 2001016, upload-time = "2026-10-11T18:33:37.57Z" },
{ url = "https://files.pythonhosted.org/packages/20/b3/fbf854c7d07ec114260c26e9e2071a4381740f9ae09641dbfcbdf2a18c45/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:64f6047f62a6c5ae08d0a6afb035667aa2d97c3d20d69762e034c5ea144d92a5", size = 2023015, upload-time = "2026-10-11T18:33:39.433Z" },
{ url = "https://files.pythonhosted.org/packages/65/20/6de55b2f92cdb614b745c6e9ced639fc4fd7e1e77604825a88bdece6fcbd/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:1ef800dd7d85bcdadf4c3076e4c94e43939493558a3b69a1ea830c706d4617bb", size = 2192543, upload-time = "2026-10-11T18:33:41.381Z" },
{ url = "https://files.pythonhosted.org/packages/0c/d9/19e91c94bd5c405945ce2f15526808aea37e162c253160de8ed7bf70b406/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b0135bcdcaa0f23573f286e4cb5e0fd2962700964ed13df085b85f2b97aeab9e", size = 2388704, upload-time = "2026-10-11T18:33:43.167Z" },
{ url = "https://files.pythonhosted.org/packages/b6/bc/2e24c8415eae1a25ee5a5484946a917123bad2e9d01689a759236928175a/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0b3a6f334c6a2345ca15318ff894502a90012536404b37c844a976c76c846e0b", size = 2464118, upload-time = "2026-10-11T18:33:44.856Z" },
{ url = "https://files.pythonhosted.org/packages/bd/1f/945b8053cb061c64e102bcaf7bfb9ed740c0bd4349f9bb978a7d4ddff4ab/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:06e01fbbfdb9be777b316a71b6c49efaf4a08b615d0a98d678cda3023f79d019", size = 2150142, upload-time = "2026-10-11T18:33:46.661Z" },
{ url = "https://files.pythonhosted.org/packages/2b/78/96a3e50bf0d64aaae781107eb9335b7529d05a85793ed6e7241c4cd1d931/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:a29a061fec0b4e2d714f277e70a3a18125ecff803f2fea6eade2f2e53711d112", size = 2245577, upload-time = "2026-10-11T18:33:48.574Z" },
{ url = "https://files.pythonhosted.org/packages/7a/5d/a6038a0322232758a6ebfa709f4ca14a60bf5b93940cd0b345056a557da4/pydantic_core-2.50.1-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f5187624823423e1d1b82b1072ac41dc837389e18d3d0572cc19bbee46cd550a", size = 2263728, upload-time = "2026-10-11T18:33:50.527Z" },
{ url = "https://files.pythonhosted.org/packages/0d/4b/76ded3333a457a9344c4f2d63f2d82d0101654b05178fa4ddfe7d3627674/pydantic_core-2.50.1-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:3e46a9eb0a0901dd6275e6b06ac3a464885ef350ec4121fe486869de8053e4bb", size = 2293630, upload-time = "2026-10-11T18:33:52.362Z" },
{ url = "https://files.pythonhosted.org/packages/a9/00/9eca378335c9c1b72bc779bf6e4c2a82ce784f14ec48a0e87102c9870e05/pydantic_core-2.50.1-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:756d669f04e62ec4148ecfe22be6a4484d9b1181a6ef32e205ebfd200540858b", size = 2468048, upload-time = "2026-10-11T18:33:54.118Z" },
{ url = "https://files.pythonhosted.org/packages/35/ca/e3832e9cf93651251de43c8c5c029ed680a3c1a0a1b17ee26c81bed08cbd/pydantic_core-2.50.1-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:c516cc5367ca3448995d42cb994bf3f4c9002d2a7c22eac9622551269ad1b807", size = 2512159, upload-time = "2026-10-11T18:33:55.99Z" },
{ url = "https://files.pythonhosted.org/packages/4b/f2/773469b5a10a39116a2cb17edaf6d722f017dd8da07161b371465311c542/pydantic_core-2.50.1-cp314-cp314t-win32.whl", hash = "sha256:9d1bed94af6a63835461f3cf7502058eb166c58c4778e11d0f433cfb1bd69e19", size = 2098406, upload-time = "2026-10-11T18:33:58.043Z" },
{ url = "https://files.pythonhosted.org/packages/ee/42/0bb74f8f25204b259b11ab7c12dc7f180893b6bd706118b385147fb6efd5/pydantic_core-2.50.1-cp314-cp314t-win_amd64.whl", hash = "sha256:c8dce1f1e0e5358b682a6ad3fa5e31b31d4560997b8e61417e9217c8d60f8a0c", size = 2148481, upload-time = "2026-10-11T18:33:59.913Z" },
{ url = "https://files.pythonhosted.org/packages/47/0d/d801646c9679a4e630e15cf521d4108b93854b42a6e6e02391bd4c6b1095/pydantic_core-2.50.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ceff0acc940be2715bd6ad17b24c0e5304abf44f6efd0f81ee8499e640f9dc86", size = 2174972, upload-time = "2026-10-11T18:34:01.875Z" },
{ url = "https://files.pythonhosted.org/packages/b2/84/23984b763d8862a02a13d27a44b6e8169428fd85ecfed88f54c29108604d/pydantic_core-2.50.1-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:8a6791afa2245e6c6b180122d105941644f5bd410bb18623b408808cc41a3102", size = 2224599, upload-time = "2026-10-11T18:34:04.016Z" },
{ url = "https://files.pythonhosted.org/packages/4d/90/a63cf8586abc1d1a3f6d9b18f0224789ebf003851f092ebda3c7c863fd32/pydantic_core-2.50.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:84f34323a61a365b4e9295de6028474754829aaddd59c7bf1a040e7487ef8f3c", size = 2024191, upload-time = "2026-10-11T18:34:05.901Z" },
{ url = "https://files.pythonhosted.org/packages/a6/6a/f34bff9808ffb4907fbf5f5040457d253cacf2da7fce9efbc99ca1b1a44d/pydantic_core-2.50.1-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:23edad659e8dbd8ca7e4e877fe6c81573abbdf215bd25a68b53e1272f58b80c7", size = 2048252, upload-time = "2026-10-11T18:34:07.757Z" },
{ url = "https://files.pythonhosted.org/packages/b2/54/13f419bf1eb59852003818e25935aaf175687d978f4c4bca70e08fe40a3b/pydantic_core-2.50.1-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3a5fce22f1e87d181e924e12da7d81cfe031fb3881a5ddf26ad28f141756ca43", size = 2173376, upload-time = "2026-10-11T18:34:09.592Z" },
{ url = "https://files.pythonhosted.org/packages/6d/6c/b5a34d24cd0c81669d8f8339d74e6815abcf2f8fb48ab4b49b84c09be1d5/pydantic_core-2.50.1-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c73622ef819328873b53109ee4f77ceb598bffedd02daf916102be3228866b78", size = 2364559, upload-time = "2026-10-11T18:34:11.534Z" },
{ url = "https://files.pythonhosted.org/packages/eb/8d/d64d6216a8df365082665927ff923f183056f9049fee08e9777c9ac05296/pydantic_core-2.50.1-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ce8c25ca38cc0e3d7753ba180808de2c0c8cb24eae0df64491e40921454e9831", size = 2444697, upload-time = "2026-10-11T18:34:13.535Z" },
{ url = "https://files.pythonhosted.org/packages/b8/0d/1b1149f60a00ea21ba5f70e28acbd40feb4598af414f80f53c921fac07c9/pydantic_core-2.50.1-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7689580e72a642ab5ec64d5f55b2e33636fa43b4ebe63c0c2c965ef307c7d1aa", size = 2159961, upload-time = "2026-10-11T18:34:15.56Z" },
{ url = "https://files.pythonhosted.org/packages/1e/35/f236549299dcc78e71e945495d7ec67e78d20844d0999c60601685003031/pydantic_core-2.50.1-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:d5c0e32fdbce7f1e8ef4d11f655694bf5f4175c757a9f1dc2be09b8864e5bcf5", size = 2234581, upload-time = "2026-10-11T18:34:17.502Z" },
{ url = "https://files.pythonhosted.org/packages/6a/85/26901a490522b7f75ef9bb9a7afb73e5bb550f0e1cb5b99a0069183e2eb9/pydantic_core-2.50.1-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:40f523349960fa30f3ea51404308ff50f9997a90df639590f47a057c1f32b415", size = 2244090, upload-time = "2026-10-11T18:34:19.402Z" },
{ url = "https://files.pythonhosted.org/packages/ca/2c/481bcfc70ceeb77a778ca6e5b705fe592cb64735c108157f81b7dd9c280e/pydantic_core-2.50.1-cp315-cp315-musllinux_1_1_aarch64.whl", hash = "sha256:d4193206b6587047437f6f11d7e776df23e1c1e23af2a54d9347275614791e10", size = 2277948, upload-time = "2026-10-11T18:34:21.317Z" },
{ url = "https://files.pythonhosted.org/packages/24/eb/f1e09333faa7ba447cde967310f758430cc7c5e987bdab5228816c70030d/pydantic_core-2.50.1-cp315-cp315-musllinux_1_1_armv7l.whl", hash = "sha256:84bc765b282a9d5b7fe0348b8648904f25a6a04b2139da52b1dd30c8ac3a2c8f", size = 2449688, upload-time = "2026-10-11T18:34:23.321Z" },
{ url = "https://files.pythonhosted.org/packages/d1/b3/036bde636db8f76d92996e81aefc75678ab5cec4a07eea1ad0c72a893fc3/pydantic_core-2.50.1-cp315-cp315-musllinux_1_1_x86_64.whl", hash = "sha256:ed1e728b39a383c81035b2459cfcb35d99dfb01f7d6ebe3a913bc1cc5b81e459", size = 2479286, upload-time = "2026-10-11T18:34:25.214Z" },
{ url = "https://files.pythonhosted.org/packages/d0/a3/07f018294ee18d144afeb6df1a47d9e92960f014be45c5ed13519fa5af95/pydantic_core-2.50.1-cp315-cp315-win32.whl", hash = "sha256:bc94f474417604bd383d2cd445d071b07dd55fedceed3ce33407bf1fcc107290", size = 2103683, upload-time = "2026-10-11T18:34:27.42Z" },
{ url = "https://files.pythonhosted.org/packages/5f/98/f9bd7e1f9b6709f155acb9ef826d9c3884fe925f811fd8e55b9b52280bad/pydantic_core-2.50.1-cp315-cp315-win_amd64.whl", hash = "sha256:983a662de2571cb2502fc8ff47b6770b03d025d2eb314c92f77b3f07c74720ed", size = 2171681, upload-time = "2026-10-11T18:34:29.508Z" },
{ url = "https://files.pythonhosted.org/packages/10/87/4bb3e1e7f385c076ab5af4d6dd0571b22042cd8207eb810d5b9fef15ae31/pydantic_core-2.50.1-cp315-cp315-win_arm64.whl", hash = "sha256:94845ff54dc5193f228cab81b2662a04bfbb892e95bdc15edf7399000ce57d54", size = 2156251, upload-time = "2026-10-11T18:34:31.455Z" },
{ url = "https://files.pythonhosted.org/packages/47/47/83643225b08f2aef6c8cc4bbe6e3f79c5e139c4364a6e450d0f399d87774/pydantic_core-2.50.1-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:4a53d13cdfbedbfa87f08b83c1a0a5efcc767d785a4b41934fa9cb672670493a", size = 2234363, upload-time = "2026-10-11T18:34:33.65Z" },
{ url = "https://files.pythonhosted.org/packages/5e/66/127ca649ba2f2462039dc1e694c6c01e00a3689f023a617364d3507e6d97/pydantic_core-2.50.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:efbecf43d321f7b9281441f1f213f7c21c66988b0e06c2730ba13ed47a46bb08", size = 2000972, upload-time = "2026-10-11T18:34:36.037Z" },
{ url = "https://files.pythonhosted.org/packages/5e/4f/e421e0a5d653b1203b090b2e48745976988d7338a647940704b5b9c2b399/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bc1f08f68dac9f9e83845a8039880aba2ab553eb9b2259c3243a313182c253fe", size = 2022925, upload-time = "2026-10-11T18:34:37.972Z" },
{ url = "https://files.pythonhosted.org/packages/d5/4e/ea5568e2491e1a71100f15ae8c2d01ef52db42a184a2d4e716bc79e5eb8f/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:5dfe41f232befddb9c4377f6cfc702b51595e2d78ed082672adf8758d2c4619f", size = 2192867, upload-time = "2026-10-11T18:34:39.921Z" },
{ url = "https://files.pythonhosted.org/packages/ae/5e/3b8c3a35acbe219909ada5defad5d7d9fed845fb2b37bd5ec518f453c119/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:adc06d218a1cadfd2ec4628424d7d79ce4eba69c2965e7e7b55106f0da5208c8", size = 2388687, upload-time = "2026-10-11T18:34:42.184Z" },
{ url = "https://files.pythonhosted.org/packages/b6/aa/7889b4e515f91a2e8c0ae6b5081fec0feb30c4398d1434e14793c60f173a/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2cf91809d0721ab81592ba67bea7694821679c10b1a2e3c3460082b286c1918a", size = 2464415, upload-time = "2026-10-11T18:34:44.384Z" },
{ url = "https://files.pythonhosted.org/packages/08/78/93449e628eb8a6fdcce3eff9043081179d1bc7ce6f1bff32dc5006f41e00/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:23923ab9292c40da026330b1ecf4dc2618c8e86e0422e5d1fbf50d94d64ca4f8", size = 2150823, upload-time = "2026-10-11T18:34:46.392Z" },
{ url = "https://files.pythonhosted.org/packages/f4/f1/72c5bc129fceb0d00f05dc1e67f518c1728de1928c55f81fc13d7690de39/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:f3377c8c2b3ce898423c5e5dd94c7982e30aa7717a7e6ab2470b9de364963709", size = 2245806, upload-time = "2026-10-11T18:34:48.805Z" },
{ url = "https://files.pythonhosted.org/packages/28/2a/922a0e78f3aa6ab837b59f88190233fb8dad546c17995fde9bb3ed3b9b49/pydantic_core-2.50.1-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:455a773617b5913bf5c20d0692e5787b119e52c4d40ea644ca31f5758fd31be2", size = 2264160, upload-time = "2026-10-11T18:34:50.876Z" },
{ url = "https://files.pythonhosted.org/packages/52/a8/0f1449e3e1b20941c9372faa18e7b6a092e30cdfa841902473f7989532ac/pydantic_core-2.50.1-cp315-cp315t-musllinux_1_1_aarch64.whl", hash = "sha256:1a9006395dece0e32e704c315eff8a00bede494f6108546cfc5539c89fef4f9a", size = 2294031, upload-time = "2026-10-11T18:34:52.876Z" },
{ url = "https://files.pythonhosted.org/packages/d1/d0/1031f492857de70355fb16524bbb03efce5fd34c93ed4a1ec60be07e0d4b/pydantic_core-2.50.1-cp315-cp315t-musllinux_1_1_armv7l.whl", hash = "sha256:d2d82aa62521c55ddfb000ae70f88cdd8de974078f6024e821dfe5addd0c818f", size = 2468423, upload-time = "2026-10-11T18:34:54.995Z" },
{ url = "https://files.pythonhosted.org/packages/46/52/269ffffa645b8e47906395a39cf9db1151ae9fa4bcd7f47b960bc31baf37/pydantic_core-2.50.1-cp315-cp315t-musllinux_1_1_x86_64.whl", hash = "sha256:009634b83993777ddcd69cad0ffcace43dabde692109528e35f0fde91e386a8b", size = 2512598, upload-time = "2026-10-11T18:34:57.149Z" },
{ url = "https://files.pythonhosted.org/packages/31/5c/e47e28281f20326ff6f3c31d626f0a83e615d2d94ba41bb0ad6ec237184a/pydantic_core-2.50.1-cp315-cp315t-win32.whl", hash = "sha256:3fde4fdc6487a58d944ca87cf5adc95d5f266e872c19599f5f4c0a8a1b1f9f9f", size = 2098535, upload-time = "2026-10-11T18:34:59.313Z" },
{ url = "https://files.pythonhosted.org/packages/03/ad/759e181e69c1b472c60b2049e5f61d5da1deefdd5ce1df4bb2ebcf771f25/pydantic_core-2.50.1-cp315-cp315t-win_amd64.whl", hash = "sha256:1c8632d4ac04e6f91128fca584b3a8a507d81604c24eeaaad00d4be42765c32b", size = 2148645, upload-time = "2026-10-11T18:35:01.571Z" },
{ url = "https://files.pythonhosted.org/packages/6d/56/8a702c27e5be9f47e5f19d8669227424290e4c024e7c370279cbaf244b4e/pydantic_core-2.50.1-cp315-cp315t-win_arm64.whl", hash = "sha256:c3ede305158e75510be50869b319550ab072008c13d64d4ab1e094fb286b6f44", size = 2175297, upload-time = "2026-10-11T18:35:04.079Z" },
]
[[package]]
name = "pyyaml"
version = "6.0.3"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/11/0fd08f8192109f7169db964b5707a2f1e8b745d4e239b784a5a1dd80d1db/pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", size = 181669, upload-time = "2025-09-25T21:32:23.673Z" },
{ url = "https://files.pythonhosted.org/packages/b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", size = 173252, upload-time = "2025-09-25T21:32:25.149Z" },
{ url = "https://files.pythonhosted.org/packages/50/31/b20f376d3f810b9b2371e72ef5adb33879b25edb7a6d072cb7ca0c486398/pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", size = 767081, upload-time = "2025-09-25T21:32:26.575Z" },
{ url = "https://files.pythonhosted.org/packages/49/1e/a55ca81e949270d5d4432fbbd19dfea5321eda7c41a849d443dc92fd1ff7/pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", size = 841159, upload-time = "2025-09-25T21:32:27.727Z" },
{ url = "https://files.pythonhosted.org/packages/74/27/e5b8f34d02d9995b80abcef563ea1f8b56d20134d8f4e5e81733b1feceb2/pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", size = 801626, upload-time = "2025-09-25T21:32:28.878Z" },
{ url = "https://files.pythonhosted.org/packages/f9/11/ba845c23988798f40e52ba45f34849aa8a1f2d4af4b798588010792ebad6/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", size = 753613, upload-time = "2025-09-25T21:32:30.178Z" },
{ url = "https://files.pythonhosted.org/packages/3d/e0/7966e1a7bfc0a45bf0a7fb6b98ea03fc9b8d84fa7f2229e9659680b69ee3/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", size = 794115, upload-time = "2025-09-25T21:32:31.353Z" },
{ url = "https://files.pythonhosted.org/packages/de/94/980b50a6531b3019e45ddeada0626d45fa85cbe22300844a7983285bed3b/pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", size = 137427, upload-time = "2025-09-25T21:32:32.58Z" },
{ url = "https://files.pythonhosted.org/packages/97/c9/39d5b874e8b28845e4ec2202b5da735d0199dbe5b8fb85f91398814a9a46/pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", size = 154090, upload-time = "2025-09-25T21:32:33.659Z" },
{ url = "https://files.pythonhosted.org/packages/73/e8/2bdf3ca2090f68bb3d75b44da7bbc71843b19c9f2b9cb9b0f4ab7a5a4329/pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", size = 140246, upload-time = "2025-09-25T21:32:34.663Z" },
{ url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814, upload-time = "2025-09-25T21:32:35.712Z" },
{ url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809, upload-time = "2025-09-25T21:32:36.789Z" },
{ url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454, upload-time = "2025-09-25T21:32:37.966Z" },
{ url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355, upload-time = "2025-09-25T21:32:39.178Z" },
{ url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175, upload-time = "2025-09-25T21:32:40.865Z" },
{ url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228, upload-time = "2025-09-25T21:32:42.084Z" },
{ url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194, upload-time = "2025-09-25T21:32:43.362Z" },
{ url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429, upload-time = "2025-09-25T21:32:57.844Z" },
{ url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912, upload-time = "2025-09-25T21:32:59.247Z" },
{ url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108, upload-time = "2025-09-25T21:32:44.377Z" },
{ url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641, upload-time = "2025-09-25T21:32:45.407Z" },
{ url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901, upload-time = "2025-09-25T21:32:48.83Z" },
{ url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132, upload-time = "2025-09-25T21:32:50.149Z" },
{ url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261, upload-time = "2025-09-25T21:32:51.808Z" },
{ url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272, upload-time = "2025-09-25T21:32:52.941Z" },
{ url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923, upload-time = "2025-09-25T21:32:54.537Z" },
{ url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062, upload-time = "2025-09-25T21:32:55.767Z" },
{ url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" },
]
[[package]]
name = "typing-extensions"
version = "4.16.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" },
]
[[package]]
name = "typing-inspection"
version = "0.4.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a3/26/b09b8010994eccc3c09092e6b34058f36a460eea2d4c3e8b910c695975a0/typing_inspection-0.4.4.tar.gz", hash = "sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47", size = 76928, upload-time = "2026-08-12T12:37:25.997Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" },
]