Compare commits

..
3 Commits
Author SHA1 Message Date
kiskaadee 5ed61acf32 fix(engine): unify manifest parsing with core_manifest and fail closed on errors
- Delegate workload manifest parsing strictly to core_manifest.parse_manifest

- Remove duplicate SourceConfig and HomepageConfig dataclasses in appctl_engine

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

- Display manifest errors explicitly in cmd_list and cmd_info without fallback

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

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

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

Part of Pre-P4 Security Gate (Milestone P4 readiness).
2026-10-15 01:52:08 -05:00
7 changed files with 407 additions and 174 deletions

No files matched your search

+26 -12
View File
@@ -1,6 +1,6 @@
# ⚡ Homelab Core — GitOps Continuous Deployment Engine # ⚡ Homelab Core — GitOps Continuous Deployment Engine
Homelab Core includes an automated GitOps deployment engine implemented in [`scripts/gitops_dispatcher.py`](../scripts/gitops_dispatcher.py). It processes Git push webhooks from Gitea (or external Git forges) and executes declared deployment actions for workloads in `~/Sites` or data vaults (such as `~/Brain`). Homelab Core includes an automated GitOps deployment engine implemented in [`scripts/gitops_dispatcher.py`](../scripts/gitops_dispatcher.py). It processes Git push webhooks from Gitea (or external Git forges) and executes declared deployment actions strictly for admitted application workloads in `~/Sites`.
--- ---
@@ -26,9 +26,9 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
│ │
▼ ▼
┌───────────────────────────────────────────────┐ ┌───────────────────────────────────────────────┐
│ 3. Canonical Repository Identity Resolution │ │ 3. Authoritative Registry Resolution │
│ Maps logical names to trusted local paths │ │ Maps names via Core/config/deployments.yaml│
│ Rejects path traversal & symlink escapes │ │ Fails closed; zero dynamic discovery on host│
└───────────────────────┬───────────────────────┘ └───────────────────────┬───────────────────────┘
│ │
▼ ▼
@@ -53,7 +53,8 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
┌───────────────────────────────────────────────┐ ┌───────────────────────────────────────────────┐
│ 7. Revision-Consistent Validation & Execution │ │ 7. Revision-Consistent Validation & Execution │
│ git pull -> re-validate manifest on-tree │ │ git pull -> re-validate manifest on-tree │
│ Execute allowlisted actions -> write status│ │ Compose AST security validator (containment│
│ & privilege checks) -> compose up -> status│
└───────────────────────────────────────────────┘ └───────────────────────────────────────────────┘
``` ```
@@ -71,13 +72,13 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
* Signatures are verified using HMAC-SHA256 with `hmac.compare_digest` against the shared secret stored in `nixos/secrets.yaml` (projected to `/run/secrets/gitops/webhook_secret`). * Signatures are verified using HMAC-SHA256 with `hmac.compare_digest` against the shared secret stored in `nixos/secrets.yaml` (projected to `/run/secrets/gitops/webhook_secret`).
* Missing, empty, or mismatched signatures are rejected. * Missing, empty, or mismatched signatures are rejected.
### C. Trusted Repository Resolution ### C. Authoritative Repository Registry (`deployments.yaml`)
* Webhook payloads identify targets by logical name (e.g. `docs`, `homelab-docs`), never by raw filesystem path. * Webhook payloads identify targets strictly by logical name (e.g. `docs`, `homelab-docs`), never by raw filesystem path.
* The engine resolves names against a trusted mapping derived from: * `Core/config/deployments.yaml` is the **sole admission authority** for GitOps workloads.
1. Authoritative Data Vaults (`~/Brain` via aliases `second-brain`, `Brain`, `brain`). * **No Dynamic Discovery**: Scanning `~/Sites` dynamically is strictly prohibited. An unapproved directory created on disk cannot receive webhook deployment rights merely by providing an `app.yaml`.
2. Workload directories in `~/Sites` by parsing `app.yaml`. * **Fail-Closed Guarantee**: If `deployments.yaml` is missing, unreadable, or malformed, the dispatcher fails closed and admits zero repositories.
* **Input Validation**: Names must match `^[a-zA-Z0-9][a-zA-Z0-9._-]*$`. Slashes, backslashes, and `..` are rejected. * **Input Validation**: Names must match `^[a-zA-Z0-9][a-zA-Z0-9._-]*$`. Slashes, backslashes, and path traversal sequences (`..`) are rejected.
* **Containment Check**: Resolved target paths must reside within `~/Sites` or `~/Brain`. Symlinks pointing outside these roots are rejected. * **Containment Check**: Declared repository paths must resolve strictly within `~/Sites`. Paths escaping `~/Sites` are rejected during registry loading.
### D. Revision-Consistent Manifest Validation ### D. Revision-Consistent Manifest Validation
* When a webhook is admitted, an initial policy check verifies that the pushed branch matches the declared `deployment.branch`. * When a webhook is admitted, an initial policy check verifies that the pushed branch matches the declared `deployment.branch`.
@@ -85,8 +86,21 @@ The GitOps engine is invoked via the `homelab-gitops.service` systemd unit runni
* The engine **re-reads and re-validates `app.yaml` from the newly pulled working tree** before running subsequent container actions (`compose_up`, `compose_build`, etc.). * The engine **re-reads and re-validates `app.yaml` from the newly pulled working tree** before running subsequent container actions (`compose_up`, `compose_build`, etc.).
* If the pulled commit introduces an invalid action, unsupported strategy, or changes the target branch away from the pushed branch, deployment is aborted. * If the pulled commit introduces an invalid action, unsupported strategy, or changes the target branch away from the pushed branch, deployment is aborted.
### E. Compose AST Security Validation
Before executing `docker compose up -d`, `validate_compose_security()` parses the application's Compose file and enforces platform security invariants:
* **File Integrity**: `docker-compose.yml` and `app.yaml` must be regular files, not symlinks escaping the workload root.
* **Privilege Containment**: Rejects `privileged: true`, `cap_add` capabilities, `devices` mounts, and `security_opt: ["apparmor:unconfined"]`.
* **Namespace Isolation**: Rejects host namespaces (`network_mode: host`, `pid: host`, `ipc: host`, `uts: host`, `userns_mode: host`).
* **Docker Socket Ban**: Rejects direct bind mounts of `/var/run/docker.sock` (reserved exclusively for Core `socket-proxy:ro`).
* **Top-Level Directives**: Rejects top-level `include:` directives to prevent out-of-tree file inclusions.
* **Bind-Mount & State Isolation**:
- Resolves all bind mounts (both relative and absolute) against the authorized workload directory.
- Bind mounts are strictly restricted to **either** the workload root (`~/Sites/<app>/`) **or** the dedicated per-workload persistent state root (`~/var/lib/homelab/<app>/`).
- Cross-tenant mounts (mounting another application's directory under `~/var/lib/homelab/`) are rejected fail-closed.
--- ---
## 3. Asynchronous Queueing, Serialization & Superseding ## 3. Asynchronous Queueing, Serialization & Superseding
To avoid blocking HTTP connections and handle overlapping pushes: To avoid blocking HTTP connections and handle overlapping pushes:
+99 -143
View File
@@ -19,7 +19,13 @@ from pathlib import Path
from typing import Any from typing import Any
import yaml import yaml
from core_manifest import Manifest, ManifestValidationError, parse_manifest from core_manifest import (
HomepageConfig,
Manifest,
ManifestValidationError,
SourceConfig,
parse_manifest,
)
from provenance import ( from provenance import (
get_local_checkout_status, get_local_checkout_status,
inspect_workload_two_axis, inspect_workload_two_axis,
@@ -64,39 +70,15 @@ def validate_environment() -> None:
sys.exit(1) sys.exit(1)
class ManifestError(Exception): ManifestError = ManifestValidationError
pass
@dataclass
class HomepageConfig:
title: str
group: str = "Applications"
icon: str = "default.png"
container: str = ""
weight: int = 50
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@dataclass
class SourceConfig:
"""Upstream source provenance descriptor."""
type: str = "git" # "git"
url: str = "" # e.g., "https://git.roadtotech.me/kiskaadee/bitetrack.git"
ref: str = "main" # Branch (e.g. "main"), tag (e.g. "v1.0.0"), or commit SHA
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@dataclass @dataclass
class App: class App:
name: str # Canonical identifier (e.g., "traefik", "jellyfin") name: str # Canonical identifier (e.g., "traefik", "jellyfin")
description: str # Human-readable summary for dashboards and CLI info description: str = "" # Human-readable summary for dashboards and CLI info
domain: str # Routing FQDN (e.g., "auth.roadtotech.me") or "internal". domain: str = "" # Routing FQDN (e.g., "auth.roadtotech.me") or "internal".
dir_path: str # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites). dir_path: str = "" # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
@property @property
def is_internal(self) -> bool: def is_internal(self) -> bool:
@@ -131,116 +113,74 @@ class SitesApp(App):
env: dict[str, Any] = field(default_factory=dict) # Environment variable overrides env: dict[str, Any] = field(default_factory=dict) # Environment variable overrides
homepage: HomepageConfig | None = None # Dashboard Card Configuration homepage: HomepageConfig | None = None # Dashboard Card Configuration
manifest_error: str | None = None # Captured syntax/loading errors manifest_error: str | None = None # Captured syntax/loading errors
manifest_obj: Manifest | None = None # Parsed authoritative Manifest
app_type: str = "app" app_type: str = "app"
def to_dict(self) -> dict[str, Any]:
def load_manifest(manifest_path: str) -> dict[str, Any]: """Serialize for JSON consumption by scripts/appctl"""
"""Load and parse the app manifest file.""" data = asdict(self)
if not os.path.isfile(manifest_path): data.pop("manifest_obj", None)
raise FileNotFoundError(f"Manifest file not found at {manifest_path}") data["type"] = getattr(self, "app_type", "app")
return data
try:
with open(manifest_path, "r", encoding="utf-8") as file:
manifest_data = yaml.safe_load(file) or {}
except (yaml.YAMLError, OSError) as err:
raise ManifestError(f"YAML parsing failed: {err}") from err
if not isinstance(manifest_data, dict):
raise ManifestError(f"Invalid manifest root: expected `dict`, got `{type(manifest_data).__name__}`")
return manifest_data
def sites_app_from_manifest( def sites_app_from_manifest(
app_dir: str, app_dir: str,
manifest: dict[str, Any], manifest: Manifest | dict[str, Any] | None = None,
manifest_error: str | None = None, manifest_error: str | None = None,
) -> SitesApp: ) -> SitesApp:
"""Construct and normalize a SitesApp domain model from raw manifest data.""" """Construct and normalize a SitesApp domain model from an authoritative Manifest or raw data."""
raw_dir_name = os.path.basename(app_dir) raw_dir_name = os.path.basename(app_dir)
canonical_name = str(manifest.get("name") or raw_dir_name.replace("homelab-", ""))
# Normalize aliases into list[str]
raw_aliases = manifest.get("aliases") or []
if isinstance(raw_aliases, str):
aliases = [raw_aliases]
elif isinstance(raw_aliases, list):
aliases = [str(alias) for alias in raw_aliases]
else:
aliases = []
# Homepage card normalization
homepage_config: HomepageConfig | None = None
raw_hp = manifest.get("homepage")
if isinstance(raw_hp, dict):
homepage_config = HomepageConfig(
title=str(raw_hp.get("title") or canonical_name),
group=str(raw_hp.get("group") or "Applications"),
icon=str(raw_hp.get("icon") or "default.png"),
container=str(raw_hp.get("container") or canonical_name),
weight=int(raw_hp.get("weight", 50)),
)
if isinstance(manifest, Manifest):
has_compose = ( has_compose = (
os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or
os.path.isfile(os.path.join(app_dir, "docker-compose.yml")) os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
) )
canonical_name = manifest.name
# Manifest Data parsing domain = manifest.domain or f"{canonical_name}.{HOMELAB_DOMAIN}"
raw_desc = manifest.get("description")
app_desc: str = str(raw_desc) if raw_desc is not None else ""
raw_dom = manifest.get("domain")
app_dom = str(raw_dom) if raw_dom is not None else f"{canonical_name}.{HOMELAB_DOMAIN}"
app_net = manifest.get("networks")
if not isinstance(app_net, list):
app_net = ["proxy-net"]
app_env = manifest.get("env")
if not isinstance(app_env, dict):
app_env = {}
def _as_bool(value: Any, default: bool) -> bool:
if isinstance(value, bool):
return value
return default
app_vis = _as_bool(manifest.get("visible"), True)
app_auth = _as_bool(manifest.get("auth"), True)
# Source provenance normalization
source_config: SourceConfig | None = None
raw_source = manifest.get("source")
if isinstance(raw_source, dict):
source_url = str(raw_source.get("url") or "")
allowed_schemes = ("https://", "ssh://", "git@")
if source_url:
if not any(source_url.startswith(s) for s in allowed_schemes):
err = f"Invalid source.url scheme: must start with {', '.join(allowed_schemes)}"
manifest_error = f"{manifest_error}; {err}" if manifest_error else err
else:
source_config = SourceConfig(
type=str(raw_source.get("type") or "git"),
url=source_url,
ref=str(raw_source.get("ref") or "main"),
)
return SitesApp( return SitesApp(
name=canonical_name, name=canonical_name,
dir_name=raw_dir_name, dir_name=raw_dir_name,
source=source_config, source=manifest.source,
description=app_desc, description=manifest.description,
domain=app_dom, domain=domain,
dir_path=app_dir, dir_path=app_dir,
has_compose=has_compose, has_compose=has_compose,
aliases=aliases, aliases=list(manifest.aliases),
visible=app_vis, visible=manifest.visible,
auth=app_auth, auth=manifest.auth,
networks=app_net, networks=list(manifest.networks),
env=app_env, env=dict(manifest.env),
homepage=homepage_config, homepage=manifest.homepage,
manifest_error=manifest_error, manifest_error=manifest_error,
manifest_obj=manifest,
)
if isinstance(manifest, dict):
try:
parsed = parse_manifest(manifest)
return sites_app_from_manifest(app_dir, parsed, manifest_error)
except ManifestValidationError as err:
manifest_error = f"{manifest_error}; {err}" if manifest_error else str(err)
canonical_name = str(manifest.get("name") or raw_dir_name.replace("homelab-", ""))
return SitesApp(
name=canonical_name,
dir_name=raw_dir_name,
domain=f"{canonical_name}.{HOMELAB_DOMAIN}",
description=str(manifest.get("description", "")),
dir_path=app_dir,
manifest_error=manifest_error,
)
canonical_name = raw_dir_name.replace("homelab-", "")
return SitesApp(
name=canonical_name,
dir_name=raw_dir_name,
description="",
domain=f"{canonical_name}.{HOMELAB_DOMAIN}",
dir_path=app_dir,
manifest_error=manifest_error or "Missing app.yaml manifest",
) )
@@ -256,15 +196,36 @@ def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]:
if entry.startswith(".") or not os.path.isdir(app_dir): if entry.startswith(".") or not os.path.isdir(app_dir):
continue continue
manifest_path = os.path.join(app_dir, "app.yaml") manifest_path = os.path.join(app_dir, "app.yaml")
manifest: dict[str, Any] = {} manifest_file = Path(manifest_path)
manifest_error: str | None = None
if not manifest_file.is_file():
apps.append(
sites_app_from_manifest(
app_dir=app_dir,
manifest=None,
manifest_error="Missing app.yaml manifest",
)
)
continue
if os.path.isfile(manifest_path):
try: try:
manifest = load_manifest(manifest_path=manifest_path) manifest_obj = parse_manifest(manifest_file)
except ManifestError as err: apps.append(sites_app_from_manifest(app_dir=app_dir, manifest=manifest_obj))
manifest_error = str(err) except (ManifestValidationError, yaml.YAMLError, OSError, ValueError, KeyError) as err:
apps.append(sites_app_from_manifest(app_dir, manifest, manifest_error)) raw_data = None
with (
contextlib.suppress(Exception),
open(manifest_path, "r", encoding="utf-8") as f,
):
raw_data = yaml.safe_load(f)
app_dict = raw_data if isinstance(raw_data, dict) else {}
apps.append(
sites_app_from_manifest(
app_dir=app_dir,
manifest=app_dict,
manifest_error=str(err),
)
)
return apps return apps
@@ -728,22 +689,17 @@ def cmd_list(args: list[str]) -> None:
app_path = Path(app.dir_path) app_path = Path(app.dir_path)
docker_status = get_docker_status(app_path) docker_status = get_docker_status(app_path)
manifest_file = app_path / "app.yaml" if app.manifest_error:
if manifest_file.is_file(): dep_str = "⚠️ Manifest Error"
try: prov_str = "⚠️ Invalid Manifest"
manifest_obj = parse_manifest(manifest_file)
except (ManifestValidationError, yaml.YAMLError, OSError, ValueError, KeyError):
manifest_obj = Manifest(name=app.name, domain=app.domain)
else: else:
manifest_obj = Manifest(name=app.name, domain=app.domain) manifest_obj = app.manifest_obj or Manifest(name=app.name, domain=app.domain)
two_axis = inspect_workload_two_axis( two_axis = inspect_workload_two_axis(
app_dir=app_path, app_dir=app_path,
manifest=manifest_obj, manifest=manifest_obj,
fetch_upstream=should_fetch, fetch_upstream=should_fetch,
docker_status=docker_status, docker_status=docker_status,
) )
dep_str = two_axis.checkout.status_label dep_str = two_axis.checkout.status_label
prov_str = two_axis.provenance.status.value prov_str = two_axis.provenance.status.value
@@ -816,15 +772,12 @@ def cmd_info(args: list[str]) -> None:
print(f"Auth Protected: {app.auth}") print(f"Auth Protected: {app.auth}")
print(f"Dashboard: {'Visible' if app.visible else 'Hidden'}") print(f"Dashboard: {'Visible' if app.visible else 'Hidden'}")
if app.manifest_error:
print(f"\n⚠️ Manifest Validation Error:\n {app.manifest_error}")
return
app_path = Path(app.dir_path) app_path = Path(app.dir_path)
manifest_file = app_path / "app.yaml" manifest_obj = app.manifest_obj or Manifest(name=app.name, domain=app.domain)
if manifest_file.is_file():
try:
manifest_obj = parse_manifest(manifest_file)
except (ManifestValidationError, yaml.YAMLError, OSError, ValueError, KeyError):
manifest_obj = Manifest(name=app.name, domain=app.domain)
else:
manifest_obj = Manifest(name=app.name, domain=app.domain)
two_axis = inspect_workload_two_axis( two_axis = inspect_workload_two_axis(
app_dir=app_path, app_dir=app_path,
@@ -869,6 +822,9 @@ def cmd_resolve(args: list[str]) -> None:
app = resolve_app(args[0]) app = resolve_app(args[0])
if not app: if not app:
sys.exit(1) sys.exit(1)
if isinstance(app, SitesApp) and app.manifest_error:
print(f"❌ Error: Workload '{app.name}' has invalid manifest: {app.manifest_error}", file=sys.stderr)
sys.exit(1)
print(json.dumps(app.to_dict())) print(json.dumps(app.to_dict()))
+1 -1
View File
@@ -102,7 +102,7 @@ def validate_transport(url: str) -> tuple[TransportScheme, str]:
raise ManifestValidationError(f"Insecure HTTP source URL rejected (HTTPS or SSH required): '{clean_url}'") raise ManifestValidationError(f"Insecure HTTP source URL rejected (HTTPS or SSH required): '{clean_url}'")
raise ManifestValidationError( raise ManifestValidationError(
f"Unsupported source URL scheme: '{clean_url}'. " f"Invalid source.url scheme: '{clean_url}'. "
"Allowed transports are https://, ssh://, or git@<host>:<path>." "Allowed transports are https://, ssh://, or git@<host>:<path>."
) )
+83 -17
View File
@@ -278,26 +278,49 @@ ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"}
ALLOWED_STRATEGIES = {"compose"} ALLOWED_STRATEGIES = {"compose"}
def validate_compose_security(compose_file: Path, allowed_root: Path) -> tuple[bool, str | None]: PROHIBITED_HOST_NAMESPACES = {"host"}
DANGEROUS_SECURITY_OPTS = {"unconfined", "apparmor:unconfined", "seccomp:unconfined"}
def validate_compose_security(
compose_file: Path,
allowed_root: Path,
app_name: str | None = None,
) -> tuple[bool, str | None]:
""" """
Pre-flight AST inspection of workload docker-compose.yml to reject security violations: Pre-flight AST inspection of workload docker-compose.yml enforcing Core platform security invariants:
1. privileged: true 1. File Integrity: regular file, non-symlink (or strictly contained symlink).
2. /var/run/docker.sock bind mounts 2. Privilege Containment: blocks 'privileged: true', 'cap_add', 'devices', and 'security_opt: unconfined'.
3. network_mode: host 3. Host Namespace Isolation: blocks 'pid: host', 'ipc: host', 'uts: host', 'userns_mode: host', 'network_mode: host'.
4. host root bind mounts outside allowed state root or workload directory 4. Docker Socket Ban: blocks direct mounts of /var/run/docker.sock.
5. Top-Level Inclusion Ban: blocks top-level 'include' directives.
6. Bind-Mount & Tenant State Isolation: resolves all relative and absolute host paths. Requires containment
strictly within either the workload root (allowed_root) OR the workload's dedicated state root
(~/var/lib/homelab/<app_name>/). Cross-tenant state mounts are rejected fail-closed.
""" """
if not compose_file.is_file(): if not compose_file.exists():
return True, None return True, None
if not compose_file.is_file():
return False, f"Compose file '{compose_file}' is not a regular file."
canonical_allowed_root = allowed_root.resolve()
if compose_file.is_symlink():
resolved_compose = compose_file.resolve()
if not resolved_compose.is_relative_to(canonical_allowed_root):
return False, f"Compose file symlink escapes workload root: {compose_file} -> {resolved_compose}"
try: try:
content = compose_file.read_text(encoding="utf-8") content = compose_file.read_text(encoding="utf-8")
except OSError as e: except OSError as e:
return False, f"Failed to read compose file {compose_file}: {e}" return False, f"Failed to read compose file {compose_file}: {e}"
yaml_errors = (yaml.YAMLError,) if yaml is not None else ()
if yaml is not None: if yaml is not None:
try: try:
data = yaml.safe_load(content) or {} data = yaml.safe_load(content) or {}
except yaml.YAMLError as e: except yaml_errors as e:
return False, f"Failed to parse compose YAML {compose_file}: {e}" return False, f"Failed to parse compose YAML {compose_file}: {e}"
else: else:
# Fallback regex inspection if yaml module is not present # Fallback regex inspection if yaml module is not present
@@ -307,16 +330,29 @@ def validate_compose_security(compose_file: Path, allowed_root: Path) -> tuple[b
return False, "Docker socket mounts are prohibited in workload compose files." return False, "Docker socket mounts are prohibited in workload compose files."
if re.search(r"^\s*network_mode:\s*[\"']?host[\"']?", content, re.MULTILINE | re.IGNORECASE): if re.search(r"^\s*network_mode:\s*[\"']?host[\"']?", content, re.MULTILINE | re.IGNORECASE):
return False, "Host networking (network_mode: host) is prohibited in workload compose files." return False, "Host networking (network_mode: host) is prohibited in workload compose files."
if re.search(r"^\s*cap_add:\s*", content, re.MULTILINE | re.IGNORECASE):
return False, "Linux capabilities (cap_add) are prohibited in workload compose files."
if re.search(r"^\s*devices:\s*", content, re.MULTILINE | re.IGNORECASE):
return False, "Host device mounts (devices) are prohibited in workload compose files."
if re.search(r"^\s*include:\s*", content, re.MULTILINE | re.IGNORECASE):
return False, "Top-level include directives are prohibited in workload compose files."
return True, None return True, None
if not isinstance(data, dict): if not isinstance(data, dict):
return False, f"Invalid compose root in {compose_file}: expected mapping" return False, f"Invalid compose root in {compose_file}: expected mapping"
if "include" in data:
return False, "Top-level 'include' directives are prohibited in workload compose files."
services = data.get("services") services = data.get("services")
if not isinstance(services, dict): if not isinstance(services, dict):
return True, None return True, None
state_root = Path(os.environ.get("HOMELAB_STATE_ROOT", Path.home() / "var/lib/homelab")).resolve() state_root = Path(os.environ.get("HOMELAB_STATE_ROOT", Path.home() / "var/lib/homelab")).resolve()
target_app_name = app_name or allowed_root.name
target_state_root = (state_root / target_app_name).resolve()
top_volumes = set(data.get("volumes", {}).keys()) if isinstance(data.get("volumes"), dict) else set()
for svc_name, svc in services.items(): for svc_name, svc in services.items():
if not isinstance(svc, dict): if not isinstance(svc, dict):
@@ -325,9 +361,24 @@ def validate_compose_security(compose_file: Path, allowed_root: Path) -> tuple[b
if svc.get("privileged") is True: if svc.get("privileged") is True:
return False, f"Service '{svc_name}' specifies prohibited 'privileged: true'." return False, f"Service '{svc_name}' specifies prohibited 'privileged: true'."
net_mode = str(svc.get("network_mode", "")).strip().lower() cap_add = svc.get("cap_add")
if net_mode == "host": if cap_add:
return False, f"Service '{svc_name}' specifies prohibited 'network_mode: host'." return False, f"Service '{svc_name}' specifies prohibited 'cap_add' capabilities: {cap_add}."
devices = svc.get("devices")
if devices:
return False, f"Service '{svc_name}' specifies prohibited host device mount: {devices}."
sec_opts = svc.get("security_opt", [])
if isinstance(sec_opts, list):
for opt in sec_opts:
if any(bad in str(opt).lower() for bad in ("unconfined", "disable")):
return False, f"Service '{svc_name}' specifies prohibited security_opt: {opt}."
for ns_key in ("network_mode", "pid", "ipc", "uts", "userns_mode"):
val = str(svc.get(ns_key, "")).strip().lower()
if val in PROHIBITED_HOST_NAMESPACES:
return False, f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'."
volumes = svc.get("volumes", []) volumes = svc.get("volumes", [])
if isinstance(volumes, list): if isinstance(volumes, list):
@@ -345,18 +396,33 @@ def validate_compose_security(compose_file: Path, allowed_root: Path) -> tuple[b
if vol.get("type") == "bind": if vol.get("type") == "bind":
host_path = src host_path = src
# Evaluate host_path escapes if not host_path:
if host_path and host_path.startswith(("/", "~")): continue
# Declared top-level named volume without path separators
if host_path in top_volumes and not (host_path.startswith((".", "/", "~")) or "/" in host_path or "\\" in host_path):
continue
# Host bind mount evaluation
if host_path.startswith("~"):
expanded = Path(host_path).expanduser().resolve() expanded = Path(host_path).expanduser().resolve()
# Allowed if inside the workload directory or inside the state root elif Path(host_path).is_absolute():
is_in_workload = allowed_root.is_dir() and expanded.is_relative_to(allowed_root.resolve()) expanded = Path(host_path).resolve()
is_in_state = state_root.is_dir() and expanded.is_relative_to(state_root) else:
if not (is_in_workload or is_in_state): # Relative path resolved against workload root
expanded = (allowed_root / host_path).resolve()
# Containment check: strictly within workload directory or dedicated state root
is_in_workload = allowed_root.is_dir() and expanded.is_relative_to(canonical_allowed_root)
is_in_own_state = expanded.is_relative_to(target_state_root)
if not (is_in_workload or is_in_own_state):
return False, f"Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'." return False, f"Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'."
return True, None return True, None
def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]: def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]:
""" """
Validate deployment policy inside app.yaml. Validate deployment policy inside app.yaml.
+111
View File
@@ -7,6 +7,8 @@ import sys
from pathlib import Path from pathlib import Path
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
import pytest
# Add Core to path so scripts can be imported # Add Core to path so scripts can be imported
CORE_ROOT = Path(__file__).resolve().parent.parent.parent CORE_ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(CORE_ROOT / "scripts")) sys.path.insert(0, str(CORE_ROOT / "scripts"))
@@ -786,6 +788,115 @@ def test_validate_compose_security_nonexistent_file(tmp_path: Path):
assert err is None assert err is None
@pytest.mark.parametrize("malicious_volume", [
"../../etc/passwd:/mnt/passwd:ro",
"./../../Core/nixos/secrets.yaml:/secrets.yaml",
"../other-workload/data:/data",
])
def test_validate_compose_security_blocks_relative_traversal(
tmp_path: Path, malicious_volume: str
):
"""Ensure relative path traversals in volume mounts cannot escape workload root."""
app_dir = tmp_path / "my-app"
app_dir.mkdir(parents=True)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"services:\n web:\n image: nginx\n volumes:\n - '{malicious_volume}'\n",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
assert valid is False, f"Expected relative traversal '{malicious_volume}' to be rejected!"
assert err is not None and "prohibited host bind mount" in err
def test_validate_compose_security_blocks_cross_tenant_state_mounts(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
"""Ensure workload 'my-app' cannot mount another workload's state directory ('other-app')."""
sites_dir = tmp_path / "Sites"
app_dir = sites_dir / "my-app"
app_dir.mkdir(parents=True)
state_root = tmp_path / "var/lib/homelab"
(state_root / "my-app").mkdir(parents=True)
(state_root / "other-app").mkdir(parents=True)
monkeypatch.setenv("HOMELAB_STATE_ROOT", str(state_root))
# Cross-tenant state mount
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"services:\n web:\n image: nginx\n volumes:\n - '{state_root}/other-app:/data'\n",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
assert valid is False, "Expected cross-tenant state mount to be rejected!"
assert err is not None and ("prohibited host bind mount" in err or "cross-tenant" in err.lower())
# Authorized own state mount must pass
compose_file.write_text(
f"services:\n web:\n image: nginx\n volumes:\n - '{state_root}/my-app:/data'\n",
encoding="utf-8",
)
valid_own, err_own = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
assert valid_own is True, f"Own state mount should be permitted, got error: {err_own}"
@pytest.mark.parametrize("unsafe_directive", [
"cap_add:\n - SYS_ADMIN",
"pid: host",
"ipc: host",
"userns_mode: host",
"devices:\n - /dev/sda:/dev/sda",
"security_opt:\n - apparmor:unconfined",
])
def test_validate_compose_security_blocks_privilege_escalation_primitives(
tmp_path: Path, unsafe_directive: str
):
"""Ensure dangerous container breakout capabilities and host namespaces are blocked."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
f"services:\n app:\n image: alpine\n {unsafe_directive}\n",
encoding="utf-8",
)
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="app")
assert valid is False, f"Directive should be blocked:\n{unsafe_directive}"
assert err is not None
def test_validate_compose_security_rejects_top_level_include(tmp_path: Path):
"""Ensure top-level Compose include directives are rejected to prevent out-of-tree includes."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text("""
include:
- /etc/shadow
services:
app:
image: alpine
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="app")
assert valid is False
assert err is not None and "include" in err.lower()
def test_validate_compose_security_rejects_symlink_escape(tmp_path: Path):
"""Ensure docker-compose.yml cannot be a symlink escaping the workload directory."""
app_dir = tmp_path / "my-app"
app_dir.mkdir(parents=True)
outside_file = tmp_path / "outside-compose.yml"
outside_file.write_text("services:\n app:\n image: alpine\n", encoding="utf-8")
compose_link = app_dir / "docker-compose.yml"
compose_link.symlink_to(outside_file)
valid, err = gitops_dispatcher.validate_compose_security(compose_link, app_dir, app_name="my-app")
assert valid is False
assert err is not None and "symlink" in err.lower()
+85
View File
@@ -378,3 +378,88 @@ def test_resolve_core_stack_type():
assert traefik is not None assert traefik is not None
assert traefik.to_dict()["type"] == "core_service" assert traefik.to_dict()["type"] == "core_service"
assert traefik.container == "traefik" assert traefik.container == "traefik"
def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(app_factory: AppFactory):
"""Ensure manifest parsing uses core_manifest and catches invalid env keys."""
app_factory.create(
dir_name="homelab-badenv",
manifest_yaml="""
name: badenv
env:
PATH: /override/bin
""",
)
apps = engine.get_sites_apps()
app = engine.resolve_app("badenv", apps)
assert app is not None
assert app.manifest_error is not None
assert "Invalid or reserved environment variable key" in app.manifest_error
def test_cmd_resolve_fails_closed_on_manifest_error(app_factory: AppFactory, capsys: pytest.CaptureFixture):
"""Ensure cmd_resolve exits with non-zero on workload with manifest errors."""
app_factory.create(
dir_name="homelab-corrupt",
manifest_yaml="""
name: corrupt
env:
ILLEGAL-KEY: forbidden
""",
)
with pytest.raises(SystemExit) as exc_info:
engine.cmd_resolve(["corrupt"])
assert exc_info.value.code != 0
captured = capsys.readouterr()
assert "invalid manifest" in captured.err.lower() or "error" in captured.err.lower()
def test_cmd_resolve_fails_closed_on_missing_app_yaml(mock_sites_dir: Path):
"""Ensure cmd_resolve exits with non-zero if workload has no app.yaml."""
no_manifest_dir = mock_sites_dir / "homelab-nomanifest"
no_manifest_dir.mkdir(parents=True, exist_ok=True)
with pytest.raises(SystemExit) as exc_info:
engine.cmd_resolve(["nomanifest"])
assert exc_info.value.code != 0
def test_unification_uses_core_manifest_dataclasses(app_factory: AppFactory):
"""Ensure SitesApp uses core_manifest SourceConfig and HomepageConfig."""
import core_manifest
app_factory.create(
dir_name="homelab-unified",
manifest_yaml="""
name: unified
source:
url: https://git.roadtotech.me/kiskaadee/unified.git
ref: v1.0.0
homepage:
title: Unified App
weight: 30
""",
)
apps = engine.get_sites_apps()
app = engine.resolve_app("unified", apps)
assert app is not None
assert isinstance(app.source, core_manifest.SourceConfig)
assert isinstance(app.homepage, core_manifest.HomepageConfig)
assert app.source.ref_type == core_manifest.RefType.TAG
assert app.source.transport == core_manifest.TransportScheme.HTTPS
def test_cmd_list_flags_manifest_error(app_factory: AppFactory, capsys: pytest.CaptureFixture):
"""Ensure cmd_list flags workloads with manifest errors instead of swallowing them."""
app_factory.create(
dir_name="homelab-broken",
manifest_yaml="""
name: broken
env:
SHELL: /bin/sh
""",
)
engine.cmd_list([])
captured = capsys.readouterr()
assert "Manifest Error" in captured.out
+2 -1
View File
@@ -14,7 +14,8 @@ x 2026-10-13 (C) Establish P4 acceptance test matrix and definition of done befo
x 2026-10-14 (A) Eliminate eval in scripts/appctl and enforce strict env key validation in scripts/core_manifest.py +security @appctl x 2026-10-14 (A) Eliminate eval in scripts/appctl and enforce strict env key validation in scripts/core_manifest.py +security @appctl
x 2026-10-15 (A) Enforce deployments.yaml as sole registry and remove dynamic discovery fallback in scripts/gitops_dispatcher.py +registry @gitops x 2026-10-15 (A) Enforce deployments.yaml as sole registry and remove dynamic discovery fallback in scripts/gitops_dispatcher.py +registry @gitops
(A) Harden validate_compose_security in scripts/gitops_dispatcher.py blocking relative traversal, cross-tenant mounts, and privilege escalation +compose @gitops x 2026-10-15 (A) Harden validate_compose_security in scripts/gitops_dispatcher.py blocking relative traversal, cross-tenant mounts, and privilege escalation +compose @gitops
(A) Unify manifest parsing on core_manifest.py and eliminate duplicate parsers in scripts/appctl_engine.py +manifest @engine (A) Unify manifest parsing on core_manifest.py and eliminate duplicate parsers in scripts/appctl_engine.py +manifest @engine
(A) Scaffold asyncio daemon server supporting dual transports (Unix socket /run/homelab/appctl.sock and HTTP) in scripts/appctl_daemon.py +daemon @p4 (A) Scaffold asyncio daemon server supporting dual transports (Unix socket /run/homelab/appctl.sock and HTTP) in scripts/appctl_daemon.py +daemon @p4
(A) Implement unit and integration tests for dual-transport requests and error handling in tests/unit/test_appctl_daemon.py +test @p4 (A) Implement unit and integration tests for dual-transport requests and error handling in tests/unit/test_appctl_daemon.py +test @p4