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.
This commit is contained in:
1 parent
c549ada3b4
commit
61627cdd5d
3 files changed
+351
-63
No files matched your search
@@ -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"
|
||||||
+153
-56
@@ -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
|
||||||
|
if dir_name not in mapping:
|
||||||
mapping[dir_name] = resolved_entry
|
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()
|
||||||
|
if canonical_name not in mapping:
|
||||||
mapping[canonical_name] = resolved_entry
|
mapping[canonical_name] = resolved_entry
|
||||||
if not canonical_name.startswith("homelab-"):
|
alias_with_prefix = f"homelab-{canonical_name}" if not canonical_name.startswith("homelab-") else canonical_name.replace("homelab-", "", 1)
|
||||||
mapping[f"homelab-{canonical_name}"] = resolved_entry
|
if alias_with_prefix not in mapping:
|
||||||
else:
|
mapping[alias_with_prefix] = resolved_entry
|
||||||
mapping[canonical_name.replace("homelab-", "", 1)] = 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,11 +451,11 @@ 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:
|
||||||
fresh_manifest = parse_yaml_simple(manifest_file.read_text(encoding="utf-8"))
|
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:
|
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
|
||||||
@@ -400,7 +481,13 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
|||||||
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,14 +592,12 @@ 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():
|
|
||||||
deployment_config = {"branch": "main", "actions": ["git_pull"]}
|
|
||||||
else:
|
|
||||||
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:
|
||||||
return False, None, {}, pushed_branch, f"Failed to parse manifest {manifest_file}: {e}"
|
return False, None, {}, pushed_branch, f"Failed to parse manifest {manifest_file}: {e}"
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Reference in new issue
Block a user