Compare commits

..
2 Commits
Author SHA1 Message Date
kiskaadee 6836233c95 feat(nixos): sandbox homelab-gitops service and update roadmap for Milestone P2
- Apply systemd sandboxing to homelab-gitops service: ProtectSystem=strict, ProtectHome=read-only, NoNewPrivileges=true, PrivateTmp=true, and kernel tunables protection.
- Restrict filesystem write paths to ~/Sites and ~/.local/state/homelab.
- Explicitly set DOCKER_CONFIG to isolated state directory to avoid home directory pollution.
- Prune obsolete SnappyMail tmpfiles rule and ensure gitops state directories exist.
- Mark Milestone P2 as completed in ROADMAP.md and advance Milestone P3 to current up next.
2026-10-13 06:51:27 -05:00
kiskaadee 61627cdd5d feat(gitops): implement authoritative registry, compose AST validation, and evict brain vault
- Add config/deployments.yaml as the authoritative Core repository registry enforcing strict containment within ~/Sites.
- Add validate_compose_security() AST pre-flight validator in gitops_dispatcher to reject privileged: true, Docker socket mounts, host networking, and unauthorized host bind mounts.
- Evict BRAIN_DIR constants and special-case bypasses from GitOps dispatcher; decouple knowledge vault synchronization from continuous workload deployment.
- Update tests to verify vault rejection, registry containment enforcement, and compose security AST validation.
2026-10-13 06:49:39 -05:00
5 changed files with 415 additions and 111 deletions

No files matched your search

+5 -5
View File
@@ -64,19 +64,19 @@ It describes the implementation trajectory and phased engineering milestones for
--- ---
### Milestone P2: GitOps Privilege & Authority Hardening ### Milestone P2: GitOps Privilege & Authority Hardening
**Status**: 🎯 **Current / Up Next** **Status**: ✅ **Completed**
* **Objective**: Close remaining trust boundaries in the webhook continuous deployment engine. * **Objective**: Close remaining trust boundaries in the webhook continuous deployment engine.
* **Key Deliverables**: * **Key Deliverables**:
1. *Authoritative Core Registry*: Establish `Core/config/deployments.yaml` as the sole authority for admitted deployment repositories. 1. *Authoritative Core Registry*: Establish `Core/config/deployments.yaml` as the sole authority for admitted deployment repositories.
2. *Data Vault Pull-Only Policy*: Designate `~/Brain` as a read-only repository with `strategy: pull-only`, isolated from Docker socket access. 2. *Decouple Data Vault from Workload GitOps*: Evict vault special-casing (`BRAIN_DIR`) from GitOps engine; continuous deployment strictly manages Sites container workloads.
3. *Compose AST Security Validator*: Pre-flight parser rejecting `privileged: true`, Docker socket bind mounts, host networking, and mounts outside `~/var/lib/homelab/<app>/`. 3. *Compose AST Security Validator*: Pre-flight parser rejecting `privileged: true`, Docker socket bind mounts, host networking, and host mounts outside workload root or state root.
4. *Systemd Sandboxing*: Apply `ProtectSystem=strict`, `NoNewPrivileges=true`, and private temporary directories to `homelab-gitops.service`. 4. *Systemd Sandboxing*: Apply `ProtectSystem=strict`, `ProtectHome=read-only`, `ReadWritePaths`, `NoNewPrivileges=true`, and private temporary directories to `homelab-gitops.service`.
* **Exit Criteria**: Path traversal rejection tests pass; Compose AST security validator rejects prohibited capabilities. * **Exit Criteria**: Path traversal rejection tests pass; Compose AST security validator rejects prohibited capabilities.
--- ---
### Milestone P3: Manifest Contract Convergence & Provenance Engine ### Milestone P3: Manifest Contract Convergence & Provenance Engine
**Status**: ⏳ **Planned** **Status**: 🎯 **Current / Up Next**
* **Objective**: Establish a single authoritative manifest schema and two-axis inspection engine across the platform. * **Objective**: Establish a single authoritative manifest schema and two-axis inspection engine across the platform.
* **Key Deliverables**: * **Key Deliverables**:
1. *Schema v1.0 & Parser Library (`core_manifest.py`)*: Strongly-typed manifest parsing, transport scheme validation (`https://`, `ssh://`, `git@`), and explicit ref semantics (moving branches vs. pinned tags vs. commit SHAs). 1. *Schema v1.0 & Parser Library (`core_manifest.py`)*: Strongly-typed manifest parsing, transport scheme validation (`https://`, `ssh://`, `git@`), and explicit ref semantics (moving branches vs. pinned tags vs. commit SHAs).
+53
View File
@@ -0,0 +1,53 @@
# Core Authoritative Repository Identity Registry
# Governs admitted continuous deployment targets for GitOps webhook execution.
# Owns: repository identity, canonical filesystem path, and aliases.
# Enforces: strict path containment within ~/Sites.
schemaVersion: "1.0"
repositories:
snappymail:
path: "/home/kiskaadee/Sites/snappymail"
aliases:
- "homelab-snappymail"
- "mail"
- "webmail"
gitea:
path: "/home/kiskaadee/Sites/homelab-gitea"
aliases:
- "homelab-gitea"
- "git"
jellyfin:
path: "/home/kiskaadee/Sites/homelab-jellyfin"
aliases:
- "homelab-jellyfin"
- "media"
docs:
path: "/home/kiskaadee/Sites/homelab-doc2site"
aliases:
- "doc2site"
- "homelab-doc2site"
courses:
path: "/home/kiskaadee/Sites/courses"
aliases:
- "homelab-courses"
bdinvite:
path: "/home/kiskaadee/Sites/homelab-bdinvite"
aliases:
- "homelab-bdinvite"
- "birthday"
landing:
path: "/home/kiskaadee/Sites/homelab-landing"
aliases:
- "homelab-landing"
mermaid:
path: "/home/kiskaadee/Sites/homelab-mermaid"
aliases:
- "homelab-mermaid"
excalidraw:
path: "/home/kiskaadee/Sites/homelab-excalidraw"
aliases:
- "homelab-excalidraw"
houston:
path: "/home/kiskaadee/Sites/homelab-houston"
aliases:
- "homelab-houston"
+18 -2
View File
@@ -70,11 +70,13 @@
environment = { environment = {
GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path; GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path;
DOCKER_CONFIG = "/home/kiskaadee/.local/state/homelab/docker";
}; };
serviceConfig = { serviceConfig = {
Type = "simple"; Type = "simple";
User = "kiskaadee"; User = "kiskaadee";
SupplementaryGroups = [ "docker" ];
WorkingDirectory = "/home/kiskaadee/Core"; WorkingDirectory = "/home/kiskaadee/Core";
ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [ ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [
{ {
@@ -91,14 +93,28 @@
])} -port 9000 -verbose"; ])} -port 9000 -verbose";
Restart = "on-failure"; Restart = "on-failure";
RestartSec = "5s"; RestartSec = "5s";
# Privilege separation & Systemd sandboxing
NoNewPrivileges = true;
PrivateTmp = true;
ProtectSystem = "strict";
ProtectHome = "read-only";
ProtectKernelTunables = true;
ProtectControlGroups = true;
ReadWritePaths = [
"/home/kiskaadee/Sites"
"/home/kiskaadee/.local/state/homelab"
];
}; };
}; };
# Ensure persistent directories have proper permissions for container runtimes (e.g. Stalwart UID 2000, SnappyMail) # Ensure persistent directories have proper permissions for container runtimes
systemd.tmpfiles.rules = [ systemd.tmpfiles.rules = [
"d /home/kiskaadee/Core/config/stalwart/data 0777 kiskaadee users -" "d /home/kiskaadee/Core/config/stalwart/data 0777 kiskaadee users -"
"d /home/kiskaadee/Core/config/stalwart/etc 0777 kiskaadee users -" "d /home/kiskaadee/Core/config/stalwart/etc 0777 kiskaadee users -"
"d /home/kiskaadee/Core/config/snappymail/data 0777 kiskaadee users -" "d /home/kiskaadee/Sites 0755 kiskaadee users -"
"d /home/kiskaadee/.local/state/homelab/gitops 0755 kiskaadee users -"
"d /home/kiskaadee/.local/state/homelab/docker 0755 kiskaadee users -"
]; ];
# Open ports in the firewall for Traefik, Gitea SSH, GitOps Webhook Receiver, and Mail (SMTP, Submission, SMTPS, IMAPS, ManageSieve) # Open ports in the firewall for Traefik, Gitea SSH, GitOps Webhook Receiver, and Mail (SMTP, Submission, SMTPS, IMAPS, ManageSieve)
+194 -97
View File
@@ -20,9 +20,15 @@ import subprocess
import sys import sys
from pathlib import Path from pathlib import Path
try:
import yaml
except ImportError:
yaml = None
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites"))) SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
BRAIN_DIR = Path(os.environ.get("BRAIN_DIR", os.path.expanduser("~/Brain"))) 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"))) 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")) 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")) STATE_DIR = Path(os.environ.get("GITOPS_STATE_DIR", Path.home() / ".local/state/homelab/gitops"))
@@ -150,16 +156,41 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
""" """
Build authoritative mapping of logical repository identities to local paths. Build authoritative mapping of logical repository identities to local paths.
Webhook payloads can only select repositories defined in this mapping. Webhook payloads can only select repositories defined in this mapping.
Prioritizes Core Authoritative Registry (deployments.yaml) over dynamic discovery.
""" """
mapping: dict[str, Path] = {} mapping: dict[str, Path] = {}
# 1. Authoritative Data Vaults # 1. Authoritative Core Repository Registry (deployments.yaml)
if BRAIN_DIR.is_dir(): registry_file = DEPLOYMENTS_FILE if DEPLOYMENTS_FILE.is_file() else (CONFIG_DIR / "deployments.yaml")
brain_canonical = BRAIN_DIR.resolve() if registry_file.is_file():
for alias in ["second-brain", "Brain", "brain"]: try:
mapping[alias] = brain_canonical 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
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}")
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
logger.warning(f"Failed to parse authoritative registry {registry_file}: {e}")
# 2. Workload Plane Applications in SITES_DIR # 2. Dynamic Discovery in SITES_DIR (for workloads not explicitly registered)
if SITES_DIR.is_dir(): if SITES_DIR.is_dir():
sites_canonical = SITES_DIR.resolve() sites_canonical = SITES_DIR.resolve()
for entry in SITES_DIR.iterdir(): for entry in SITES_DIR.iterdir():
@@ -176,55 +207,36 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
if not manifest_file.is_file(): if not manifest_file.is_file():
continue continue
# Register entry directory name # Register entry directory name if not already mapped
dir_name = entry.name dir_name = entry.name
mapping[dir_name] = resolved_entry if dir_name not in mapping:
mapping[dir_name] = resolved_entry
# Parse app.yaml for canonical name and aliases # Parse app.yaml for canonical name and aliases
manifest = {} manifest = {}
try: try:
manifest = parse_yaml_simple(manifest_file.read_text(encoding="utf-8")) 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: except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
logger.warning(f"Failed to parse {manifest_file}: {e}") logger.warning(f"Failed to parse {manifest_file}: {e}")
canonical_name = manifest.get("name") canonical_name = manifest.get("name")
if canonical_name and isinstance(canonical_name, str): if canonical_name and isinstance(canonical_name, str):
canonical_name = canonical_name.strip() canonical_name = canonical_name.strip()
mapping[canonical_name] = resolved_entry if canonical_name not in mapping:
if not canonical_name.startswith("homelab-"): mapping[canonical_name] = resolved_entry
mapping[f"homelab-{canonical_name}"] = resolved_entry alias_with_prefix = f"homelab-{canonical_name}" if not canonical_name.startswith("homelab-") else canonical_name.replace("homelab-", "", 1)
else: if alias_with_prefix not in mapping:
mapping[canonical_name.replace("homelab-", "", 1)] = resolved_entry mapping[alias_with_prefix] = resolved_entry
aliases = manifest.get("aliases", []) aliases = manifest.get("aliases", [])
if isinstance(aliases, str): if isinstance(aliases, str):
aliases = [aliases] aliases = [aliases]
if isinstance(aliases, list): if isinstance(aliases, list):
for alias in aliases: for alias in aliases:
if isinstance(alias, str) and alias.strip(): if isinstance(alias, str) and alias.strip() and alias.strip() not in mapping:
mapping[alias.strip()] = resolved_entry mapping[alias.strip()] = resolved_entry
# 3. Optional local override registry with strict containment
registry_file = CONFIG_DIR / "deployments.yaml"
if registry_file.is_file():
try:
registry = parse_yaml_simple(registry_file.read_text(encoding="utf-8"))
for reg_name, entry in registry.items():
if not isinstance(entry, dict):
continue
raw_path = entry.get("path")
if not raw_path:
continue
p = Path(raw_path).resolve()
# Must be strictly relative to SITES_DIR or BRAIN_DIR
if (SITES_DIR.is_dir() and p.is_relative_to(SITES_DIR.resolve())) or \
(BRAIN_DIR.is_dir() and p.is_relative_to(BRAIN_DIR.resolve())):
mapping[reg_name] = p
else:
logger.warning(f"Rejecting out-of-bounds path in deployments.yaml for '{reg_name}': {p}")
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
logger.warning(f"Failed to parse custom registry {registry_file}: {e}")
return mapping return mapping
@@ -262,13 +274,9 @@ def resolve_repository(repo_name: str) -> Path | None:
logger.warning(f"Trusted repository target '{canonical_target}' does not exist or is not a directory.") logger.warning(f"Trusted repository target '{canonical_target}' does not exist or is not a directory.")
return None return None
# Defense-in-depth: check allowed root containment # Defense-in-depth: check allowed root containment strictly within SITES_DIR
allowed = False if not (SITES_DIR.is_dir() and canonical_target.is_relative_to(SITES_DIR.resolve())):
if SITES_DIR.is_dir() and canonical_target.is_relative_to(SITES_DIR.resolve()) or BRAIN_DIR.is_dir() and canonical_target.is_relative_to(BRAIN_DIR.resolve()): logger.warning(f"Resolved path '{canonical_target}' escapes allowed SITES_DIR root for repository '{cleaned_name}'.")
allowed = True
if not allowed:
logger.warning(f"Resolved path '{canonical_target}' escapes allowed roots for repository '{cleaned_name}'.")
return None return None
return canonical_target return canonical_target
@@ -283,18 +291,12 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
if not target_dir: if not target_dir:
return None, {} return None, {}
# Data vault default deployment config
if BRAIN_DIR.is_dir() and target_dir == BRAIN_DIR.resolve():
return target_dir, {
"branch": "main",
"actions": ["git_pull"]
}
manifest_file = target_dir / "app.yaml" manifest_file = target_dir / "app.yaml"
manifest = {} manifest = {}
if manifest_file.is_file(): if manifest_file.is_file():
try: try:
manifest = parse_yaml_simple(manifest_file.read_text(encoding="utf-8")) 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: except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
logger.warning(f"Failed to parse {manifest_file}: {e}") logger.warning(f"Failed to parse {manifest_file}: {e}")
@@ -312,6 +314,85 @@ ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"}
ALLOWED_STRATEGIES = {"compose"} ALLOWED_STRATEGIES = {"compose"}
def validate_compose_security(compose_file: Path, allowed_root: Path) -> tuple[bool, str | None]:
"""
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
"""
if not compose_file.is_file():
return True, None
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 not None:
try:
data = yaml.safe_load(content) or {}
except yaml.YAMLError 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."
return True, None
if not isinstance(data, dict):
return False, f"Invalid compose root in {compose_file}: expected mapping"
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()
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'."
net_mode = str(svc.get("network_mode", "")).strip().lower()
if net_mode == "host":
return False, f"Service '{svc_name}' specifies prohibited 'network_mode: host'."
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()
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}."
if vol.get("type") == "bind":
host_path = src
# Evaluate host_path escapes
if host_path and 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):
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]: def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]:
""" """
Validate deployment policy inside app.yaml. Validate deployment policy inside app.yaml.
@@ -370,37 +451,43 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
# Revision-consistent manifest validation: # Revision-consistent manifest validation:
# The working tree has now advanced to the deployed revision. # The working tree has now advanced to the deployed revision.
# Re-read and re-validate app.yaml from the exact deployed revision. # Re-read and re-validate app.yaml from the exact deployed revision.
if not (BRAIN_DIR.is_dir() and target_dir == BRAIN_DIR.resolve()): manifest_file = target_dir / "app.yaml"
manifest_file = target_dir / "app.yaml" if manifest_file.is_file():
if manifest_file.is_file(): try:
try: manifest_text = manifest_file.read_text(encoding="utf-8")
fresh_manifest = parse_yaml_simple(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: except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
logger.error(f"❌ Post-pull manifest parse failure in {manifest_file}: {e}") logger.error(f"❌ Post-pull manifest parse failure in {manifest_file}: {e}")
return False return False
valid, err_msg = validate_manifest_deployment(fresh_manifest) valid, err_msg = validate_manifest_deployment(fresh_manifest)
if not valid: if not valid:
logger.error(f"❌ Post-pull manifest validation failed for '{target_dir.name}': {err_msg}") logger.error(f"❌ Post-pull manifest validation failed for '{target_dir.name}': {err_msg}")
return False return False
fresh_config = fresh_manifest.get("deployment") fresh_config = fresh_manifest.get("deployment")
if isinstance(fresh_config, dict): if isinstance(fresh_config, dict):
fresh_branch = fresh_config.get("branch", "main") fresh_branch = fresh_config.get("branch", "main")
if branch and branch != fresh_branch: if branch and branch != fresh_branch:
logger.error( logger.error(
f"❌ Post-pull branch policy violation: revision declared branch '{fresh_branch}', " f"❌ Post-pull branch policy violation: revision declared branch '{fresh_branch}', "
f"but pushed branch was '{branch}'. Aborting deployment." f"but pushed branch was '{branch}'. Aborting deployment."
) )
return False return False
# Adopt the freshly validated actions from the deployed revision # Adopt the freshly validated actions from the deployed revision
fresh_actions = fresh_config.get("actions", actions) fresh_actions = fresh_config.get("actions", actions)
actions = [a for a in fresh_actions if a != "git_pull"] actions = [a for a in fresh_actions if a != "git_pull"]
idx = 0 idx = 0
continue continue
elif action == "compose_up": elif action == "compose_up":
compose_file = target_dir / "docker-compose.yml" 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(): if compose_file.is_file():
valid_sec, sec_err = validate_compose_security(compose_file, target_dir)
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)...") logger.info(" ↳ [compose_up] Recreating containers (docker compose up -d)...")
subprocess.run( subprocess.run(
["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"], ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"],
@@ -408,7 +495,13 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
) )
elif action == "compose_build": elif action == "compose_build":
compose_file = target_dir / "docker-compose.yml" 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(): if compose_file.is_file():
valid_sec, sec_err = validate_compose_security(compose_file, target_dir)
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...") logger.info(" ↳ [compose_build] Building & recreating containers...")
subprocess.run( subprocess.run(
["docker", "compose", "-f", str(compose_file), "build"], ["docker", "compose", "-f", str(compose_file), "build"],
@@ -420,7 +513,13 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
) )
elif action == "compose_restart": elif action == "compose_restart":
compose_file = target_dir / "docker-compose.yml" 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(): if compose_file.is_file():
valid_sec, sec_err = validate_compose_security(compose_file, target_dir)
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...") logger.info(" ↳ [compose_restart] Restarting containers...")
subprocess.run( subprocess.run(
["docker", "compose", "-f", str(compose_file), "restart"], ["docker", "compose", "-f", str(compose_file), "restart"],
@@ -493,27 +592,25 @@ def admit_deployment(
return False, None, {}, pushed_branch, f"Repository '{repo_name}' is not recognized in trusted registry." return False, None, {}, pushed_branch, f"Repository '{repo_name}' is not recognized in trusted registry."
# 4. Manifest & Strategy Validation # 4. Manifest & Strategy Validation
if BRAIN_DIR.is_dir() and target_dir == BRAIN_DIR.resolve(): manifest_file = target_dir / "app.yaml"
deployment_config = {"branch": "main", "actions": ["git_pull"]} manifest = {}
else: if manifest_file.is_file():
manifest_file = target_dir / "app.yaml" try:
manifest = {} manifest_text = manifest_file.read_text(encoding="utf-8")
if manifest_file.is_file(): manifest = (yaml.safe_load(manifest_text) if yaml else parse_yaml_simple(manifest_text)) or {}
try: except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
manifest = parse_yaml_simple(manifest_file.read_text(encoding="utf-8")) return False, None, {}, pushed_branch, f"Failed to parse manifest {manifest_file}: {e}"
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
return False, None, {}, pushed_branch, f"Failed to parse manifest {manifest_file}: {e}"
valid, err_msg = validate_manifest_deployment(manifest) valid, err_msg = validate_manifest_deployment(manifest)
if not valid: if not valid:
return False, None, {}, pushed_branch, f"Manifest validation error: {err_msg}" return False, None, {}, pushed_branch, f"Manifest validation error: {err_msg}"
deployment_config = manifest.get("deployment") deployment_config = manifest.get("deployment")
if not isinstance(deployment_config, dict): if not isinstance(deployment_config, dict):
deployment_config = { deployment_config = {
"branch": "main", "branch": "main",
"actions": ["git_pull", "compose_up"] "actions": ["git_pull", "compose_up"]
} }
# 5. Branch Policy Admission # 5. Branch Policy Admission
expected_branch = deployment_config.get("branch", "main") expected_branch = deployment_config.get("branch", "main")
+145 -7
View File
@@ -131,16 +131,52 @@ def test_resolve_repository_resolves_valid_manifest(tmp_path: Path, monkeypatch)
assert gitops_dispatcher.resolve_repository("notes") == canonical assert gitops_dispatcher.resolve_repository("notes") == canonical
def test_resolve_repository_resolves_vault(tmp_path: Path, monkeypatch): def test_resolve_repository_rejects_vault(tmp_path: Path, monkeypatch):
"""Ensure authoritative data vault identities resolve strictly to BRAIN_DIR.""" """Ensure data vault identities (Brain / second-brain) are not recognized by GitOps."""
sites_dir = tmp_path / "Sites"
sites_dir.mkdir()
brain_dir = tmp_path / "Brain" brain_dir = tmp_path / "Brain"
brain_dir.mkdir() brain_dir.mkdir()
monkeypatch.setattr(gitops_dispatcher, "BRAIN_DIR", brain_dir) monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
canonical = brain_dir.resolve() assert gitops_dispatcher.resolve_repository("second-brain") is None
assert gitops_dispatcher.resolve_repository("second-brain") == canonical assert gitops_dispatcher.resolve_repository("Brain") is None
assert gitops_dispatcher.resolve_repository("Brain") == canonical assert gitops_dispatcher.resolve_repository("brain") is None
assert gitops_dispatcher.resolve_repository("brain") == canonical
def test_get_trusted_repository_mapping_from_registry(tmp_path: Path, monkeypatch):
"""Ensure authoritative Core registry (deployments.yaml) is loaded with containment checks."""
sites_dir = tmp_path / "Sites"
sites_dir.mkdir()
app_dir = sites_dir / "my-app"
app_dir.mkdir()
outside_dir = tmp_path / "outside"
outside_dir.mkdir()
deployments_content = f"""
schemaVersion: "1.0"
repositories:
my-app:
path: "{app_dir}"
aliases:
- "app-alias"
escaped-app:
path: "{outside_dir}"
"""
deployments_file = tmp_path / "deployments.yaml"
deployments_file.write_text(deployments_content, encoding="utf-8")
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", deployments_file)
mapping = gitops_dispatcher.get_trusted_repository_mapping()
assert "my-app" in mapping
assert mapping["my-app"] == app_dir.resolve()
assert "app-alias" in mapping
assert mapping["app-alias"] == app_dir.resolve()
# Out-of-bounds path must be rejected
assert "escaped-app" not in mapping
def test_webhook_verification_valid_signature(): def test_webhook_verification_valid_signature():
@@ -565,6 +601,108 @@ def test_worker_records_status_file(tmp_path: Path, monkeypatch):
assert "timestamp" in status assert "timestamp" in status
def test_validate_compose_security_rejects_privileged(tmp_path: Path):
"""Ensure docker-compose with privileged: true fails pre-flight validation."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text("""
services:
app:
image: alpine:latest
privileged: true
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is False
assert err is not None and "privileged: true" in err
def test_validate_compose_security_rejects_docker_socket_mount(tmp_path: Path):
"""Ensure docker-compose with /var/run/docker.sock mount fails validation."""
# Test string syntax
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text("""
services:
app:
image: alpine:latest
volumes:
- /var/run/docker.sock:/var/run/docker.sock
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is False
assert err is not None and "Docker socket" in err
# Test dict / long syntax
compose_file.write_text("""
services:
app:
image: alpine:latest
volumes:
- type: bind
source: /var/run/docker.sock
target: /var/run/docker.sock
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is False
assert err is not None and "Docker socket" in err
def test_validate_compose_security_rejects_host_network(tmp_path: Path):
"""Ensure docker-compose with network_mode: host fails pre-flight validation."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text("""
services:
app:
image: alpine:latest
network_mode: host
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is False
assert err is not None and "network_mode: host" in err
def test_validate_compose_security_rejects_out_of_bounds_host_bind(tmp_path: Path):
"""Ensure host bind mounts outside workload directory or state root are rejected."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text("""
services:
app:
image: alpine:latest
volumes:
- /etc/shadow:/etc/shadow:ro
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is False
assert err is not None and "prohibited host bind mount" in err
def test_validate_compose_security_allows_safe_compose(tmp_path: Path):
"""Ensure safe compose definitions with relative binds and named volumes pass validation."""
data_dir = tmp_path / "data"
data_dir.mkdir()
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(f"""
services:
app:
image: alpine:latest
volumes:
- {data_dir}:/data
- named_vol:/var/log
volumes:
named_vol:
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is True
assert err is None
def test_validate_compose_security_nonexistent_file(tmp_path: Path):
"""Ensure validation passes when compose file is absent."""
compose_file = tmp_path / "nonexistent.yml"
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is True
assert err is None