Compare commits

..
8 Commits
Author SHA1 Message Date
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
23 changed files with 964 additions and 208 deletions

No files matched your search

+3
View File
@@ -54,3 +54,6 @@ mutants/
scripts/bootstrap_lldap_users.py scripts/bootstrap_lldap_users.py
scripts/bootstrap_*.py scripts/bootstrap_*.py
!scripts/bootstrap_token.py !scripts/bootstrap_token.py
# Worktrees & Slices
.worktrees/
+26 -11
View File
@@ -9,7 +9,7 @@ It is designed around a strict two-tier boundary:
All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime. All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime.
> [!NOTE] > [!NOTE]
> **Current Implementation Baseline vs. Target Architecture**: This README documents the **currently implemented CLI and runtime baseline (Milestone P3)**. Under [Milestone P4 in `ROADMAP.md`](ROADMAP.md), `appctl` is transitioning from a host CLI orchestrator into a dedicated daemon service (`homelab-appctl.service`) exposing a unified logical API across local Unix socket and HTTP transports. See [`ROADMAP.md`](ROADMAP.md) for the full baseline-to-target matrix. > **Milestone P4 Control Plane Architecture**: Under [Milestone P4 in `ROADMAP.md`](ROADMAP.md), `appctl` operates as an operational control plane daemon service (`homelab-appctl.service`) exposing a unified logical API across a local Unix Domain Socket (`/run/homelab/appctl.sock`) and loopback HTTP (`127.0.0.1:9876`). 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.
--- ---
@@ -49,8 +49,10 @@ All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_
▲ ▲
│ (Host Orchestration & CD) │ (Host Orchestration & CD)
┌───────────────┴───────────────┐ ┌───────────────┴───────────────┐
│ Host Control Plane Baseline │ │ Host Control Plane (P4) │
│ • appctl CLI + Engine │ │ • thin appctl CLI │
│ • homelab-appctl.service │
│ (UDS / HTTP daemon) │
│ • homelab-gitops.service │ │ • homelab-gitops.service │
└───────────────────────────────┘ └───────────────────────────────┘
``` ```
@@ -82,10 +84,17 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran
├── nixos/ # Declarative NixOS modules, systemd units, and SOPS secret wiring ├── nixos/ # Declarative NixOS modules, systemd units, and SOPS secret wiring
├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml) ├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml)
├── scripts/ ├── scripts/
│ ├── appctl # Operational CLI entrypoint and Compose environment orchestrator │ ├── appctl # Thin operational CLI delegating to control plane daemon
│ ├── appctl_engine.py # Discovery, two-axis provenance, TLS inspection, and Homepage sync engine │ ├── appctl_daemon.py # Async HTTP/UDS daemon server (homelab-appctl.service)
│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for workload app.yaml │ ├── appctl_router.py # Operational router, locking, RBAC & dispatch
│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST security validation │ ├── appctl_auth.py # SO_PEERCRED & Bearer token RBAC authentication
│ ├── appctl_audit.py # Append-only fail-closed structured audit logger
│ ├── appctl_contracts.py # Pydantic v2 schemas for daemon RPC requests & responses
│ ├── appctl_cli.py # Unified CLI client with dual transport fallbacks
│ ├── appctl_engine.py # Discovery, two-axis provenance, TLS inspection, and Homepage sync
│ ├── bootstrap_token.py # Operator Bearer token provisioning helper
│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for app.yaml
│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST validation
│ └── test # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks) │ └── test # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks)
├── tests/ # Unit, structural, and security invariant test suites ├── tests/ # Unit, structural, and security invariant test suites
└── docs/ # Architecture references, operational runbooks, and MADR decisions └── docs/ # Architecture references, operational runbooks, and MADR decisions
@@ -93,7 +102,7 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran
--- ---
## Quickstart & Operations (Current CLI Baseline) ## Quickstart & Operations (Control Plane Daemon & CLI)
### Development & Verification ### Development & Verification
@@ -111,7 +120,12 @@ pyright
### Workload Management (`appctl` CLI) ### 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 ```bash
# Check daemon health status
appctl health
# List all workloads with container health and local Git checkout status # List all workloads with container health and local Git checkout status
appctl list appctl list
@@ -121,7 +135,7 @@ appctl list --fetch --ssl --core
# Inspect detailed manifest, provenance, and container diagnostics for a workload # Inspect detailed manifest, provenance, and container diagnostics for a workload
appctl info <service> appctl info <service>
# Manage workload or Core service lifecycle (executes docker compose locally in the current baseline) # Manage workload or Core service lifecycle (dispatched via homelab-appctl daemon)
appctl up <service|core> appctl up <service|core>
appctl down <service|core> appctl down <service|core>
appctl restart <service|core> appctl restart <service|core>
@@ -136,11 +150,12 @@ appctl sync
### Host System Management ### Host System Management
```bash ```bash
# Rebuild and activate the NixOS host configuration # Rebuild and activate the NixOS host configuration (or use the 'nix-switch' alias)
sudo nixos-rebuild switch --flake .#server sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
# Inspect platform systemd units # Inspect platform systemd units
systemctl status homeserver-core.service systemctl status homeserver-core.service
systemctl status homelab-appctl.service
systemctl status homelab-gitops.service systemctl status homelab-gitops.service
systemctl status dynu-monitor.service systemctl status dynu-monitor.service
``` ```
+12
View File
@@ -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
@@ -57,3 +66,6 @@ This document outlines the security controls, container isolation rules, and ope
- [x] Invariant test runner (`./scripts/test`) passing on changes. - [x] Invariant test runner (`./scripts/test`) 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
@@ -111,7 +111,7 @@ appctl:
Save and exit your editor (SOPS will re-encrypt the file), then project the updated secrets: Save and exit your editor (SOPS will re-encrypt the file), then project the updated secrets:
```bash ```bash
sudo nixos-rebuild switch --flake ~/Core#server 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. This updates `/run/secrets/appctl/tokens.json` (owned by `homelab-appctl:homelab-operators`, mode `0400`), which `homelab-appctl.service` consumes.
@@ -135,7 +135,7 @@ Verify permissions using both unauthenticated and authenticated queries:
To rotate an operator token: To rotate an operator token:
1. Run `python3 scripts/bootstrap_token.py --force --token-id "operator-admin-$(date +%Y%m%d)"`. 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. 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 ~/Core#server` to apply the updated token store. 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`). 4. Verify CLI operations (`appctl config docs`).
5. Remove the deprecated token descriptor from `nixos/secrets.yaml` and re-run `nixos-rebuild switch`. 5. Remove the deprecated token descriptor from `nixos/secrets.yaml` and re-run `nixos-rebuild switch`.
+58 -18
View File
@@ -296,20 +296,29 @@ To bring up a replacement host from version control:
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. 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 ### Stage 1: Pre-Flight Checks & Session Preservation
Before initiating data synchronization or service cutover, verify the target `operator` account environment:
1. **Verify `operator` account existence and home directory**: > [!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 ```bash
id operator id operator
# Expected output must include membership in: wheel, docker, homelab-operators ```
ls -ld /home/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**: 2. **Verify SSH key provisioning & permissions**:
Ensure the operator's authorized keys are installed with strict permissions: Ensure the operator's authorized keys are installed with strict permissions (copying from `<legacy-operator>` if needed):
```bash ```bash
sudo ls -la /home/operator/.ssh/authorized_keys 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 700 /home/operator/.ssh
sudo chmod 600 /home/operator/.ssh/authorized_keys sudo chmod 600 /home/operator/.ssh/authorized_keys
sudo chown -R operator:users /home/operator/.ssh sudo chown -R operator:users /home/operator/.ssh
@@ -321,20 +330,20 @@ Before initiating data synchronization or service cutover, verify the target `op
sudo -u operator sudo -n true || echo "Passwordless or password sudo required for operator" sudo -u operator sudo -n true || echo "Passwordless or password sudo required for operator"
``` ```
4. **Verify persistent directories**: 4. **Prepare persistent directories**:
Ensure `/home/operator/Sites` and `/home/operator/Core` target parent paths are ready: Ensure `/home/operator/Sites`, `/home/operator/Core`, `/home/operator/var/lib/homelab`, and state parent paths are ready:
```bash ```bash
sudo mkdir -p /home/operator/{Core,Sites,.config/homelab} 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} sudo chown -R operator:homelab-operators /home/operator/{Core,Sites,.config,var,.local}
``` ```
--- ---
### Stage 2: State and Repository Synchronization ### Stage 2: State and Repository Synchronization
Synchronize repository checkouts, environment definitions, and runtime state from the legacy user account to `/home/operator/` using non-destructive archive flags (`-aHAX` preserves hard links, attributes, and extended ACLs): 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**: 1. **Initial background synchronization**:
Seed the file trees for Core and Sites while services continue running: Seed the file trees for Core, Sites, workload databases, and configurations while services continue running:
```bash ```bash
sudo rsync -aHAX --info=progress2 \ sudo rsync -aHAX --info=progress2 \
--exclude=".venv" \ --exclude=".venv" \
@@ -344,6 +353,16 @@ Synchronize repository checkouts, environment definitions, and runtime state fro
sudo rsync -aHAX --info=progress2 \ sudo rsync -aHAX --info=progress2 \
/home/<legacy-operator>/Sites/ /home/operator/Sites/ /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 if [ -d "/home/<legacy-operator>/.config/homelab" ]; then
sudo rsync -aHAX --info=progress2 \ sudo rsync -aHAX --info=progress2 \
/home/<legacy-operator>/.config/homelab/ /home/operator/.config/homelab/ /home/<legacy-operator>/.config/homelab/ /home/operator/.config/homelab/
@@ -351,9 +370,15 @@ Synchronize repository checkouts, environment definitions, and runtime state fro
``` ```
2. **Quiesce active database writers**: 2. **Quiesce active database writers**:
Stop the platform stack to guarantee point-in-time consistency across SQLite databases (e.g. LLDAP `users.db`, Authelia `db.sqlite3`, Stalwart storage) before the cutover sync: 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 ```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 homeserver-core
sudo systemctl stop homelab-appctl
sudo systemctl stop homelab-gitops
``` ```
3. **Final delta synchronization (`--delete`)**: 3. **Final delta synchronization (`--delete`)**:
@@ -366,13 +391,28 @@ Synchronize repository checkouts, environment definitions, and runtime state fro
sudo rsync -aHAX --delete --info=progress2 \ sudo rsync -aHAX --delete --info=progress2 \
/home/<legacy-operator>/Sites/ /home/operator/Sites/ /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**: 4. **Fix ownership and permissions**:
Set primary ownership to `operator` and group to `homelab-operators`: Set primary ownership to `operator` and group to `homelab-operators` across all migrated trees:
```bash ```bash
sudo chown -R operator:homelab-operators /home/operator/Core /home/operator/Sites /home/operator/.config sudo chown -R operator:homelab-operators \
sudo chmod -R u+rwX,g+rX /home/operator/Core /home/operator/Sites /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; # ACME certificate security invariant: Traefik strictly requires 0600 on acme.json;
# recursive group read permissions will cause Traefik to refuse to start. # recursive group read permissions will cause Traefik to refuse to start.
+1 -1
View File
@@ -103,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
``` ```
--- ---
+1
View File
@@ -22,6 +22,7 @@
programs.git = { programs.git = {
enable = true; enable = true;
config.safe.directory = [ config.safe.directory = [
"/home/${config.homelab.operatorUser}/Core"
"/home/${config.homelab.operatorUser}/Sites/*" "/home/${config.homelab.operatorUser}/Sites/*"
]; ];
}; };
+2 -2
View File
@@ -62,8 +62,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 = ''
+7 -3
View File
@@ -28,7 +28,7 @@ DEFAULT_AUDIT_LOG = Path("/var/log/homelab/appctl/audit.jsonl")
DEFAULT_LOCK_DIR = Path("/var/lib/homelab/appctl/locks") DEFAULT_LOCK_DIR = Path("/var/lib/homelab/appctl/locks")
REDACT_KEY_PATTERNS = re.compile( REDACT_KEY_PATTERNS = re.compile(
r".*(?:_KEY|_SECRET|_PASSWORD|_TOKEN|_PASS|_HASH)$", re.IGNORECASE r"^(?:.*_)?(?:KEY|SECRET|PASSWORD|TOKEN|PASS|HASH)$", re.IGNORECASE
) )
@@ -105,7 +105,9 @@ class ConcurrentMutationError(Exception):
def __init__(self, target: str, message: str | None = None) -> None: def __init__(self, target: str, message: str | None = None) -> None:
self.target = target self.target = target
msg = message or f"Operation on target '{target}' is locked by a concurrent task." msg = (
message or f"Operation on target '{target}' is locked by a concurrent task."
)
super().__init__(msg) super().__init__(msg)
@@ -116,7 +118,9 @@ def redact_sensitive_data(val: Any) -> Any:
""" """
if isinstance(val, dict): if isinstance(val, dict):
return { return {
k: "[REDACTED]" if REDACT_KEY_PATTERNS.match(str(k)) else redact_sensitive_data(v) k: "[REDACTED]"
if REDACT_KEY_PATTERNS.match(str(k))
else redact_sensitive_data(v)
for k, v in val.items() for k, v in val.items()
} }
if isinstance(val, list): if isinstance(val, list):
+43 -15
View File
@@ -33,9 +33,12 @@ except ImportError:
yaml = None # type: ignore[assignment] yaml = None # type: ignore[assignment]
DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json") DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json")
DEFAULT_DEPLOYMENTS_FILE = Path(__file__).resolve().parent.parent / "config" / "deployments.yaml" DEFAULT_DEPLOYMENTS_FILE = (
Path(__file__).resolve().parent.parent / "config" / "deployments.yaml"
)
CORE_TARGETS: frozenset[str] = frozenset({ CORE_TARGETS: frozenset[str] = frozenset(
{
"core", "core",
"traefik", "traefik",
"authelia", "authelia",
@@ -46,29 +49,36 @@ CORE_TARGETS: frozenset[str] = frozenset({
"homepage", "homepage",
"diun", "diun",
"watchtower", "watchtower",
}) }
)
SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset({ SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset(
{
OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_CONFIG,
OperationType.WORKLOAD_LOGS, OperationType.WORKLOAD_LOGS,
}) }
)
MUTATING_OPERATIONS: frozenset[OperationType] = frozenset({ MUTATING_OPERATIONS: frozenset[OperationType] = frozenset(
{
OperationType.WORKLOAD_DEPLOY, OperationType.WORKLOAD_DEPLOY,
OperationType.WORKLOAD_STOP, OperationType.WORKLOAD_STOP,
OperationType.WORKLOAD_RESTART, OperationType.WORKLOAD_RESTART,
OperationType.WORKLOAD_UPDATE, OperationType.WORKLOAD_UPDATE,
OperationType.WORKLOAD_PULL, OperationType.WORKLOAD_PULL,
OperationType.PLATFORM_SYNC_HOMEPAGE, OperationType.PLATFORM_SYNC_HOMEPAGE,
}) }
)
READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset({ READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset(
{
OperationType.WORKLOAD_LIST, OperationType.WORKLOAD_LIST,
OperationType.WORKLOAD_GET, OperationType.WORKLOAD_GET,
OperationType.WORKLOAD_RESOLVE, OperationType.WORKLOAD_RESOLVE,
OperationType.PLATFORM_SSL, OperationType.PLATFORM_SSL,
OperationType.PLATFORM_HEALTH, OperationType.PLATFORM_HEALTH,
}) }
)
class Role(StrEnum): class Role(StrEnum):
@@ -119,7 +129,11 @@ class TokenDescriptor(StrictModel):
class AuthenticationError(Exception): class AuthenticationError(Exception):
"""Raised when authentication fails (401 Unauthorized).""" """Raised when authentication fails (401 Unauthorized)."""
def __init__(self, message: str = "Authentication required", code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED) -> None: def __init__(
self,
message: str = "Authentication required",
code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED,
) -> None:
super().__init__(message) super().__init__(message)
self.code = code self.code = code
self.http_status = 401 self.http_status = 401
@@ -128,7 +142,11 @@ class AuthenticationError(Exception):
class AuthorizationError(Exception): class AuthorizationError(Exception):
"""Raised when an authenticated principal lacks required role or scope (403 Forbidden).""" """Raised when an authenticated principal lacks required role or scope (403 Forbidden)."""
def __init__(self, message: str = "Permission denied", code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED) -> None: def __init__(
self,
message: str = "Permission denied",
code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED,
) -> None:
super().__init__(message) super().__init__(message)
self.code = code self.code = code
self.http_status = 403 self.http_status = 403
@@ -181,13 +199,15 @@ class TokenStore:
constant-time hmac.compare_digest. constant-time hmac.compare_digest.
""" """
if not secret: if not secret:
raise AuthenticationError("Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED) raise AuthenticationError(
"Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED
)
secret_hash = hashlib.sha256(secret.encode("utf-8")).hexdigest() secret_hash = hashlib.sha256(secret.encode("utf-8")).hexdigest()
tokens = self.load_tokens() tokens = self.load_tokens()
for token in tokens: for token in tokens:
if hmac.compare_digest(secret_hash, token.sha256): if hmac.compare_digest(secret_hash, token.sha256.lower()):
return Principal( return Principal(
identity=token.identity, identity=token.identity,
role=token.role, role=token.role,
@@ -195,7 +215,9 @@ class TokenStore:
auth_method="bearer_token", auth_method="bearer_token",
) )
raise AuthenticationError("Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED) raise AuthenticationError(
"Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED
)
def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[str]: def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[str]:
@@ -235,7 +257,13 @@ def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[s
if isinstance(alias, str) and alias.strip(): if isinstance(alias, str) and alias.strip():
admitted.add(alias.strip()) admitted.add(alias.strip())
return admitted return admitted
except (OSError, UnicodeDecodeError, ValueError, json.JSONDecodeError, *yaml_errors): except (
OSError,
UnicodeDecodeError,
ValueError,
json.JSONDecodeError,
*yaml_errors,
):
return set() return set()
+160 -37
View File
@@ -18,6 +18,7 @@ import time
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
import yaml
from appctl_audit import ( from appctl_audit import (
AuditLogger, AuditLogger,
AuditPersistenceError, AuditPersistenceError,
@@ -208,6 +209,18 @@ def assemble_workload_env(
if local_env.is_file(): if local_env.is_file():
env.update(parse_dotenv(local_env, validate_keys=True)) env.update(parse_dotenv(local_env, validate_keys=True))
# Re-assert immutable platform infrastructure keys (defense-in-depth)
env["HOMELAB_DOMAIN"] = domain
env["DOMAIN_SUFFIX"] = domain
env["DOMAIN"] = domain
env["PROXY_NETWORK"] = os.environ.get("PROXY_NETWORK", "proxy-net")
env["CERT_RESOLVER"] = os.environ.get("CERT_RESOLVER", "myresolver")
env["SERVICE_NAME"] = app_name
env["CONTAINER_NAME"] = app_name
env["SERVICE_DOMAIN"] = f"{app_name}.{domain}"
if "DOCKER_CONFIG" in os.environ:
env["DOCKER_CONFIG"] = os.environ["DOCKER_CONFIG"]
return env return env
@@ -290,7 +303,9 @@ def validate_workload_preflight(
try: try:
manifest = parse_manifest(manifest_file) manifest = parse_manifest(manifest_file)
except ManifestValidationError as err: except ManifestValidationError as err:
raise RouterValidationError(f"Workload manifest validation failed: {err}") from err raise RouterValidationError(
f"Workload manifest validation failed: {err}"
) from err
effective_name = app_name or manifest.name effective_name = app_name or manifest.name
compose_file = _resolve_compose_file(app_dir) compose_file = _resolve_compose_file(app_dir)
@@ -328,7 +343,9 @@ def validate_core_preflight(
if not compose_file.is_file(): if not compose_file.is_file():
raise RouterValidationError(f"Core compose file not found at '{compose_file}'") raise RouterValidationError(f"Core compose file not found at '{compose_file}'")
if compose_file.is_symlink() and not compose_file.resolve().is_relative_to(core_dir_resolved): if compose_file.is_symlink() and not compose_file.resolve().is_relative_to(
core_dir_resolved
):
raise RouterValidationError( raise RouterValidationError(
f"Core compose file symlink escapes Core root: '{compose_file}'" f"Core compose file symlink escapes Core root: '{compose_file}'"
) )
@@ -592,7 +609,9 @@ class OperationalRouter:
elif operation == OperationType.WORKLOAD_PULL: elif operation == OperationType.WORKLOAD_PULL:
result_data = self._op_workload_pull(resolved_app) result_data = self._op_workload_pull(resolved_app)
elif operation == OperationType.WORKLOAD_UPDATE: elif operation == OperationType.WORKLOAD_UPDATE:
result_data, commit_sha = self._op_workload_update(request, resolved_app) result_data, commit_sha = self._op_workload_update(
request, resolved_app
)
elif operation == OperationType.PLATFORM_SYNC_HOMEPAGE: elif operation == OperationType.PLATFORM_SYNC_HOMEPAGE:
result_data = self._op_platform_sync_homepage() result_data = self._op_platform_sync_homepage()
else: else:
@@ -601,7 +620,10 @@ class OperationalRouter:
duration_ms = int((time.perf_counter() - start_time) * 1000) duration_ms = int((time.perf_counter() - start_time) * 1000)
# Audit COMPLETED for mutating ops and sensitive reads # Audit COMPLETED for mutating ops and sensitive reads
if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS: if (
operation in MUTATING_OPERATIONS
or operation in SENSITIVE_READ_OPERATIONS
):
self.audit_logger.log_completed( self.audit_logger.log_completed(
operation_id=op_id, operation_id=op_id,
principal=principal_audit, principal=principal_audit,
@@ -613,7 +635,9 @@ class OperationalRouter:
parameters=request.parameters, parameters=request.parameters,
duration_ms=duration_ms, duration_ms=duration_ms,
commit_sha=commit_sha, commit_sha=commit_sha,
message=result_data.get("message", "Operation completed successfully"), message=result_data.get(
"message", "Operation completed successfully"
),
) )
return OperationResponse( return OperationResponse(
@@ -630,7 +654,10 @@ class OperationalRouter:
except (RouterValidationError, RouterExecutionError) as err: except (RouterValidationError, RouterExecutionError) as err:
duration_ms = int((time.perf_counter() - start_time) * 1000) duration_ms = int((time.perf_counter() - start_time) * 1000)
if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS: if (
operation in MUTATING_OPERATIONS
or operation in SENSITIVE_READ_OPERATIONS
):
self.audit_logger.log_failed( self.audit_logger.log_failed(
operation_id=op_id, operation_id=op_id,
principal=principal_audit, principal=principal_audit,
@@ -699,7 +726,9 @@ class OperationalRouter:
dir_path=self.core_dir, dir_path=self.core_dir,
container_name=svc.container_name, container_name=svc.container_name,
) )
svc_dict["deployment_status"] = core_checkout.status_label if i == 0 else "" svc_dict["deployment_status"] = (
core_checkout.status_label if i == 0 else ""
)
svc_dict["provenance_status"] = "— Core Platform" svc_dict["provenance_status"] = "— Core Platform"
if params.ssl and not svc.is_internal: if params.ssl and not svc.is_internal:
svc_dict["ssl"] = check_ssl_cert(svc.domain) svc_dict["ssl"] = check_ssl_cert(svc.domain)
@@ -726,9 +755,14 @@ class OperationalRouter:
domain = target or resolve_canonical_domain() domain = target or resolve_canonical_domain()
try: try:
cert_info = check_ssl_cert(domain) cert_info = check_ssl_cert(domain)
return {"ssl": cert_info, "message": f"SSL certificate inspected for {domain}"} return {
"ssl": cert_info,
"message": f"SSL certificate inspected for {domain}",
}
except Exception as err: except Exception as err:
raise RouterExecutionError(f"SSL inspection failed for '{domain}': {err}") from err raise RouterExecutionError(
f"SSL inspection failed for '{domain}': {err}"
) from err
def _op_platform_health(self) -> dict[str, Any]: def _op_platform_health(self) -> dict[str, Any]:
return { return {
@@ -742,13 +776,23 @@ class OperationalRouter:
app_dir, _, compose_file, env, _ = self._prepare_target_context(app) app_dir, _, compose_file, env, _ = self._prepare_target_context(app)
cmd = ["docker", "compose", "-f", str(compose_file), "config"] cmd = ["docker", "compose", "-f", str(compose_file), "config"]
code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0) code, stdout, stderr = run_bounded_subprocess(
cmd, cwd=app_dir, env=env, timeout=15.0
)
if code != 0: if code != 0:
raise RouterExecutionError(f"docker compose config failed: {stderr}", exit_code=code) raise RouterExecutionError(
f"docker compose config failed: {stderr}", exit_code=code
)
config_output = stdout config_output = stdout
if principal.role != Role.ADMIN: if principal.role != Role.ADMIN:
# Redact secrets for non-admin callers # Redact secrets for non-admin callers
try:
parsed_yaml = yaml.safe_load(stdout)
if isinstance(parsed_yaml, (dict, list)):
redacted_parsed = redact_sensitive_data(parsed_yaml)
config_output = yaml.safe_dump(redacted_parsed, sort_keys=False)
except (yaml.YAMLError, ValueError):
config_output = redact_sensitive_data(config_output) config_output = redact_sensitive_data(config_output)
return {"output": config_output, "message": "Evaluated compose configuration"} return {"output": config_output, "message": "Evaluated compose configuration"}
@@ -771,13 +815,23 @@ class OperationalRouter:
if container: if container:
cmd.append(container) cmd.append(container)
code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0) code, stdout, stderr = run_bounded_subprocess(
cmd, cwd=app_dir, env=env, timeout=15.0
)
if code != 0: if code != 0:
raise RouterExecutionError(f"docker compose logs failed: {stderr}", exit_code=code) raise RouterExecutionError(
f"docker compose logs failed: {stderr}", exit_code=code
)
return {"output": stdout, "tail": params.tail, "message": f"Tail {params.tail} logs"} return {
"output": stdout,
"tail": params.tail,
"message": f"Tail {params.tail} logs",
}
def _op_workload_deploy(self, request: OperationRequest, app: Any) -> dict[str, Any]: def _op_workload_deploy(
self, request: OperationRequest, app: Any
) -> dict[str, Any]:
params = request.parse_parameters() params = request.parse_parameters()
assert isinstance(params, DeployParams) assert isinstance(params, DeployParams)
app_dir, _, compose_file, env, container = self._prepare_target_context(app) app_dir, _, compose_file, env, container = self._prepare_target_context(app)
@@ -785,14 +839,25 @@ class OperationalRouter:
# Optional build # Optional build
if params.build: if params.build:
build_cmd = ["docker", "compose", "-f", str(compose_file), "build", "--pull"] build_cmd = [
"docker",
"compose",
"-f",
str(compose_file),
"build",
"--pull",
]
if params.no_cache: if params.no_cache:
build_cmd.append("--no-cache") build_cmd.append("--no-cache")
if container: if container:
build_cmd.append(container) build_cmd.append(container)
code, out, err = run_bounded_subprocess(build_cmd, cwd=app_dir, env=env, timeout=300.0) code, out, err = run_bounded_subprocess(
build_cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError(f"docker compose build failed: {err}", exit_code=code) raise RouterExecutionError(
f"docker compose build failed: {err}", exit_code=code
)
# Deploy up # Deploy up
up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d"] up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d"]
@@ -801,9 +866,13 @@ class OperationalRouter:
if container: if container:
up_cmd.append(container) up_cmd.append(container)
code, out, err = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0) code, out, err = run_bounded_subprocess(
up_cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError(f"docker compose up failed: {err}", exit_code=code) raise RouterExecutionError(
f"docker compose up failed: {err}", exit_code=code
)
# Trigger Homepage sync for Sites workloads # Trigger Homepage sync for Sites workloads
if not is_core: if not is_core:
@@ -824,13 +893,21 @@ class OperationalRouter:
else: else:
cmd = ["docker", "compose", "-f", str(compose_file), "down"] cmd = ["docker", "compose", "-f", str(compose_file), "down"]
code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0) code, out, err = run_bounded_subprocess(
cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError(f"docker compose stop/down failed: {err}", exit_code=code) raise RouterExecutionError(
f"docker compose stop/down failed: {err}", exit_code=code
)
if not is_core: if not is_core:
self._trigger_homepage_sync() self._trigger_homepage_sync()
return {"output": out, "action": "stopped", "message": f"Workload '{app.name}' stopped"} return {
"output": out,
"action": "stopped",
"message": f"Workload '{app.name}' stopped",
}
def _op_workload_restart(self, app: Any) -> dict[str, Any]: def _op_workload_restart(self, app: Any) -> dict[str, Any]:
app_dir, _, compose_file, env, container = self._prepare_target_context(app) app_dir, _, compose_file, env, container = self._prepare_target_context(app)
@@ -840,13 +917,21 @@ class OperationalRouter:
if container: if container:
cmd.append(container) cmd.append(container)
code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0) code, out, err = run_bounded_subprocess(
cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError(f"docker compose restart failed: {err}", exit_code=code) raise RouterExecutionError(
f"docker compose restart failed: {err}", exit_code=code
)
if not is_core: if not is_core:
self._trigger_homepage_sync() self._trigger_homepage_sync()
return {"output": out, "action": "restarted", "message": f"Workload '{app.name}' restarted"} return {
"output": out,
"action": "restarted",
"message": f"Workload '{app.name}' restarted",
}
def _op_workload_pull(self, app: Any) -> dict[str, Any]: def _op_workload_pull(self, app: Any) -> dict[str, Any]:
app_dir, _, compose_file, env, container = self._prepare_target_context(app) app_dir, _, compose_file, env, container = self._prepare_target_context(app)
@@ -855,20 +940,40 @@ class OperationalRouter:
pull_cmd = ["docker", "compose", "-f", str(compose_file), "pull"] pull_cmd = ["docker", "compose", "-f", str(compose_file), "pull"]
if container: if container:
pull_cmd.append(container) pull_cmd.append(container)
code, _, err = run_bounded_subprocess(pull_cmd, cwd=app_dir, env=env, timeout=300.0) code, _, err = run_bounded_subprocess(
pull_cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError(f"docker compose pull failed: {err}", exit_code=code) raise RouterExecutionError(
f"docker compose pull failed: {err}", exit_code=code
)
up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"] up_cmd = [
"docker",
"compose",
"-f",
str(compose_file),
"up",
"-d",
"--remove-orphans",
]
if container: if container:
up_cmd.append(container) up_cmd.append(container)
code, out_up, err_up = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0) code, out_up, err_up = run_bounded_subprocess(
up_cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError(f"docker compose up failed after pull: {err_up}", exit_code=code) raise RouterExecutionError(
f"docker compose up failed after pull: {err_up}", exit_code=code
)
if not is_core: if not is_core:
self._trigger_homepage_sync() self._trigger_homepage_sync()
return {"output": out_up, "action": "pulled", "message": f"Workload '{app.name}' pulled and updated"} return {
"output": out_up,
"action": "pulled",
"message": f"Workload '{app.name}' pulled and updated",
}
def _op_workload_update( def _op_workload_update(
self, request: OperationRequest, app: Any self, request: OperationRequest, app: Any
@@ -906,7 +1011,9 @@ class OperationalRouter:
pull_cmd, cwd=app_dir, timeout=60.0 pull_cmd, cwd=app_dir, timeout=60.0
) )
if code != 0: if code != 0:
raise RouterExecutionError(f"git pull failed for '{app.name}': {pull_err}", exit_code=code) raise RouterExecutionError(
f"git pull failed for '{app.name}': {pull_err}", exit_code=code
)
# 3. Post-pull re-validation of manifest and expected_branch # 3. Post-pull re-validation of manifest and expected_branch
if is_core: if is_core:
@@ -914,7 +1021,9 @@ class OperationalRouter:
manifest = None manifest = None
declared_actions = ["compose_pull", "compose_up"] declared_actions = ["compose_pull", "compose_up"]
else: else:
manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) manifest, compose_file = validate_workload_preflight(
app_dir, self.sites_dir, app.name
)
if ( if (
params.expected_branch params.expected_branch
and manifest.source and manifest.source
@@ -948,7 +1057,15 @@ class OperationalRouter:
if params.no_cache: if params.no_cache:
cmd.append("--no-cache") cmd.append("--no-cache")
elif action == "compose_up": elif action == "compose_up":
cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"] cmd = [
"docker",
"compose",
"-f",
str(compose_file),
"up",
"-d",
"--remove-orphans",
]
elif action == "compose_restart": elif action == "compose_restart":
cmd = ["docker", "compose", "-f", str(compose_file), "restart"] cmd = ["docker", "compose", "-f", str(compose_file), "restart"]
else: else:
@@ -957,7 +1074,9 @@ class OperationalRouter:
if container: if container:
cmd.append(container) cmd.append(container)
code, act_out, act_err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0) code, act_out, act_err = run_bounded_subprocess(
cmd, cwd=app_dir, env=env, timeout=300.0
)
if code != 0: if code != 0:
raise RouterExecutionError( raise RouterExecutionError(
f"Action '{action}' failed during workload.update for '{app.name}': {act_err}", f"Action '{action}' failed during workload.update for '{app.name}': {act_err}",
@@ -986,7 +1105,10 @@ class OperationalRouter:
def _op_platform_sync_homepage(self) -> dict[str, Any]: def _op_platform_sync_homepage(self) -> dict[str, Any]:
self._trigger_homepage_sync() self._trigger_homepage_sync()
return {"action": "sync_homepage", "message": "Homepage dashboard synchronized successfully"} return {
"action": "sync_homepage",
"message": "Homepage dashboard synchronized successfully",
}
def _trigger_homepage_sync(self) -> None: def _trigger_homepage_sync(self) -> None:
"""Atomic compile of Homepage dashboard services.yaml under _homepage_sync.lock.""" """Atomic compile of Homepage dashboard services.yaml under _homepage_sync.lock."""
@@ -994,4 +1116,5 @@ class OperationalRouter:
cmd_sync_homepage() cmd_sync_homepage()
except (OSError, ValueError, RuntimeError) as exc: except (OSError, ValueError, RuntimeError) as exc:
import sys import sys
print(f"Warning: Homepage sync non-fatal error: {exc}", file=sys.stderr) print(f"Warning: Homepage sync non-fatal error: {exc}", file=sys.stderr)
+1 -1
View File
@@ -163,7 +163,7 @@ def main(argv: list[str] | None = None) -> int:
f"Add the following descriptor to your SOPS tokens store (nixos/secrets.yaml -> appctl/tokens_json):\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"{json_snippet}\n\n"
f"After updating nixos/secrets.yaml with `sops nixos/secrets.yaml`, apply changes with:\n" f"After updating nixos/secrets.yaml with `sops nixos/secrets.yaml`, apply changes with:\n"
f" sudo nixos-rebuild switch --flake ~/Core#server\n" f" sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure\n"
) )
return 0 return 0
+16 -6
View File
@@ -72,10 +72,25 @@ RESERVED_ENV_KEYS = {
"SITES_DIR", "SITES_DIR",
"ENV_FILE", "ENV_FILE",
"HOMESERVER_ENV", "HOMESERVER_ENV",
"HOMELAB_DOMAIN",
"DOMAIN_SUFFIX",
"DOMAIN",
"PROXY_NETWORK",
"CERT_RESOLVER",
"DOCKER_CONFIG",
"SERVICE_NAME",
"CONTAINER_NAME",
"SERVICE_DOMAIN",
} }
ALLOWED_STRATEGIES = {"compose"} ALLOWED_STRATEGIES = {"compose"}
ALLOWED_ACTIONS = {"git_pull", "compose_pull", "compose_up", "compose_build", "compose_restart"} ALLOWED_ACTIONS = {
"git_pull",
"compose_pull",
"compose_up",
"compose_build",
"compose_restart",
}
def validate_transport(url: str) -> tuple[TransportScheme, str]: def validate_transport(url: str) -> tuple[TransportScheme, str]:
@@ -168,13 +183,11 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]:
return RefType.BRANCH, ref return RefType.BRANCH, ref
class SourceConfig(BaseModel): class SourceConfig(BaseModel):
"""Upstream source provenance descriptor.""" """Upstream source provenance descriptor."""
model_config = ConfigDict(extra="forbid", ignored_types=(dict,)) model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
url: str url: str
ref: str = "main" ref: str = "main"
type: str = "git" type: str = "git"
@@ -223,7 +236,6 @@ class DeploymentConfig(BaseModel):
model_config = ConfigDict(extra="forbid", ignored_types=(dict,)) model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
strategy: str = "compose" strategy: str = "compose"
branch: str = "main" branch: str = "main"
actions: list[str] = Field(default_factory=lambda: ["git_pull", "compose_up"]) actions: list[str] = Field(default_factory=lambda: ["git_pull", "compose_up"])
@@ -264,7 +276,6 @@ class HomepageConfig(BaseModel):
model_config = ConfigDict(extra="forbid", ignored_types=(dict,)) model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
title: str title: str
group: str = "Applications" group: str = "Applications"
icon: str = "default.png" icon: str = "default.png"
@@ -295,7 +306,6 @@ class Manifest(BaseModel):
ignored_types=(dict,), ignored_types=(dict,),
) )
name: str name: str
schema_version: str = Field(default="1.0", alias="schemaVersion") schema_version: str = Field(default="1.0", alias="schemaVersion")
domain: str = "" domain: str = ""
+13 -4
View File
@@ -110,7 +110,9 @@ def execute_deployment_via_daemon(
timeout=330.0, timeout=330.0,
) )
if resp.success: if resp.success:
logger.info(f"✨ Deployment of '{target}' via daemon completed successfully.") logger.info(
f"✨ Deployment of '{target}' via daemon completed successfully."
)
return True return True
err_msg = resp.error.message if resp.error else "Unknown daemon error" err_msg = resp.error.message if resp.error else "Unknown daemon error"
logger.error(f"❌ Deployment of '{target}' via daemon failed: {err_msg}") logger.error(f"❌ Deployment of '{target}' via daemon failed: {err_msg}")
@@ -407,8 +409,6 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
return target_dir, deployment_config return target_dir, deployment_config
PROHIBITED_HOST_NAMESPACES = {"host"} PROHIBITED_HOST_NAMESPACES = {"host"}
DANGEROUS_SECURITY_OPTS = {"unconfined", "apparmor:unconfined", "seccomp:unconfined"} DANGEROUS_SECURITY_OPTS = {"unconfined", "apparmor:unconfined", "seccomp:unconfined"}
@@ -607,6 +607,8 @@ def validate_compose_security(
) )
if ":" in vol: if ":" in vol:
host_path = vol.split(":")[0].strip() host_path = vol.split(":")[0].strip()
else:
host_path = vol.strip()
elif isinstance(vol, dict): elif isinstance(vol, dict):
src = str(vol.get("source", "")) src = str(vol.get("source", ""))
if "/var/run/docker.sock" in src: if "/var/run/docker.sock" in src:
@@ -614,12 +616,19 @@ def validate_compose_security(
False, False,
f"Service '{svc_name}' directly mounts Docker socket: {src}.", f"Service '{svc_name}' directly mounts Docker socket: {src}.",
) )
if vol.get("type") == "bind": vol_type = vol.get("type")
if vol_type in ("bind", "volume") or (vol_type is None and src):
host_path = src host_path = src
if not host_path: if not host_path:
continue continue
if "${" in host_path or "}" in host_path:
return (
False,
f"Service '{svc_name}' specifies prohibited variable interpolation in volume host path: '{host_path}'.",
)
# Declared top-level named volume without path separators # Declared top-level named volume without path separators
if host_path in top_volumes and not ( if host_path in top_volumes and not (
host_path.startswith((".", "/", "~")) host_path.startswith((".", "/", "~"))
+10 -2
View File
@@ -109,6 +109,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
# 1. Check cleanliness # 1. Check cleanliness
is_dirty = False is_dirty = False
git_error: str | None = None
try: try:
status_res = subprocess.run( status_res = subprocess.run(
["git", "-C", str(path), "status", "--porcelain"], ["git", "-C", str(path), "status", "--porcelain"],
@@ -118,10 +119,14 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
timeout=5.0, timeout=5.0,
env=git_env, env=git_env,
) )
if status_res.returncode == 0 and status_res.stdout.strip(): if status_res.returncode == 0:
if status_res.stdout.strip():
is_dirty = True is_dirty = True
except (subprocess.SubprocessError, OSError): else:
git_error = f"⚠️ Git Error (exit {status_res.returncode})"
except (subprocess.SubprocessError, OSError) as exc:
is_dirty = False is_dirty = False
git_error = f"⚠️ Git Error ({exc.__class__.__name__})"
# 2. Get active branch # 2. Get active branch
branch = "" branch = ""
@@ -168,6 +173,9 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
commit_sha = "" commit_sha = ""
# 4. Format status label # 4. Format status label
if git_error:
status_label = git_error
else:
state_symbol = "* Dirty" if is_dirty else "✓ Clean" state_symbol = "* Dirty" if is_dirty else "✓ Clean"
ref_desc = f"{branch}@{commit_sha}" if commit_sha else branch ref_desc = f"{branch}@{commit_sha}" if commit_sha else branch
status_label = f"{state_symbol} ({ref_desc})" if ref_desc else state_symbol status_label = f"{state_symbol} ({ref_desc})" if ref_desc else state_symbol
+92
View File
@@ -1068,3 +1068,95 @@ services:
) )
assert valid is False assert valid is False
assert err is not None and "security_opt" in err.lower() assert err is not None and "security_opt" in err.lower()
def test_validate_compose_security_rejects_dict_volume_without_type_bind(
tmp_path: Path,
):
"""Ensure dictionary volume declarations without explicit type: bind enforce host containment (CR-DI-01)."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
volumes:
- source: /etc/shadow
target: /app/shadow
""",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is False
assert err is not None and "prohibited host bind mount" in err.lower()
def test_validate_compose_security_rejects_variable_interpolation_in_volume_host_path(
tmp_path: Path,
):
"""Ensure volume host paths containing variable interpolation (${...}) fail closed (CR-DI-02)."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
volumes:
- "${HOST_DIR}/data:/data"
""",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is False
assert err is not None and "variable interpolation" in err.lower()
def test_validate_compose_security_rejects_variable_interpolation_in_dict_volume_source(
tmp_path: Path,
):
"""Ensure dictionary volume source containing variable interpolation (${...}) fails closed (CR-DI-02)."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
volumes:
- source: "${HOST_DIR}/data"
target: /data
""",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is False
assert err is not None and "variable interpolation" in err.lower()
def test_validate_compose_security_allows_valid_dict_volume_within_workload(
tmp_path: Path,
):
"""Ensure valid dictionary volume within workload root is accepted even without type: bind."""
(tmp_path / "data").mkdir()
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
app:
image: alpine
volumes:
- source: ./data
target: /data
""",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is True
assert err is None
@@ -419,3 +419,55 @@ def test_gitignore_includes_instance_nix():
) )
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 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}/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/Sites/*" in safe_dirs, (
f"Expected '/home/operator/Sites/*' in git safe.directory, got {safe_dirs}"
)
+25
View File
@@ -232,6 +232,31 @@ def test_redact_sensitive_data_masks_secret_keys():
assert redacted["nested"]["list_items"][1] == "safe_string" 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( def test_audit_logger_automatically_redacts_sensitive_parameters(
temp_audit_file: Path, sample_principal: PrincipalAudit temp_audit_file: Path, sample_principal: PrincipalAudit
): ):
+134 -34
View File
@@ -37,8 +37,12 @@ def secret_tokens() -> dict[str, str]:
@pytest.fixture @pytest.fixture
def temp_tokens_file(tmp_path: Path, secret_tokens: dict[str, str]) -> Path: def temp_tokens_file(tmp_path: Path, secret_tokens: dict[str, str]) -> Path:
tokens_path = tmp_path / "tokens.json" tokens_path = tmp_path / "tokens.json"
admin_hash = hashlib.sha256(secret_tokens["admin_secret"].encode("utf-8")).hexdigest() admin_hash = hashlib.sha256(
op_hash = hashlib.sha256(secret_tokens["operator_secret"].encode("utf-8")).hexdigest() secret_tokens["admin_secret"].encode("utf-8")
).hexdigest()
op_hash = hashlib.sha256(
secret_tokens["operator_secret"].encode("utf-8")
).hexdigest()
data = [ data = [
{ {
@@ -121,6 +125,31 @@ def test_token_store_authenticates_valid_bearer_secrets(
assert p_op.token_id == "tok_gitops_01" 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): def test_token_store_rejects_invalid_bearer_secret(temp_tokens_file: Path):
store = TokenStore(temp_tokens_file) store = TokenStore(temp_tokens_file)
@@ -178,7 +207,9 @@ def test_authenticate_request_over_uds_falls_back_to_viewer(
# Explicit Bearer token over UDS confers full privileges # Explicit Bearer token over UDS confers full privileges
auth_header = f"Bearer {secret_tokens['admin_secret']}" auth_header = f"Bearer {secret_tokens['admin_secret']}"
p_admin = authenticate_request("unix_socket", auth_header, peer_uid=1000, token_store=store) p_admin = authenticate_request(
"unix_socket", auth_header, peer_uid=1000, token_store=store
)
assert p_admin.role == Role.ADMIN assert p_admin.role == Role.ADMIN
assert p_admin.auth_method == "bearer_token" assert p_admin.auth_method == "bearer_token"
@@ -196,7 +227,8 @@ def test_authenticate_request_over_uds_rejects_missing_peer_uid():
def test_load_admitted_workloads_parses_names_and_aliases(tmp_path: Path): def test_load_admitted_workloads_parses_names_and_aliases(tmp_path: Path):
deploy_file = tmp_path / "deployments.yaml" deploy_file = tmp_path / "deployments.yaml"
deploy_file.write_text(""" deploy_file.write_text(
"""
schemaVersion: "1.0" schemaVersion: "1.0"
repositories: repositories:
snappymail: snappymail:
@@ -208,7 +240,9 @@ repositories:
path: "/home/operator/Sites/homelab-jellyfin" path: "/home/operator/Sites/homelab-jellyfin"
aliases: aliases:
- "media" - "media"
""", encoding="utf-8") """,
encoding="utf-8",
)
admitted = load_admitted_workloads(deploy_file) admitted = load_admitted_workloads(deploy_file)
assert "snappymail" in admitted assert "snappymail" in admitted
@@ -221,14 +255,19 @@ repositories:
def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: Path): def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: Path):
deploy_file = tmp_path / "deployments.json" deploy_file = tmp_path / "deployments.json"
deploy_file.write_text(json.dumps({ deploy_file.write_text(
json.dumps(
{
"repositories": { "repositories": {
"app1": { "app1": {
"path": "/home/operator/Sites/app1", "path": "/home/operator/Sites/app1",
"aliases": [123, None, " ", "valid_alias"] "aliases": [123, None, " ", "valid_alias"],
} }
} }
}), encoding="utf-8") }
),
encoding="utf-8",
)
admitted = load_admitted_workloads(deploy_file) admitted = load_admitted_workloads(deploy_file)
assert "app1" in admitted assert "app1" in admitted
@@ -238,13 +277,17 @@ def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: P
assert "" not in admitted assert "" not in admitted
def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): def test_load_admitted_workloads_fails_closed_on_missing_file(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
admitted = load_admitted_workloads(tmp_path / "missing.yaml") admitted = load_admitted_workloads(tmp_path / "missing.yaml")
assert admitted == set() assert admitted == set()
# Test HOMELAB_DEPLOYMENTS_FILE fallback # Test HOMELAB_DEPLOYMENTS_FILE fallback
deploy_file = tmp_path / "env_deploy.yaml" deploy_file = tmp_path / "env_deploy.yaml"
deploy_file.write_text("repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8") deploy_file.write_text(
"repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8"
)
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deploy_file)) monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deploy_file))
admitted_env = load_admitted_workloads(None) admitted_env = load_admitted_workloads(None)
assert "env_app" in admitted_env assert "env_app" in admitted_env
@@ -258,12 +301,16 @@ def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path, mo
def test_rbac_admin_permitted_across_all_operations_and_targets( def test_rbac_admin_permitted_across_all_operations_and_targets(
admitted_workloads: set[str], admitted_workloads: set[str],
): ):
admin = Principal(identity="admin_user", role=Role.ADMIN, auth_method="bearer_token") admin = Principal(
identity="admin_user", role=Role.ADMIN, auth_method="bearer_token"
)
# Mutations across Core and Sites # Mutations across Core and Sites
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads) enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads)
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "traefik", admitted_workloads) enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "traefik", admitted_workloads)
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads) enforce_rbac(
admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads
)
enforce_rbac(admin, OperationType.WORKLOAD_CONFIG, "core", admitted_workloads) enforce_rbac(admin, OperationType.WORKLOAD_CONFIG, "core", admitted_workloads)
enforce_rbac(admin, OperationType.WORKLOAD_LOGS, "traefik", 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.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads)
@@ -273,79 +320,128 @@ def test_rbac_admin_permitted_across_all_operations_and_targets(
def test_rbac_operator_permitted_on_admitted_workloads( def test_rbac_operator_permitted_on_admitted_workloads(
admitted_workloads: set[str], admitted_workloads: set[str],
): ):
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") operator = Principal(
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
# Permitted on admitted workload # Permitted on admitted workload
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads) enforce_rbac(
operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads
)
enforce_rbac(operator, OperationType.WORKLOAD_UPDATE, "mail", admitted_workloads) enforce_rbac(operator, OperationType.WORKLOAD_UPDATE, "mail", admitted_workloads)
enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads) enforce_rbac(
operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads
)
enforce_rbac(operator, OperationType.WORKLOAD_LOGS, "docs", admitted_workloads) enforce_rbac(operator, OperationType.WORKLOAD_LOGS, "docs", admitted_workloads)
enforce_rbac(operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads) enforce_rbac(
operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads
)
enforce_rbac(operator, OperationType.WORKLOAD_LIST, None, admitted_workloads) enforce_rbac(operator, OperationType.WORKLOAD_LIST, None, admitted_workloads)
def test_rbac_operator_denied_on_core_targets( def test_rbac_operator_denied_on_core_targets(
admitted_workloads: set[str], admitted_workloads: set[str],
): ):
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") operator = Principal(
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
# Targeting "core" stack # Targeting "core" stack
with pytest.raises(AuthorizationError) as exc_info: with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads) enforce_rbac(
operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads
)
assert "not permitted to target core service 'core'" in str(exc_info.value) assert "not permitted to target core service 'core'" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
# Targeting core services (traefik, stalwart, etc.) # Targeting core services (traefik, stalwart, etc.)
for core_svc in ["traefik", "authelia", "stalwart", "socket-proxy"]: for core_svc in ["traefik", "authelia", "stalwart", "socket-proxy"]:
with pytest.raises(AuthorizationError) as exc_info: with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads) enforce_rbac(
assert f"not permitted to target core service '{core_svc}'" in str(exc_info.value) 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 assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_operator_denied_without_target_on_mutating_or_sensitive_ops( def test_rbac_operator_denied_without_target_on_mutating_or_sensitive_ops(
admitted_workloads: set[str], admitted_workloads: set[str],
): ):
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") operator = Principal(
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
for op in [OperationType.WORKLOAD_DEPLOY, OperationType.WORKLOAD_UPDATE, OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]: for op in [
OperationType.WORKLOAD_DEPLOY,
OperationType.WORKLOAD_UPDATE,
OperationType.WORKLOAD_CONFIG,
OperationType.WORKLOAD_LOGS,
]:
with pytest.raises(AuthorizationError) as exc_info: with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, op, None, admitted_workloads) enforce_rbac(operator, op, None, admitted_workloads)
assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value) assert f"Operation '{op.value}' requires an explicit workload target" in str(
exc_info.value
)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
with pytest.raises(AuthorizationError) as exc_info: with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, op, "", admitted_workloads) enforce_rbac(operator, op, "", admitted_workloads)
assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value) assert f"Operation '{op.value}' requires an explicit workload target" in str(
exc_info.value
)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_operator_with_default_admitted_workloads(monkeypatch: pytest.MonkeyPatch, tmp_path: Path): def test_rbac_operator_with_default_admitted_workloads(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
):
deployments_file = tmp_path / "deployments.yaml" deployments_file = tmp_path / "deployments.yaml"
deployments_file.write_text("repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8") deployments_file.write_text(
"repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8"
)
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file)) monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file))
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") operator = Principal(
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "customapp", admitted_workloads=None) 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: with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unknownapp", admitted_workloads=None) enforce_rbac(
operator,
OperationType.WORKLOAD_DEPLOY,
"unknownapp",
admitted_workloads=None,
)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_operator_denied_on_unregistered_workload( def test_rbac_operator_denied_on_unregistered_workload(
admitted_workloads: set[str], admitted_workloads: set[str],
): ):
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") operator = Principal(
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
with pytest.raises(AuthorizationError) as exc_info: with pytest.raises(AuthorizationError) as exc_info:
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unregistered_app", admitted_workloads) enforce_rbac(
operator,
OperationType.WORKLOAD_DEPLOY,
"unregistered_app",
admitted_workloads,
)
assert "not registered in deployments.yaml" in str(exc_info.value) assert "not registered in deployments.yaml" in str(exc_info.value)
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
def test_rbac_viewer_permitted_only_on_non_sensitive_reads(): def test_rbac_viewer_permitted_only_on_non_sensitive_reads():
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred") viewer = Principal(
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
)
# Permitted reads # Permitted reads
enforce_rbac(viewer, OperationType.WORKLOAD_LIST, None) enforce_rbac(viewer, OperationType.WORKLOAD_LIST, None)
@@ -356,7 +452,9 @@ def test_rbac_viewer_permitted_only_on_non_sensitive_reads():
def test_rbac_viewer_denied_on_mutations(): def test_rbac_viewer_denied_on_mutations():
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred") viewer = Principal(
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
)
mutations = [ mutations = [
OperationType.WORKLOAD_DEPLOY, OperationType.WORKLOAD_DEPLOY,
@@ -374,7 +472,9 @@ def test_rbac_viewer_denied_on_mutations():
def test_rbac_viewer_denied_on_sensitive_reads(): def test_rbac_viewer_denied_on_sensitive_reads():
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred") viewer = Principal(
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
)
for sens_op in [OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]: for sens_op in [OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]:
with pytest.raises(AuthorizationError) as exc_info: with pytest.raises(AuthorizationError) as exc_info:
+270 -68
View File
@@ -11,6 +11,7 @@ from pathlib import Path
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
import pytest import pytest
import yaml
from appctl_audit import AuditLogger, TargetLockManager from appctl_audit import AuditLogger, TargetLockManager
from appctl_auth import Principal, Role from appctl_auth import Principal, Role
from appctl_contracts import ErrorCode, OperationRequest from appctl_contracts import ErrorCode, OperationRequest
@@ -77,7 +78,9 @@ services:
container_name: "snappymail" container_name: "snappymail"
restart: "unless-stopped" restart: "unless-stopped"
""" """
(app_dir / "docker-compose.yml").write_text(compose_content.strip(), encoding="utf-8") (app_dir / "docker-compose.yml").write_text(
compose_content.strip(), encoding="utf-8"
)
return app_dir return app_dir
@@ -88,12 +91,16 @@ def admin_principal() -> Principal:
@pytest.fixture @pytest.fixture
def operator_principal() -> Principal: def operator_principal() -> Principal:
return Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") return Principal(
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
)
@pytest.fixture @pytest.fixture
def viewer_principal() -> Principal: def viewer_principal() -> Principal:
return Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred") return Principal(
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -103,14 +110,17 @@ def viewer_principal() -> Principal:
def test_parse_dotenv_parses_valid_key_values(tmp_path: Path): def test_parse_dotenv_parses_valid_key_values(tmp_path: Path):
env_file = tmp_path / ".env" env_file = tmp_path / ".env"
env_file.write_text(""" env_file.write_text(
"""
# Comment line # Comment line
APP_PORT=8080 APP_PORT=8080
APP_HOST="127.0.0.1" APP_HOST="127.0.0.1"
SINGLE_QUOTE='single_val' SINGLE_QUOTE='single_val'
EMPTY_VAL= EMPTY_VAL=
WITH_EQUALS=key=value=more WITH_EQUALS=key=value=more
""", encoding="utf-8") """,
encoding="utf-8",
)
parsed = parse_dotenv(env_file) parsed = parse_dotenv(env_file)
assert parsed["APP_PORT"] == "8080" assert parsed["APP_PORT"] == "8080"
@@ -122,11 +132,14 @@ WITH_EQUALS=key=value=more
def test_parse_dotenv_preserves_shell_injection_as_inert_literals(tmp_path: Path): def test_parse_dotenv_preserves_shell_injection_as_inert_literals(tmp_path: Path):
env_file = tmp_path / ".env" env_file = tmp_path / ".env"
env_file.write_text(""" env_file.write_text(
"""
INJECTION_ONE=$(touch /tmp/pwned) INJECTION_ONE=$(touch /tmp/pwned)
INJECTION_TWO=`cat /etc/passwd` INJECTION_TWO=`cat /etc/passwd`
VARIABLE_REF=$HOMELAB_DOMAIN VARIABLE_REF=$HOMELAB_DOMAIN
""", encoding="utf-8") """,
encoding="utf-8",
)
parsed = parse_dotenv(env_file) parsed = parse_dotenv(env_file)
assert parsed["INJECTION_ONE"] == "$(touch /tmp/pwned)" assert parsed["INJECTION_ONE"] == "$(touch /tmp/pwned)"
@@ -187,7 +200,6 @@ def test_resolve_canonical_domain_precedence(monkeypatch: pytest.MonkeyPatch):
assert resolve_canonical_domain() == "stripped.example.test" assert resolve_canonical_domain() == "stripped.example.test"
def test_assemble_workload_env_constructs_6_layer_environment( def test_assemble_workload_env_constructs_6_layer_environment(
mock_workload_dir: Path, monkeypatch: pytest.MonkeyPatch mock_workload_dir: Path, monkeypatch: pytest.MonkeyPatch
): ):
@@ -195,7 +207,9 @@ def test_assemble_workload_env_constructs_6_layer_environment(
manifest = parse_manifest(mock_workload_dir / "app.yaml") manifest = parse_manifest(mock_workload_dir / "app.yaml")
# Add local .env # Add local .env
(mock_workload_dir / ".env").write_text("LOCAL_ENV_VAR=local_val\n", encoding="utf-8") (mock_workload_dir / ".env").write_text(
"LOCAL_ENV_VAR=local_val\n", encoding="utf-8"
)
env = assemble_workload_env(mock_workload_dir, manifest, "snappymail") env = assemble_workload_env(mock_workload_dir, manifest, "snappymail")
@@ -292,7 +306,9 @@ services:
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def test_operational_router_dispatches_platform_health(tmp_path: Path, admin_principal: Principal): def test_operational_router_dispatches_platform_health(
tmp_path: Path, admin_principal: Principal
):
router = OperationalRouter( router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"), audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"), lock_manager=TargetLockManager(tmp_path / "locks"),
@@ -325,10 +341,12 @@ def test_operational_router_enforces_rbac_denial(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"), audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"), lock_manager=TargetLockManager(tmp_path / "locks"),
) )
req = OperationRequest.model_validate({ req = OperationRequest.model_validate(
{
"operation": "workload.deploy", "operation": "workload.deploy",
"target": "snappymail", "target": "snappymail",
}) }
)
resp = router.dispatch(req, viewer_principal) resp = router.dispatch(req, viewer_principal)
assert resp.success is False assert resp.success is False
assert resp.error is not None assert resp.error is not None
@@ -342,10 +360,12 @@ def test_operational_router_rejects_non_existent_target(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"), audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"), lock_manager=TargetLockManager(tmp_path / "locks"),
) )
req = OperationRequest.model_validate({ req = OperationRequest.model_validate(
{
"operation": "workload.get", "operation": "workload.get",
"target": "nonexistent_workload_999", "target": "nonexistent_workload_999",
}) }
)
resp = router.dispatch(req, admin_principal) resp = router.dispatch(req, admin_principal)
assert resp.success is False assert resp.success is False
assert resp.error is not None assert resp.error is not None
@@ -360,10 +380,12 @@ def test_operational_router_rejects_concurrent_mutation(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"), audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=lock_mgr, lock_manager=lock_mgr,
) )
req = OperationRequest.model_validate({ req = OperationRequest.model_validate(
{
"operation": "workload.deploy", "operation": "workload.deploy",
"target": "snappymail", "target": "snappymail",
}) }
)
mock_app = MagicMock() mock_app = MagicMock()
mock_app.name = "snappymail" mock_app.name = "snappymail"
@@ -388,11 +410,13 @@ def test_operational_router_dispatches_workload_deploy(
lock_manager=TargetLockManager(tmp_path / "locks"), lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_workload_dir.parent, sites_dir=mock_workload_dir.parent,
) )
req = OperationRequest.model_validate({ req = OperationRequest.model_validate(
{
"operation": "workload.deploy", "operation": "workload.deploy",
"target": "snappymail", "target": "snappymail",
"parameters": {"recreate": True, "remove_orphans": True, "build": False}, "parameters": {"recreate": True, "remove_orphans": True, "build": False},
}) }
)
mock_app = MagicMock() mock_app = MagicMock()
mock_app.name = "snappymail" mock_app.name = "snappymail"
@@ -400,7 +424,10 @@ def test_operational_router_dispatches_workload_deploy(
with ( with (
patch("appctl_router.resolve_app", return_value=mock_app), patch("appctl_router.resolve_app", return_value=mock_app),
patch("appctl_router.run_bounded_subprocess", return_value=(0, "Container started", "")) as mock_run, patch(
"appctl_router.run_bounded_subprocess",
return_value=(0, "Container started", ""),
) as mock_run,
patch("appctl_router.cmd_sync_homepage"), patch("appctl_router.cmd_sync_homepage"),
): ):
resp = router.dispatch(req, admin_principal) resp = router.dispatch(req, admin_principal)
@@ -424,11 +451,13 @@ def test_operational_router_workload_deploy_build_flags(
mock_app.dir_path = str(mock_workload_dir) mock_app.dir_path = str(mock_workload_dir)
# 1. Deploy with build=True passes --pull # 1. Deploy with build=True passes --pull
req_build = OperationRequest.model_validate({ req_build = OperationRequest.model_validate(
{
"operation": "workload.deploy", "operation": "workload.deploy",
"target": "snappymail", "target": "snappymail",
"parameters": {"build": True}, "parameters": {"build": True},
}) }
)
executed_commands: list[list[str]] = [] executed_commands: list[list[str]] = []
def mock_subproc(cmd: list[str], **kwargs): def mock_subproc(cmd: list[str], **kwargs):
@@ -445,15 +474,22 @@ def test_operational_router_workload_deploy_build_flags(
build_calls = [c for c in executed_commands if "build" in c] build_calls = [c for c in executed_commands if "build" in c]
assert len(build_calls) == 1 assert len(build_calls) == 1
assert build_calls[0] == [ assert build_calls[0] == [
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull" "docker",
"compose",
"-f",
str(mock_workload_dir / "docker-compose.yml"),
"build",
"--pull",
] ]
# 2. Deploy with no_cache=True passes --pull and --no-cache # 2. Deploy with no_cache=True passes --pull and --no-cache
req_no_cache = OperationRequest.model_validate({ req_no_cache = OperationRequest.model_validate(
{
"operation": "workload.deploy", "operation": "workload.deploy",
"target": "snappymail", "target": "snappymail",
"parameters": {"no_cache": True}, "parameters": {"no_cache": True},
}) }
)
executed_commands.clear() executed_commands.clear()
with ( with (
@@ -466,7 +502,13 @@ def test_operational_router_workload_deploy_build_flags(
build_calls = [c for c in executed_commands if "build" in c] build_calls = [c for c in executed_commands if "build" in c]
assert len(build_calls) == 1 assert len(build_calls) == 1
assert build_calls[0] == [ assert build_calls[0] == [
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull", "--no-cache" "docker",
"compose",
"-f",
str(mock_workload_dir / "docker-compose.yml"),
"build",
"--pull",
"--no-cache",
] ]
@@ -478,10 +520,12 @@ def test_operational_router_workload_update_rejects_dirty_git_tree(
lock_manager=TargetLockManager(tmp_path / "locks"), lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_workload_dir.parent, sites_dir=mock_workload_dir.parent,
) )
req = OperationRequest.model_validate({ req = OperationRequest.model_validate(
{
"operation": "workload.update", "operation": "workload.update",
"target": "snappymail", "target": "snappymail",
}) }
)
mock_app = MagicMock() mock_app = MagicMock()
mock_app.name = "snappymail" mock_app.name = "snappymail"
@@ -512,11 +556,13 @@ def test_operational_router_workload_update_rejects_branch_mismatch(
lock_manager=TargetLockManager(tmp_path / "locks"), lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_workload_dir.parent, sites_dir=mock_workload_dir.parent,
) )
req = OperationRequest.model_validate({ req = OperationRequest.model_validate(
{
"operation": "workload.update", "operation": "workload.update",
"target": "snappymail", "target": "snappymail",
"parameters": {"expected_branch": "feature/branch"}, "parameters": {"expected_branch": "feature/branch"},
}) }
)
mock_app = MagicMock() mock_app = MagicMock()
mock_app.name = "snappymail" mock_app.name = "snappymail"
@@ -550,11 +596,13 @@ def test_operational_router_workload_update_succeeds_on_clean_tree(
lock_manager=TargetLockManager(tmp_path / "locks"), lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_workload_dir.parent, sites_dir=mock_workload_dir.parent,
) )
req = OperationRequest.model_validate({ req = OperationRequest.model_validate(
{
"operation": "workload.update", "operation": "workload.update",
"target": "snappymail", "target": "snappymail",
"parameters": {"expected_branch": "main"}, "parameters": {"expected_branch": "main"},
}) }
)
mock_app = MagicMock() mock_app = MagicMock()
mock_app.name = "snappymail" mock_app.name = "snappymail"
@@ -611,11 +659,13 @@ def test_operational_router_workload_update_build_and_no_cache_flags(
return 0, "success", "" return 0, "success", ""
# 1. Update with build=True # 1. Update with build=True
req_build = OperationRequest.model_validate({ req_build = OperationRequest.model_validate(
{
"operation": "workload.update", "operation": "workload.update",
"target": "snappymail", "target": "snappymail",
"parameters": {"build": True}, "parameters": {"build": True},
}) }
)
with ( with (
patch("appctl_router.resolve_app", return_value=mock_app), patch("appctl_router.resolve_app", return_value=mock_app),
@@ -627,18 +677,25 @@ def test_operational_router_workload_update_build_and_no_cache_flags(
build_calls = [c for c in executed_commands if "build" in c] build_calls = [c for c in executed_commands if "build" in c]
assert len(build_calls) == 1 assert len(build_calls) == 1
assert build_calls[0] == [ assert build_calls[0] == [
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull" "docker",
"compose",
"-f",
str(mock_workload_dir / "docker-compose.yml"),
"build",
"--pull",
] ]
# Also ensure compose_up was executed # Also ensure compose_up was executed
up_calls = [c for c in executed_commands if "up" in c] up_calls = [c for c in executed_commands if "up" in c]
assert len(up_calls) == 1 assert len(up_calls) == 1
# 2. Update with no_cache=True implies build=True and appends --no-cache # 2. Update with no_cache=True implies build=True and appends --no-cache
req_no_cache = OperationRequest.model_validate({ req_no_cache = OperationRequest.model_validate(
{
"operation": "workload.update", "operation": "workload.update",
"target": "snappymail", "target": "snappymail",
"parameters": {"no_cache": True}, "parameters": {"no_cache": True},
}) }
)
executed_commands.clear() executed_commands.clear()
with ( with (
@@ -651,7 +708,13 @@ def test_operational_router_workload_update_build_and_no_cache_flags(
build_calls = [c for c in executed_commands if "build" in c] build_calls = [c for c in executed_commands if "build" in c]
assert len(build_calls) == 1 assert len(build_calls) == 1
assert build_calls[0] == [ assert build_calls[0] == [
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull", "--no-cache" "docker",
"compose",
"-f",
str(mock_workload_dir / "docker-compose.yml"),
"build",
"--pull",
"--no-cache",
] ]
up_calls = [c for c in executed_commands if "up" in c] up_calls = [c for c in executed_commands if "up" in c]
assert len(up_calls) == 1 assert len(up_calls) == 1
@@ -675,7 +738,9 @@ deployment:
- "compose_build" - "compose_build"
- "compose_up" - "compose_up"
""" """
(mock_workload_dir / "app.yaml").write_text(manifest_content.strip(), encoding="utf-8") (mock_workload_dir / "app.yaml").write_text(
manifest_content.strip(), encoding="utf-8"
)
router = OperationalRouter( router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"), audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
@@ -699,10 +764,12 @@ deployment:
return 0, "success", "" return 0, "success", ""
# Update with declared compose_build invokes build --pull # Update with declared compose_build invokes build --pull
req = OperationRequest.model_validate({ req = OperationRequest.model_validate(
{
"operation": "workload.update", "operation": "workload.update",
"target": "snappymail", "target": "snappymail",
}) }
)
with ( with (
patch("appctl_router.resolve_app", return_value=mock_app), patch("appctl_router.resolve_app", return_value=mock_app),
@@ -714,7 +781,12 @@ deployment:
build_calls = [c for c in executed_commands if "build" in c] build_calls = [c for c in executed_commands if "build" in c]
assert len(build_calls) == 1 assert len(build_calls) == 1
assert build_calls[0] == [ assert build_calls[0] == [
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull" "docker",
"compose",
"-f",
str(mock_workload_dir / "docker-compose.yml"),
"build",
"--pull",
] ]
@@ -738,7 +810,9 @@ services:
image: "authelia/authelia:latest" image: "authelia/authelia:latest"
container_name: "authelia" container_name: "authelia"
""" """
(mock_core_dir / "docker-compose.yml").write_text(compose_content.strip(), encoding="utf-8") (mock_core_dir / "docker-compose.yml").write_text(
compose_content.strip(), encoding="utf-8"
)
router = OperationalRouter( router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"), audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
@@ -759,7 +833,9 @@ services:
): ):
# 1. Deploy core stack # 1. Deploy core stack
resp_deploy = router.dispatch( resp_deploy = router.dispatch(
OperationRequest.model_validate({"operation": "workload.deploy", "target": "core"}), OperationRequest.model_validate(
{"operation": "workload.deploy", "target": "core"}
),
admin_principal, admin_principal,
) )
assert resp_deploy.success is True assert resp_deploy.success is True
@@ -775,7 +851,9 @@ services:
# 2. Stop core stack (uses `down` for full stack) # 2. Stop core stack (uses `down` for full stack)
resp_stop = router.dispatch( resp_stop = router.dispatch(
OperationRequest.model_validate({"operation": "workload.stop", "target": "core"}), OperationRequest.model_validate(
{"operation": "workload.stop", "target": "core"}
),
admin_principal, admin_principal,
) )
assert resp_stop.success is True assert resp_stop.success is True
@@ -789,7 +867,9 @@ services:
# 3. Restart core stack # 3. Restart core stack
resp_restart = router.dispatch( resp_restart = router.dispatch(
OperationRequest.model_validate({"operation": "workload.restart", "target": "core"}), OperationRequest.model_validate(
{"operation": "workload.restart", "target": "core"}
),
admin_principal, admin_principal,
) )
assert resp_restart.success is True assert resp_restart.success is True
@@ -803,7 +883,9 @@ services:
# 4. Config core stack # 4. Config core stack
resp_config = router.dispatch( resp_config = router.dispatch(
OperationRequest.model_validate({"operation": "workload.config", "target": "core"}), OperationRequest.model_validate(
{"operation": "workload.config", "target": "core"}
),
admin_principal, admin_principal,
) )
assert resp_config.success is True assert resp_config.success is True
@@ -845,7 +927,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations(
with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc): with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc):
# 1. Deploy single core service (traefik) # 1. Deploy single core service (traefik)
resp_deploy = router.dispatch( resp_deploy = router.dispatch(
OperationRequest.model_validate({"operation": "workload.deploy", "target": "traefik"}), OperationRequest.model_validate(
{"operation": "workload.deploy", "target": "traefik"}
),
admin_principal, admin_principal,
) )
assert resp_deploy.success is True assert resp_deploy.success is True
@@ -854,7 +938,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations(
# 2. Stop single core service (uses `stop traefik`, NOT `down`) # 2. Stop single core service (uses `stop traefik`, NOT `down`)
resp_stop = router.dispatch( resp_stop = router.dispatch(
OperationRequest.model_validate({"operation": "workload.stop", "target": "traefik"}), OperationRequest.model_validate(
{"operation": "workload.stop", "target": "traefik"}
),
admin_principal, admin_principal,
) )
assert resp_stop.success is True assert resp_stop.success is True
@@ -869,7 +955,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations(
# 3. Restart single core service # 3. Restart single core service
resp_restart = router.dispatch( resp_restart = router.dispatch(
OperationRequest.model_validate({"operation": "workload.restart", "target": "traefik"}), OperationRequest.model_validate(
{"operation": "workload.restart", "target": "traefik"}
),
admin_principal, admin_principal,
) )
assert resp_restart.success is True assert resp_restart.success is True
@@ -884,7 +972,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations(
# 4. Pull single core service # 4. Pull single core service
resp_pull = router.dispatch( resp_pull = router.dispatch(
OperationRequest.model_validate({"operation": "workload.pull", "target": "traefik"}), OperationRequest.model_validate(
{"operation": "workload.pull", "target": "traefik"}
),
admin_principal, admin_principal,
) )
assert resp_pull.success is True assert resp_pull.success is True
@@ -909,7 +999,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations(
# 5. Logs single core service # 5. Logs single core service
resp_logs = router.dispatch( resp_logs = router.dispatch(
OperationRequest.model_validate({"operation": "workload.logs", "target": "traefik"}), OperationRequest.model_validate(
{"operation": "workload.logs", "target": "traefik"}
),
admin_principal, admin_principal,
) )
assert resp_logs.success is True assert resp_logs.success is True
@@ -945,7 +1037,9 @@ def test_operational_router_dispatches_core_update_without_manifest(
with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc): with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc):
resp = router.dispatch( resp = router.dispatch(
OperationRequest.model_validate({"operation": "workload.update", "target": "core"}), OperationRequest.model_validate(
{"operation": "workload.update", "target": "core"}
),
admin_principal, admin_principal,
) )
assert resp.success is True assert resp.success is True
@@ -968,7 +1062,9 @@ def test_operational_router_rejects_operator_role_on_core_targets(
) )
for target in ("core", "traefik", "authelia"): for target in ("core", "traefik", "authelia"):
resp = router.dispatch( resp = router.dispatch(
OperationRequest.model_validate({"operation": "workload.restart", "target": target}), OperationRequest.model_validate(
{"operation": "workload.restart", "target": target}
),
operator_principal, operator_principal,
) )
assert resp.success is False assert resp.success is False
@@ -991,10 +1087,12 @@ def test_operational_router_workload_list_honors_filter_params(
# Without --core: only Sites workloads (1) # Without --core: only Sites workloads (1)
resp_sites = router.dispatch( resp_sites = router.dispatch(
OperationRequest.model_validate({ OperationRequest.model_validate(
{
"operation": "workload.list", "operation": "workload.list",
"parameters": {"core": False, "fetch": False, "ssl": False}, "parameters": {"core": False, "fetch": False, "ssl": False},
}), }
),
viewer_principal, viewer_principal,
) )
assert resp_sites.success is True assert resp_sites.success is True
@@ -1003,12 +1101,17 @@ def test_operational_router_workload_list_honors_filter_params(
assert resp_sites.result["workloads"][0]["name"] == "snappymail" assert resp_sites.result["workloads"][0]["name"] == "snappymail"
# With --core and --ssl: includes Core services and SSL inspection # With --core and --ssl: includes Core services and SSL inspection
with patch("appctl_router.check_ssl_cert", return_value={"status": "🟢 80d remaining", "domain": "example.test"}) as mock_ssl: with patch(
"appctl_router.check_ssl_cert",
return_value={"status": "🟢 80d remaining", "domain": "example.test"},
) as mock_ssl:
resp_core = router.dispatch( resp_core = router.dispatch(
OperationRequest.model_validate({ OperationRequest.model_validate(
{
"operation": "workload.list", "operation": "workload.list",
"parameters": {"core": True, "fetch": False, "ssl": True}, "parameters": {"core": True, "fetch": False, "ssl": True},
}), }
),
viewer_principal, viewer_principal,
) )
assert resp_core.success is True assert resp_core.success is True
@@ -1034,13 +1137,17 @@ def test_operational_router_workload_list_includes_live_docker_and_two_axis_stat
core_dir=mock_core_dir, core_dir=mock_core_dir,
) )
with patch("appctl_router.get_docker_status", return_value="🟢 Running (1)") as mock_docker: with patch(
"appctl_router.get_docker_status", return_value="🟢 Running (1)"
) as mock_docker:
# 1. Sites workload offline (fetch=False) # 1. Sites workload offline (fetch=False)
resp = router.dispatch( resp = router.dispatch(
OperationRequest.model_validate({ OperationRequest.model_validate(
{
"operation": "workload.list", "operation": "workload.list",
"parameters": {"core": False, "fetch": False, "ssl": False}, "parameters": {"core": False, "fetch": False, "ssl": False},
}), }
),
viewer_principal, viewer_principal,
) )
assert resp.success is True assert resp.success is True
@@ -1055,10 +1162,12 @@ def test_operational_router_workload_list_includes_live_docker_and_two_axis_stat
# 2. Core services included (core=True) # 2. Core services included (core=True)
resp_core = router.dispatch( resp_core = router.dispatch(
OperationRequest.model_validate({ OperationRequest.model_validate(
{
"operation": "workload.list", "operation": "workload.list",
"parameters": {"core": True, "fetch": False, "ssl": False}, "parameters": {"core": True, "fetch": False, "ssl": False},
}), }
),
viewer_principal, viewer_principal,
) )
assert resp_core.success is True assert resp_core.success is True
@@ -1095,10 +1204,12 @@ def test_operational_router_workload_list_fetch_passes_fetch_upstream(
mock_inspect.return_value = mock_two_axis mock_inspect.return_value = mock_two_axis
resp_fetch = router.dispatch( resp_fetch = router.dispatch(
OperationRequest.model_validate({ OperationRequest.model_validate(
{
"operation": "workload.list", "operation": "workload.list",
"parameters": {"core": False, "fetch": True, "ssl": False}, "parameters": {"core": False, "fetch": True, "ssl": False},
}), }
),
viewer_principal, viewer_principal,
) )
assert resp_fetch.success is True assert resp_fetch.success is True
@@ -1120,7 +1231,9 @@ def test_operational_router_workload_list_handles_manifest_error(
"""Ensure workload.list sets deployment_status and provenance_status correctly for apps with manifest errors.""" """Ensure workload.list sets deployment_status and provenance_status correctly for apps with manifest errors."""
broken_app_dir = mock_sites_dir / "broken-app" broken_app_dir = mock_sites_dir / "broken-app"
broken_app_dir.mkdir(parents=True, exist_ok=True) broken_app_dir.mkdir(parents=True, exist_ok=True)
(broken_app_dir / "app.yaml").write_text("invalid_yaml: [unclosed list", encoding="utf-8") (broken_app_dir / "app.yaml").write_text(
"invalid_yaml: [unclosed list", encoding="utf-8"
)
router = OperationalRouter( router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"), audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
@@ -1131,10 +1244,12 @@ def test_operational_router_workload_list_handles_manifest_error(
with patch("appctl_router.get_docker_status", return_value="🔴 Stopped"): with patch("appctl_router.get_docker_status", return_value="🔴 Stopped"):
resp = router.dispatch( resp = router.dispatch(
OperationRequest.model_validate({ OperationRequest.model_validate(
{
"operation": "workload.list", "operation": "workload.list",
"parameters": {"core": False, "fetch": False, "ssl": False}, "parameters": {"core": False, "fetch": False, "ssl": False},
}), }
),
viewer_principal, viewer_principal,
) )
assert resp.success is True assert resp.success is True
@@ -1147,5 +1262,92 @@ def test_operational_router_workload_list_handles_manifest_error(
assert broken["provenance_status"] == "⚠️ Invalid Manifest" assert broken["provenance_status"] == "⚠️ Invalid Manifest"
def test_operational_router_workload_config_redacts_evaluated_secrets_for_operator(
tmp_path: Path,
mock_sites_dir: Path,
mock_core_dir: Path,
):
"""Ensure workload.config redacts evaluated secrets in YAML output for non-admin operators (CR-DI-03)."""
router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_sites_dir,
core_dir=mock_core_dir,
)
workload_dir = mock_sites_dir / "docs"
workload_dir.mkdir(parents=True, exist_ok=True)
(workload_dir / "docker-compose.yml").write_text(
"services:\n docs:\n image: docs:latest\n"
)
(workload_dir / "app.yaml").write_text("name: docs\n")
operator_principal = Principal(
identity="alice", role=Role.OPERATOR, auth_method="bearer_token"
)
admin_principal = Principal(
identity="admin", role=Role.ADMIN, auth_method="bearer_token"
)
raw_yaml_stdout = """services:
docs:
environment:
DB_PASSWORD: supersecretpassword123
API_TOKEN: tok_secretabc
PUBLIC_SETTING: allowed_value
image: docs:latest
"""
mock_app = MagicMock(name="docs")
mock_app.name = "docs"
mock_app.dir_path = workload_dir
mock_app.is_core = False
req = OperationRequest.model_validate(
{"operation": "workload.config", "target": "docs"}
)
with (
patch("appctl_router.resolve_app", return_value=mock_app),
patch("appctl_router.load_admitted_workloads", return_value={"docs"}),
patch(
"appctl_router.run_bounded_subprocess",
return_value=(0, raw_yaml_stdout, ""),
),
):
# 1. Non-admin operator receives redacted output
resp_op = router.dispatch(req, operator_principal)
assert resp_op.success is True
assert resp_op.result is not None
output_yaml = resp_op.result["output"]
assert "supersecretpassword123" not in output_yaml
assert "tok_secretabc" not in output_yaml
assert "allowed_value" in output_yaml
parsed_op = yaml.safe_load(output_yaml)
env = parsed_op["services"]["docs"]["environment"]
assert env["DB_PASSWORD"] == "[REDACTED]"
assert env["API_TOKEN"] == "[REDACTED]"
assert env["PUBLIC_SETTING"] == "allowed_value"
# 2. Admin receives plaintext unredacted output
resp_admin = router.dispatch(req, admin_principal)
assert resp_admin.success is True
assert resp_admin.result is not None
assert "supersecretpassword123" in resp_admin.result["output"]
def test_parse_dotenv_rejects_reserved_platform_keys(tmp_path: Path):
"""Ensure parse_dotenv rejects platform routing and docker config variables in .env (CR-DI-07)."""
env_file = tmp_path / ".env"
for reserved_key in [
"HOMELAB_DOMAIN",
"DOMAIN_SUFFIX",
"DOMAIN",
"PROXY_NETWORK",
"CERT_RESOLVER",
"DOCKER_CONFIG",
]:
env_file.write_text(f"{reserved_key}=override_val\n", encoding="utf-8")
with pytest.raises(
RouterValidationError, match="Prohibited reserved environment key"
):
parse_dotenv(env_file, validate_keys=True)
+1
View File
@@ -126,6 +126,7 @@ def test_bootstrap_cli_never_prints_raw_secret_to_stdout_or_stderr(
# Ensure stdout provides helpful human guidance # Ensure stdout provides helpful human guidance
assert "operator-admin" in captured.out assert "operator-admin" in captured.out
assert "sops nixos/secrets.yaml" 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( def test_bootstrap_cli_print_json_outputs_valid_json_descriptor(
+19 -4
View File
@@ -66,7 +66,9 @@ def test_validate_transport_rejects_http(insecure_url: str):
], ],
) )
def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url): def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url):
with pytest.raises(ManifestValidationError, match=r"^Source URL cannot be empty\.$"): with pytest.raises(
ManifestValidationError, match=r"^Source URL cannot be empty\.$"
):
validate_transport(empty_or_invalid_url) # type: ignore[arg-type] validate_transport(empty_or_invalid_url) # type: ignore[arg-type]
@@ -77,7 +79,9 @@ def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url):
("ssh://git.example.com/", "SSH"), ("ssh://git.example.com/", "SSH"),
], ],
) )
def test_validate_transport_rejects_root_repository_path(root_path_url: str, scheme: str): def test_validate_transport_rejects_root_repository_path(
root_path_url: str, scheme: str
):
with pytest.raises( with pytest.raises(
ManifestValidationError, ManifestValidationError,
match=rf"^Malformed {scheme} source URL \(missing repository path\)", match=rf"^Malformed {scheme} source URL \(missing repository path\)",
@@ -132,8 +136,10 @@ def test_classify_ref_branches():
"feat/manifest-engine", "feat/manifest-engine",
) )
assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0") assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0")
assert classify_ref("custom-adhoc-branch") == (RefType.BRANCH, "custom-adhoc-branch") assert classify_ref("custom-adhoc-branch") == (
RefType.BRANCH,
"custom-adhoc-branch",
)
def test_classify_ref_tags(): def test_classify_ref_tags():
@@ -271,6 +277,15 @@ def test_parse_manifest_from_path(tmp_path: Path):
"IFS", "IFS",
"CORE_DIR", "CORE_DIR",
"SITES_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): def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str):
+16
View File
@@ -250,3 +250,19 @@ def test_resolve_upstream_provenance_class_b_and_default_timeout():
prov = resolve_upstream_provenance(source, local_commit="abc1234") prov = resolve_upstream_provenance(source, local_commit="abc1234")
assert prov.status == ProvenanceStatus.SYNCED assert prov.status == ProvenanceStatus.SYNCED
assert mock_run.call_args[1]["timeout"] == 10.0 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)"