Files
nixos-core/scripts/gitops_dispatcher.py
kiskaadee 1a8e3b5eae
Core Architecture & Invariant CI / validate (pull_request) Failing after 0s
fix(security,tests): harden compose fallback, root UID check, and split grant tests
- Fail closed in validate_compose_security() when PyYAML is unavailable instead of regex fallback (CR-01)

- Reject zero-padded root UIDs (e.g. 00:1000) in _validate_service_user() via int() parsing (CR-02)

- Extract _resolve_contained_host_path() and _validate_service_volumes() and add docstrings across capability helpers (CR-03, CR-04)

- Fix missing-device-node test and split multi-behavior grant tests into focused single-behavior tests (Axis 3 CR-01, CR-02)
2026-11-21 04:13:59 -05:00

1944 lines
70 KiB
Python
Executable File

#!/usr/bin/env python3
"""
gitops_dispatcher.py - Dynamic Decentralized GitOps Deployment Engine for Homelab
Receives Gitea/Git webhook payloads, dynamically resolves target repositories
in ~/Sites (via app.yaml) or data vaults (like ~/Brain), and executes the declared
deployment actions with zero Core restarts.
"""
import contextlib
import datetime
import fcntl
import grp
import hashlib
import hmac
import http.client
import json
import logging
import os
import re
import subprocess
import sys
from collections.abc import Callable
from pathlib import Path, PurePosixPath
from typing import Any
from appctl_contracts import OperationRequest, OperationType
from core_manifest import (
ALLOWED_ACTIONS,
ALLOWED_STRATEGIES,
ManifestValidationError,
parse_manifest,
)
from pydantic import ValidationError
from workload_grants import (
PRIVILEGED_GROUPS,
WorkloadGrant,
WorkloadGrantsError,
load_workload_grants,
)
try:
import yaml
except ImportError:
yaml = None
WORKLOADS_DIR = Path(
os.environ.get("WORKLOADS_DIR")
or os.environ.get("SITES_DIR")
or os.path.expanduser("~/Workloads")
)
SITES_DIR = WORKLOADS_DIR
CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent))
CONFIG_DIR = Path(
os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab"))
)
DEPLOYMENTS_FILE = Path(
os.environ.get("HOMELAB_DEPLOYMENTS_FILE") or (WORKLOADS_DIR / "deployments.yaml")
)
DEFAULT_SECRET_PATH = Path(
os.environ.get("GITOPS_SECRET_FILE", "/run/secrets/gitops/webhook_secret")
)
STATE_DIR = Path(
os.environ.get("GITOPS_STATE_DIR", Path.home() / ".local/state/homelab/gitops")
)
DEFAULT_APPCTL_SOCKET_PATH = Path(
os.environ.get("APPCTL_SOCKET_PATH", "/run/homelab/appctl.sock")
)
DEFAULT_APPCTL_TOKEN_PATH = Path(
os.environ.get("GITOPS_APPCTL_TOKEN_FILE", "/run/secrets/gitops/appctl_token")
)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] [GitOps] %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger = logging.getLogger("gitops_dispatcher")
def load_appctl_token(token_file: Path | None = None) -> str | None:
"""
Load Bearer token for appctl daemon communication from environment or secrets file.
"""
if "GITOPS_APPCTL_TOKEN" in os.environ:
return os.environ["GITOPS_APPCTL_TOKEN"].strip()
path = token_file or DEFAULT_APPCTL_TOKEN_PATH
if path.is_file():
try:
return path.read_text(encoding="utf-8").strip()
except OSError as e:
logger.error(f"Failed to read appctl token from {path}: {e}")
return None
return None
def execute_deployment_via_daemon(
target: str,
branch: str,
socket_path: Path | str | None = None,
token: str | None = None,
) -> bool:
"""
Execute deployment by delegating workload.update to appctl daemon over UDS.
"""
sock = Path(socket_path or DEFAULT_APPCTL_SOCKET_PATH)
auth_token = token or load_appctl_token()
logger.info(
f"Delegating workload.update for '{target}' to daemon at {sock} (branch: {branch})"
)
from appctl_daemon import send_daemon_request
try:
req = OperationRequest(
operation=OperationType.WORKLOAD_UPDATE,
target=target,
parameters={"expected_branch": branch},
)
resp = send_daemon_request(
endpoint=sock,
operation_request=req,
token=auth_token,
timeout=330.0,
)
if resp.success:
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}")
return False
except (
OSError,
http.client.HTTPException,
json.JSONDecodeError,
ValidationError,
TimeoutError,
KeyError,
TypeError,
ValueError,
) as e:
logger.error(f"❌ Failed to communicate with appctl daemon at {sock}: {e}")
return False
def load_webhook_secret(secret_file: Path | None = None) -> bytes:
"""
Load webhook shared secret from projected secret file or environment.
Never hardcoded in code or repository manifests.
"""
path = secret_file or Path(
os.environ.get("GITOPS_SECRET_FILE", DEFAULT_SECRET_PATH)
)
if path.is_file():
try:
return path.read_bytes().strip()
except OSError as e:
logger.error(f"Failed to read webhook secret from {path}: {e}")
return b""
env_secret = os.environ.get("GITOPS_WEBHOOK_SECRET")
if env_secret:
return env_secret.strip().encode("utf-8")
return b""
def verify_signature(raw_body: bytes, signature: str | None, secret: bytes) -> bool:
"""
Verify incoming webhook HMAC-SHA256 signature using constant-time comparison.
Primary Gitea path: X-Gitea-Signature provides the bare 64-character hex digest of the raw body.
Compatibility path: X-Hub-Signature-256 provides 'sha256=<hex>'.
Fail-closed: missing signature, malformed signature, empty secret, or mismatch returns False.
"""
if not secret:
logger.error(
"Authentication failed: Webhook shared secret is empty or missing."
)
return False
if not signature or not isinstance(signature, str):
logger.error("Authentication failed: Missing signature header.")
return False
cleaned_signature = signature.strip()
cleaned_signature = cleaned_signature.removeprefix("sha256=")
# SHA256 hex digest is exactly 64 hexadecimal characters
if len(cleaned_signature) != 64 or not all(
c in "0123456789abcdefABCDEF" for c in cleaned_signature
):
logger.error("Authentication failed: Malformed signature format.")
return False
expected_mac = hmac.new(secret, raw_body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected_mac.lower(), cleaned_signature.lower()):
logger.error("Authentication failed: Signature mismatch.")
return False
return True
def parse_yaml_simple(text: str) -> dict:
"""Lightweight, zero-dependency YAML parser tailored for app.yaml manifests."""
data = {}
current_section = None
current_subsection = None
lines = text.splitlines()
for line in lines:
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
indent = len(line) - len(line.lstrip(" "))
# List item
if stripped.startswith("- "):
item = stripped[2:].strip().strip("\"'")
if current_section:
if current_subsection and isinstance(data.get(current_section), dict):
if not isinstance(
data[current_section].get(current_subsection), list
):
data[current_section][current_subsection] = []
data[current_section][current_subsection].append(item)
else:
if not isinstance(data.get(current_section), list):
data[current_section] = []
data[current_section].append(item)
continue
if ":" in stripped:
k, v = stripped.split(":", 1)
k = k.strip()
v = v.strip().strip("\"'")
if v.lower() == "true":
v = True
elif v.lower() == "false":
v = False
elif v.isdigit():
v = int(v)
if indent == 0:
current_section = k
current_subsection = None
if v == "":
data[k] = {}
else:
data[k] = v
elif indent > 0 and current_section:
if not isinstance(data.get(current_section), dict):
data[current_section] = {}
current_subsection = k
if v == "":
data[current_section][k] = []
else:
data[current_section][k] = v
return data
REPO_NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]*$")
def get_trusted_repository_mapping() -> dict[str, Path]:
"""
Build authoritative mapping of logical repository identities to local paths.
Webhook payloads can only select repositories defined in this mapping.
Workloads admission registry (~/Workloads/deployments.yaml, templated by config/deployments.yaml) is the sole admission authority.
Fails closed if the registry is missing, unreadable, or malformed.
"""
mapping: dict[str, Path] = {}
registry_file = DEPLOYMENTS_FILE
if not registry_file.is_file():
logger.error(
f"Authoritative registry {registry_file} not found. Failing closed with zero admitted repositories."
)
return mapping
yaml_errors = (yaml.YAMLError,) if yaml is not None else ()
try:
content = registry_file.read_text(encoding="utf-8")
registry = (
yaml.safe_load(content) if yaml else parse_yaml_simple(content)
) or {}
repo_entries = (
registry.get("repositories", registry) if isinstance(registry, dict) else {}
)
if isinstance(repo_entries, dict):
for reg_name, entry in repo_entries.items():
if not isinstance(entry, dict):
continue
raw_path = entry.get("path")
if not raw_path:
continue
if raw_path.startswith("~/Workloads/") or raw_path == "~/Workloads":
sub = raw_path[len("~/Workloads") :].lstrip("/")
p = (SITES_DIR / sub).resolve() if sub else SITES_DIR.resolve()
elif raw_path.startswith("~/Sites/") or raw_path == "~/Sites":
sub = raw_path[len("~/Sites") :].lstrip("/")
p = (SITES_DIR / sub).resolve() if sub else SITES_DIR.resolve()
else:
p = Path(raw_path).expanduser().resolve()
# Enforce strict containment strictly inside SITES_DIR
if SITES_DIR.is_dir() and p.is_relative_to(SITES_DIR.resolve()):
mapping[reg_name] = p
raw_aliases = entry.get("aliases", [])
if isinstance(raw_aliases, str):
raw_aliases = [raw_aliases]
if isinstance(raw_aliases, list):
for alias in raw_aliases:
if isinstance(alias, str) and alias.strip():
mapping[alias.strip()] = p
else:
logger.warning(
f"Rejecting out-of-bounds path in deployments.yaml for '{reg_name}': {p}"
)
else:
logger.error(
f"Malformed repositories block in {registry_file}: expected dictionary mapping."
)
return {}
except (
OSError,
UnicodeDecodeError,
ValueError,
KeyError,
AttributeError,
TypeError,
*yaml_errors,
) as e:
logger.critical(
f"Failed to parse authoritative registry {registry_file}: {e}. Failing closed."
)
return {}
return mapping
def resolve_repository(repo_name: str) -> Path | None:
"""
Resolve a logical repository identity to a trusted local directory.
Rejects directory traversal, unknown repositories, and path escapes.
"""
if not repo_name or not isinstance(repo_name, str):
return None
cleaned_name = repo_name.strip()
if not REPO_NAME_RE.match(cleaned_name):
logger.warning(f"Invalid repository name format rejected: '{repo_name}'")
return None
if ".." in cleaned_name or "/" in cleaned_name or "\\" in cleaned_name:
logger.warning(
f"Path traversal characters detected in repository name: '{repo_name}'"
)
return None
trusted_mapping = get_trusted_repository_mapping()
target = trusted_mapping.get(cleaned_name)
if not target:
logger.warning(
f"Repository '{cleaned_name}' is not in trusted repository registry."
)
return None
try:
canonical_target = target.resolve()
except (OSError, RuntimeError) as e:
logger.warning(f"Failed to resolve target path for '{cleaned_name}': {e}")
return None
if not canonical_target.is_dir():
logger.warning(
f"Trusted repository target '{canonical_target}' does not exist or is not a directory."
)
return None
# Defense-in-depth: check allowed root containment strictly within SITES_DIR
if not (
SITES_DIR.is_dir() and canonical_target.is_relative_to(SITES_DIR.resolve())
):
logger.warning(
f"Resolved path '{canonical_target}' escapes allowed SITES_DIR root for repository '{cleaned_name}'."
)
return None
return canonical_target
def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
"""
Dynamically resolve target directory and deployment configuration.
Uses resolve_repository() as the single authoritative resolver.
"""
target_dir = resolve_repository(repo_name)
if not target_dir:
return None, {}
manifest_file = target_dir / "app.yaml"
manifest = {}
if manifest_file.is_file():
try:
manifest_text = manifest_file.read_text(encoding="utf-8")
manifest = (
yaml.safe_load(manifest_text)
if yaml
else parse_yaml_simple(manifest_text)
) or {}
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
logger.warning(f"Failed to parse {manifest_file}: {e}")
deployment_config = manifest.get("deployment")
if not isinstance(deployment_config, dict):
deployment_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
return target_dir, deployment_config
PROHIBITED_HOST_NAMESPACES = {"host"}
DANGEROUS_SECURITY_OPTS = {"unconfined", "apparmor:unconfined", "seccomp:unconfined"}
UNSAFE_BIND_PROPAGATIONS = {"shared", "rshared", "slave", "rslave"}
_COMPOSE_VAR_RE = re.compile(
r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?:(:-|-)([^}]*))?\}"
)
def _interpolate_compose_value(
value: str, resolved_env: dict[str, str] | None
) -> str:
"""Resolve ${VAR}, ${VAR:-default}, and ${VAR-default} using resolved_env without shell evaluation."""
if resolved_env is None or "${" not in value:
return value
def _replace(match: re.Match[str]) -> str:
var_name = match.group(1)
op = match.group(2)
default = match.group(3)
if op == ":-":
val = resolved_env.get(var_name)
return val if val else (default or "")
if op == "-":
return resolved_env.get(var_name, default or "")
return resolved_env.get(var_name, match.group(0))
return _COMPOSE_VAR_RE.sub(_replace, value)
def _default_group_lookup(key: str | int) -> tuple[str, int]:
"""Resolve a group name or numeric GID against the host group database."""
if isinstance(key, int) or (isinstance(key, str) and key.isdigit()):
entry = grp.getgrgid(int(key))
else:
entry = grp.getgrnam(str(key))
return entry.gr_name, entry.gr_gid
def _resolve_granted_groups(
grant_groups: list[str],
lookup_fn: Callable[[str | int], tuple[str, int]],
) -> tuple[set[str], set[int]]:
"""Canonicalize granted groups bidirectionally between group names and integer GIDs."""
granted_names: set[str] = set()
granted_gids: set[int] = set()
for raw in grant_groups:
key: str | int = int(raw) if raw.isdigit() else raw
try:
res = lookup_fn(key)
except KeyError as exc:
raise WorkloadGrantsError(
f"Granted group '{raw}' does not exist in host group database."
) from exc
if res is None:
raise WorkloadGrantsError(
f"Granted group '{raw}' does not exist in host group database."
)
gr_name, gr_gid = res
if gr_name.lower() in PRIVILEGED_GROUPS or str(gr_gid) in PRIVILEGED_GROUPS:
raise WorkloadGrantsError(
f"Granted group '{raw}' resolves to privileged group '{gr_name}:{gr_gid}'."
)
granted_names.add(gr_name)
granted_gids.add(gr_gid)
return granted_names, granted_gids
def _validate_service_group_add(
svc_name: str,
svc: dict[str, Any],
grant: WorkloadGrant,
resolved_env: dict[str, str] | None,
lookup_fn: Callable[[str | int], tuple[str, int]],
granted_names: set[str],
granted_gids: set[int],
) -> tuple[bool, str | None]:
"""Enforce default-deny and host-granted group_add membership."""
group_add = svc.get("group_add")
if not group_add:
return True, None
if not isinstance(group_add, list):
return (
False,
f"Service '{svc_name}' specifies invalid 'group_add' configuration.",
)
if not grant.groups:
return (
False,
f"Capability not granted: Service '{svc_name}' requests 'group_add' without any granted groups.",
)
for item in group_add:
val = _interpolate_compose_value(str(item).strip(), resolved_env)
if "${" in val or "}" in val:
return (
False,
f"Service '{svc_name}' specifies prohibited variable interpolation in group_add: '{val}'.",
)
key: str | int = int(val) if val.isdigit() else val
try:
res = lookup_fn(key)
except KeyError:
res = None
if res is None:
return (
False,
f"Capability not granted: Service '{svc_name}' requests unknown group_add '{val}'.",
)
req_name, req_gid = res
if req_name.lower() in PRIVILEGED_GROUPS or str(req_gid) in PRIVILEGED_GROUPS:
return (
False,
f"Capability not granted: Service '{svc_name}' requests privileged group_add '{val}'.",
)
if req_name not in granted_names and req_gid not in granted_gids:
return (
False,
f"Capability not granted: Service '{svc_name}' requests ungranted group_add '{val}' ({req_name}:{req_gid}).",
)
return True, None
def _validate_service_user(
svc_name: str,
svc: dict[str, Any],
resolved_env: dict[str, str] | None,
lookup_fn: Callable[[str | int], tuple[str, int]],
granted_names: set[str],
granted_gids: set[int],
) -> tuple[bool, str | None]:
"""Enforce non-root UID and granted/unprivileged primary GID containment for service user."""
raw_user = svc.get("user")
if raw_user is None:
return True, None
user_val = _interpolate_compose_value(str(raw_user).strip(), resolved_env)
if "${" in user_val or "}" in user_val:
return (
False,
f"Service '{svc_name}' specifies prohibited variable interpolation in user: '{user_val}'.",
)
if not user_val:
return True, None
if ":" in user_val:
uid_part, gid_part = user_val.split(":", 1)
else:
uid_part, gid_part = user_val, None
uid_clean = uid_part.strip()
try:
is_zero_uid = int(uid_clean) == 0
except ValueError:
is_zero_uid = False
if uid_clean.lower() == "root" or is_zero_uid:
return (
False,
f"Capability not granted: Service '{svc_name}' requests root user '{user_val}'.",
)
if gid_part is not None:
gid_clean = gid_part.strip()
if gid_clean.lower() in PRIVILEGED_GROUPS:
return (
False,
f"Capability not granted: Service '{svc_name}' requests privileged primary group '{gid_clean}' in user '{user_val}'.",
)
if gid_clean.isdigit():
gid_num = int(gid_clean)
if gid_num == 0:
return (
False,
f"Capability not granted: Service '{svc_name}' requests root GID 0 in user '{user_val}'.",
)
if gid_num in granted_gids:
return True, None
if gid_num < 1000:
return (
False,
f"Capability not granted: Service '{svc_name}' requests ungranted system GID '{gid_clean}' in user '{user_val}'.",
)
try:
res = lookup_fn(gid_num)
except KeyError:
res = None
if res is not None and res[0].lower() in PRIVILEGED_GROUPS:
return (
False,
f"Capability not granted: Service '{svc_name}' requests privileged GID '{gid_clean}' ({res[0]}).",
)
else:
try:
res = lookup_fn(gid_clean)
except KeyError:
res = None
if res is None:
return (
False,
f"Capability not granted: Service '{svc_name}' requests unknown primary group '{gid_clean}' in user '{user_val}'.",
)
req_name, req_gid = res
if req_name.lower() in PRIVILEGED_GROUPS or req_gid == 0:
return (
False,
f"Capability not granted: Service '{svc_name}' requests privileged primary group '{gid_clean}' in user '{user_val}'.",
)
if req_name not in granted_names and req_gid not in granted_gids:
return (
False,
f"Capability not granted: Service '{svc_name}' requests ungranted primary group '{gid_clean}' in user '{user_val}'.",
)
return True, None
def _resolve_contained_host_path(
svc_name: str,
kind: str,
host_path: str,
granted_roots: list[Path],
) -> tuple[bool, str | None]:
"""Verify an absolute host path exists canonically without '..' and falls within a granted root."""
posix = PurePosixPath(host_path)
if not posix.is_absolute() or ".." in posix.parts:
return (
False,
f"Capability not granted: Service '{svc_name}' {kind} '{host_path}' must be absolute without '..'.",
)
try:
strict_host = Path(host_path).resolve(strict=True)
except OSError:
return (
False,
f"Capability not granted: Service '{svc_name}' {kind} '{host_path}' does not exist on host.",
)
if not any(
strict_host == g_res or strict_host.is_relative_to(g_res)
for g_res in granted_roots
):
return (
False,
f"Capability not granted: Service '{svc_name}' requests ungranted {kind} '{host_path}'.",
)
return True, None
def _validate_service_devices(
svc_name: str,
svc: dict[str, Any],
grant: WorkloadGrant,
resolved_env: dict[str, str] | None,
) -> tuple[bool, str | None]:
"""Validate host device mounts against granted device paths and forbid mknod ('m') permissions."""
devices = svc.get("devices")
if not devices:
return True, None
if not isinstance(devices, list):
return (
False,
f"Service '{svc_name}' specifies invalid 'devices' configuration.",
)
if not grant.devices:
return (
False,
f"Capability not granted: Service '{svc_name}' specifies prohibited host device mount: {devices}.",
)
granted_resolved: list[Path] = []
for g_dev in grant.devices:
try:
granted_resolved.append(Path(g_dev).resolve(strict=True))
except OSError:
continue
for dev_entry in devices:
dev_str = _interpolate_compose_value(str(dev_entry).strip(), resolved_env)
if "${" in dev_str or "}" in dev_str:
return (
False,
f"Service '{svc_name}' specifies prohibited variable interpolation in devices: '{dev_str}'.",
)
parts = dev_str.split(":")
if len(parts) in (1, 2):
host_dev, perms = parts[0].strip(), ""
elif len(parts) == 3:
host_dev, perms = parts[0].strip(), parts[2].strip()
else:
return (
False,
f"Service '{svc_name}' specifies malformed device entry '{dev_str}'.",
)
if "m" in perms.lower():
return (
False,
f"Capability not granted: Service '{svc_name}' requests prohibited 'm' (mknod) device permission in '{dev_str}'.",
)
ok_path, path_err = _resolve_contained_host_path(
svc_name, "device", host_dev, granted_resolved
)
if not ok_path:
return False, path_err
return True, None
def _validate_service_volumes(
svc_name: str,
svc: dict[str, Any],
allowed_root: Path,
canonical_allowed_root: Path,
target_state_root: Path,
top_volumes: set[str],
grant: WorkloadGrant,
resolved_env: dict[str, str] | None,
) -> tuple[bool, str | None]:
"""Validate service volume mounts against workload/state roots and granted readOnlyPaths."""
volumes = svc.get("volumes", [])
if not isinstance(volumes, list):
return True, None
granted_ro_resolved: list[Path] = []
for g_ro in grant.readOnlyPaths:
try:
granted_ro_resolved.append(Path(g_ro).resolve(strict=True))
except OSError:
continue
for vol in volumes:
host_path = ""
is_short_ro = False
is_long_bind_ro = False
is_long_syntax = False
unsafe_prop: str | None = None
if isinstance(vol, str):
vol_resolved = _interpolate_compose_value(vol, resolved_env)
if "/var/run/docker.sock" in vol_resolved:
return (
False,
f"Service '{svc_name}' directly mounts Docker socket: {vol_resolved}.",
)
if ":" in vol_resolved:
parts = vol_resolved.split(":")
host_path = parts[0].strip()
if len(parts) >= 3:
opts = [
o.strip().lower()
for o in parts[2].split(",")
if o.strip()
]
for opt in opts:
if opt in UNSAFE_BIND_PROPAGATIONS:
unsafe_prop = opt
is_short_ro = ("ro" in opts) and ("rw" not in opts)
else:
host_path = vol_resolved.strip()
elif isinstance(vol, dict):
is_long_syntax = True
src = _interpolate_compose_value(
str(vol.get("source", "")), resolved_env
)
if "/var/run/docker.sock" in src:
return (
False,
f"Service '{svc_name}' directly mounts Docker socket: {src}.",
)
vol_type = vol.get("type")
if vol_type in ("bind", "volume") or (vol_type is None and src):
host_path = src
bind_cfg = vol.get("bind")
if isinstance(bind_cfg, dict):
prop = _interpolate_compose_value(
str(bind_cfg.get("propagation", "")).strip().lower(),
resolved_env,
)
if prop in UNSAFE_BIND_PROPAGATIONS:
unsafe_prop = prop
is_long_bind_ro = (vol_type == "bind") and (
vol.get("read_only") is True
)
if unsafe_prop is not None:
return (
False,
f"Capability not granted: Service '{svc_name}' specifies unsafe bind propagation '{unsafe_prop}'.",
)
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}'.",
)
if host_path in top_volumes and not (
host_path.startswith((".", "/", "~"))
or "/" in host_path
or "\\" in host_path
):
continue
if not (
host_path.startswith((".", "/", "~"))
or "/" in host_path
or "\\" in host_path
):
return (
False,
f"Service '{svc_name}' specifies undeclared named volume or ambiguous path: '{host_path}'.",
)
if host_path.startswith("~"):
expanded = Path(host_path).expanduser().resolve()
elif Path(host_path).is_absolute():
expanded = Path(host_path).resolve()
else:
expanded = (allowed_root / host_path).resolve()
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 is_in_workload or is_in_own_state:
continue
if not grant.readOnlyPaths:
return (
False,
f"Capability not granted: Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'.",
)
if is_long_syntax and not is_long_bind_ro:
return (
False,
f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must specify type=bind and read_only=true.",
)
if not is_long_syntax and not is_short_ro:
return (
False,
f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must be read-only (:ro).",
)
ok_path, path_err = _resolve_contained_host_path(
svc_name, "external bind mount", host_path, granted_ro_resolved
)
if not ok_path:
return False, path_err
return True, None
def validate_compose_security(
compose_file: Path,
allowed_root: Path,
app_name: str | None = None,
resolved_env: dict[str, str] | None = None,
grants_file: Path | None = None,
group_lookup: Callable[[str | int], tuple[str, int]] | None = None,
) -> tuple[bool, str | None]:
"""
Pre-flight AST inspection of workload docker-compose.yml enforcing Core platform security invariants
and host-granted workload capabilities (ADR-0005):
1. File Integrity & Parser: regular file, non-symlink (or strictly contained symlink); fails closed if PyYAML is unavailable.
2. Privilege Containment: blocks 'privileged: true', 'cap_add', 'device_cgroup_rules', and 'security_opt: unconfined'.
3. Host Namespace Isolation: blocks 'host', 'container:*', and 'service:*' across 'network_mode', 'pid', 'ipc', 'uts', 'userns_mode'.
4. Docker Socket & Include Bans: blocks direct mounts of /var/run/docker.sock and top-level 'include' directives.
5. Host-Granted Capabilities: enforces fail-closed workloadGrants for 'devices' (forbidding mknod 'm'), 'group_add',
'user' primary GIDs, and external ':ro' 'volumes' ('readOnlyPaths', rejecting unsafe bind propagation).
6. Bind-Mount & Tenant State Isolation: resolves all relative and absolute host paths within allowed_root or ~/var/lib/homelab/<app_name>/.
"""
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}"
if yaml is None:
return False, "PyYAML is required for Compose security validation."
try:
data = yaml.safe_load(content) or {}
except yaml.YAMLError as e:
return False, f"Failed to parse compose YAML {compose_file}: {e}"
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
try:
grants = load_workload_grants(grants_file)
except WorkloadGrantsError as exc:
return False, f"Capability grants integrity check failed: {exc}"
grant = grants.get(app_name, WorkloadGrant()) if app_name else WorkloadGrant()
lookup_fn = group_lookup or _default_group_lookup
try:
granted_names, granted_gids = _resolve_granted_groups(grant.groups, lookup_fn)
except WorkloadGrantsError as exc:
return False, f"Capability grants integrity check failed: {exc}"
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):
continue
if svc.get("privileged") is True:
return (
False,
f"Service '{svc_name}' specifies prohibited 'privileged: true'.",
)
cap_add = svc.get("cap_add")
if cap_add:
return (
False,
f"Service '{svc_name}' specifies prohibited 'cap_add' capabilities: {cap_add}.",
)
if svc.get("device_cgroup_rules"):
return (
False,
f"Service '{svc_name}' specifies prohibited 'device_cgroup_rules'.",
)
ok_dev, dev_err = _validate_service_devices(svc_name, svc, grant, resolved_env)
if not ok_dev:
return False, dev_err
ok_grp, grp_err = _validate_service_group_add(
svc_name, svc, grant, resolved_env, lookup_fn, granted_names, granted_gids
)
if not ok_grp:
return False, grp_err
ok_usr, usr_err = _validate_service_user(
svc_name, svc, resolved_env, lookup_fn, granted_names, granted_gids
)
if not ok_usr:
return False, usr_err
sec_opts = svc.get("security_opt", [])
if isinstance(sec_opts, str):
sec_opts = [sec_opts]
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}.",
)
build_cfg = svc.get("build")
if build_cfg is not None:
build_context: str | None = None
if isinstance(build_cfg, str):
build_context = build_cfg.strip()
elif isinstance(build_cfg, dict):
raw_ctx = build_cfg.get("context")
if raw_ctx is not None:
build_context = str(raw_ctx).strip()
else:
return (
False,
f"Service '{svc_name}' specifies invalid 'build' configuration.",
)
if build_context:
if "${" in build_context or "}" in build_context:
return (
False,
f"Service '{svc_name}' specifies prohibited variable interpolation in build context: '{build_context}'.",
)
remote_prefixes = ("https://", "http://", "ssh://", "git@", "git://")
if not build_context.startswith(remote_prefixes):
if build_context.startswith("~"):
resolved_build = Path(build_context).expanduser().resolve()
elif Path(build_context).is_absolute():
resolved_build = Path(build_context).resolve()
else:
resolved_build = (allowed_root / build_context).resolve()
if not (
allowed_root.is_dir()
and resolved_build.is_relative_to(canonical_allowed_root)
):
return (
False,
f"Service '{svc_name}' specifies prohibited build context escaping workload root: '{build_context}'.",
)
raw_env_files = svc.get("env_file")
if raw_env_files:
env_file_list: list[str] = []
if isinstance(raw_env_files, str):
env_file_list = [raw_env_files]
elif isinstance(raw_env_files, list):
for item in raw_env_files:
if isinstance(item, str):
env_file_list.append(item)
elif isinstance(item, dict) and "path" in item:
env_file_list.append(str(item["path"]))
elif isinstance(raw_env_files, dict) and "path" in raw_env_files:
env_file_list = [str(raw_env_files["path"])]
for env_path in env_file_list:
clean_env = env_path.strip()
if not clean_env:
continue
if clean_env.startswith("~"):
env_file_resolved = Path(clean_env).expanduser().resolve()
elif Path(clean_env).is_absolute():
env_file_resolved = Path(clean_env).resolve()
else:
env_file_resolved = (allowed_root / clean_env).resolve()
if not (
allowed_root.is_dir()
and env_file_resolved.is_relative_to(canonical_allowed_root)
):
return (
False,
f"Service '{svc_name}' specifies prohibited env_file escaping workload root: '{clean_env}'.",
)
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 or val.startswith(
("container:", "service:")
):
return (
False,
f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'.",
)
ok_vol, vol_err = _validate_service_volumes(
svc_name,
svc,
allowed_root,
canonical_allowed_root,
target_state_root,
top_volumes,
grant,
resolved_env,
)
if not ok_vol:
return False, vol_err
return True, None
def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]:
"""
Validate deployment policy inside app.yaml.
Rejects unsupported deployment strategies or unknown actions.
"""
deployment = manifest.get("deployment")
if deployment is None:
return True, ""
if not isinstance(deployment, dict):
return False, "Field 'deployment' must be a mapping/dictionary."
# Validate strategy if specified
strategy = deployment.get("strategy")
if strategy is not None and strategy not in ALLOWED_STRATEGIES:
return (
False,
f"Unsupported deployment strategy '{strategy}'. Allowed strategies: {sorted(ALLOWED_STRATEGIES)}",
)
# Validate actions if specified
actions = deployment.get("actions")
if actions is not None:
if not isinstance(actions, list):
return False, "Field 'deployment.actions' must be a list of strings."
for action in actions:
if not isinstance(action, str) or action not in ALLOWED_ACTIONS:
return (
False,
f"Unsupported deployment action '{action}'. Allowed actions: {sorted(ALLOWED_ACTIONS)}",
)
return True, ""
def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -> bool:
"""
Execute declared deployment actions sequentially.
Enforces revision-consistent manifest validation:
After pulling the target revision, app.yaml is re-read and re-validated
from the freshly updated tree, ensuring deployment policy is derived
from the exact revision being deployed.
"""
expected_branch = deployment_config.get("branch", "main")
if branch and branch != expected_branch:
logger.info(
f"Skipping deployment: pushed branch '{branch}' != target branch '{expected_branch}'"
)
return True
daemon_sock = Path(os.environ.get("APPCTL_SOCKET_PATH", DEFAULT_APPCTL_SOCKET_PATH))
if daemon_sock.is_socket():
canonical_app_name = target_dir.name.removeprefix("homelab-")
return execute_deployment_via_daemon(
target=canonical_app_name,
branch=expected_branch,
socket_path=daemon_sock,
)
canonical_app_name = target_dir.name.removeprefix("homelab-")
manifest_file = target_dir / "app.yaml"
if manifest_file.is_file():
with contextlib.suppress(Exception):
pre_manifest = (
yaml.safe_load(manifest_file.read_text(encoding="utf-8"))
if yaml
else parse_yaml_simple(manifest_file.read_text(encoding="utf-8"))
) or {}
if isinstance(pre_manifest, dict) and pre_manifest.get("name"):
canonical_app_name = str(pre_manifest["name"]).strip()
logger.info(
f"🚀 Deploying '{target_dir.name}' at {target_dir} (branch: {expected_branch})..."
)
actions = deployment_config.get("actions", ["git_pull"])
try:
idx = 0
while idx < len(actions):
action = actions[idx]
if action == "git_pull":
logger.info(f" ↳ [git_pull] Pulling latest '{expected_branch}'...")
subprocess.run(
[
"git",
"-C",
str(target_dir),
"pull",
"--ff-only",
"origin",
expected_branch,
],
check=True,
)
# Revision-consistent manifest validation:
# The working tree has now advanced to the deployed revision.
# Re-read and re-validate app.yaml from the exact deployed revision.
manifest_file = target_dir / "app.yaml"
if manifest_file.is_file():
try:
manifest_text = manifest_file.read_text(encoding="utf-8")
fresh_manifest = (
yaml.safe_load(manifest_text)
if yaml
else parse_yaml_simple(manifest_text)
) or {}
except (
OSError,
UnicodeDecodeError,
ValueError,
KeyError,
AttributeError,
) as e:
logger.error(
f"❌ Post-pull manifest parse failure in {manifest_file}: {e}"
)
return False
valid, err_msg = validate_manifest_deployment(fresh_manifest)
if not valid:
logger.error(
f"❌ Post-pull manifest validation failed for '{target_dir.name}': {err_msg}"
)
return False
if isinstance(fresh_manifest, dict) and fresh_manifest.get("name"):
canonical_app_name = str(fresh_manifest["name"]).strip()
fresh_config = fresh_manifest.get("deployment")
if isinstance(fresh_config, dict):
fresh_branch = fresh_config.get("branch", "main")
if branch and branch != fresh_branch:
logger.error(
f"❌ Post-pull branch policy violation: revision declared branch '{fresh_branch}', "
f"but pushed branch was '{branch}'. Aborting deployment."
)
return False
# Adopt the freshly validated actions from the deployed revision
fresh_actions = fresh_config.get("actions", actions)
actions = [a for a in fresh_actions if a != "git_pull"]
idx = 0
continue
elif action == "compose_up":
compose_file = target_dir / "docker-compose.yml"
if not compose_file.is_file():
compose_file = target_dir / "docker-compose.yaml"
if compose_file.is_file():
valid_sec, sec_err = validate_compose_security(
compose_file, target_dir, app_name=canonical_app_name
)
if not valid_sec:
logger.error(
f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}"
)
return False
logger.info(
" ↳ [compose_up] Recreating containers (docker compose up -d)..."
)
subprocess.run(
[
"docker",
"compose",
"-f",
str(compose_file),
"up",
"-d",
"--remove-orphans",
],
check=True,
)
elif action == "compose_build":
compose_file = target_dir / "docker-compose.yml"
if not compose_file.is_file():
compose_file = target_dir / "docker-compose.yaml"
if compose_file.is_file():
valid_sec, sec_err = validate_compose_security(
compose_file, target_dir, app_name=canonical_app_name
)
if not valid_sec:
logger.error(
f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}"
)
return False
logger.info(
" ↳ [compose_build] Building & recreating containers..."
)
subprocess.run(
["docker", "compose", "-f", str(compose_file), "build"],
check=True,
)
subprocess.run(
[
"docker",
"compose",
"-f",
str(compose_file),
"up",
"-d",
"--remove-orphans",
],
check=True,
)
elif action == "compose_restart":
compose_file = target_dir / "docker-compose.yml"
if not compose_file.is_file():
compose_file = target_dir / "docker-compose.yaml"
if compose_file.is_file():
valid_sec, sec_err = validate_compose_security(
compose_file, target_dir, app_name=canonical_app_name
)
if not valid_sec:
logger.error(
f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}"
)
return False
logger.info(" ↳ [compose_restart] Restarting containers...")
subprocess.run(
["docker", "compose", "-f", str(compose_file), "restart"],
check=True,
)
else:
logger.error(
f"❌ Unsupported or rejected deployment action '{action}'. Aborting deployment."
)
return False
idx += 1
logger.info(f"✨ Deployment of '{target_dir.name}' completed successfully.")
return True
except subprocess.CalledProcessError as e:
logger.error(f"❌ Deployment step failed with exit code {e.returncode}: {e}")
return False
except (
subprocess.SubprocessError,
OSError,
KeyError,
TypeError,
ValueError,
RuntimeError,
) as e:
logger.error(f"❌ Unexpected deployment error: {e}")
return False
def is_monorepo_push(payload: dict) -> bool:
"""Return True when payload targets the unified workloads monorepo (e.g. canopy-workloads)."""
if not (SITES_DIR / ".git").exists():
return False
repo_field = payload.get("repository")
if not isinstance(repo_field, dict):
return False
repo_name = repo_field.get("name")
if not isinstance(repo_name, str):
return False
cleaned = repo_name.strip()
return cleaned in ("canopy-workloads", SITES_DIR.name)
def extract_monorepo_changed_subdirs(
payload: dict, monorepo_dir: Path, git_env: dict[str, str] | None = None
) -> list[str]:
"""
Extract safe top-level workload subdirectory names touched by a monorepo push.
Combines commit payload file lists (added/modified/removed) with git diff when available.
Rejects absolute paths, '..' traversal, and root-level files.
"""
raw_paths: list[str] = []
commits = payload.get("commits")
if isinstance(commits, list):
for commit in commits:
if not isinstance(commit, dict):
continue
for key in ("added", "modified", "removed"):
items = commit.get(key)
if isinstance(items, list):
for item in items:
if isinstance(item, str) and item.strip():
raw_paths.append(item.strip())
before_sha = str(payload.get("before", "")).strip()
after_sha = str(payload.get("after", "")).strip()
zero_sha = "0" * 40
if (
before_sha
and after_sha
and before_sha != zero_sha
and after_sha != zero_sha
and REPO_NAME_RE.match(before_sha)
and REPO_NAME_RE.match(after_sha)
):
env = git_env or {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
try:
diff_res = subprocess.run(
["git", "-C", str(monorepo_dir), "diff", "--name-only", before_sha, after_sha],
capture_output=True,
text=True,
check=False,
timeout=15.0,
env=env,
)
if diff_res.returncode == 0:
for line in diff_res.stdout.splitlines():
if line.strip():
raw_paths.append(line.strip())
except (subprocess.SubprocessError, OSError):
pass
seen: set[str] = set()
subdirs: list[str] = []
for rel in raw_paths:
if rel.startswith("/") or "\\" in rel:
continue
parts = Path(rel).parts
if len(parts) < 2 or ".." in parts:
continue
top = parts[0]
if not REPO_NAME_RE.match(top):
continue
if top not in seen:
seen.add(top)
subdirs.append(top)
return subdirs
def dispatch_monorepo_push(
payload: dict, event_type: str | None = None
) -> tuple[bool, list[Path], str]:
"""
Handle a Gitea push webhook for the unified workloads monorepo:
1. Validate push event and refs/heads/<branch>.
2. Pull ~/Workloads once under an exclusive lock.
3. Determine changed top-level <app>/ subdirectories, filter strictly against
deployments.yaml, validate each affected manifest, and enqueue/spawn workers.
"""
if event_type and event_type.strip().lower() != "push":
return (
False,
[],
f"Event '{event_type}' is not eligible for deployment. Only 'push' is allowed.",
)
if "pull_request" in payload or "issue" in payload or "release" in payload:
return (
False,
[],
"Payload represents non-push event (pull_request/issue/release). Rejected.",
)
ref = payload.get("ref", "")
if not isinstance(ref, str) or not ref:
return False, [], "Missing or invalid 'ref' in payload."
if ref.startswith("refs/tags/"):
return False, [], f"Tag push '{ref}' is not deployable."
if not ref.startswith("refs/heads/"):
return False, [], f"Ref '{ref}' is not a head branch. Only 'refs/heads/*' is supported."
pushed_branch = ref.removeprefix("refs/heads/")
if not pushed_branch:
return False, [], "Empty branch name extracted from ref."
expected_monorepo_branch = os.environ.get("MONOREPO_BRANCH", "main")
if pushed_branch != expected_monorepo_branch:
return (
False,
[],
f"Branch mismatch: pushed branch '{pushed_branch}' does not match monorepo branch '{expected_monorepo_branch}'.",
)
git_env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
lock_file_path = get_target_lock("_monorepo")
with open(lock_file_path, "w", encoding="utf-8") as lock_fd:
fcntl.flock(lock_fd, fcntl.LOCK_EX)
try:
pull_res = subprocess.run(
[
"git",
"-C",
str(SITES_DIR),
"pull",
"--ff-only",
"origin",
"--",
pushed_branch,
],
capture_output=True,
text=True,
check=False,
timeout=60.0,
env=git_env,
)
if pull_res.returncode != 0:
return (
False,
[],
f"Failed to pull monorepo '{SITES_DIR}': {pull_res.stderr.strip()}",
)
finally:
with contextlib.suppress(OSError):
fcntl.flock(lock_fd, fcntl.LOCK_UN)
changed_subdirs = extract_monorepo_changed_subdirs(payload, SITES_DIR, git_env=git_env)
trusted_mapping = get_trusted_repository_mapping()
admitted_paths = {p.resolve() for p in trusted_mapping.values()}
canonical_sites = SITES_DIR.resolve()
commit_sha = str(payload.get("after", "") or "")
if not commit_sha and isinstance(payload.get("head_commit"), dict):
commit_sha = str(payload.get("head_commit", {}).get("id", "") or "")
dispatched: list[Path] = []
for subdir in changed_subdirs:
candidate = (SITES_DIR / subdir).resolve()
if not (candidate.is_relative_to(canonical_sites) and candidate in admitted_paths and candidate.is_dir()):
logger.info(
f"Ignoring unregistered or out-of-bounds monorepo subdirectory '{subdir}'."
)
continue
manifest_file = candidate / "app.yaml"
manifest: dict[str, Any] = {}
if manifest_file.is_file():
try:
parsed_manifest = parse_manifest(manifest_file)
manifest = parsed_manifest.model_dump()
except (ManifestValidationError, OSError) as e:
logger.warning(f"Skipping '{subdir}' due to manifest error: {e}")
continue
valid, err_msg = validate_manifest_deployment(manifest)
if not valid:
logger.warning(f"Skipping '{subdir}' due to deployment policy error: {err_msg}")
continue
deployment_config = manifest.get("deployment")
if not isinstance(deployment_config, dict):
deployment_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
if deployment_config.get("branch", "main") != pushed_branch:
logger.info(
f"Skipping '{subdir}': declared branch '{deployment_config.get('branch', 'main')}' != '{pushed_branch}'."
)
continue
enqueue_deployment(candidate, deployment_config, pushed_branch, commit_sha=commit_sha)
spawn_worker_async(candidate.name)
dispatched.append(candidate)
return (
True,
dispatched,
f"Monorepo push dispatched {len(dispatched)} workload(s) on branch '{pushed_branch}'.",
)
def admit_deployment(
payload: dict, event_type: str | None = None
) -> tuple[bool, Path | None, dict, str, str]:
"""
Evaluate webhook deployment admission against strict policy gates:
1. Event Admission (must be a push event, rejects PRs, tags, releases)
2. Ref Format (must be 'refs/heads/<branch>')
3. Repository Admission (must resolve against trusted mapping)
4. Manifest & Strategy Validation (app.yaml must be valid)
5. Branch Policy Admission (pushed branch must match declared deployment branch)
Returns: (admitted: bool, target_dir: Path | None, deployment_config: dict, branch: str, reason: str)
"""
# 1. Event Admission
if event_type and event_type.strip().lower() != "push":
return (
False,
None,
{},
"",
f"Event '{event_type}' is not eligible for deployment. Only 'push' is allowed.",
)
if "pull_request" in payload or "issue" in payload or "release" in payload:
return (
False,
None,
{},
"",
"Payload represents non-push event (pull_request/issue/release). Rejected.",
)
# 2. Ref Admission
ref = payload.get("ref", "")
if not isinstance(ref, str) or not ref:
return False, None, {}, "", "Missing or invalid 'ref' in payload."
if ref.startswith("refs/tags/"):
return False, None, {}, "", f"Tag push '{ref}' is not deployable."
if not ref.startswith("refs/heads/"):
return (
False,
None,
{},
"",
f"Ref '{ref}' is not a head branch. Only 'refs/heads/*' is supported.",
)
pushed_branch = ref.removeprefix("refs/heads/")
if not pushed_branch:
return False, None, {}, "", "Empty branch name extracted from ref."
# 3. Repository Admission
repo_field = payload.get("repository")
if not isinstance(repo_field, dict):
return (
False,
None,
{},
pushed_branch,
"Missing or invalid 'repository' object in payload.",
)
repo_name = repo_field.get("name")
if not isinstance(repo_name, str) or not repo_name.strip():
return (
False,
None,
{},
pushed_branch,
"Missing or empty repository name in payload.",
)
repo_name = repo_name.strip()
target_dir = resolve_repository(repo_name)
if not target_dir:
return (
False,
None,
{},
pushed_branch,
f"Repository '{repo_name}' is not recognized in trusted registry.",
)
# 4. Manifest & Strategy Validation
manifest_file = target_dir / "app.yaml"
manifest: dict[str, Any] = {}
if manifest_file.is_file():
try:
parsed_manifest = parse_manifest(manifest_file)
manifest = parsed_manifest.model_dump()
except ManifestValidationError as e:
return (
False,
None,
{},
pushed_branch,
f"Manifest validation error: {e}",
)
except OSError as e:
return (
False,
None,
{},
pushed_branch,
f"Failed to read manifest {manifest_file}: {e}",
)
valid, err_msg = validate_manifest_deployment(manifest)
if not valid:
return (
False,
None,
{},
pushed_branch,
f"Manifest validation error: {err_msg}",
)
deployment_config = manifest.get("deployment")
if not isinstance(deployment_config, dict):
deployment_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
# 5. Branch Policy Admission
expected_branch = deployment_config.get("branch", "main")
if pushed_branch != expected_branch:
return (
False,
target_dir,
deployment_config,
pushed_branch,
(
f"Branch mismatch: pushed branch '{pushed_branch}' does not match "
f"declared target branch '{expected_branch}'."
),
)
return (
True,
target_dir,
deployment_config,
pushed_branch,
f"Admitted for deployment on branch '{pushed_branch}'.",
)
def get_target_lock(target_name: str) -> Path:
STATE_DIR.mkdir(parents=True, exist_ok=True)
return STATE_DIR / f"{target_name}.lock"
def get_pending_file(target_name: str) -> Path:
STATE_DIR.mkdir(parents=True, exist_ok=True)
return STATE_DIR / f"{target_name}.pending.json"
def enqueue_deployment(
target_dir: Path, deployment_config: dict, branch: str, commit_sha: str = ""
) -> Path:
"""
Atomically enqueue a deployment request.
Supersedes any existing pending request for this target.
"""
target_name = target_dir.name
pending_file = get_pending_file(target_name)
temp_file = STATE_DIR / f"{target_name}.pending.tmp.{os.getpid()}"
data = {
"target_dir": str(target_dir),
"deployment_config": deployment_config,
"branch": branch,
"commit_sha": commit_sha,
"queued_at": datetime.datetime.now(datetime.UTC).isoformat(),
}
temp_file.write_text(json.dumps(data), encoding="utf-8")
temp_file.replace(pending_file)
logger.info(
f"📥 Enqueued deployment for '{target_name}' (branch: {branch}, superseding previous pending)."
)
return pending_file
def run_target_worker(target_name: str) -> bool:
"""
Serialized worker for a specific repository.
Acquires exclusive flock and processes pending deployments until queue is empty.
Records intentional execution status in the state directory.
"""
lock_file_path = get_target_lock(target_name)
pending_file_path = get_pending_file(target_name)
with open(lock_file_path, "w", encoding="utf-8") as lock_fd:
try:
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (BlockingIOError, OSError):
logger.info(
f"Deployment worker for '{target_name}' is already active. Pending update will be picked up."
)
return True
overall_success = True
try:
while True:
if not pending_file_path.is_file():
break
try:
content = pending_file_path.read_text(encoding="utf-8")
pending_file_path.unlink(missing_ok=True)
item = json.loads(content)
except (OSError, json.JSONDecodeError) as e:
logger.error(f"Failed to read pending deployment file: {e}")
break
target_dir = Path(item["target_dir"])
deployment_config = item["deployment_config"]
branch = item["branch"]
commit_sha = item.get("commit_sha", "")
success = execute_deployment(target_dir, deployment_config, branch)
# Record intentional execution status
status_file = STATE_DIR / f"{target_name}.status.json"
try:
status_data = {
"target": target_name,
"branch": branch,
"commit_sha": commit_sha,
"success": success,
"timestamp": datetime.datetime.now(datetime.UTC).isoformat(),
}
status_file.write_text(
json.dumps(status_data, indent=2), encoding="utf-8"
)
except OSError as e:
logger.warning(
f"Failed to write deployment status file {status_file}: {e}"
)
if not success:
overall_success = False
return overall_success
finally:
with contextlib.suppress(OSError):
fcntl.flock(lock_fd, fcntl.LOCK_UN)
def spawn_worker_async(target_name: str):
"""Spawn a detached worker process to execute deployments asynchronously."""
dispatcher_script = Path(__file__).resolve()
cmd = [sys.executable, str(dispatcher_script), "--worker", target_name]
subprocess.Popen(
cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
start_new_session=True,
)
def main():
payload_raw = ""
repo_name = ""
branch = "main"
signature = None
event_type = None
if "--worker" in sys.argv:
w_idx = sys.argv.index("--worker")
if w_idx + 1 < len(sys.argv):
worker_target = sys.argv[w_idx + 1]
success = run_target_worker(worker_target)
sys.exit(0 if success else 1)
else:
logger.error("--worker requires a repository/target name.")
sys.exit(1)
if "--signature" in sys.argv:
sig_idx = sys.argv.index("--signature")
if sig_idx + 1 < len(sys.argv):
signature = sys.argv[sig_idx + 1]
elif len(sys.argv) > 2 and not sys.argv[2].startswith("-"):
signature = sys.argv[2]
elif os.environ.get("HTTP_X_GITEA_SIGNATURE"):
signature = os.environ.get("HTTP_X_GITEA_SIGNATURE")
elif os.environ.get("X_GITEA_SIGNATURE"):
signature = os.environ.get("X_GITEA_SIGNATURE")
if "--event" in sys.argv:
ev_idx = sys.argv.index("--event")
if ev_idx + 1 < len(sys.argv):
event_type = sys.argv[ev_idx + 1]
elif len(sys.argv) > 3 and not sys.argv[3].startswith("-"):
event_type = sys.argv[3]
elif os.environ.get("HTTP_X_GITEA_EVENT"):
event_type = os.environ.get("HTTP_X_GITEA_EVENT")
elif os.environ.get("X_GITEA_EVENT"):
event_type = os.environ.get("X_GITEA_EVENT")
# Support CLI arguments for manual trigger: --repo <name> [--branch <branch>]
if "--repo" in sys.argv:
idx = sys.argv.index("--repo")
if idx + 1 < len(sys.argv):
repo_name = sys.argv[idx + 1]
if "--branch" in sys.argv:
b_idx = sys.argv.index("--branch")
if b_idx + 1 < len(sys.argv):
branch = sys.argv[b_idx + 1].replace("refs/heads/", "")
logger.info(
f"Local manual trigger: repository='{repo_name}', branch='{branch}'"
)
target_dir, deployment_config = resolve_target(repo_name)
if not target_dir or not target_dir.is_dir():
logger.error(f"Target repository '{repo_name}' could not be resolved.")
sys.exit(1)
success = execute_deployment(target_dir, deployment_config, branch)
sys.exit(0 if success else 1)
else:
# 1. Check if first argument is a raw JSON payload string
if len(sys.argv) > 1 and sys.argv[1].strip().startswith("{"):
payload_raw = sys.argv[1].strip()
# 2. Fallback to reading from stdin
elif not sys.stdin.isatty():
payload_raw = sys.stdin.read().strip()
if not payload_raw:
logger.error("No webhook payload provided (checked sys.argv and stdin).")
sys.exit(1)
raw_body = payload_raw.encode("utf-8")
secret = load_webhook_secret()
if not verify_signature(raw_body, signature, secret):
logger.error("❌ Webhook authentication failed. Rejecting request.")
sys.exit(1)
try:
payload = json.loads(payload_raw)
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON payload: {e}")
sys.exit(1)
if is_monorepo_push(payload):
ok, dispatched, reason = dispatch_monorepo_push(payload, event_type)
if not ok:
logger.warning(f"🚫 Monorepo webhook rejected: {reason}")
sys.exit(0 if "Branch mismatch" in reason else 1)
logger.info(f"✅ {reason} ({[d.name for d in dispatched]})")
sys.exit(0)
admitted, target_dir, deployment_config, branch, reason = admit_deployment(
payload, event_type
)
if not admitted:
logger.warning(f"🚫 Webhook admission rejected: {reason}")
# Branch mismatch on valid push is benign skip; other violations fail closed
sys.exit(0 if "Branch mismatch" in reason else 1)
logger.info(f"✅ Webhook admission passed: {reason}")
assert target_dir is not None, (
"admitted deployment must have a valid target directory"
)
commit_sha = payload.get("after", "")
if not commit_sha and isinstance(payload.get("head_commit"), dict):
commit_sha = payload.get("head_commit", {}).get("id", "")
enqueue_deployment(target_dir, deployment_config, branch, commit_sha=commit_sha)
spawn_worker_async(target_dir.name)
logger.info(
f"🚀 Asynchronous deployment scheduled for '{target_dir.name}'. Returning HTTP 200."
)
sys.exit(0)
if __name__ == "__main__":
main()