Compare commits
9
Commits
66174ec558
...
1fea9024f1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1fea9024f1 | ||
|
|
4622392ca5 | ||
|
|
c740ed8c71 | ||
|
|
55acf00c10 | ||
|
|
c8c79bef89 | ||
|
|
5156cf4306 | ||
|
|
5dfebac35c | ||
|
|
d0213d7209 | ||
|
|
178a0c8990 |
No files matched your search
@@ -41,6 +41,7 @@ config/homepage/custom.js
|
||||
Thumbs.db
|
||||
.vscode/
|
||||
.idea/
|
||||
.worktrees/
|
||||
|
||||
# Python & Testing Caches
|
||||
__pycache__/
|
||||
@@ -54,3 +55,6 @@ mutants/
|
||||
scripts/bootstrap_lldap_users.py
|
||||
scripts/bootstrap_*.py
|
||||
!scripts/bootstrap_token.py
|
||||
|
||||
# Worktrees & Slices
|
||||
.worktrees/
|
||||
+96
-18
@@ -145,9 +145,8 @@ appctl restart docs
|
||||
appctl restart traefik
|
||||
appctl restart authelia
|
||||
|
||||
# Sequential stack update (clean working tree check -> git pull -> compose pull -> up -> sync)
|
||||
# Sequential stack update for independent Sites workloads (clean tree check -> git pull -> compose pull -> up -> sync)
|
||||
appctl update docs
|
||||
appctl update core
|
||||
|
||||
# Stream live container logs
|
||||
appctl logs docs
|
||||
@@ -157,6 +156,37 @@ appctl logs -f stalwart
|
||||
appctl config docs
|
||||
```
|
||||
|
||||
### Workload vs. Core Update Policy
|
||||
|
||||
Homelab enforces a strict architectural boundary between independent application workloads (`~/Sites/<app>`) and Homelab Core (`~/Core`):
|
||||
|
||||
#### 1. Independent Sites Workloads (`~/Sites/<app>`)
|
||||
- **Automated Lifecycle**: Workloads declare their lifecycle via `app.yaml` manifests and Compose definitions.
|
||||
- **Update Command**: `appctl update <workload>` performs pre-flight verification, branch matching, `git pull --ff-only`, container image pull, stack reload, and dashboard synchronization.
|
||||
- **GitOps Webhook Dispatch**: Workloads registered in `config/deployments.yaml` can be triggered automatically via authenticated GitOps webhooks on Gitea push events.
|
||||
- **Daemon Permissions**: `homelab-appctl.service` holds read-write permissions over `~/Sites` to manage files, compose configurations, and workload state.
|
||||
|
||||
#### 2. Homelab Core Platform Stack (`~/Core`)
|
||||
- **Host Foundation & Invariant Boundary**: Core defines NixOS host definitions, platform secrets, edge ingress, and security sandboxes.
|
||||
- **No Untrusted Webhooks**: Core does **not** register for webhook dispatch in `config/deployments.yaml`. External push events can never trigger an automated deployment or rebuild of Core.
|
||||
- **Read-Only Sandbox**: Under NixOS systemd sandboxing (`ProtectHome = "read-only"`), `homelab-appctl.service` has strictly read-only access to `/home/operator/Core`. The daemon cannot mutate the Core Git repository or run `git pull` on Core.
|
||||
- **Operator-Driven Update Workflow**: Core updates must be executed explicitly by the operator:
|
||||
1. Review and pull repository changes:
|
||||
```bash
|
||||
cd ~/Core && git pull --ff-only
|
||||
```
|
||||
2. If NixOS modules or secrets changed, evaluate and activate the new system generation:
|
||||
```bash
|
||||
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
|
||||
```
|
||||
3. If Compose definitions changed, restart the platform stack:
|
||||
```bash
|
||||
docker compose up -d --remove-orphans
|
||||
# or via systemd:
|
||||
sudo systemctl restart homeserver-core
|
||||
```
|
||||
4. Individual platform services can be restarted via appctl using an authenticated admin token (`appctl restart traefik`, `appctl restart authelia`).
|
||||
|
||||
---
|
||||
|
||||
## 4. User Identity & Access Management (LLDAP & Authelia)
|
||||
@@ -437,7 +467,51 @@ Activate the declarative configuration under the `operator` profile:
|
||||
chmod 600 /home/operator/Core/nixos/instance.nix
|
||||
```
|
||||
|
||||
2. **Rebuild NixOS host configuration**:
|
||||
2. **Bootstrap appctl control plane tokens (CR-SO-08)**:
|
||||
The `homelab-appctl.service` control plane daemon enforces 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`) authenticated via SHA-256 Bearer tokens stored in `/run/secrets/appctl/tokens.json`.
|
||||
|
||||
Generate the operator administrator token and local CLI credentials:
|
||||
```bash
|
||||
sudo -u operator python3 /home/operator/Core/scripts/bootstrap_token.py
|
||||
```
|
||||
This command:
|
||||
- Creates `~/.config/homelab/token` (mode `0600`) owned by `operator:homelab-operators` containing the raw Bearer token used automatically by the `appctl` CLI.
|
||||
- Outputs the JSON token descriptor containing the SHA-256 digest:
|
||||
```json
|
||||
{
|
||||
"token_id": "operator-admin",
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"sha256": "<64-character-sha256-digest>"
|
||||
}
|
||||
```
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Unprovisioned Token Behavior & RBAC Fallback**:
|
||||
> If tokens are not provisioned in `/run/secrets/appctl/tokens.json`, local UDS connections (`/run/homelab/appctl.sock`) fall back to Linux `SO_PEERCRED` socket credentials, granting callers in `homelab-operators` the read-only `homelab-viewer` role.
|
||||
> Under `homelab-viewer`, safe queries succeed (`appctl list`, `appctl status`, `appctl health`).
|
||||
> However, **all mutating and privileged operations** (`appctl up`, `appctl down`, `appctl restart`, `appctl update`, `appctl deploy`, `appctl config`, `appctl info`) **strictly require** a valid Bearer token with `homelab-operator` or `homelab-admin` role. If tokens are not enrolled in SOPS, attempting mutating actions fails with HTTP 403 `ERR_PERMISSION_DENIED`.
|
||||
|
||||
Enroll the token descriptor into SOPS secrets:
|
||||
```bash
|
||||
sops /home/operator/Core/nixos/secrets.yaml
|
||||
```
|
||||
Under `appctl.tokens_json`, insert the descriptor into the JSON array:
|
||||
```yaml
|
||||
appctl:
|
||||
tokens_json: |
|
||||
[
|
||||
{
|
||||
"token_id": "operator-admin",
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"sha256": "<paste-sha256-digest-here>"
|
||||
}
|
||||
]
|
||||
```
|
||||
*(Optional: If GitOps webhook dispatch is enabled, generate and enroll a `gitops-webhook` token with `homelab-operator` role using `python3 scripts/bootstrap_token.py --identity gitops --role homelab-operator --token-id gitops-webhook --print-json`).*
|
||||
|
||||
3. **Rebuild NixOS host configuration**:
|
||||
Execute the rebuild from the new canonical Core path using `--impure` and the `path:` scheme to import the untracked instance profile:
|
||||
```bash
|
||||
cd /home/operator/Core
|
||||
@@ -445,10 +519,10 @@ Activate the declarative configuration under the `operator` profile:
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index, ensuring untracked/gitignored `nixos/instance.nix` is evaluated. (If using `/etc/nixos/homelab-instance.nix`, bare `--flake .#server --impure` works directly).
|
||||
> The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index, ensuring untracked/gitignored `nixos/instance.nix` is evaluated. (If using `/etc/nixos/homelab-instance.nix`, bare `--flake .#server --impure` works directly). Rebuilding also decrypts and projects `/run/secrets/appctl/tokens.json` via `sops-nix`.
|
||||
|
||||
3. **Restart platform services**:
|
||||
Restart the Core Compose stack and control plane services to consume updated paths:
|
||||
4. **Restart platform services**:
|
||||
Restart the Core Compose stack and control plane services to consume updated paths and secrets:
|
||||
```bash
|
||||
sudo systemctl restart homeserver-core
|
||||
sudo systemctl restart homelab-appctl
|
||||
@@ -467,22 +541,26 @@ Validate system health and operational readiness under the `operator` identity:
|
||||
sudo -u operator git -C /home/operator/Sites/<any-workload> status
|
||||
```
|
||||
|
||||
2. **Verify appctl control plane status**:
|
||||
Execute CLI inspection using both UDS peercred authentication and token authentication:
|
||||
```bash
|
||||
# Peercred UDS inspection
|
||||
sudo -u operator appctl list --core
|
||||
|
||||
# Workload health check
|
||||
sudo -u operator appctl status
|
||||
```
|
||||
|
||||
3. **Verify SOPS secrets and tokens**:
|
||||
Ensure `/run/secrets/appctl/tokens.json` is readable by `homelab-appctl` and valid tokens exist for operator administration:
|
||||
2. **Verify SOPS secrets and tokens projection**:
|
||||
Ensure `/run/secrets/appctl/tokens.json` is readable by `homelab-appctl` (mode `0400`, owned by `homelab-appctl:homelab-operators`) and contains valid descriptors:
|
||||
```bash
|
||||
sudo ls -l /run/secrets/appctl/tokens.json
|
||||
```
|
||||
|
||||
3. **Verify appctl control plane status & RBAC authentication**:
|
||||
Execute CLI inspection using both UDS peercred authentication (read-only viewer fallback) and authenticated admin token operations:
|
||||
```bash
|
||||
# 1. Peercred UDS inspection (demonstrates viewer fallback for read-only actions)
|
||||
sudo -u operator appctl list --core
|
||||
sudo -u operator appctl status
|
||||
sudo -u operator appctl health
|
||||
|
||||
# 2. Authenticated operator admin verification (requires homelab-admin Bearer token)
|
||||
sudo -u operator appctl info docs
|
||||
sudo -u operator appctl config docs
|
||||
```
|
||||
Confirm that `info` and `config` return resolved configuration without `ERR_PERMISSION_DENIED`, verifying that `~/.config/homelab/token` matches the provisioned SHA-256 digest in `/run/secrets/appctl/tokens.json`.
|
||||
|
||||
4. **Verify container reachability & proxy routing**:
|
||||
Check that external endpoints and internal reverse proxies resolve:
|
||||
```bash
|
||||
|
||||
@@ -103,8 +103,8 @@
|
||||
# Declarative Dynamic GitOps Webhook Service (Internal Port 9000)
|
||||
systemd.services.homelab-gitops = {
|
||||
description = "Dynamic Homelab GitOps Webhook Dispatcher";
|
||||
after = [ "network-online.target" "docker.service" ];
|
||||
wants = [ "network-online.target" ];
|
||||
after = [ "network-online.target" "docker.service" "homelab-appctl.service" ];
|
||||
wants = [ "network-online.target" "homelab-appctl.service" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
|
||||
path = with pkgs; [
|
||||
@@ -154,7 +154,7 @@
|
||||
ReadWritePaths = [
|
||||
config.homelab.sitesDir
|
||||
"/home/${config.homelab.operatorUser}/.local/state/homelab"
|
||||
"/run/homelab"
|
||||
"-/run/homelab"
|
||||
];
|
||||
};
|
||||
};
|
||||
@@ -226,11 +226,11 @@
|
||||
ProtectControlGroups = true;
|
||||
ReadWritePaths = [
|
||||
config.homelab.sitesDir
|
||||
"/home/${config.homelab.operatorUser}/var/lib/homelab"
|
||||
"${config.homelab.coreDir}/config/homepage"
|
||||
"-/home/${config.homelab.operatorUser}/var/lib/homelab"
|
||||
"-${config.homelab.coreDir}/config/homepage"
|
||||
"/var/log/homelab/appctl"
|
||||
"/var/lib/homelab/appctl"
|
||||
"/run/homelab"
|
||||
"-/var/lib/homelab/appctl"
|
||||
"-/run/homelab"
|
||||
];
|
||||
};
|
||||
};
|
||||
@@ -242,6 +242,7 @@
|
||||
"d ${config.homelab.sitesDir} 0755 ${config.homelab.operatorUser} users -"
|
||||
"d /home/${config.homelab.operatorUser}/.local/state/homelab/gitops 0755 ${config.homelab.operatorUser} users -"
|
||||
"d /home/${config.homelab.operatorUser}/.local/state/homelab/docker 0755 ${config.homelab.operatorUser} users -"
|
||||
"d /home/${config.homelab.operatorUser}/var/lib/homelab 0755 ${config.homelab.operatorUser} users -"
|
||||
# POSIX ACLs granting homelab-appctl traverse and access to operator sites & homepage config
|
||||
"a+ /home/${config.homelab.operatorUser} - - - - u:homelab-appctl:x"
|
||||
"a+ ${config.homelab.coreDir} - - - - u:homelab-appctl:x"
|
||||
|
||||
@@ -28,7 +28,7 @@ DEFAULT_AUDIT_LOG = Path("/var/log/homelab/appctl/audit.jsonl")
|
||||
DEFAULT_LOCK_DIR = Path("/var/lib/homelab/appctl/locks")
|
||||
|
||||
REDACT_KEY_PATTERNS = re.compile(
|
||||
r".*(?:_KEY|_SECRET|_PASSWORD|_TOKEN|_PASS|_HASH)$", re.IGNORECASE
|
||||
r"^(?:.*_)?(?:KEY|SECRET|PASSWORD|TOKEN|PASS|HASH)$", re.IGNORECASE
|
||||
)
|
||||
|
||||
|
||||
@@ -105,7 +105,9 @@ class ConcurrentMutationError(Exception):
|
||||
|
||||
def __init__(self, target: str, message: str | None = None) -> None:
|
||||
self.target = target
|
||||
msg = message or f"Operation on target '{target}' is locked by a concurrent task."
|
||||
msg = (
|
||||
message or f"Operation on target '{target}' is locked by a concurrent task."
|
||||
)
|
||||
super().__init__(msg)
|
||||
|
||||
|
||||
@@ -116,7 +118,9 @@ def redact_sensitive_data(val: Any) -> Any:
|
||||
"""
|
||||
if isinstance(val, dict):
|
||||
return {
|
||||
k: "[REDACTED]" if REDACT_KEY_PATTERNS.match(str(k)) else redact_sensitive_data(v)
|
||||
k: "[REDACTED]"
|
||||
if REDACT_KEY_PATTERNS.match(str(k))
|
||||
else redact_sensitive_data(v)
|
||||
for k, v in val.items()
|
||||
}
|
||||
if isinstance(val, list):
|
||||
|
||||
+44
-16
@@ -33,9 +33,12 @@ except ImportError:
|
||||
yaml = None # type: ignore[assignment]
|
||||
|
||||
DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json")
|
||||
DEFAULT_DEPLOYMENTS_FILE = Path(__file__).resolve().parent.parent / "config" / "deployments.yaml"
|
||||
DEFAULT_DEPLOYMENTS_FILE = (
|
||||
Path(__file__).resolve().parent.parent / "config" / "deployments.yaml"
|
||||
)
|
||||
|
||||
CORE_TARGETS: frozenset[str] = frozenset({
|
||||
CORE_TARGETS: frozenset[str] = frozenset(
|
||||
{
|
||||
"core",
|
||||
"traefik",
|
||||
"authelia",
|
||||
@@ -46,29 +49,36 @@ CORE_TARGETS: frozenset[str] = frozenset({
|
||||
"homepage",
|
||||
"diun",
|
||||
"watchtower",
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset(
|
||||
{
|
||||
OperationType.WORKLOAD_CONFIG,
|
||||
OperationType.WORKLOAD_LOGS,
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
MUTATING_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
MUTATING_OPERATIONS: frozenset[OperationType] = frozenset(
|
||||
{
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_STOP,
|
||||
OperationType.WORKLOAD_RESTART,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_PULL,
|
||||
OperationType.PLATFORM_SYNC_HOMEPAGE,
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset(
|
||||
{
|
||||
OperationType.WORKLOAD_LIST,
|
||||
OperationType.WORKLOAD_GET,
|
||||
OperationType.WORKLOAD_RESOLVE,
|
||||
OperationType.PLATFORM_SSL,
|
||||
OperationType.PLATFORM_HEALTH,
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class Role(StrEnum):
|
||||
@@ -119,7 +129,11 @@ class TokenDescriptor(StrictModel):
|
||||
class AuthenticationError(Exception):
|
||||
"""Raised when authentication fails (401 Unauthorized)."""
|
||||
|
||||
def __init__(self, message: str = "Authentication required", code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Authentication required",
|
||||
code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.http_status = 401
|
||||
@@ -128,7 +142,11 @@ class AuthenticationError(Exception):
|
||||
class AuthorizationError(Exception):
|
||||
"""Raised when an authenticated principal lacks required role or scope (403 Forbidden)."""
|
||||
|
||||
def __init__(self, message: str = "Permission denied", code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Permission denied",
|
||||
code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.http_status = 403
|
||||
@@ -181,13 +199,15 @@ class TokenStore:
|
||||
constant-time hmac.compare_digest.
|
||||
"""
|
||||
if not secret:
|
||||
raise AuthenticationError("Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED)
|
||||
raise AuthenticationError(
|
||||
"Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED
|
||||
)
|
||||
|
||||
secret_hash = hashlib.sha256(secret.encode("utf-8")).hexdigest()
|
||||
tokens = self.load_tokens()
|
||||
|
||||
for token in tokens:
|
||||
if hmac.compare_digest(secret_hash, token.sha256):
|
||||
if hmac.compare_digest(secret_hash, token.sha256.lower()):
|
||||
return Principal(
|
||||
identity=token.identity,
|
||||
role=token.role,
|
||||
@@ -195,7 +215,9 @@ class TokenStore:
|
||||
auth_method="bearer_token",
|
||||
)
|
||||
|
||||
raise AuthenticationError("Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED)
|
||||
raise AuthenticationError(
|
||||
"Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED
|
||||
)
|
||||
|
||||
|
||||
def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[str]:
|
||||
@@ -235,7 +257,13 @@ def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[s
|
||||
if isinstance(alias, str) and alias.strip():
|
||||
admitted.add(alias.strip())
|
||||
return admitted
|
||||
except (OSError, UnicodeDecodeError, ValueError, json.JSONDecodeError, *yaml_errors):
|
||||
except (
|
||||
OSError,
|
||||
UnicodeDecodeError,
|
||||
ValueError,
|
||||
json.JSONDecodeError,
|
||||
*yaml_errors,
|
||||
):
|
||||
return set()
|
||||
|
||||
|
||||
@@ -310,7 +338,7 @@ def enforce_rbac(
|
||||
return
|
||||
|
||||
# Target checks for operations targeting infrastructure
|
||||
if target is not None and target in CORE_TARGETS:
|
||||
if target is not None and target.strip().lower() in CORE_TARGETS:
|
||||
raise AuthorizationError(
|
||||
f"Role 'homelab-operator' is not permitted to target core service '{target}'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
|
||||
@@ -386,6 +386,7 @@ class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
|
||||
return
|
||||
|
||||
# Dispatch operation to OperationalRouter
|
||||
try:
|
||||
resp = self.appctl_server.router.dispatch(
|
||||
request=req,
|
||||
principal=principal,
|
||||
@@ -393,6 +394,19 @@ class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
|
||||
origin=origin,
|
||||
client=client_header,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Top-level unhandled exception during operation dispatch")
|
||||
self._send_operation_error(
|
||||
status_code=500,
|
||||
error=OperationError(
|
||||
code=ErrorCode.ERR_EXECUTION_FAILED,
|
||||
message=f"Internal daemon execution error: {exc}",
|
||||
),
|
||||
operation=req.operation,
|
||||
target=req.target,
|
||||
op_id=generate_operation_id(),
|
||||
)
|
||||
return
|
||||
|
||||
status_code = resp.error.code.http_status if (not resp.success and resp.error) else 200
|
||||
self._send_operation_response(status_code, resp)
|
||||
|
||||
@@ -742,8 +742,12 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
||||
lines.append("")
|
||||
|
||||
content = "\n".join(lines).strip() + "\n"
|
||||
with open(services_yaml_path, "w", encoding="utf-8") as f:
|
||||
tmp_services_path = services_yaml_path + ".tmp"
|
||||
with open(tmp_services_path, "w", encoding="utf-8") as f:
|
||||
f.write(content)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp_services_path, services_yaml_path)
|
||||
|
||||
print(
|
||||
f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)"
|
||||
|
||||
+213
-43
@@ -12,12 +12,16 @@ Implements the single command execution pipeline for homelab-appctl.service:
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
logger = logging.getLogger("appctl_router")
|
||||
from appctl_audit import (
|
||||
AuditLogger,
|
||||
AuditPersistenceError,
|
||||
@@ -208,6 +212,18 @@ def assemble_workload_env(
|
||||
if local_env.is_file():
|
||||
env.update(parse_dotenv(local_env, validate_keys=True))
|
||||
|
||||
# Re-assert immutable platform infrastructure keys (defense-in-depth)
|
||||
env["HOMELAB_DOMAIN"] = domain
|
||||
env["DOMAIN_SUFFIX"] = domain
|
||||
env["DOMAIN"] = domain
|
||||
env["PROXY_NETWORK"] = os.environ.get("PROXY_NETWORK", "proxy-net")
|
||||
env["CERT_RESOLVER"] = os.environ.get("CERT_RESOLVER", "myresolver")
|
||||
env["SERVICE_NAME"] = app_name
|
||||
env["CONTAINER_NAME"] = app_name
|
||||
env["SERVICE_DOMAIN"] = f"{app_name}.{domain}"
|
||||
if "DOCKER_CONFIG" in os.environ:
|
||||
env["DOCKER_CONFIG"] = os.environ["DOCKER_CONFIG"]
|
||||
|
||||
return env
|
||||
|
||||
|
||||
@@ -290,7 +306,9 @@ def validate_workload_preflight(
|
||||
try:
|
||||
manifest = parse_manifest(manifest_file)
|
||||
except ManifestValidationError as err:
|
||||
raise RouterValidationError(f"Workload manifest validation failed: {err}") from err
|
||||
raise RouterValidationError(
|
||||
f"Workload manifest validation failed: {err}"
|
||||
) from err
|
||||
|
||||
effective_name = app_name or manifest.name
|
||||
compose_file = _resolve_compose_file(app_dir)
|
||||
@@ -328,7 +346,9 @@ def validate_core_preflight(
|
||||
if not compose_file.is_file():
|
||||
raise RouterValidationError(f"Core compose file not found at '{compose_file}'")
|
||||
|
||||
if compose_file.is_symlink() and not compose_file.resolve().is_relative_to(core_dir_resolved):
|
||||
if compose_file.is_symlink() and not compose_file.resolve().is_relative_to(
|
||||
core_dir_resolved
|
||||
):
|
||||
raise RouterValidationError(
|
||||
f"Core compose file symlink escapes Core root: '{compose_file}'"
|
||||
)
|
||||
@@ -592,7 +612,9 @@ class OperationalRouter:
|
||||
elif operation == OperationType.WORKLOAD_PULL:
|
||||
result_data = self._op_workload_pull(resolved_app)
|
||||
elif operation == OperationType.WORKLOAD_UPDATE:
|
||||
result_data, commit_sha = self._op_workload_update(request, resolved_app)
|
||||
result_data, commit_sha = self._op_workload_update(
|
||||
request, resolved_app
|
||||
)
|
||||
elif operation == OperationType.PLATFORM_SYNC_HOMEPAGE:
|
||||
result_data = self._op_platform_sync_homepage()
|
||||
else:
|
||||
@@ -601,7 +623,12 @@ class OperationalRouter:
|
||||
duration_ms = int((time.perf_counter() - start_time) * 1000)
|
||||
|
||||
# Audit COMPLETED for mutating ops and sensitive reads
|
||||
if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS:
|
||||
# Audit COMPLETED for mutating ops and sensitive reads
|
||||
if (
|
||||
operation in MUTATING_OPERATIONS
|
||||
or operation in SENSITIVE_READ_OPERATIONS
|
||||
):
|
||||
try:
|
||||
self.audit_logger.log_completed(
|
||||
operation_id=op_id,
|
||||
principal=principal_audit,
|
||||
@@ -613,8 +640,12 @@ class OperationalRouter:
|
||||
parameters=request.parameters,
|
||||
duration_ms=duration_ms,
|
||||
commit_sha=commit_sha,
|
||||
message=result_data.get("message", "Operation completed successfully"),
|
||||
message=result_data.get(
|
||||
"message", "Operation completed successfully"
|
||||
),
|
||||
)
|
||||
except AuditPersistenceError as audit_err:
|
||||
logger.error("Failed to persist COMPLETED audit record: %s", audit_err)
|
||||
|
||||
return OperationResponse(
|
||||
version="1.0",
|
||||
@@ -630,7 +661,11 @@ class OperationalRouter:
|
||||
|
||||
except (RouterValidationError, RouterExecutionError) as err:
|
||||
duration_ms = int((time.perf_counter() - start_time) * 1000)
|
||||
if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS:
|
||||
if (
|
||||
operation in MUTATING_OPERATIONS
|
||||
or operation in SENSITIVE_READ_OPERATIONS
|
||||
):
|
||||
try:
|
||||
self.audit_logger.log_failed(
|
||||
operation_id=op_id,
|
||||
principal=principal_audit,
|
||||
@@ -645,6 +680,8 @@ class OperationalRouter:
|
||||
error_code=err.code.value,
|
||||
message=str(err),
|
||||
)
|
||||
except AuditPersistenceError as audit_err:
|
||||
logger.error("Failed to persist FAILED audit record: %s", audit_err)
|
||||
return OperationResponse(
|
||||
version="1.0",
|
||||
success=False,
|
||||
@@ -654,6 +691,42 @@ class OperationalRouter:
|
||||
duration_ms=duration_ms,
|
||||
error=OperationError(code=err.code, message=str(err)),
|
||||
)
|
||||
except Exception as err:
|
||||
logger.exception("Unexpected execution error in router")
|
||||
duration_ms = int((time.perf_counter() - start_time) * 1000)
|
||||
if (
|
||||
operation in MUTATING_OPERATIONS
|
||||
or operation in SENSITIVE_READ_OPERATIONS
|
||||
):
|
||||
try:
|
||||
self.audit_logger.log_failed(
|
||||
operation_id=op_id,
|
||||
principal=principal_audit,
|
||||
action=operation.value,
|
||||
target=target,
|
||||
transport=transport,
|
||||
origin=origin,
|
||||
client=client,
|
||||
parameters=request.parameters,
|
||||
duration_ms=duration_ms,
|
||||
exit_code=1,
|
||||
error_code=ErrorCode.ERR_EXECUTION_FAILED.value,
|
||||
message=f"Unexpected execution failure: {err}",
|
||||
)
|
||||
except AuditPersistenceError as audit_err:
|
||||
logger.error("Failed to persist FAILED audit record: %s", audit_err)
|
||||
return OperationResponse(
|
||||
version="1.0",
|
||||
success=False,
|
||||
operation_id=op_id,
|
||||
operation=operation,
|
||||
target=target,
|
||||
duration_ms=duration_ms,
|
||||
error=OperationError(
|
||||
code=ErrorCode.ERR_EXECUTION_FAILED,
|
||||
message=f"Unexpected execution failure: {err}",
|
||||
),
|
||||
)
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# Domain Operation Implementations
|
||||
@@ -699,7 +772,9 @@ class OperationalRouter:
|
||||
dir_path=self.core_dir,
|
||||
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"
|
||||
if params.ssl and not svc.is_internal:
|
||||
svc_dict["ssl"] = check_ssl_cert(svc.domain)
|
||||
@@ -726,9 +801,14 @@ class OperationalRouter:
|
||||
domain = target or resolve_canonical_domain()
|
||||
try:
|
||||
cert_info = check_ssl_cert(domain)
|
||||
return {"ssl": cert_info, "message": f"SSL certificate inspected for {domain}"}
|
||||
return {
|
||||
"ssl": cert_info,
|
||||
"message": f"SSL certificate inspected for {domain}",
|
||||
}
|
||||
except Exception as err:
|
||||
raise RouterExecutionError(f"SSL inspection failed for '{domain}': {err}") from err
|
||||
raise RouterExecutionError(
|
||||
f"SSL inspection failed for '{domain}': {err}"
|
||||
) from err
|
||||
|
||||
def _op_platform_health(self) -> dict[str, Any]:
|
||||
return {
|
||||
@@ -742,13 +822,23 @@ class OperationalRouter:
|
||||
app_dir, _, compose_file, env, _ = self._prepare_target_context(app)
|
||||
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "config"]
|
||||
code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0)
|
||||
code, stdout, stderr = run_bounded_subprocess(
|
||||
cmd, cwd=app_dir, env=env, timeout=15.0
|
||||
)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose config failed: {stderr}", exit_code=code)
|
||||
raise RouterExecutionError(
|
||||
f"docker compose config failed: {stderr}", exit_code=code
|
||||
)
|
||||
|
||||
config_output = stdout
|
||||
if principal.role != Role.ADMIN:
|
||||
# Redact secrets for non-admin callers
|
||||
try:
|
||||
parsed_yaml = yaml.safe_load(stdout)
|
||||
if isinstance(parsed_yaml, (dict, list)):
|
||||
redacted_parsed = redact_sensitive_data(parsed_yaml)
|
||||
config_output = yaml.safe_dump(redacted_parsed, sort_keys=False)
|
||||
except (yaml.YAMLError, ValueError):
|
||||
config_output = redact_sensitive_data(config_output)
|
||||
|
||||
return {"output": config_output, "message": "Evaluated compose configuration"}
|
||||
@@ -771,13 +861,23 @@ class OperationalRouter:
|
||||
if container:
|
||||
cmd.append(container)
|
||||
|
||||
code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0)
|
||||
code, stdout, stderr = run_bounded_subprocess(
|
||||
cmd, cwd=app_dir, env=env, timeout=15.0
|
||||
)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose logs failed: {stderr}", exit_code=code)
|
||||
raise RouterExecutionError(
|
||||
f"docker compose logs failed: {stderr}", exit_code=code
|
||||
)
|
||||
|
||||
return {"output": stdout, "tail": params.tail, "message": f"Tail {params.tail} logs"}
|
||||
return {
|
||||
"output": stdout,
|
||||
"tail": params.tail,
|
||||
"message": f"Tail {params.tail} logs",
|
||||
}
|
||||
|
||||
def _op_workload_deploy(self, request: OperationRequest, app: Any) -> dict[str, Any]:
|
||||
def _op_workload_deploy(
|
||||
self, request: OperationRequest, app: Any
|
||||
) -> dict[str, Any]:
|
||||
params = request.parse_parameters()
|
||||
assert isinstance(params, DeployParams)
|
||||
app_dir, _, compose_file, env, container = self._prepare_target_context(app)
|
||||
@@ -785,14 +885,25 @@ class OperationalRouter:
|
||||
|
||||
# Optional 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:
|
||||
build_cmd.append("--no-cache")
|
||||
if container:
|
||||
build_cmd.append(container)
|
||||
code, out, err = run_bounded_subprocess(build_cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
code, out, err = run_bounded_subprocess(
|
||||
build_cmd, cwd=app_dir, env=env, timeout=300.0
|
||||
)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose build failed: {err}", exit_code=code)
|
||||
raise RouterExecutionError(
|
||||
f"docker compose build failed: {err}", exit_code=code
|
||||
)
|
||||
|
||||
# Deploy up
|
||||
up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d"]
|
||||
@@ -801,9 +912,13 @@ class OperationalRouter:
|
||||
if container:
|
||||
up_cmd.append(container)
|
||||
|
||||
code, out, err = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
code, out, err = run_bounded_subprocess(
|
||||
up_cmd, cwd=app_dir, env=env, timeout=300.0
|
||||
)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose up failed: {err}", exit_code=code)
|
||||
raise RouterExecutionError(
|
||||
f"docker compose up failed: {err}", exit_code=code
|
||||
)
|
||||
|
||||
# Trigger Homepage sync for Sites workloads
|
||||
if not is_core:
|
||||
@@ -824,13 +939,21 @@ class OperationalRouter:
|
||||
else:
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "down"]
|
||||
|
||||
code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
code, out, err = run_bounded_subprocess(
|
||||
cmd, cwd=app_dir, env=env, timeout=300.0
|
||||
)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose stop/down failed: {err}", exit_code=code)
|
||||
raise RouterExecutionError(
|
||||
f"docker compose stop/down failed: {err}", exit_code=code
|
||||
)
|
||||
|
||||
if not is_core:
|
||||
self._trigger_homepage_sync()
|
||||
return {"output": out, "action": "stopped", "message": f"Workload '{app.name}' stopped"}
|
||||
return {
|
||||
"output": out,
|
||||
"action": "stopped",
|
||||
"message": f"Workload '{app.name}' stopped",
|
||||
}
|
||||
|
||||
def _op_workload_restart(self, app: Any) -> dict[str, Any]:
|
||||
app_dir, _, compose_file, env, container = self._prepare_target_context(app)
|
||||
@@ -840,13 +963,21 @@ class OperationalRouter:
|
||||
if container:
|
||||
cmd.append(container)
|
||||
|
||||
code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
code, out, err = run_bounded_subprocess(
|
||||
cmd, cwd=app_dir, env=env, timeout=300.0
|
||||
)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose restart failed: {err}", exit_code=code)
|
||||
raise RouterExecutionError(
|
||||
f"docker compose restart failed: {err}", exit_code=code
|
||||
)
|
||||
|
||||
if not is_core:
|
||||
self._trigger_homepage_sync()
|
||||
return {"output": out, "action": "restarted", "message": f"Workload '{app.name}' restarted"}
|
||||
return {
|
||||
"output": out,
|
||||
"action": "restarted",
|
||||
"message": f"Workload '{app.name}' restarted",
|
||||
}
|
||||
|
||||
def _op_workload_pull(self, app: Any) -> dict[str, Any]:
|
||||
app_dir, _, compose_file, env, container = self._prepare_target_context(app)
|
||||
@@ -855,20 +986,40 @@ class OperationalRouter:
|
||||
pull_cmd = ["docker", "compose", "-f", str(compose_file), "pull"]
|
||||
if container:
|
||||
pull_cmd.append(container)
|
||||
code, _, err = run_bounded_subprocess(pull_cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
code, _, err = run_bounded_subprocess(
|
||||
pull_cmd, cwd=app_dir, env=env, timeout=300.0
|
||||
)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose pull failed: {err}", exit_code=code)
|
||||
raise RouterExecutionError(
|
||||
f"docker compose pull failed: {err}", exit_code=code
|
||||
)
|
||||
|
||||
up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"]
|
||||
up_cmd = [
|
||||
"docker",
|
||||
"compose",
|
||||
"-f",
|
||||
str(compose_file),
|
||||
"up",
|
||||
"-d",
|
||||
"--remove-orphans",
|
||||
]
|
||||
if container:
|
||||
up_cmd.append(container)
|
||||
code, out_up, err_up = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
code, out_up, err_up = run_bounded_subprocess(
|
||||
up_cmd, cwd=app_dir, env=env, timeout=300.0
|
||||
)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"docker compose up failed after pull: {err_up}", exit_code=code)
|
||||
raise RouterExecutionError(
|
||||
f"docker compose up failed after pull: {err_up}", exit_code=code
|
||||
)
|
||||
|
||||
if not is_core:
|
||||
self._trigger_homepage_sync()
|
||||
return {"output": out_up, "action": "pulled", "message": f"Workload '{app.name}' pulled and updated"}
|
||||
return {
|
||||
"output": out_up,
|
||||
"action": "pulled",
|
||||
"message": f"Workload '{app.name}' pulled and updated",
|
||||
}
|
||||
|
||||
def _op_workload_update(
|
||||
self, request: OperationRequest, app: Any
|
||||
@@ -901,12 +1052,14 @@ class OperationalRouter:
|
||||
# 2. git pull --ff-only
|
||||
pull_cmd = ["git", "-C", str(app_dir), "pull", "--ff-only"]
|
||||
if params.expected_branch:
|
||||
pull_cmd.extend(["origin", params.expected_branch])
|
||||
pull_cmd.extend(["origin", "--", params.expected_branch])
|
||||
code, pull_out, pull_err = run_bounded_subprocess(
|
||||
pull_cmd, cwd=app_dir, timeout=60.0
|
||||
)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(f"git pull failed for '{app.name}': {pull_err}", exit_code=code)
|
||||
raise RouterExecutionError(
|
||||
f"git pull failed for '{app.name}': {pull_err}", exit_code=code
|
||||
)
|
||||
|
||||
# 3. Post-pull re-validation of manifest and expected_branch
|
||||
if is_core:
|
||||
@@ -914,15 +1067,17 @@ class OperationalRouter:
|
||||
manifest = None
|
||||
declared_actions = ["compose_pull", "compose_up"]
|
||||
else:
|
||||
manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name)
|
||||
manifest, compose_file = validate_workload_preflight(
|
||||
app_dir, self.sites_dir, app.name
|
||||
)
|
||||
if (
|
||||
params.expected_branch
|
||||
and manifest.source
|
||||
and manifest.source.ref != params.expected_branch
|
||||
and manifest.deployment
|
||||
and manifest.deployment.branch != params.expected_branch
|
||||
):
|
||||
raise RouterValidationError(
|
||||
f"Post-pull branch mismatch for '{app.name}': expected '{params.expected_branch}', "
|
||||
f"manifest declared '{manifest.source.ref}'"
|
||||
f"manifest declared '{manifest.deployment.branch}'"
|
||||
)
|
||||
declared_actions = manifest.deployment.actions or ["compose_up"]
|
||||
|
||||
@@ -948,7 +1103,15 @@ class OperationalRouter:
|
||||
if params.no_cache:
|
||||
cmd.append("--no-cache")
|
||||
elif action == "compose_up":
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"]
|
||||
cmd = [
|
||||
"docker",
|
||||
"compose",
|
||||
"-f",
|
||||
str(compose_file),
|
||||
"up",
|
||||
"-d",
|
||||
"--remove-orphans",
|
||||
]
|
||||
elif action == "compose_restart":
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "restart"]
|
||||
else:
|
||||
@@ -957,7 +1120,9 @@ class OperationalRouter:
|
||||
if container:
|
||||
cmd.append(container)
|
||||
|
||||
code, act_out, act_err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
code, act_out, act_err = run_bounded_subprocess(
|
||||
cmd, cwd=app_dir, env=env, timeout=300.0
|
||||
)
|
||||
if code != 0:
|
||||
raise RouterExecutionError(
|
||||
f"Action '{action}' failed during workload.update for '{app.name}': {act_err}",
|
||||
@@ -985,13 +1150,18 @@ class OperationalRouter:
|
||||
}, commit_sha
|
||||
|
||||
def _op_platform_sync_homepage(self) -> dict[str, Any]:
|
||||
self._trigger_homepage_sync()
|
||||
return {"action": "sync_homepage", "message": "Homepage dashboard synchronized successfully"}
|
||||
cmd_sync_homepage()
|
||||
return {
|
||||
"action": "sync_homepage",
|
||||
"message": "Homepage dashboard synchronized successfully",
|
||||
}
|
||||
|
||||
def _trigger_homepage_sync(self) -> None:
|
||||
"""Atomic compile of Homepage dashboard services.yaml under _homepage_sync.lock."""
|
||||
try:
|
||||
with self.lock_manager.homepage_sync_lock():
|
||||
cmd_sync_homepage()
|
||||
except (OSError, ValueError, RuntimeError) as exc:
|
||||
except (OSError, ValueError, RuntimeError, ConcurrentMutationError) as exc:
|
||||
import sys
|
||||
|
||||
print(f"Warning: Homepage sync non-fatal error: {exc}", file=sys.stderr)
|
||||
@@ -72,10 +72,25 @@ RESERVED_ENV_KEYS = {
|
||||
"SITES_DIR",
|
||||
"ENV_FILE",
|
||||
"HOMESERVER_ENV",
|
||||
"HOMELAB_DOMAIN",
|
||||
"DOMAIN_SUFFIX",
|
||||
"DOMAIN",
|
||||
"PROXY_NETWORK",
|
||||
"CERT_RESOLVER",
|
||||
"DOCKER_CONFIG",
|
||||
"SERVICE_NAME",
|
||||
"CONTAINER_NAME",
|
||||
"SERVICE_DOMAIN",
|
||||
}
|
||||
|
||||
ALLOWED_STRATEGIES = {"compose"}
|
||||
ALLOWED_ACTIONS = {"git_pull", "compose_pull", "compose_up", "compose_build", "compose_restart"}
|
||||
ALLOWED_ACTIONS = {
|
||||
"git_pull",
|
||||
"compose_pull",
|
||||
"compose_up",
|
||||
"compose_build",
|
||||
"compose_restart",
|
||||
}
|
||||
|
||||
|
||||
def validate_transport(url: str) -> tuple[TransportScheme, str]:
|
||||
@@ -168,13 +183,11 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]:
|
||||
return RefType.BRANCH, ref
|
||||
|
||||
|
||||
|
||||
class SourceConfig(BaseModel):
|
||||
"""Upstream source provenance descriptor."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||
|
||||
|
||||
url: str
|
||||
ref: str = "main"
|
||||
type: str = "git"
|
||||
@@ -223,7 +236,6 @@ class DeploymentConfig(BaseModel):
|
||||
|
||||
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||
|
||||
|
||||
strategy: str = "compose"
|
||||
branch: str = "main"
|
||||
actions: list[str] = Field(default_factory=lambda: ["git_pull", "compose_up"])
|
||||
@@ -264,7 +276,6 @@ class HomepageConfig(BaseModel):
|
||||
|
||||
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||
|
||||
|
||||
title: str
|
||||
group: str = "Applications"
|
||||
icon: str = "default.png"
|
||||
@@ -295,7 +306,6 @@ class Manifest(BaseModel):
|
||||
ignored_types=(dict,),
|
||||
)
|
||||
|
||||
|
||||
name: str
|
||||
schema_version: str = Field(default="1.0", alias="schemaVersion")
|
||||
domain: str = ""
|
||||
|
||||
@@ -110,7 +110,9 @@ def execute_deployment_via_daemon(
|
||||
timeout=330.0,
|
||||
)
|
||||
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
|
||||
err_msg = resp.error.message if resp.error else "Unknown daemon error"
|
||||
logger.error(f"❌ Deployment of '{target}' via daemon failed: {err_msg}")
|
||||
@@ -286,7 +288,7 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
|
||||
if not raw_path:
|
||||
continue
|
||||
if raw_path.startswith("~/Sites/") or raw_path == "~/Sites":
|
||||
sub = raw_path[len("~/Sites"):].lstrip("/")
|
||||
sub = raw_path[len("~/Sites") :].lstrip("/")
|
||||
p = (SITES_DIR / sub).resolve() if sub else SITES_DIR.resolve()
|
||||
else:
|
||||
p = Path(raw_path).expanduser().resolve()
|
||||
@@ -407,8 +409,6 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
|
||||
return target_dir, deployment_config
|
||||
|
||||
|
||||
|
||||
|
||||
PROHIBITED_HOST_NAMESPACES = {"host"}
|
||||
DANGEROUS_SECURITY_OPTS = {"unconfined", "apparmor:unconfined", "seccomp:unconfined"}
|
||||
|
||||
@@ -607,6 +607,8 @@ def validate_compose_security(
|
||||
)
|
||||
if ":" in vol:
|
||||
host_path = vol.split(":")[0].strip()
|
||||
else:
|
||||
host_path = vol.strip()
|
||||
elif isinstance(vol, dict):
|
||||
src = str(vol.get("source", ""))
|
||||
if "/var/run/docker.sock" in src:
|
||||
@@ -614,12 +616,19 @@ def validate_compose_security(
|
||||
False,
|
||||
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
|
||||
|
||||
if not host_path:
|
||||
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
|
||||
if host_path in top_volumes and not (
|
||||
host_path.startswith((".", "/", "~"))
|
||||
|
||||
@@ -1068,3 +1068,95 @@ services:
|
||||
)
|
||||
assert valid is False
|
||||
assert err is not None and "security_opt" in err.lower()
|
||||
|
||||
|
||||
def test_validate_compose_security_rejects_dict_volume_without_type_bind(
|
||||
tmp_path: Path,
|
||||
):
|
||||
"""Ensure dictionary volume declarations without explicit type: bind enforce host containment (CR-DI-01)."""
|
||||
compose_file = tmp_path / "docker-compose.yml"
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine
|
||||
volumes:
|
||||
- source: /etc/shadow
|
||||
target: /app/shadow
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, tmp_path, app_name="my-app"
|
||||
)
|
||||
assert valid is False
|
||||
assert err is not None and "prohibited host bind mount" in err.lower()
|
||||
|
||||
|
||||
def test_validate_compose_security_rejects_variable_interpolation_in_volume_host_path(
|
||||
tmp_path: Path,
|
||||
):
|
||||
"""Ensure volume host paths containing variable interpolation (${...}) fail closed (CR-DI-02)."""
|
||||
compose_file = tmp_path / "docker-compose.yml"
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine
|
||||
volumes:
|
||||
- "${HOST_DIR}/data:/data"
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, tmp_path, app_name="my-app"
|
||||
)
|
||||
assert valid is False
|
||||
assert err is not None and "variable interpolation" in err.lower()
|
||||
|
||||
|
||||
def test_validate_compose_security_rejects_variable_interpolation_in_dict_volume_source(
|
||||
tmp_path: Path,
|
||||
):
|
||||
"""Ensure dictionary volume source containing variable interpolation (${...}) fails closed (CR-DI-02)."""
|
||||
compose_file = tmp_path / "docker-compose.yml"
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine
|
||||
volumes:
|
||||
- source: "${HOST_DIR}/data"
|
||||
target: /data
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, tmp_path, app_name="my-app"
|
||||
)
|
||||
assert valid is False
|
||||
assert err is not None and "variable interpolation" in err.lower()
|
||||
|
||||
|
||||
def test_validate_compose_security_allows_valid_dict_volume_within_workload(
|
||||
tmp_path: Path,
|
||||
):
|
||||
"""Ensure valid dictionary volume within workload root is accepted even without type: bind."""
|
||||
(tmp_path / "data").mkdir()
|
||||
compose_file = tmp_path / "docker-compose.yml"
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine
|
||||
volumes:
|
||||
- source: ./data
|
||||
target: /data
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, tmp_path, app_name="my-app"
|
||||
)
|
||||
assert valid is True
|
||||
assert err is None
|
||||
@@ -2,6 +2,7 @@
|
||||
Security invariant tests for Docker Compose and container isolation.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
@@ -291,6 +292,61 @@ def test_nixos_tmpfiles_rules_use_recursive_acls():
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_tmpfiles_rules_creates_operator_var_lib_homelab():
|
||||
"""Ensure tmpfiles.rules creates operator var/lib/homelab state dir before ACL assignment (#22)."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
expected_create = '"d /home/${config.homelab.operatorUser}/var/lib/homelab 0755 ${config.homelab.operatorUser} users -"'
|
||||
expected_acl = '"A+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"'
|
||||
|
||||
assert expected_create in content, (
|
||||
"tmpfiles.rules must declare creation of operator var/lib/homelab directory"
|
||||
)
|
||||
assert expected_acl in content, (
|
||||
"tmpfiles.rules must declare ACLs for operator var/lib/homelab directory"
|
||||
)
|
||||
assert content.index(expected_create) < content.index(expected_acl), (
|
||||
"operator var/lib/homelab directory creation must precede its ACL rule"
|
||||
)
|
||||
|
||||
|
||||
def test_nixos_appctl_readwritepaths_optional_prefixes():
|
||||
"""Ensure appctl service ReadWritePaths uses '-' prefix for optional runtime paths (#22)."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert '"-/home/${config.homelab.operatorUser}/var/lib/homelab"' in content
|
||||
assert '"-${config.homelab.coreDir}/config/homepage"' in content
|
||||
assert '"-/var/lib/homelab/appctl"' in content
|
||||
assert '"-/run/homelab"' in content
|
||||
|
||||
|
||||
def test_nixos_gitops_orders_after_appctl():
|
||||
"""Ensure homelab-gitops service declares after and wants dependency on homelab-appctl.service (#22)."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
content = homeserver_nix.read_text(encoding="utf-8")
|
||||
|
||||
assert '"homelab-appctl.service"' in content
|
||||
|
||||
nix_bin = shutil.which("nix")
|
||||
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
|
||||
for attr in ["after", "wants"]:
|
||||
cmd = [
|
||||
nix_bin,
|
||||
"eval",
|
||||
f".#nixosConfigurations.server.config.systemd.services.homelab-gitops.{attr}",
|
||||
"--json",
|
||||
]
|
||||
res = subprocess.run(
|
||||
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
|
||||
)
|
||||
data = json.loads(res.stdout)
|
||||
assert "homelab-appctl.service" in data, (
|
||||
f"homelab-gitops {attr} must include homelab-appctl.service"
|
||||
)
|
||||
|
||||
|
||||
def test_default_homelab_domain_evaluates_to_example_test():
|
||||
"""Assert default homelab.domain in NixOS config evaluates to 'example.test'."""
|
||||
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
|
||||
|
||||
@@ -232,6 +232,31 @@ def test_redact_sensitive_data_masks_secret_keys():
|
||||
assert redacted["nested"]["list_items"][1] == "safe_string"
|
||||
|
||||
|
||||
def test_redact_sensitive_data_masks_bare_keys():
|
||||
"""Ensure bare keys (token, secret, password, key, pass, hash) without underscores are redacted (CR-DI-04)."""
|
||||
raw_params = {
|
||||
"token": "tok_12345",
|
||||
"secret": "shh_secret",
|
||||
"password": "mypassword",
|
||||
"key": "encryption_key",
|
||||
"pass": "quick_pass",
|
||||
"hash": "$2b$12$hashval",
|
||||
"TOKEN": "uppercase_tok",
|
||||
"SECRET": "uppercase_sec",
|
||||
"normal_field": "keep_this",
|
||||
}
|
||||
redacted = redact_sensitive_data(raw_params)
|
||||
assert redacted["token"] == "[REDACTED]"
|
||||
assert redacted["secret"] == "[REDACTED]"
|
||||
assert redacted["password"] == "[REDACTED]"
|
||||
assert redacted["key"] == "[REDACTED]"
|
||||
assert redacted["pass"] == "[REDACTED]"
|
||||
assert redacted["hash"] == "[REDACTED]"
|
||||
assert redacted["TOKEN"] == "[REDACTED]"
|
||||
assert redacted["SECRET"] == "[REDACTED]"
|
||||
assert redacted["normal_field"] == "keep_this"
|
||||
|
||||
|
||||
def test_audit_logger_automatically_redacts_sensitive_parameters(
|
||||
temp_audit_file: Path, sample_principal: PrincipalAudit
|
||||
):
|
||||
|
||||
+145
-34
@@ -37,8 +37,12 @@ def secret_tokens() -> dict[str, str]:
|
||||
@pytest.fixture
|
||||
def temp_tokens_file(tmp_path: Path, secret_tokens: dict[str, str]) -> Path:
|
||||
tokens_path = tmp_path / "tokens.json"
|
||||
admin_hash = hashlib.sha256(secret_tokens["admin_secret"].encode("utf-8")).hexdigest()
|
||||
op_hash = hashlib.sha256(secret_tokens["operator_secret"].encode("utf-8")).hexdigest()
|
||||
admin_hash = hashlib.sha256(
|
||||
secret_tokens["admin_secret"].encode("utf-8")
|
||||
).hexdigest()
|
||||
op_hash = hashlib.sha256(
|
||||
secret_tokens["operator_secret"].encode("utf-8")
|
||||
).hexdigest()
|
||||
|
||||
data = [
|
||||
{
|
||||
@@ -121,6 +125,31 @@ def test_token_store_authenticates_valid_bearer_secrets(
|
||||
assert p_op.token_id == "tok_gitops_01"
|
||||
|
||||
|
||||
def test_token_store_authenticates_uppercase_hex_descriptor(tmp_path: Path):
|
||||
"""Ensure tokens with uppercase hex characters in tokens.json authenticate cleanly (CR-DI-10)."""
|
||||
raw_secret = "my_custom_secret_token"
|
||||
raw_hash_upper = hashlib.sha256(raw_secret.encode("utf-8")).hexdigest().upper()
|
||||
tokens_file = tmp_path / "upper_tokens.json"
|
||||
tokens_file.write_text(
|
||||
json.dumps(
|
||||
[
|
||||
{
|
||||
"token_id": "tok_upper_01",
|
||||
"identity": "upper-user",
|
||||
"role": "homelab-operator",
|
||||
"sha256": raw_hash_upper,
|
||||
}
|
||||
]
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
os.chmod(tokens_file, 0o400)
|
||||
store = TokenStore(tokens_file)
|
||||
principal = store.authenticate_bearer(raw_secret)
|
||||
assert principal.identity == "upper-user"
|
||||
assert principal.role == Role.OPERATOR
|
||||
|
||||
|
||||
def test_token_store_rejects_invalid_bearer_secret(temp_tokens_file: Path):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
@@ -178,7 +207,9 @@ def test_authenticate_request_over_uds_falls_back_to_viewer(
|
||||
|
||||
# Explicit Bearer token over UDS confers full privileges
|
||||
auth_header = f"Bearer {secret_tokens['admin_secret']}"
|
||||
p_admin = authenticate_request("unix_socket", auth_header, peer_uid=1000, token_store=store)
|
||||
p_admin = authenticate_request(
|
||||
"unix_socket", auth_header, peer_uid=1000, token_store=store
|
||||
)
|
||||
assert p_admin.role == Role.ADMIN
|
||||
assert p_admin.auth_method == "bearer_token"
|
||||
|
||||
@@ -196,7 +227,8 @@ def test_authenticate_request_over_uds_rejects_missing_peer_uid():
|
||||
|
||||
def test_load_admitted_workloads_parses_names_and_aliases(tmp_path: Path):
|
||||
deploy_file = tmp_path / "deployments.yaml"
|
||||
deploy_file.write_text("""
|
||||
deploy_file.write_text(
|
||||
"""
|
||||
schemaVersion: "1.0"
|
||||
repositories:
|
||||
snappymail:
|
||||
@@ -208,7 +240,9 @@ repositories:
|
||||
path: "/home/operator/Sites/homelab-jellyfin"
|
||||
aliases:
|
||||
- "media"
|
||||
""", encoding="utf-8")
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
admitted = load_admitted_workloads(deploy_file)
|
||||
assert "snappymail" in admitted
|
||||
@@ -221,14 +255,19 @@ repositories:
|
||||
|
||||
def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: Path):
|
||||
deploy_file = tmp_path / "deployments.json"
|
||||
deploy_file.write_text(json.dumps({
|
||||
deploy_file.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"repositories": {
|
||||
"app1": {
|
||||
"path": "/home/operator/Sites/app1",
|
||||
"aliases": [123, None, " ", "valid_alias"]
|
||||
"aliases": [123, None, " ", "valid_alias"],
|
||||
}
|
||||
}
|
||||
}), encoding="utf-8")
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
admitted = load_admitted_workloads(deploy_file)
|
||||
assert "app1" in admitted
|
||||
@@ -238,13 +277,17 @@ def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: P
|
||||
assert "" not in admitted
|
||||
|
||||
|
||||
def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
|
||||
def test_load_admitted_workloads_fails_closed_on_missing_file(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
admitted = load_admitted_workloads(tmp_path / "missing.yaml")
|
||||
assert admitted == set()
|
||||
|
||||
# Test HOMELAB_DEPLOYMENTS_FILE fallback
|
||||
deploy_file = tmp_path / "env_deploy.yaml"
|
||||
deploy_file.write_text("repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8")
|
||||
deploy_file.write_text(
|
||||
"repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8"
|
||||
)
|
||||
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deploy_file))
|
||||
admitted_env = load_admitted_workloads(None)
|
||||
assert "env_app" in admitted_env
|
||||
@@ -258,12 +301,16 @@ def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path, mo
|
||||
def test_rbac_admin_permitted_across_all_operations_and_targets(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
admin = Principal(identity="admin_user", role=Role.ADMIN, auth_method="bearer_token")
|
||||
admin = Principal(
|
||||
identity="admin_user", role=Role.ADMIN, auth_method="bearer_token"
|
||||
)
|
||||
|
||||
# Mutations across Core and Sites
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "traefik", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads)
|
||||
enforce_rbac(
|
||||
admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads
|
||||
)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_CONFIG, "core", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_LOGS, "traefik", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads)
|
||||
@@ -273,79 +320,139 @@ def test_rbac_admin_permitted_across_all_operations_and_targets(
|
||||
def test_rbac_operator_permitted_on_admitted_workloads(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
operator = Principal(
|
||||
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
|
||||
)
|
||||
|
||||
# Permitted on admitted workload
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads)
|
||||
enforce_rbac(
|
||||
operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads
|
||||
)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_UPDATE, "mail", admitted_workloads)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads)
|
||||
enforce_rbac(
|
||||
operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads
|
||||
)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_LOGS, "docs", admitted_workloads)
|
||||
enforce_rbac(operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads)
|
||||
enforce_rbac(
|
||||
operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads
|
||||
)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_LIST, None, admitted_workloads)
|
||||
|
||||
|
||||
def test_rbac_operator_denied_on_core_targets(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
operator = Principal(
|
||||
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
|
||||
)
|
||||
|
||||
# Targeting "core" stack
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads)
|
||||
enforce_rbac(
|
||||
operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads
|
||||
)
|
||||
assert "not permitted to target core service 'core'" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
# Targeting core services (traefik, stalwart, etc.)
|
||||
for core_svc in ["traefik", "authelia", "stalwart", "socket-proxy"]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads)
|
||||
assert f"not permitted to target core service '{core_svc}'" in str(exc_info.value)
|
||||
enforce_rbac(
|
||||
operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads
|
||||
)
|
||||
assert f"not permitted to target core service '{core_svc}'" in str(
|
||||
exc_info.value
|
||||
)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_operator_denied_on_case_variant_core_targets(admitted_workloads: set[str]):
|
||||
"""Ensure case variants ('Core', 'TRAEFIK', 'Authelia') are rejected for operator role (CR-DI-06)."""
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
for variant in ["Core", "CORE", "Traefik", "TRAEFIK", "Authelia"]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, variant, admitted_workloads)
|
||||
assert "not permitted to target core service" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
|
||||
def test_rbac_operator_denied_without_target_on_mutating_or_sensitive_ops(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
operator = Principal(
|
||||
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
|
||||
)
|
||||
|
||||
for op in [OperationType.WORKLOAD_DEPLOY, OperationType.WORKLOAD_UPDATE, OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]:
|
||||
for op in [
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_CONFIG,
|
||||
OperationType.WORKLOAD_LOGS,
|
||||
]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, op, None, admitted_workloads)
|
||||
assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value)
|
||||
assert f"Operation '{op.value}' requires an explicit workload target" in str(
|
||||
exc_info.value
|
||||
)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, op, "", admitted_workloads)
|
||||
assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value)
|
||||
assert f"Operation '{op.value}' requires an explicit workload target" in str(
|
||||
exc_info.value
|
||||
)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_operator_with_default_admitted_workloads(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
|
||||
def test_rbac_operator_with_default_admitted_workloads(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
):
|
||||
deployments_file = tmp_path / "deployments.yaml"
|
||||
deployments_file.write_text("repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8")
|
||||
deployments_file.write_text(
|
||||
"repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8"
|
||||
)
|
||||
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file))
|
||||
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "customapp", admitted_workloads=None)
|
||||
operator = Principal(
|
||||
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
|
||||
)
|
||||
enforce_rbac(
|
||||
operator, OperationType.WORKLOAD_DEPLOY, "customapp", admitted_workloads=None
|
||||
)
|
||||
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unknownapp", admitted_workloads=None)
|
||||
enforce_rbac(
|
||||
operator,
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
"unknownapp",
|
||||
admitted_workloads=None,
|
||||
)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_operator_denied_on_unregistered_workload(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
operator = Principal(
|
||||
identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token"
|
||||
)
|
||||
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unregistered_app", admitted_workloads)
|
||||
enforce_rbac(
|
||||
operator,
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
"unregistered_app",
|
||||
admitted_workloads,
|
||||
)
|
||||
assert "not registered in deployments.yaml" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_viewer_permitted_only_on_non_sensitive_reads():
|
||||
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
|
||||
viewer = Principal(
|
||||
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
|
||||
)
|
||||
|
||||
# Permitted reads
|
||||
enforce_rbac(viewer, OperationType.WORKLOAD_LIST, None)
|
||||
@@ -356,7 +463,9 @@ def test_rbac_viewer_permitted_only_on_non_sensitive_reads():
|
||||
|
||||
|
||||
def test_rbac_viewer_denied_on_mutations():
|
||||
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
|
||||
viewer = Principal(
|
||||
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
|
||||
)
|
||||
|
||||
mutations = [
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
@@ -374,7 +483,9 @@ def test_rbac_viewer_denied_on_mutations():
|
||||
|
||||
|
||||
def test_rbac_viewer_denied_on_sensitive_reads():
|
||||
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
|
||||
viewer = Principal(
|
||||
identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred"
|
||||
)
|
||||
|
||||
for sens_op in [OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
|
||||
@@ -7,10 +7,12 @@ test_<subject>_<accepts|rejects|enforces>_<condition>
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
from appctl_audit import AuditLogger, TargetLockManager
|
||||
from appctl_auth import Principal, Role
|
||||
from appctl_contracts import ErrorCode, OperationRequest
|
||||
@@ -77,7 +79,9 @@ services:
|
||||
container_name: "snappymail"
|
||||
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
|
||||
|
||||
|
||||
@@ -88,12 +92,16 @@ def admin_principal() -> Principal:
|
||||
|
||||
@pytest.fixture
|
||||
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
|
||||
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 +111,17 @@ def viewer_principal() -> Principal:
|
||||
|
||||
def test_parse_dotenv_parses_valid_key_values(tmp_path: Path):
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text("""
|
||||
env_file.write_text(
|
||||
"""
|
||||
# Comment line
|
||||
APP_PORT=8080
|
||||
APP_HOST="127.0.0.1"
|
||||
SINGLE_QUOTE='single_val'
|
||||
EMPTY_VAL=
|
||||
WITH_EQUALS=key=value=more
|
||||
""", encoding="utf-8")
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
parsed = parse_dotenv(env_file)
|
||||
assert parsed["APP_PORT"] == "8080"
|
||||
@@ -122,11 +133,14 @@ WITH_EQUALS=key=value=more
|
||||
|
||||
def test_parse_dotenv_preserves_shell_injection_as_inert_literals(tmp_path: Path):
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text("""
|
||||
env_file.write_text(
|
||||
"""
|
||||
INJECTION_ONE=$(touch /tmp/pwned)
|
||||
INJECTION_TWO=`cat /etc/passwd`
|
||||
VARIABLE_REF=$HOMELAB_DOMAIN
|
||||
""", encoding="utf-8")
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
parsed = parse_dotenv(env_file)
|
||||
assert parsed["INJECTION_ONE"] == "$(touch /tmp/pwned)"
|
||||
@@ -187,7 +201,6 @@ def test_resolve_canonical_domain_precedence(monkeypatch: pytest.MonkeyPatch):
|
||||
assert resolve_canonical_domain() == "stripped.example.test"
|
||||
|
||||
|
||||
|
||||
def test_assemble_workload_env_constructs_6_layer_environment(
|
||||
mock_workload_dir: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
@@ -195,7 +208,9 @@ def test_assemble_workload_env_constructs_6_layer_environment(
|
||||
manifest = parse_manifest(mock_workload_dir / "app.yaml")
|
||||
|
||||
# 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")
|
||||
|
||||
@@ -292,7 +307,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(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
@@ -325,10 +342,12 @@ def test_operational_router_enforces_rbac_denial(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
req = OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
})
|
||||
}
|
||||
)
|
||||
resp = router.dispatch(req, viewer_principal)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
@@ -342,10 +361,12 @@ def test_operational_router_rejects_non_existent_target(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
req = OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.get",
|
||||
"target": "nonexistent_workload_999",
|
||||
})
|
||||
}
|
||||
)
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
@@ -360,10 +381,12 @@ def test_operational_router_rejects_concurrent_mutation(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=lock_mgr,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
req = OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "snappymail"
|
||||
@@ -388,11 +411,13 @@ def test_operational_router_dispatches_workload_deploy(
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_workload_dir.parent,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
req = OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
"parameters": {"recreate": True, "remove_orphans": True, "build": False},
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "snappymail"
|
||||
@@ -400,7 +425,10 @@ def test_operational_router_dispatches_workload_deploy(
|
||||
|
||||
with (
|
||||
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"),
|
||||
):
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
@@ -424,11 +452,13 @@ def test_operational_router_workload_deploy_build_flags(
|
||||
mock_app.dir_path = str(mock_workload_dir)
|
||||
|
||||
# 1. Deploy with build=True passes --pull
|
||||
req_build = OperationRequest.model_validate({
|
||||
req_build = OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
"parameters": {"build": True},
|
||||
})
|
||||
}
|
||||
)
|
||||
executed_commands: list[list[str]] = []
|
||||
|
||||
def mock_subproc(cmd: list[str], **kwargs):
|
||||
@@ -445,15 +475,22 @@ def test_operational_router_workload_deploy_build_flags(
|
||||
build_calls = [c for c in executed_commands if "build" in c]
|
||||
assert len(build_calls) == 1
|
||||
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
|
||||
req_no_cache = OperationRequest.model_validate({
|
||||
req_no_cache = OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
"parameters": {"no_cache": True},
|
||||
})
|
||||
}
|
||||
)
|
||||
executed_commands.clear()
|
||||
|
||||
with (
|
||||
@@ -466,7 +503,13 @@ def test_operational_router_workload_deploy_build_flags(
|
||||
build_calls = [c for c in executed_commands if "build" in c]
|
||||
assert len(build_calls) == 1
|
||||
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 +521,12 @@ def test_operational_router_workload_update_rejects_dirty_git_tree(
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_workload_dir.parent,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
req = OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.update",
|
||||
"target": "snappymail",
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "snappymail"
|
||||
@@ -512,11 +557,13 @@ def test_operational_router_workload_update_rejects_branch_mismatch(
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_workload_dir.parent,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
req = OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.update",
|
||||
"target": "snappymail",
|
||||
"parameters": {"expected_branch": "feature/branch"},
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "snappymail"
|
||||
@@ -550,11 +597,13 @@ def test_operational_router_workload_update_succeeds_on_clean_tree(
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_workload_dir.parent,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
req = OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.update",
|
||||
"target": "snappymail",
|
||||
"parameters": {"expected_branch": "main"},
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "snappymail"
|
||||
@@ -611,11 +660,13 @@ def test_operational_router_workload_update_build_and_no_cache_flags(
|
||||
return 0, "success", ""
|
||||
|
||||
# 1. Update with build=True
|
||||
req_build = OperationRequest.model_validate({
|
||||
req_build = OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.update",
|
||||
"target": "snappymail",
|
||||
"parameters": {"build": True},
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
@@ -627,18 +678,25 @@ def test_operational_router_workload_update_build_and_no_cache_flags(
|
||||
build_calls = [c for c in executed_commands if "build" in c]
|
||||
assert len(build_calls) == 1
|
||||
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
|
||||
up_calls = [c for c in executed_commands if "up" in c]
|
||||
assert len(up_calls) == 1
|
||||
|
||||
# 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",
|
||||
"target": "snappymail",
|
||||
"parameters": {"no_cache": True},
|
||||
})
|
||||
}
|
||||
)
|
||||
executed_commands.clear()
|
||||
|
||||
with (
|
||||
@@ -651,7 +709,13 @@ def test_operational_router_workload_update_build_and_no_cache_flags(
|
||||
build_calls = [c for c in executed_commands if "build" in c]
|
||||
assert len(build_calls) == 1
|
||||
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]
|
||||
assert len(up_calls) == 1
|
||||
@@ -675,7 +739,9 @@ deployment:
|
||||
- "compose_build"
|
||||
- "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(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
@@ -699,10 +765,12 @@ deployment:
|
||||
return 0, "success", ""
|
||||
|
||||
# Update with declared compose_build invokes build --pull
|
||||
req = OperationRequest.model_validate({
|
||||
req = OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.update",
|
||||
"target": "snappymail",
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
@@ -714,7 +782,12 @@ deployment:
|
||||
build_calls = [c for c in executed_commands if "build" in c]
|
||||
assert len(build_calls) == 1
|
||||
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 +811,9 @@ services:
|
||||
image: "authelia/authelia:latest"
|
||||
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(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
@@ -759,7 +834,9 @@ services:
|
||||
):
|
||||
# 1. Deploy core stack
|
||||
resp_deploy = router.dispatch(
|
||||
OperationRequest.model_validate({"operation": "workload.deploy", "target": "core"}),
|
||||
OperationRequest.model_validate(
|
||||
{"operation": "workload.deploy", "target": "core"}
|
||||
),
|
||||
admin_principal,
|
||||
)
|
||||
assert resp_deploy.success is True
|
||||
@@ -775,7 +852,9 @@ services:
|
||||
|
||||
# 2. Stop core stack (uses `down` for full stack)
|
||||
resp_stop = router.dispatch(
|
||||
OperationRequest.model_validate({"operation": "workload.stop", "target": "core"}),
|
||||
OperationRequest.model_validate(
|
||||
{"operation": "workload.stop", "target": "core"}
|
||||
),
|
||||
admin_principal,
|
||||
)
|
||||
assert resp_stop.success is True
|
||||
@@ -789,7 +868,9 @@ services:
|
||||
|
||||
# 3. Restart core stack
|
||||
resp_restart = router.dispatch(
|
||||
OperationRequest.model_validate({"operation": "workload.restart", "target": "core"}),
|
||||
OperationRequest.model_validate(
|
||||
{"operation": "workload.restart", "target": "core"}
|
||||
),
|
||||
admin_principal,
|
||||
)
|
||||
assert resp_restart.success is True
|
||||
@@ -803,7 +884,9 @@ services:
|
||||
|
||||
# 4. Config core stack
|
||||
resp_config = router.dispatch(
|
||||
OperationRequest.model_validate({"operation": "workload.config", "target": "core"}),
|
||||
OperationRequest.model_validate(
|
||||
{"operation": "workload.config", "target": "core"}
|
||||
),
|
||||
admin_principal,
|
||||
)
|
||||
assert resp_config.success is True
|
||||
@@ -845,7 +928,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations(
|
||||
with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc):
|
||||
# 1. Deploy single core service (traefik)
|
||||
resp_deploy = router.dispatch(
|
||||
OperationRequest.model_validate({"operation": "workload.deploy", "target": "traefik"}),
|
||||
OperationRequest.model_validate(
|
||||
{"operation": "workload.deploy", "target": "traefik"}
|
||||
),
|
||||
admin_principal,
|
||||
)
|
||||
assert resp_deploy.success is True
|
||||
@@ -854,7 +939,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations(
|
||||
|
||||
# 2. Stop single core service (uses `stop traefik`, NOT `down`)
|
||||
resp_stop = router.dispatch(
|
||||
OperationRequest.model_validate({"operation": "workload.stop", "target": "traefik"}),
|
||||
OperationRequest.model_validate(
|
||||
{"operation": "workload.stop", "target": "traefik"}
|
||||
),
|
||||
admin_principal,
|
||||
)
|
||||
assert resp_stop.success is True
|
||||
@@ -869,7 +956,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations(
|
||||
|
||||
# 3. Restart single core service
|
||||
resp_restart = router.dispatch(
|
||||
OperationRequest.model_validate({"operation": "workload.restart", "target": "traefik"}),
|
||||
OperationRequest.model_validate(
|
||||
{"operation": "workload.restart", "target": "traefik"}
|
||||
),
|
||||
admin_principal,
|
||||
)
|
||||
assert resp_restart.success is True
|
||||
@@ -884,7 +973,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations(
|
||||
|
||||
# 4. Pull single core service
|
||||
resp_pull = router.dispatch(
|
||||
OperationRequest.model_validate({"operation": "workload.pull", "target": "traefik"}),
|
||||
OperationRequest.model_validate(
|
||||
{"operation": "workload.pull", "target": "traefik"}
|
||||
),
|
||||
admin_principal,
|
||||
)
|
||||
assert resp_pull.success is True
|
||||
@@ -909,7 +1000,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations(
|
||||
|
||||
# 5. Logs single core service
|
||||
resp_logs = router.dispatch(
|
||||
OperationRequest.model_validate({"operation": "workload.logs", "target": "traefik"}),
|
||||
OperationRequest.model_validate(
|
||||
{"operation": "workload.logs", "target": "traefik"}
|
||||
),
|
||||
admin_principal,
|
||||
)
|
||||
assert resp_logs.success is True
|
||||
@@ -945,7 +1038,9 @@ def test_operational_router_dispatches_core_update_without_manifest(
|
||||
|
||||
with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc):
|
||||
resp = router.dispatch(
|
||||
OperationRequest.model_validate({"operation": "workload.update", "target": "core"}),
|
||||
OperationRequest.model_validate(
|
||||
{"operation": "workload.update", "target": "core"}
|
||||
),
|
||||
admin_principal,
|
||||
)
|
||||
assert resp.success is True
|
||||
@@ -968,7 +1063,9 @@ def test_operational_router_rejects_operator_role_on_core_targets(
|
||||
)
|
||||
for target in ("core", "traefik", "authelia"):
|
||||
resp = router.dispatch(
|
||||
OperationRequest.model_validate({"operation": "workload.restart", "target": target}),
|
||||
OperationRequest.model_validate(
|
||||
{"operation": "workload.restart", "target": target}
|
||||
),
|
||||
operator_principal,
|
||||
)
|
||||
assert resp.success is False
|
||||
@@ -991,10 +1088,12 @@ def test_operational_router_workload_list_honors_filter_params(
|
||||
|
||||
# Without --core: only Sites workloads (1)
|
||||
resp_sites = router.dispatch(
|
||||
OperationRequest.model_validate({
|
||||
OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.list",
|
||||
"parameters": {"core": False, "fetch": False, "ssl": False},
|
||||
}),
|
||||
}
|
||||
),
|
||||
viewer_principal,
|
||||
)
|
||||
assert resp_sites.success is True
|
||||
@@ -1003,12 +1102,17 @@ def test_operational_router_workload_list_honors_filter_params(
|
||||
assert resp_sites.result["workloads"][0]["name"] == "snappymail"
|
||||
|
||||
# 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(
|
||||
OperationRequest.model_validate({
|
||||
OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.list",
|
||||
"parameters": {"core": True, "fetch": False, "ssl": True},
|
||||
}),
|
||||
}
|
||||
),
|
||||
viewer_principal,
|
||||
)
|
||||
assert resp_core.success is True
|
||||
@@ -1034,13 +1138,17 @@ def test_operational_router_workload_list_includes_live_docker_and_two_axis_stat
|
||||
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)
|
||||
resp = router.dispatch(
|
||||
OperationRequest.model_validate({
|
||||
OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.list",
|
||||
"parameters": {"core": False, "fetch": False, "ssl": False},
|
||||
}),
|
||||
}
|
||||
),
|
||||
viewer_principal,
|
||||
)
|
||||
assert resp.success is True
|
||||
@@ -1055,10 +1163,12 @@ def test_operational_router_workload_list_includes_live_docker_and_two_axis_stat
|
||||
|
||||
# 2. Core services included (core=True)
|
||||
resp_core = router.dispatch(
|
||||
OperationRequest.model_validate({
|
||||
OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.list",
|
||||
"parameters": {"core": True, "fetch": False, "ssl": False},
|
||||
}),
|
||||
}
|
||||
),
|
||||
viewer_principal,
|
||||
)
|
||||
assert resp_core.success is True
|
||||
@@ -1095,10 +1205,12 @@ def test_operational_router_workload_list_fetch_passes_fetch_upstream(
|
||||
mock_inspect.return_value = mock_two_axis
|
||||
|
||||
resp_fetch = router.dispatch(
|
||||
OperationRequest.model_validate({
|
||||
OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.list",
|
||||
"parameters": {"core": False, "fetch": True, "ssl": False},
|
||||
}),
|
||||
}
|
||||
),
|
||||
viewer_principal,
|
||||
)
|
||||
assert resp_fetch.success is True
|
||||
@@ -1120,7 +1232,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."""
|
||||
broken_app_dir = mock_sites_dir / "broken-app"
|
||||
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(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
@@ -1131,10 +1245,12 @@ def test_operational_router_workload_list_handles_manifest_error(
|
||||
|
||||
with patch("appctl_router.get_docker_status", return_value="🔴 Stopped"):
|
||||
resp = router.dispatch(
|
||||
OperationRequest.model_validate({
|
||||
OperationRequest.model_validate(
|
||||
{
|
||||
"operation": "workload.list",
|
||||
"parameters": {"core": False, "fetch": False, "ssl": False},
|
||||
}),
|
||||
}
|
||||
),
|
||||
viewer_principal,
|
||||
)
|
||||
assert resp.success is True
|
||||
@@ -1147,5 +1263,256 @@ def test_operational_router_workload_list_handles_manifest_error(
|
||||
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)
|
||||
|
||||
|
||||
def test_operational_router_workload_update_succeeds_when_source_ref_is_tag_and_deployment_branch_matches(
|
||||
tmp_path: Path, admin_principal: Principal, mock_sites_dir: Path
|
||||
):
|
||||
"""Ensure workload.update validates deployment.branch (Tier 2) and does not conflate with source.ref (Tier 1) (CR-SS-01)."""
|
||||
app_dir = mock_sites_dir / "bitetrack"
|
||||
app_dir.mkdir(parents=True, exist_ok=True)
|
||||
manifest_content = """
|
||||
name: "bitetrack"
|
||||
source:
|
||||
type: "git"
|
||||
url: "https://github.com/example/bitetrack.git"
|
||||
ref: "v2.5.0"
|
||||
deployment:
|
||||
strategy: "compose"
|
||||
branch: "main"
|
||||
actions:
|
||||
- "compose_up"
|
||||
"""
|
||||
(app_dir / "app.yaml").write_text(manifest_content.strip(), encoding="utf-8")
|
||||
(app_dir / "docker-compose.yml").write_text("services:\n app:\n image: app:latest\n", encoding="utf-8")
|
||||
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_sites_dir,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "workload.update",
|
||||
"target": "bitetrack",
|
||||
"parameters": {"expected_branch": "main"},
|
||||
})
|
||||
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "bitetrack"
|
||||
mock_app.dir_path = str(app_dir)
|
||||
|
||||
executed_cmds: list[list[str]] = []
|
||||
|
||||
def mock_subproc(cmd: list[str], **kwargs):
|
||||
executed_cmds.append(cmd)
|
||||
if "status" in cmd:
|
||||
return 0, "", ""
|
||||
if "pull" in cmd and "git" in cmd:
|
||||
return 0, "Fast-forward", ""
|
||||
if "rev-parse" in cmd:
|
||||
return 0, "1234567", ""
|
||||
return 0, "ok", ""
|
||||
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
|
||||
patch("appctl_router.cmd_sync_homepage"),
|
||||
):
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
assert resp.success is True
|
||||
assert resp.result is not None
|
||||
pull_calls = [c for c in executed_cmds if "pull" in c and "git" in c]
|
||||
assert len(pull_calls) == 1
|
||||
assert pull_calls[0] == ["git", "-C", str(app_dir), "pull", "--ff-only", "origin", "--", "main"]
|
||||
|
||||
|
||||
def test_operational_router_workload_update_rejects_deployment_branch_mismatch_image_only(
|
||||
tmp_path: Path, admin_principal: Principal, mock_sites_dir: Path
|
||||
):
|
||||
"""Ensure workload.update validates deployment.branch for image-only workloads with source=None (CR-SS-01)."""
|
||||
app_dir = mock_sites_dir / "imageonly"
|
||||
app_dir.mkdir(parents=True, exist_ok=True)
|
||||
manifest_content = """
|
||||
name: "imageonly"
|
||||
deployment:
|
||||
strategy: "compose"
|
||||
branch: "production"
|
||||
actions:
|
||||
- "compose_up"
|
||||
"""
|
||||
(app_dir / "app.yaml").write_text(manifest_content.strip(), encoding="utf-8")
|
||||
(app_dir / "docker-compose.yml").write_text("services:\n app:\n image: app:latest\n", encoding="utf-8")
|
||||
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_sites_dir,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "workload.update",
|
||||
"target": "imageonly",
|
||||
"parameters": {"expected_branch": "main"},
|
||||
})
|
||||
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "imageonly"
|
||||
mock_app.dir_path = str(app_dir)
|
||||
|
||||
def mock_subproc(cmd: list[str], **kwargs):
|
||||
if "status" in cmd:
|
||||
return 0, "", ""
|
||||
if "pull" in cmd and "git" in cmd:
|
||||
return 0, "Fast-forward", ""
|
||||
if "rev-parse" in cmd:
|
||||
return 0, "1234567", ""
|
||||
return 0, "ok", ""
|
||||
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
|
||||
):
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_VALIDATION_FAILED
|
||||
assert "Post-pull branch mismatch" in resp.error.message
|
||||
assert "expected 'main'" in resp.error.message
|
||||
assert "declared 'production'" in resp.error.message
|
||||
|
||||
|
||||
def test_operational_router_catches_unhandled_runtime_exceptions_and_records_failed_audit(
|
||||
tmp_path: Path, admin_principal: Principal, mock_sites_dir: Path
|
||||
):
|
||||
"""Ensure unexpected exceptions in router return 500 ERR_EXECUTION_FAILED and log FAILED audit (CR-SO-04)."""
|
||||
audit_file = tmp_path / "audit.jsonl"
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(audit_file),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_sites_dir,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "platform.sync_homepage",
|
||||
})
|
||||
|
||||
with patch("appctl_router.cmd_sync_homepage", side_effect=RuntimeError("Corrupt filesystem")):
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
assert resp.success is False
|
||||
assert resp.error is not None
|
||||
assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED
|
||||
assert "Unexpected execution failure" in resp.error.message
|
||||
|
||||
events = [json.loads(line) for line in audit_file.read_text().splitlines() if line.strip()]
|
||||
assert len(events) == 2
|
||||
assert events[0]["phase"] == "DISPATCHED"
|
||||
assert events[1]["phase"] == "FAILED"
|
||||
assert events[1]["result"]["error_code"] == ErrorCode.ERR_EXECUTION_FAILED.value
|
||||
|
||||
|
||||
def test_trigger_homepage_sync_acquires_homepage_sync_lock(tmp_path: Path, mock_sites_dir: Path):
|
||||
"""Ensure _trigger_homepage_sync executes under homepage_sync_lock (CR-DI-05)."""
|
||||
lock_mgr = TargetLockManager(tmp_path / "locks")
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=lock_mgr,
|
||||
sites_dir=mock_sites_dir,
|
||||
)
|
||||
lock_acquired = False
|
||||
|
||||
def mock_sync():
|
||||
nonlocal lock_acquired
|
||||
lock_file = lock_mgr.lock_dir / "_homepage_sync.lock"
|
||||
assert lock_file.exists()
|
||||
lock_acquired = True
|
||||
|
||||
with patch("appctl_router.cmd_sync_homepage", side_effect=mock_sync):
|
||||
router._trigger_homepage_sync()
|
||||
assert lock_acquired is True
|
||||
@@ -66,7 +66,9 @@ def test_validate_transport_rejects_http(insecure_url: str):
|
||||
],
|
||||
)
|
||||
def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url):
|
||||
with pytest.raises(ManifestValidationError, match=r"^Source URL cannot be empty\.$"):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match=r"^Source URL cannot be empty\.$"
|
||||
):
|
||||
validate_transport(empty_or_invalid_url) # type: ignore[arg-type]
|
||||
|
||||
|
||||
@@ -77,7 +79,9 @@ def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url):
|
||||
("ssh://git.example.com/", "SSH"),
|
||||
],
|
||||
)
|
||||
def test_validate_transport_rejects_root_repository_path(root_path_url: str, scheme: str):
|
||||
def test_validate_transport_rejects_root_repository_path(
|
||||
root_path_url: str, scheme: str
|
||||
):
|
||||
with pytest.raises(
|
||||
ManifestValidationError,
|
||||
match=rf"^Malformed {scheme} source URL \(missing repository path\)",
|
||||
@@ -132,8 +136,10 @@ def test_classify_ref_branches():
|
||||
"feat/manifest-engine",
|
||||
)
|
||||
assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0")
|
||||
assert classify_ref("custom-adhoc-branch") == (RefType.BRANCH, "custom-adhoc-branch")
|
||||
|
||||
assert classify_ref("custom-adhoc-branch") == (
|
||||
RefType.BRANCH,
|
||||
"custom-adhoc-branch",
|
||||
)
|
||||
|
||||
|
||||
def test_classify_ref_tags():
|
||||
@@ -271,6 +277,15 @@ def test_parse_manifest_from_path(tmp_path: Path):
|
||||
"IFS",
|
||||
"CORE_DIR",
|
||||
"SITES_DIR",
|
||||
"HOMELAB_DOMAIN",
|
||||
"DOMAIN_SUFFIX",
|
||||
"DOMAIN",
|
||||
"PROXY_NETWORK",
|
||||
"CERT_RESOLVER",
|
||||
"DOCKER_CONFIG",
|
||||
"SERVICE_NAME",
|
||||
"CONTAINER_NAME",
|
||||
"SERVICE_DOMAIN",
|
||||
],
|
||||
)
|
||||
def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str):
|
||||
|
||||
Reference in new issue
Block a user