Compare commits
3
Commits
0d9a2ce511
...
5ed61acf32
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ed61acf32 | ||
|
|
93feb0d3f2 | ||
|
|
8356819f08 |
No files matched your search
+26
-12
@@ -1,6 +1,6 @@
|
||||
# ⚡ 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 │
|
||||
│ Maps logical names to trusted local paths │
|
||||
│ Rejects path traversal & symlink escapes │
|
||||
│ 3. Authoritative Registry Resolution │
|
||||
│ Maps names via Core/config/deployments.yaml│
|
||||
│ 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 │
|
||||
│ 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`).
|
||||
* Missing, empty, or mismatched signatures are rejected.
|
||||
|
||||
### C. Trusted Repository Resolution
|
||||
* Webhook payloads identify targets by logical name (e.g. `docs`, `homelab-docs`), never by raw filesystem path.
|
||||
* The engine resolves names against a trusted mapping derived from:
|
||||
1. Authoritative Data Vaults (`~/Brain` via aliases `second-brain`, `Brain`, `brain`).
|
||||
2. Workload directories in `~/Sites` by parsing `app.yaml`.
|
||||
* **Input Validation**: Names must match `^[a-zA-Z0-9][a-zA-Z0-9._-]*$`. Slashes, backslashes, and `..` are rejected.
|
||||
* **Containment Check**: Resolved target paths must reside within `~/Sites` or `~/Brain`. Symlinks pointing outside these roots are rejected.
|
||||
### C. Authoritative Repository Registry (`deployments.yaml`)
|
||||
* Webhook payloads identify targets strictly by logical name (e.g. `docs`, `homelab-docs`), never by raw filesystem path.
|
||||
* `Core/config/deployments.yaml` is the **sole admission authority** for GitOps workloads.
|
||||
* **No Dynamic Discovery**: Scanning `~/Sites` dynamically is strictly prohibited. An unapproved directory created on disk cannot receive webhook deployment rights merely by providing an `app.yaml`.
|
||||
* **Fail-Closed Guarantee**: If `deployments.yaml` is missing, unreadable, or malformed, the dispatcher fails closed and admits zero repositories.
|
||||
* **Input Validation**: Names must match `^[a-zA-Z0-9][a-zA-Z0-9._-]*$`. Slashes, backslashes, and path traversal sequences (`..`) are rejected.
|
||||
* **Containment Check**: Declared repository paths must resolve strictly within `~/Sites`. Paths escaping `~/Sites` are rejected during registry loading.
|
||||
|
||||
### D. Revision-Consistent Manifest Validation
|
||||
* 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.).
|
||||
* 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
|
||||
|
||||
To avoid blocking HTTP connections and handle overlapping pushes:
|
||||
|
||||
+99
-143
@@ -19,7 +19,13 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
from core_manifest import Manifest, ManifestValidationError, parse_manifest
|
||||
from core_manifest import (
|
||||
HomepageConfig,
|
||||
Manifest,
|
||||
ManifestValidationError,
|
||||
SourceConfig,
|
||||
parse_manifest,
|
||||
)
|
||||
from provenance import (
|
||||
get_local_checkout_status,
|
||||
inspect_workload_two_axis,
|
||||
@@ -64,39 +70,15 @@ def validate_environment() -> None:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
class ManifestError(Exception):
|
||||
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)
|
||||
ManifestError = ManifestValidationError
|
||||
|
||||
|
||||
@dataclass
|
||||
class App:
|
||||
name: str # Canonical identifier (e.g., "traefik", "jellyfin")
|
||||
description: str # Human-readable summary for dashboards and CLI info
|
||||
domain: str # Routing FQDN (e.g., "auth.roadtotech.me") or "internal".
|
||||
dir_path: str # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
|
||||
description: str = "" # Human-readable summary for dashboards and CLI info
|
||||
domain: str = "" # Routing FQDN (e.g., "auth.roadtotech.me") or "internal".
|
||||
dir_path: str = "" # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
|
||||
|
||||
@property
|
||||
def is_internal(self) -> bool:
|
||||
@@ -131,116 +113,74 @@ class SitesApp(App):
|
||||
env: dict[str, Any] = field(default_factory=dict) # Environment variable overrides
|
||||
homepage: HomepageConfig | None = None # Dashboard Card Configuration
|
||||
manifest_error: str | None = None # Captured syntax/loading errors
|
||||
manifest_obj: Manifest | None = None # Parsed authoritative Manifest
|
||||
app_type: str = "app"
|
||||
|
||||
|
||||
def load_manifest(manifest_path: str) -> dict[str, Any]:
|
||||
"""Load and parse the app manifest file."""
|
||||
if not os.path.isfile(manifest_path):
|
||||
raise FileNotFoundError(f"Manifest file not found at {manifest_path}")
|
||||
|
||||
try:
|
||||
with open(manifest_path, "r", encoding="utf-8") as file:
|
||||
manifest_data = yaml.safe_load(file) or {}
|
||||
except (yaml.YAMLError, OSError) as err:
|
||||
raise ManifestError(f"YAML parsing failed: {err}") from err
|
||||
|
||||
if not isinstance(manifest_data, dict):
|
||||
raise ManifestError(f"Invalid manifest root: expected `dict`, got `{type(manifest_data).__name__}`")
|
||||
|
||||
return manifest_data
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Serialize for JSON consumption by scripts/appctl"""
|
||||
data = asdict(self)
|
||||
data.pop("manifest_obj", None)
|
||||
data["type"] = getattr(self, "app_type", "app")
|
||||
return data
|
||||
|
||||
|
||||
def sites_app_from_manifest(
|
||||
app_dir: str,
|
||||
manifest: dict[str, Any],
|
||||
manifest: Manifest | dict[str, Any] | None = None,
|
||||
manifest_error: str | None = None,
|
||||
) -> 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)
|
||||
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 = (
|
||||
os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or
|
||||
os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
|
||||
)
|
||||
|
||||
# Manifest Data parsing
|
||||
raw_desc = manifest.get("description")
|
||||
app_desc: str = str(raw_desc) if raw_desc is not None else ""
|
||||
|
||||
raw_dom = manifest.get("domain")
|
||||
app_dom = str(raw_dom) if raw_dom is not None else f"{canonical_name}.{HOMELAB_DOMAIN}"
|
||||
|
||||
app_net = manifest.get("networks")
|
||||
if not isinstance(app_net, list):
|
||||
app_net = ["proxy-net"]
|
||||
|
||||
app_env = manifest.get("env")
|
||||
if not isinstance(app_env, dict):
|
||||
app_env = {}
|
||||
|
||||
def _as_bool(value: Any, default: bool) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return default
|
||||
|
||||
app_vis = _as_bool(manifest.get("visible"), True)
|
||||
app_auth = _as_bool(manifest.get("auth"), True)
|
||||
|
||||
# Source provenance normalization
|
||||
source_config: SourceConfig | None = None
|
||||
raw_source = manifest.get("source")
|
||||
if isinstance(raw_source, dict):
|
||||
source_url = str(raw_source.get("url") or "")
|
||||
allowed_schemes = ("https://", "ssh://", "git@")
|
||||
if source_url:
|
||||
if not any(source_url.startswith(s) for s in allowed_schemes):
|
||||
err = f"Invalid source.url scheme: must start with {', '.join(allowed_schemes)}"
|
||||
manifest_error = f"{manifest_error}; {err}" if manifest_error else err
|
||||
else:
|
||||
source_config = SourceConfig(
|
||||
type=str(raw_source.get("type") or "git"),
|
||||
url=source_url,
|
||||
ref=str(raw_source.get("ref") or "main"),
|
||||
)
|
||||
|
||||
canonical_name = manifest.name
|
||||
domain = manifest.domain or f"{canonical_name}.{HOMELAB_DOMAIN}"
|
||||
return SitesApp(
|
||||
name=canonical_name,
|
||||
dir_name=raw_dir_name,
|
||||
source=source_config,
|
||||
description=app_desc,
|
||||
domain=app_dom,
|
||||
source=manifest.source,
|
||||
description=manifest.description,
|
||||
domain=domain,
|
||||
dir_path=app_dir,
|
||||
has_compose=has_compose,
|
||||
aliases=aliases,
|
||||
visible=app_vis,
|
||||
auth=app_auth,
|
||||
networks=app_net,
|
||||
env=app_env,
|
||||
homepage=homepage_config,
|
||||
aliases=list(manifest.aliases),
|
||||
visible=manifest.visible,
|
||||
auth=manifest.auth,
|
||||
networks=list(manifest.networks),
|
||||
env=dict(manifest.env),
|
||||
homepage=manifest.homepage,
|
||||
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):
|
||||
continue
|
||||
manifest_path = os.path.join(app_dir, "app.yaml")
|
||||
manifest: dict[str, Any] = {}
|
||||
manifest_error: str | None = None
|
||||
manifest_file = Path(manifest_path)
|
||||
|
||||
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:
|
||||
manifest = load_manifest(manifest_path=manifest_path)
|
||||
except ManifestError as err:
|
||||
manifest_error = str(err)
|
||||
apps.append(sites_app_from_manifest(app_dir, manifest, manifest_error))
|
||||
manifest_obj = parse_manifest(manifest_file)
|
||||
apps.append(sites_app_from_manifest(app_dir=app_dir, manifest=manifest_obj))
|
||||
except (ManifestValidationError, yaml.YAMLError, OSError, ValueError, KeyError) as err:
|
||||
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
|
||||
|
||||
@@ -728,22 +689,17 @@ def cmd_list(args: list[str]) -> None:
|
||||
app_path = Path(app.dir_path)
|
||||
docker_status = get_docker_status(app_path)
|
||||
|
||||
manifest_file = app_path / "app.yaml"
|
||||
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)
|
||||
if app.manifest_error:
|
||||
dep_str = "⚠️ Manifest Error"
|
||||
prov_str = "⚠️ Invalid Manifest"
|
||||
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(
|
||||
app_dir=app_path,
|
||||
manifest=manifest_obj,
|
||||
fetch_upstream=should_fetch,
|
||||
docker_status=docker_status,
|
||||
)
|
||||
|
||||
dep_str = two_axis.checkout.status_label
|
||||
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"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)
|
||||
manifest_file = app_path / "app.yaml"
|
||||
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)
|
||||
manifest_obj = app.manifest_obj or Manifest(name=app.name, domain=app.domain)
|
||||
|
||||
two_axis = inspect_workload_two_axis(
|
||||
app_dir=app_path,
|
||||
@@ -869,6 +822,9 @@ def cmd_resolve(args: list[str]) -> None:
|
||||
app = resolve_app(args[0])
|
||||
if not app:
|
||||
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()))
|
||||
|
||||
|
||||
|
||||
@@ -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"Unsupported source URL scheme: '{clean_url}'. "
|
||||
f"Invalid source.url scheme: '{clean_url}'. "
|
||||
"Allowed transports are https://, ssh://, or git@<host>:<path>."
|
||||
)
|
||||
|
||||
|
||||
@@ -278,26 +278,49 @@ ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"}
|
||||
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:
|
||||
1. privileged: true
|
||||
2. /var/run/docker.sock bind mounts
|
||||
3. network_mode: host
|
||||
4. host root bind mounts outside allowed state root or workload directory
|
||||
Pre-flight AST inspection of workload docker-compose.yml enforcing Core platform security invariants:
|
||||
1. File Integrity: regular file, non-symlink (or strictly contained symlink).
|
||||
2. Privilege Containment: blocks 'privileged: true', 'cap_add', 'devices', and 'security_opt: unconfined'.
|
||||
3. Host Namespace Isolation: blocks 'pid: host', 'ipc: host', 'uts: host', 'userns_mode: host', 'network_mode: host'.
|
||||
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
|
||||
|
||||
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:
|
||||
content = compose_file.read_text(encoding="utf-8")
|
||||
except OSError as 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:
|
||||
try:
|
||||
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}"
|
||||
else:
|
||||
# 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."
|
||||
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."
|
||||
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
|
||||
|
||||
if not isinstance(data, dict):
|
||||
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")
|
||||
if not isinstance(services, dict):
|
||||
return True, None
|
||||
|
||||
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():
|
||||
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:
|
||||
return False, f"Service '{svc_name}' specifies prohibited 'privileged: true'."
|
||||
|
||||
net_mode = str(svc.get("network_mode", "")).strip().lower()
|
||||
if net_mode == "host":
|
||||
return False, f"Service '{svc_name}' specifies prohibited 'network_mode: host'."
|
||||
cap_add = svc.get("cap_add")
|
||||
if cap_add:
|
||||
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", [])
|
||||
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":
|
||||
host_path = src
|
||||
|
||||
# Evaluate host_path escapes
|
||||
if host_path and host_path.startswith(("/", "~")):
|
||||
if not host_path:
|
||||
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()
|
||||
# Allowed if inside the workload directory or inside the state root
|
||||
is_in_workload = allowed_root.is_dir() and expanded.is_relative_to(allowed_root.resolve())
|
||||
is_in_state = state_root.is_dir() and expanded.is_relative_to(state_root)
|
||||
if not (is_in_workload or is_in_state):
|
||||
elif Path(host_path).is_absolute():
|
||||
expanded = Path(host_path).resolve()
|
||||
else:
|
||||
# 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 True, None
|
||||
|
||||
|
||||
|
||||
def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]:
|
||||
"""
|
||||
Validate deployment policy inside app.yaml.
|
||||
|
||||
@@ -7,6 +7,8 @@ import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
# Add Core to path so scripts can be imported
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
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
|
||||
|
||||
|
||||
@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()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -378,3 +378,88 @@ def test_resolve_core_stack_type():
|
||||
assert traefik is not None
|
||||
assert traefik.to_dict()["type"] == "core_service"
|
||||
assert traefik.container == "traefik"
|
||||
|
||||
|
||||
def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(app_factory: AppFactory):
|
||||
"""Ensure manifest parsing uses core_manifest and catches invalid env keys."""
|
||||
app_factory.create(
|
||||
dir_name="homelab-badenv",
|
||||
manifest_yaml="""
|
||||
name: badenv
|
||||
env:
|
||||
PATH: /override/bin
|
||||
""",
|
||||
)
|
||||
apps = engine.get_sites_apps()
|
||||
app = engine.resolve_app("badenv", apps)
|
||||
assert app is not None
|
||||
assert app.manifest_error is not None
|
||||
assert "Invalid or reserved environment variable key" in app.manifest_error
|
||||
|
||||
|
||||
def test_cmd_resolve_fails_closed_on_manifest_error(app_factory: AppFactory, capsys: pytest.CaptureFixture):
|
||||
"""Ensure cmd_resolve exits with non-zero on workload with manifest errors."""
|
||||
app_factory.create(
|
||||
dir_name="homelab-corrupt",
|
||||
manifest_yaml="""
|
||||
name: corrupt
|
||||
env:
|
||||
ILLEGAL-KEY: forbidden
|
||||
""",
|
||||
)
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
engine.cmd_resolve(["corrupt"])
|
||||
assert exc_info.value.code != 0
|
||||
captured = capsys.readouterr()
|
||||
assert "invalid manifest" in captured.err.lower() or "error" in captured.err.lower()
|
||||
|
||||
|
||||
def test_cmd_resolve_fails_closed_on_missing_app_yaml(mock_sites_dir: Path):
|
||||
"""Ensure cmd_resolve exits with non-zero if workload has no app.yaml."""
|
||||
no_manifest_dir = mock_sites_dir / "homelab-nomanifest"
|
||||
no_manifest_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
engine.cmd_resolve(["nomanifest"])
|
||||
assert exc_info.value.code != 0
|
||||
|
||||
|
||||
def test_unification_uses_core_manifest_dataclasses(app_factory: AppFactory):
|
||||
"""Ensure SitesApp uses core_manifest SourceConfig and HomepageConfig."""
|
||||
import core_manifest
|
||||
|
||||
app_factory.create(
|
||||
dir_name="homelab-unified",
|
||||
manifest_yaml="""
|
||||
name: unified
|
||||
source:
|
||||
url: https://git.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
|
||||
|
||||
@@ -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-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) 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
|
||||
|
||||
Reference in new issue
Block a user