Files
nixos-core/scripts/gitops_dispatcher.py
T
kiskaadee 178a0c8990 fix(compose): enforce host containment on dictionary volumes and reject variable interpolation
- Default dictionary volume declarations omitting 'type: bind' to host containment checks when 'source' is specified (CR-DI-01)
- Reject volume host paths containing dynamic variable interpolation (${...}) to prevent runtime boundary escapes (CR-DI-02)
- Add security regression tests in tests/security/test_gitops_security.py
2026-10-31 14:04:28 -05:00

1288 lines
47 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 hashlib
import hmac
import http.client
import json
import logging
import os
import re
import subprocess
import sys
from pathlib import Path
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
try:
import yaml
except ImportError:
yaml = None
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
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", CORE_DIR / "config" / "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.
Core Authoritative Registry (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 DEPLOYMENTS_FILE.is_file()
else (CONFIG_DIR / "deployments.yaml")
)
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("~/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"}
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 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.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_errors as e:
return False, f"Failed to parse compose YAML {compose_file}: {e}"
else:
# Fallback regex inspection if yaml module is not present
if re.search(
r"^\s*privileged:\s*true\b", content, re.MULTILINE | re.IGNORECASE
):
return False, "Privileged mode is prohibited in workload compose files."
if "/var/run/docker.sock" in content:
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):
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}.",
)
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, 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}.",
)
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("~"):
resolved_env = Path(clean_env).expanduser().resolve()
elif Path(clean_env).is_absolute():
resolved_env = Path(clean_env).resolve()
else:
resolved_env = (allowed_root / clean_env).resolve()
if not (
allowed_root.is_dir()
and resolved_env.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:
return (
False,
f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'.",
)
volumes = svc.get("volumes", [])
if isinstance(volumes, list):
for vol in volumes:
host_path = ""
if isinstance(vol, str):
if "/var/run/docker.sock" in vol:
return (
False,
f"Service '{svc_name}' directly mounts Docker socket: {vol}.",
)
if ":" in vol:
host_path = vol.split(":")[0].strip()
else:
host_path = vol.strip()
elif isinstance(vol, dict):
src = str(vol.get("source", ""))
if "/var/run/docker.sock" in src:
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
if not host_path:
continue
if "${" in host_path or "}" in host_path:
return (
False,
f"Service '{svc_name}' specifies prohibited variable interpolation in volume host path: '{host_path}'.",
)
# Declared top-level named volume without path separators
if host_path in top_volumes and not (
host_path.startswith((".", "/", "~"))
or "/" in host_path
or "\\" in host_path
):
continue
# Undeclared named volumes or bare identifiers not starting with ., /, ~ or containing / are prohibited
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}'.",
)
# Host bind mount evaluation
if host_path.startswith("~"):
expanded = Path(host_path).expanduser().resolve()
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.
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 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)
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()