style: format python files with ruff
This commit is contained in:
1 parent
51c43f71ff
commit
dc880928a9
11 files changed
+1150
-527
No files matched your search
@@ -28,7 +28,7 @@ PROVIDERS = [
|
||||
"https://api.ipify.org",
|
||||
"https://ifconfig.me/ip",
|
||||
"https://icanhazip.com",
|
||||
"https://wtfismyip.com/text"
|
||||
"https://wtfismyip.com/text",
|
||||
]
|
||||
|
||||
|
||||
@@ -78,14 +78,11 @@ def get_public_ip():
|
||||
for provider in PROVIDERS:
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
provider,
|
||||
headers={
|
||||
'User-Agent': 'Mozilla/5.0 (NixOS WAN Monitor)'
|
||||
}
|
||||
provider, headers={"User-Agent": "Mozilla/5.0 (NixOS WAN Monitor)"}
|
||||
)
|
||||
# Fetch with 5s timeout to avoid hanging the systemd service
|
||||
with urllib.request.urlopen(req, timeout=5) as response:
|
||||
ip = response.read().decode('utf-8').strip()
|
||||
ip = response.read().decode("utf-8").strip()
|
||||
if is_valid_public_ipv4(ip):
|
||||
return ip
|
||||
else:
|
||||
@@ -94,8 +91,7 @@ def get_public_ip():
|
||||
errors.append(f"{provider}: {e!s}")
|
||||
|
||||
print(
|
||||
f"Error: All IP discovery providers failed. Details: {errors}",
|
||||
file=sys.stderr
|
||||
f"Error: All IP discovery providers failed. Details: {errors}", file=sys.stderr
|
||||
)
|
||||
return None
|
||||
|
||||
@@ -132,11 +128,7 @@ def record_ip(ip, status, details=None):
|
||||
Appends a new event entry into the JSONLines history registry.
|
||||
"""
|
||||
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
|
||||
entry = {
|
||||
"timestamp": datetime.now(tz=UTC).isoformat(),
|
||||
"ip": ip,
|
||||
"status": status
|
||||
}
|
||||
entry = {"timestamp": datetime.now(tz=UTC).isoformat(), "ip": ip, "status": status}
|
||||
if details:
|
||||
entry["details"] = details
|
||||
try:
|
||||
@@ -164,10 +156,7 @@ def trigger_ddclient():
|
||||
if res.returncode == 0:
|
||||
return True, None
|
||||
else:
|
||||
err_msg = (
|
||||
f"systemctl exited with {res.returncode}: "
|
||||
f"{res.stderr.strip()}"
|
||||
)
|
||||
err_msg = f"systemctl exited with {res.returncode}: {res.stderr.strip()}"
|
||||
return False, err_msg
|
||||
except (OSError, subprocess.SubprocessError) as e:
|
||||
return False, str(e)
|
||||
|
||||
+173
-79
@@ -33,7 +33,8 @@ from provenance import (
|
||||
|
||||
# Dynamic Environment Paths
|
||||
CORE_DIR = os.environ.get(
|
||||
"CORE_DIR", os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
||||
"CORE_DIR",
|
||||
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
||||
)
|
||||
|
||||
SITES_DIR = os.environ.get(
|
||||
@@ -75,15 +76,22 @@ ManifestError = ManifestValidationError
|
||||
|
||||
@dataclass
|
||||
class App:
|
||||
name: str # Canonical identifier (e.g., "traefik", "jellyfin")
|
||||
description: str = "" # Human-readable summary for dashboards and CLI info
|
||||
domain: str = "" # Routing FQDN (e.g., "auth.example.com") or "internal".
|
||||
dir_path: str = "" # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
|
||||
name: str # Canonical identifier (e.g., "traefik", "jellyfin")
|
||||
description: str = "" # Human-readable summary for dashboards and CLI info
|
||||
domain: str = "" # Routing FQDN (e.g., "auth.example.com") or "internal".
|
||||
dir_path: str = (
|
||||
"" # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
|
||||
)
|
||||
|
||||
@property
|
||||
def is_internal(self) -> bool:
|
||||
"""Returns True if the service does not expose a public TLS endpoint."""
|
||||
return not self.domain or self.domain == "internal" or self.domain.endswith(".local") or ":" in self.domain
|
||||
return (
|
||||
not self.domain
|
||||
or self.domain == "internal"
|
||||
or self.domain.endswith(".local")
|
||||
or ":" in self.domain
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Serialize for JSON consumption by scripts/appctl"""
|
||||
@@ -94,26 +102,30 @@ class App:
|
||||
|
||||
@dataclass
|
||||
class CoreService(App):
|
||||
container: str = "" # Target container name inside Core's docker-compose.yml
|
||||
weight: int = 50 # Homepage ordering weight
|
||||
icon: str = "default.png" # Dashboard icon filename
|
||||
container: str = "" # Target container name inside Core's docker-compose.yml
|
||||
weight: int = 50 # Homepage ordering weight
|
||||
icon: str = "default.png" # Dashboard icon filename
|
||||
app_type: str = "core_service"
|
||||
dir_path: str = CORE_DIR
|
||||
|
||||
|
||||
@dataclass
|
||||
class SitesApp(App):
|
||||
dir_name: str = "" # directory name in ~/Sites (e.g., "homelab-vaultwarden")
|
||||
source: SourceConfig | None = None # Upstream source provenance (None = Class B Image-Only)
|
||||
aliases: list[str] = field(default_factory=list) # CLI resolution aliases
|
||||
visible: bool = True # Defines whether the icon is visible in Homepage
|
||||
auth: bool = True # Authelia protection guard indicator
|
||||
has_compose: bool = False # Whether a docker-compose.yml exists
|
||||
networks: list[str] = field(default_factory=lambda: ["proxy-net"]) # Docker network attachments
|
||||
env: dict[str, Any] = field(default_factory=dict) # Environment variable overrides
|
||||
homepage: HomepageConfig | None = None # Dashboard Card Configuration
|
||||
manifest_error: str | None = None # Captured syntax/loading errors
|
||||
manifest_obj: Manifest | None = None # Parsed authoritative Manifest
|
||||
dir_name: str = "" # directory name in ~/Sites (e.g., "homelab-vaultwarden")
|
||||
source: SourceConfig | None = (
|
||||
None # Upstream source provenance (None = Class B Image-Only)
|
||||
)
|
||||
aliases: list[str] = field(default_factory=list) # CLI resolution aliases
|
||||
visible: bool = True # Defines whether the icon is visible in Homepage
|
||||
auth: bool = True # Authelia protection guard indicator
|
||||
has_compose: bool = False # Whether a docker-compose.yml exists
|
||||
networks: list[str] = field(
|
||||
default_factory=lambda: ["proxy-net"]
|
||||
) # Docker network attachments
|
||||
env: dict[str, Any] = field(default_factory=dict) # Environment variable overrides
|
||||
homepage: HomepageConfig | None = None # Dashboard Card Configuration
|
||||
manifest_error: str | None = None # Captured syntax/loading errors
|
||||
manifest_obj: Manifest | None = None # Parsed authoritative Manifest
|
||||
app_type: str = "app"
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
@@ -121,15 +133,21 @@ class SitesApp(App):
|
||||
data = asdict(self)
|
||||
data.pop("manifest_obj", None)
|
||||
if self.source is not None:
|
||||
data["source"] = self.source.to_dict() if hasattr(self.source, "to_dict") else self.source.model_dump()
|
||||
data["source"] = (
|
||||
self.source.to_dict()
|
||||
if hasattr(self.source, "to_dict")
|
||||
else self.source.model_dump()
|
||||
)
|
||||
if self.homepage is not None:
|
||||
data["homepage"] = self.homepage.to_dict() if hasattr(self.homepage, "to_dict") else self.homepage.model_dump()
|
||||
data["homepage"] = (
|
||||
self.homepage.to_dict()
|
||||
if hasattr(self.homepage, "to_dict")
|
||||
else self.homepage.model_dump()
|
||||
)
|
||||
data["type"] = getattr(self, "app_type", "app")
|
||||
return data
|
||||
|
||||
|
||||
|
||||
|
||||
def sites_app_from_manifest(
|
||||
app_dir: str,
|
||||
manifest: Manifest | dict[str, Any] | None = None,
|
||||
@@ -139,10 +157,9 @@ def sites_app_from_manifest(
|
||||
raw_dir_name = os.path.basename(app_dir)
|
||||
|
||||
if isinstance(manifest, Manifest):
|
||||
has_compose = (
|
||||
os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or
|
||||
os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
|
||||
)
|
||||
has_compose = os.path.isfile(
|
||||
os.path.join(app_dir, "docker-compose.yaml")
|
||||
) or os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
|
||||
canonical_name = manifest.name
|
||||
domain = manifest.domain or f"{canonical_name}.{HOMELAB_DOMAIN}"
|
||||
return SitesApp(
|
||||
@@ -169,7 +186,9 @@ def sites_app_from_manifest(
|
||||
return sites_app_from_manifest(app_dir, parsed, manifest_error)
|
||||
except ManifestValidationError as err:
|
||||
manifest_error = f"{manifest_error}; {err}" if manifest_error else str(err)
|
||||
canonical_name = str(manifest.get("name") or raw_dir_name.replace("homelab-", ""))
|
||||
canonical_name = str(
|
||||
manifest.get("name") or raw_dir_name.replace("homelab-", "")
|
||||
)
|
||||
return SitesApp(
|
||||
name=canonical_name,
|
||||
dir_name=raw_dir_name,
|
||||
@@ -217,7 +236,13 @@ def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]:
|
||||
try:
|
||||
manifest_obj = parse_manifest(manifest_file)
|
||||
apps.append(sites_app_from_manifest(app_dir=app_dir, manifest=manifest_obj))
|
||||
except (ManifestValidationError, yaml.YAMLError, OSError, ValueError, KeyError) as err:
|
||||
except (
|
||||
ManifestValidationError,
|
||||
yaml.YAMLError,
|
||||
OSError,
|
||||
ValueError,
|
||||
KeyError,
|
||||
) as err:
|
||||
raw_data = None
|
||||
with (
|
||||
contextlib.suppress(Exception),
|
||||
@@ -328,7 +353,9 @@ def resolve_app(
|
||||
Priority: Canonical Name > Alias > Dir Name > Stripped 'homelab-' Prefix > Core Services.
|
||||
"""
|
||||
if apps is None:
|
||||
apps = get_sites_apps(sites_dir=sites_dir if sites_dir is not None else SITES_DIR)
|
||||
apps = get_sites_apps(
|
||||
sites_dir=sites_dir if sites_dir is not None else SITES_DIR
|
||||
)
|
||||
|
||||
query_clean = query.strip().lower()
|
||||
|
||||
@@ -389,7 +416,11 @@ def get_docker_status(
|
||||
return "🔴 Stopped"
|
||||
|
||||
path = Path(dir_path)
|
||||
if path.exists() and not (path / "docker-compose.yml").is_file() and not (path / "docker-compose.yaml").is_file():
|
||||
if (
|
||||
path.exists()
|
||||
and not (path / "docker-compose.yml").is_file()
|
||||
and not (path / "docker-compose.yaml").is_file()
|
||||
):
|
||||
return "⚪ Not Stack"
|
||||
|
||||
res = subprocess.run(
|
||||
@@ -465,7 +496,9 @@ def get_docker_image_revision(
|
||||
return None
|
||||
|
||||
|
||||
def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[str, Any]:
|
||||
def check_ssl_cert(
|
||||
domain: str, port: int = 443, timeout: float = 3.0
|
||||
) -> dict[str, Any]:
|
||||
"""Inspect SSL/TLS certificate for a domain using standard library ssl and socket."""
|
||||
if not domain or domain == "internal" or domain.endswith(".local") or ":" in domain:
|
||||
return {
|
||||
@@ -492,9 +525,9 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
||||
days_remaining = None
|
||||
formatted_expiry = "-"
|
||||
if not_after_str:
|
||||
expiry_dt = datetime.datetime.strptime(not_after_str, "%b %d %H:%M:%S %Y %Z").replace(
|
||||
tzinfo=datetime.UTC
|
||||
)
|
||||
expiry_dt = datetime.datetime.strptime(
|
||||
not_after_str, "%b %d %H:%M:%S %Y %Z"
|
||||
).replace(tzinfo=datetime.UTC)
|
||||
now_dt = datetime.datetime.now(datetime.UTC)
|
||||
days_remaining = (expiry_dt - now_dt).days
|
||||
formatted_expiry = expiry_dt.strftime("%Y-%m-%d")
|
||||
@@ -507,7 +540,11 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
||||
entry = rdn[0]
|
||||
if isinstance(entry, (list, tuple)) and len(entry) >= 2:
|
||||
issuer_dict[str(entry[0])] = str(entry[1])
|
||||
issuer = str(issuer_dict.get("organizationName") or issuer_dict.get("commonName") or "Unknown")
|
||||
issuer = str(
|
||||
issuer_dict.get("organizationName")
|
||||
or issuer_dict.get("commonName")
|
||||
or "Unknown"
|
||||
)
|
||||
|
||||
subject_dict: dict[str, str] = {}
|
||||
subject_raw = cert.get("subject")
|
||||
@@ -519,7 +556,6 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
||||
subject_dict[str(entry[0])] = str(entry[1])
|
||||
subject = str(subject_dict.get("commonName") or domain)
|
||||
|
||||
|
||||
if days_remaining is not None:
|
||||
if days_remaining < 0:
|
||||
status = f"🔴 Expired ({abs(days_remaining)}d ago)"
|
||||
@@ -540,7 +576,14 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
||||
"formatted_expiry": formatted_expiry,
|
||||
"error": None,
|
||||
}
|
||||
except (ssl.SSLError, socket.gaierror, TimeoutError, ConnectionRefusedError, OSError, ValueError) as e:
|
||||
except (
|
||||
ssl.SSLError,
|
||||
socket.gaierror,
|
||||
TimeoutError,
|
||||
ConnectionRefusedError,
|
||||
OSError,
|
||||
ValueError,
|
||||
) as e:
|
||||
return {
|
||||
"domain": domain,
|
||||
"status": "🔴 Failed",
|
||||
@@ -555,13 +598,19 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
||||
|
||||
def check_all_ssl_certs(domains: list[str]) -> dict[str, dict[str, Any]]:
|
||||
"""Check multiple domains concurrently with ThreadPoolExecutor."""
|
||||
valid_domains = [d for d in set(domains) if d and d != "internal" and not d.endswith(".local") and ":" not in d]
|
||||
valid_domains = [
|
||||
d
|
||||
for d in set(domains)
|
||||
if d and d != "internal" and not d.endswith(".local") and ":" not in d
|
||||
]
|
||||
results: dict[str, dict[str, Any]] = {}
|
||||
if not valid_domains:
|
||||
return results
|
||||
|
||||
with ThreadPoolExecutor(max_workers=min(len(valid_domains), 8)) as executor:
|
||||
future_to_domain = {executor.submit(check_ssl_cert, d): d for d in valid_domains}
|
||||
future_to_domain = {
|
||||
executor.submit(check_ssl_cert, d): d for d in valid_domains
|
||||
}
|
||||
for future, d in future_to_domain.items():
|
||||
with contextlib.suppress(subprocess.SubprocessError, OSError):
|
||||
results[d] = future.result()
|
||||
@@ -591,15 +640,17 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
||||
groups[core_group] = []
|
||||
for svc in core_services:
|
||||
if not svc.is_internal:
|
||||
groups[core_group].append({
|
||||
"title": svc.name.title(),
|
||||
"icon": getattr(svc, "icon", "default.png"),
|
||||
"href": f"https://{svc.domain}",
|
||||
"description": svc.description,
|
||||
"server": "my-docker",
|
||||
"container": getattr(svc, "container", svc.name),
|
||||
"weight": getattr(svc, "weight", 50),
|
||||
})
|
||||
groups[core_group].append(
|
||||
{
|
||||
"title": svc.name.title(),
|
||||
"icon": getattr(svc, "icon", "default.png"),
|
||||
"href": f"https://{svc.domain}",
|
||||
"description": svc.description,
|
||||
"server": "my-docker",
|
||||
"container": getattr(svc, "container", svc.name),
|
||||
"weight": getattr(svc, "weight", 50),
|
||||
}
|
||||
)
|
||||
|
||||
# 2. Add Sites applications
|
||||
icons_dir = os.path.join(hp_dir, "icons")
|
||||
@@ -633,15 +684,17 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
||||
if matched_icon:
|
||||
icon = f"/icons/{matched_icon}"
|
||||
|
||||
groups[group_name].append({
|
||||
"title": card_title,
|
||||
"icon": icon,
|
||||
"href": f"https://{app.domain}",
|
||||
"description": desc,
|
||||
"server": "my-docker",
|
||||
"container": container,
|
||||
"weight": weight,
|
||||
})
|
||||
groups[group_name].append(
|
||||
{
|
||||
"title": card_title,
|
||||
"icon": icon,
|
||||
"href": f"https://{app.domain}",
|
||||
"description": desc,
|
||||
"server": "my-docker",
|
||||
"container": container,
|
||||
"weight": weight,
|
||||
}
|
||||
)
|
||||
|
||||
# Preferred group order
|
||||
preferred_order = [
|
||||
@@ -678,7 +731,9 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
||||
with open(services_yaml_path, "w", encoding="utf-8") as f:
|
||||
f.write(content)
|
||||
|
||||
print(f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)")
|
||||
print(
|
||||
f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)"
|
||||
)
|
||||
print(f"📄 Generated {services_yaml_path}")
|
||||
|
||||
|
||||
@@ -699,11 +754,19 @@ def cmd_list(args: list[str]) -> None:
|
||||
ssl_data = check_all_ssl_certs(domains_to_check)
|
||||
|
||||
if show_ssl:
|
||||
print(f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}")
|
||||
print(f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}")
|
||||
print(
|
||||
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
|
||||
)
|
||||
print(
|
||||
f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
|
||||
)
|
||||
else:
|
||||
print(f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}")
|
||||
print(f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}")
|
||||
print(
|
||||
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}"
|
||||
)
|
||||
print(
|
||||
f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}"
|
||||
)
|
||||
|
||||
for app in apps:
|
||||
app_path = Path(app.dir_path)
|
||||
@@ -713,7 +776,9 @@ def cmd_list(args: list[str]) -> None:
|
||||
dep_str = "⚠️ Manifest Error"
|
||||
prov_str = "⚠️ Invalid Manifest"
|
||||
else:
|
||||
manifest_obj = app.manifest_obj or Manifest(name=app.name, domain=app.domain)
|
||||
manifest_obj = app.manifest_obj or Manifest(
|
||||
name=app.name, domain=app.domain
|
||||
)
|
||||
two_axis = inspect_workload_two_axis(
|
||||
app_dir=app_path,
|
||||
manifest=manifest_obj,
|
||||
@@ -726,9 +791,13 @@ def cmd_list(args: list[str]) -> None:
|
||||
if show_ssl:
|
||||
cert_info = ssl_data.get(app.domain, check_ssl_cert(app.domain))
|
||||
cert_badge = cert_info.get("status", "-")
|
||||
print(f"{app.name:<16} {dep_str:<22} {prov_str:<22} {docker_status:<15} {app.domain:<28} {cert_badge}")
|
||||
print(
|
||||
f"{app.name:<16} {dep_str:<22} {prov_str:<22} {docker_status:<15} {app.domain:<28} {cert_badge}"
|
||||
)
|
||||
else:
|
||||
print(f"{app.name:<16} {dep_str:<22} {prov_str:<24} {docker_status:<15} {app.domain:<28}")
|
||||
print(
|
||||
f"{app.name:<16} {dep_str:<22} {prov_str:<24} {docker_status:<15} {app.domain:<28}"
|
||||
)
|
||||
|
||||
if show_core:
|
||||
core_path = Path(CORE_DIR)
|
||||
@@ -736,11 +805,19 @@ def cmd_list(args: list[str]) -> None:
|
||||
core_dep_str = core_checkout.status_label
|
||||
print()
|
||||
if show_ssl:
|
||||
print(f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}")
|
||||
print(f"{'------------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}")
|
||||
print(
|
||||
f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
|
||||
)
|
||||
print(
|
||||
f"{'------------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
|
||||
)
|
||||
else:
|
||||
print(f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}")
|
||||
print(f"{'------------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}")
|
||||
print(
|
||||
f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}"
|
||||
)
|
||||
print(
|
||||
f"{'------------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}"
|
||||
)
|
||||
|
||||
core_services = get_core_services()
|
||||
for i, svc in enumerate(core_services):
|
||||
@@ -749,9 +826,13 @@ def cmd_list(args: list[str]) -> None:
|
||||
if show_ssl:
|
||||
cert_info = ssl_data.get(svc.domain, check_ssl_cert(svc.domain))
|
||||
cert_badge = cert_info.get("status", "-")
|
||||
print(f"{svc.name:<16} {row_dep:<22} {'— Core Platform':<22} {svc_docker:<15} {svc.domain:<28} {cert_badge}")
|
||||
print(
|
||||
f"{svc.name:<16} {row_dep:<22} {'— Core Platform':<22} {svc_docker:<15} {svc.domain:<28} {cert_badge}"
|
||||
)
|
||||
else:
|
||||
print(f"{svc.name:<16} {row_dep:<22} {'— Core Platform':<24} {svc_docker:<15} {svc.domain:<28}")
|
||||
print(
|
||||
f"{svc.name:<16} {row_dep:<22} {'— Core Platform':<24} {svc_docker:<15} {svc.domain:<28}"
|
||||
)
|
||||
|
||||
|
||||
def cmd_info(args: list[str]) -> None:
|
||||
@@ -775,7 +856,9 @@ def cmd_info(args: list[str]) -> None:
|
||||
print(f"Directory: {app.dir_path}")
|
||||
print(f"Domain: {app.domain}")
|
||||
print(f"Container: {app.container}")
|
||||
print(f"Status: {get_docker_status(Path(app.dir_path), app.container)}")
|
||||
print(
|
||||
f"Status: {get_docker_status(Path(app.dir_path), app.container)}"
|
||||
)
|
||||
print(f"Description: {app.description}")
|
||||
return
|
||||
|
||||
@@ -791,7 +874,9 @@ def cmd_info(args: list[str]) -> None:
|
||||
print(f"Description: {app.description}")
|
||||
if app.aliases:
|
||||
print(f"Aliases: {', '.join(app.aliases)}")
|
||||
print(f"Class: {'Class A (Source-Backed)' if app.source else 'Class B (Image-Only)'}")
|
||||
print(
|
||||
f"Class: {'Class A (Source-Backed)' if app.source else 'Class B (Image-Only)'}"
|
||||
)
|
||||
print(f"Networks: {', '.join(app.networks)}")
|
||||
print(f"Auth Protected: {app.auth}")
|
||||
print(f"Dashboard: {'Visible' if app.visible else 'Hidden'}")
|
||||
@@ -816,7 +901,9 @@ def cmd_info(args: list[str]) -> None:
|
||||
if two_axis.checkout.is_git:
|
||||
print(f" Branch: {two_axis.checkout.branch}")
|
||||
print(f" Commit SHA: {two_axis.checkout.commit_sha}")
|
||||
print(f" Checkout: {'* Dirty (Uncommitted changes)' if two_axis.checkout.is_dirty else '✓ Clean'}")
|
||||
print(
|
||||
f" Checkout: {'* Dirty (Uncommitted changes)' if two_axis.checkout.is_dirty else '✓ Clean'}"
|
||||
)
|
||||
print(f" Docker Status: {two_axis.docker_status}")
|
||||
if two_axis.image_revision:
|
||||
print(f" Image Revision:{two_axis.image_revision}")
|
||||
@@ -847,7 +934,10 @@ def cmd_resolve(args: list[str]) -> None:
|
||||
if not app:
|
||||
sys.exit(1)
|
||||
if isinstance(app, SitesApp) and app.manifest_error:
|
||||
print(f"❌ Error: Workload '{app.name}' has invalid manifest: {app.manifest_error}", file=sys.stderr)
|
||||
print(
|
||||
f"❌ Error: Workload '{app.name}' has invalid manifest: {app.manifest_error}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
print(json.dumps(app.to_dict()))
|
||||
|
||||
@@ -874,7 +964,9 @@ def cmd_ssl(args: list[str]) -> None:
|
||||
print(f"Subject: {cert_info['subject']}")
|
||||
print(f"Expiration: {cert_info['not_after']}")
|
||||
if cert_info["days_remaining"] is not None:
|
||||
print(f"Days Remaining: {cert_info['days_remaining']} days ({cert_info['formatted_expiry']})")
|
||||
print(
|
||||
f"Days Remaining: {cert_info['days_remaining']} days ({cert_info['formatted_expiry']})"
|
||||
)
|
||||
if cert_info["error"]:
|
||||
print(f"Details/Error: {cert_info['error']}")
|
||||
print()
|
||||
@@ -896,7 +988,9 @@ def cmd_ssl(args: list[str]) -> None:
|
||||
|
||||
for name, domain in services_to_check:
|
||||
info = ssl_results.get(domain, check_ssl_cert(domain))
|
||||
print(f"{name:<20} {domain:<30} {info['status']:<24} {info['issuer']:<20} {info['formatted_expiry']}")
|
||||
print(
|
||||
f"{name:<20} {domain:<30} {info['status']:<24} {info['issuer']:<20} {info['formatted_expiry']}"
|
||||
)
|
||||
|
||||
|
||||
def cmd_complete(args: list[str]) -> None:
|
||||
|
||||
+90
-26
@@ -36,17 +36,18 @@ class ManifestValidationError(Exception):
|
||||
"""Raised when an application manifest violates schema or security constraints."""
|
||||
|
||||
|
||||
|
||||
class RefType(str, Enum):
|
||||
"""Semantic classification of an upstream git reference."""
|
||||
BRANCH = "branch" # Moving branch (e.g. main, master, develop, release/v1)
|
||||
TAG = "tag" # Pinned release tag (e.g. v1.0.0, 2.3.1)
|
||||
COMMIT = "commit" # Immutable commit SHA (40-character hex)
|
||||
|
||||
BRANCH = "branch" # Moving branch (e.g. main, master, develop, release/v1)
|
||||
TAG = "tag" # Pinned release tag (e.g. v1.0.0, 2.3.1)
|
||||
COMMIT = "commit" # Immutable commit SHA (40-character hex)
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
class TransportScheme(str, Enum):
|
||||
"""Supported secure git network transports."""
|
||||
|
||||
HTTPS = "https"
|
||||
SSH = "ssh"
|
||||
GIT_SCP = "git_scp"
|
||||
@@ -57,11 +58,20 @@ NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]*$")
|
||||
COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$")
|
||||
SHORT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,12}$")
|
||||
SEMVER_TAG_RE = re.compile(r"^v?[0-9]+(\.[0-9]+)+([a-zA-Z0-9._-]*)$")
|
||||
SCP_URL_RE = re.compile(r"^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:([0-9]+/)?([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+(\.git)?$")
|
||||
SCP_URL_RE = re.compile(
|
||||
r"^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:([0-9]+/)?([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+(\.git)?$"
|
||||
)
|
||||
ENV_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
|
||||
RESERVED_ENV_KEYS = {
|
||||
"PATH", "LD_PRELOAD", "IFS", "SHELL", "USER",
|
||||
"CORE_DIR", "SITES_DIR", "ENV_FILE", "HOMESERVER_ENV"
|
||||
"PATH",
|
||||
"LD_PRELOAD",
|
||||
"IFS",
|
||||
"SHELL",
|
||||
"USER",
|
||||
"CORE_DIR",
|
||||
"SITES_DIR",
|
||||
"ENV_FILE",
|
||||
"HOMESERVER_ENV",
|
||||
}
|
||||
|
||||
ALLOWED_STRATEGIES = {"compose"}
|
||||
@@ -80,35 +90,49 @@ def validate_transport(url: str) -> tuple[TransportScheme, str]:
|
||||
|
||||
# Reject path traversal / directory escapes
|
||||
if ".." in clean_url or "\\" in clean_url or clean_url.startswith(("/", "~")):
|
||||
raise ManifestValidationError(f"Prohibited filesystem path or traversal in source URL: '{clean_url}'")
|
||||
raise ManifestValidationError(
|
||||
f"Prohibited filesystem path or traversal in source URL: '{clean_url}'"
|
||||
)
|
||||
|
||||
# 1. HTTPS transport
|
||||
if clean_url.startswith("https://"):
|
||||
parsed = urlparse(clean_url)
|
||||
if not parsed.netloc:
|
||||
raise ManifestValidationError(f"Malformed HTTPS source URL (missing host): '{clean_url}'")
|
||||
raise ManifestValidationError(
|
||||
f"Malformed HTTPS source URL (missing host): '{clean_url}'"
|
||||
)
|
||||
if not parsed.path or parsed.path == "/":
|
||||
raise ManifestValidationError(f"Malformed HTTPS source URL (missing repository path): '{clean_url}'")
|
||||
raise ManifestValidationError(
|
||||
f"Malformed HTTPS source URL (missing repository path): '{clean_url}'"
|
||||
)
|
||||
return TransportScheme.HTTPS, clean_url
|
||||
|
||||
# 2. Standard SSH transport (ssh://[user@]host[:port]/path)
|
||||
if clean_url.startswith("ssh://"):
|
||||
parsed = urlparse(clean_url)
|
||||
if not parsed.netloc:
|
||||
raise ManifestValidationError(f"Malformed SSH source URL (missing host): '{clean_url}'")
|
||||
raise ManifestValidationError(
|
||||
f"Malformed SSH source URL (missing host): '{clean_url}'"
|
||||
)
|
||||
if not parsed.path or parsed.path == "/":
|
||||
raise ManifestValidationError(f"Malformed SSH source URL (missing repository path): '{clean_url}'")
|
||||
raise ManifestValidationError(
|
||||
f"Malformed SSH source URL (missing repository path): '{clean_url}'"
|
||||
)
|
||||
return TransportScheme.SSH, clean_url
|
||||
|
||||
# 3. SCP-style SSH transport (git@host:owner/repo.git)
|
||||
if clean_url.startswith("git@") or ("@" in clean_url and ":" in clean_url and not clean_url.startswith("http")):
|
||||
if clean_url.startswith("git@") or (
|
||||
"@" in clean_url and ":" in clean_url and not clean_url.startswith("http")
|
||||
):
|
||||
if SCP_URL_RE.match(clean_url):
|
||||
return TransportScheme.GIT_SCP, clean_url
|
||||
raise ManifestValidationError(f"Malformed SCP-style source URL: '{clean_url}'")
|
||||
|
||||
# Reject plaintext HTTP or unsupported schemes
|
||||
if clean_url.startswith("http://"):
|
||||
raise ManifestValidationError(f"Insecure HTTP source URL rejected (HTTPS or SSH required): '{clean_url}'")
|
||||
raise ManifestValidationError(
|
||||
f"Insecure HTTP source URL rejected (HTTPS or SSH required): '{clean_url}'"
|
||||
)
|
||||
|
||||
raise ManifestValidationError(
|
||||
f"Invalid source.url scheme: '{clean_url}'. "
|
||||
@@ -141,7 +165,16 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]:
|
||||
return RefType.TAG, ref
|
||||
|
||||
# Standard branch naming patterns
|
||||
if ref in {"main", "master", "develop", "dev", "trunk", "staging", "prod", "production"}:
|
||||
if ref in {
|
||||
"main",
|
||||
"master",
|
||||
"develop",
|
||||
"dev",
|
||||
"trunk",
|
||||
"staging",
|
||||
"prod",
|
||||
"production",
|
||||
}:
|
||||
return RefType.BRANCH, ref
|
||||
|
||||
if ref.startswith(("feat/", "fix/", "release/", "chore/", "refactor/")):
|
||||
@@ -153,6 +186,7 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]:
|
||||
|
||||
class SourceConfig(BaseModel):
|
||||
"""Upstream source provenance descriptor."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
url: str
|
||||
@@ -167,7 +201,9 @@ class SourceConfig(BaseModel):
|
||||
if isinstance(data, dict):
|
||||
src_type = str(data.get("type", "git")).strip().lower()
|
||||
if src_type != "git":
|
||||
raise ManifestValidationError(f"Unsupported source type '{src_type}'. Only 'git' is supported.")
|
||||
raise ManifestValidationError(
|
||||
f"Unsupported source type '{src_type}'. Only 'git' is supported."
|
||||
)
|
||||
data["type"] = src_type
|
||||
|
||||
raw_url = data.get("url")
|
||||
@@ -198,6 +234,7 @@ class SourceConfig(BaseModel):
|
||||
|
||||
class DeploymentConfig(BaseModel):
|
||||
"""Continuous deployment strategy and action policy."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
strategy: str = "compose"
|
||||
@@ -237,6 +274,7 @@ class DeploymentConfig(BaseModel):
|
||||
|
||||
class HomepageConfig(BaseModel):
|
||||
"""Dashboard card metadata for Homepage."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
title: str
|
||||
@@ -262,6 +300,7 @@ class Manifest(BaseModel):
|
||||
Authoritative Workload Manifest Model (Schema v1.0).
|
||||
Represents the full contract declared in a workload's app.yaml.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", populate_by_name=True)
|
||||
|
||||
name: str
|
||||
@@ -282,8 +321,14 @@ class Manifest(BaseModel):
|
||||
def prepare_manifest(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict):
|
||||
raw_name = data.get("name")
|
||||
if raw_name is None or not isinstance(raw_name, str) or not raw_name.strip():
|
||||
raise ManifestValidationError("Manifest is missing mandatory string field 'name'.")
|
||||
if (
|
||||
raw_name is None
|
||||
or not isinstance(raw_name, str)
|
||||
or not raw_name.strip()
|
||||
):
|
||||
raise ManifestValidationError(
|
||||
"Manifest is missing mandatory string field 'name'."
|
||||
)
|
||||
clean_name = raw_name.strip()
|
||||
if not NAME_RE.match(clean_name):
|
||||
raise ManifestValidationError(
|
||||
@@ -359,7 +404,12 @@ class Manifest(BaseModel):
|
||||
@property
|
||||
def is_internal(self) -> bool:
|
||||
"""True if the workload does not expose a public TLS endpoint."""
|
||||
return not self.domain or self.domain == "internal" or self.domain.endswith(".local") or ":" in self.domain
|
||||
return (
|
||||
not self.domain
|
||||
or self.domain == "internal"
|
||||
or self.domain.endswith(".local")
|
||||
or ":" in self.domain
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
data: dict[str, Any] = {
|
||||
@@ -401,23 +451,35 @@ def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest:
|
||||
try:
|
||||
content = raw_input.read_text(encoding="utf-8")
|
||||
except OSError as e:
|
||||
raise ManifestValidationError(f"Failed to read manifest {raw_input}: {e}") from e
|
||||
raise ManifestValidationError(
|
||||
f"Failed to read manifest {raw_input}: {e}"
|
||||
) from e
|
||||
try:
|
||||
data = (yaml.safe_load(content) if yaml else _parse_yaml_basic(content)) or {}
|
||||
data = (
|
||||
yaml.safe_load(content) if yaml else _parse_yaml_basic(content)
|
||||
) or {}
|
||||
except Exception as e:
|
||||
raise ManifestValidationError(f"YAML parsing error in {raw_input}: {e}") from e
|
||||
raise ManifestValidationError(
|
||||
f"YAML parsing error in {raw_input}: {e}"
|
||||
) from e
|
||||
elif isinstance(raw_input, str):
|
||||
try:
|
||||
data = (yaml.safe_load(raw_input) if yaml else _parse_yaml_basic(raw_input)) or {}
|
||||
data = (
|
||||
yaml.safe_load(raw_input) if yaml else _parse_yaml_basic(raw_input)
|
||||
) or {}
|
||||
except Exception as e:
|
||||
raise ManifestValidationError(f"YAML parsing error: {e}") from e
|
||||
elif isinstance(raw_input, dict):
|
||||
data = raw_input
|
||||
else:
|
||||
raise ManifestValidationError(f"Invalid input type for manifest parsing: {type(raw_input)}")
|
||||
raise ManifestValidationError(
|
||||
f"Invalid input type for manifest parsing: {type(raw_input)}"
|
||||
)
|
||||
|
||||
if not isinstance(data, dict):
|
||||
raise ManifestValidationError("Manifest root must be a YAML dictionary mapping.")
|
||||
raise ManifestValidationError(
|
||||
"Manifest root must be a YAML dictionary mapping."
|
||||
)
|
||||
|
||||
try:
|
||||
return Manifest.model_validate(data)
|
||||
@@ -433,7 +495,9 @@ def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest:
|
||||
msg = msg.removeprefix("Value error, ")
|
||||
loc = ".".join(str(p) for p in first_error.get("loc", []))
|
||||
if loc and first_error.get("type") == "extra_forbidden":
|
||||
raise ManifestValidationError(f"Manifest contains unrecognized or forbidden field '{loc}'.") from e
|
||||
raise ManifestValidationError(
|
||||
f"Manifest contains unrecognized or forbidden field '{loc}'."
|
||||
) from e
|
||||
raise ManifestValidationError(msg) from e
|
||||
|
||||
|
||||
|
||||
+390
-117
@@ -27,15 +27,23 @@ except ImportError:
|
||||
|
||||
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"))
|
||||
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")
|
||||
)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] [GitOps] %(message)s",
|
||||
handlers=[logging.StreamHandler(sys.stdout)]
|
||||
handlers=[logging.StreamHandler(sys.stdout)],
|
||||
)
|
||||
logger = logging.getLogger("gitops_dispatcher")
|
||||
|
||||
@@ -45,7 +53,9 @@ 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))
|
||||
path = secret_file or Path(
|
||||
os.environ.get("GITOPS_SECRET_FILE", DEFAULT_SECRET_PATH)
|
||||
)
|
||||
if path.is_file():
|
||||
try:
|
||||
return path.read_bytes().strip()
|
||||
@@ -68,7 +78,9 @@ def verify_signature(raw_body: bytes, signature: str | None, secret: bytes) -> b
|
||||
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.")
|
||||
logger.error(
|
||||
"Authentication failed: Webhook shared secret is empty or missing."
|
||||
)
|
||||
return False
|
||||
|
||||
if not signature or not isinstance(signature, str):
|
||||
@@ -79,7 +91,9 @@ def verify_signature(raw_body: bytes, signature: str | None, secret: bytes) -> b
|
||||
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):
|
||||
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
|
||||
|
||||
@@ -109,7 +123,9 @@ def parse_yaml_simple(text: str) -> dict:
|
||||
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):
|
||||
if not isinstance(
|
||||
data[current_section].get(current_subsection), list
|
||||
):
|
||||
data[current_section][current_subsection] = []
|
||||
data[current_section][current_subsection].append(item)
|
||||
else:
|
||||
@@ -161,16 +177,26 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
|
||||
"""
|
||||
mapping: dict[str, Path] = {}
|
||||
|
||||
registry_file = DEPLOYMENTS_FILE if DEPLOYMENTS_FILE.is_file() else (CONFIG_DIR / "deployments.yaml")
|
||||
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.")
|
||||
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 {}
|
||||
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):
|
||||
@@ -190,20 +216,31 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
|
||||
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}")
|
||||
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.")
|
||||
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.")
|
||||
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.
|
||||
@@ -218,14 +255,18 @@ def resolve_repository(repo_name: str) -> Path | None:
|
||||
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}'")
|
||||
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.")
|
||||
logger.warning(
|
||||
f"Repository '{cleaned_name}' is not in trusted repository registry."
|
||||
)
|
||||
return None
|
||||
|
||||
try:
|
||||
@@ -235,12 +276,18 @@ def resolve_repository(repo_name: str) -> Path | None:
|
||||
return None
|
||||
|
||||
if not canonical_target.is_dir():
|
||||
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
|
||||
|
||||
# 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}'.")
|
||||
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
|
||||
@@ -260,16 +307,17 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
|
||||
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 {}
|
||||
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"]
|
||||
}
|
||||
deployment_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
|
||||
|
||||
return target_dir, deployment_config
|
||||
|
||||
@@ -309,7 +357,10 @@ def validate_compose_security(
|
||||
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}"
|
||||
return (
|
||||
False,
|
||||
f"Compose file symlink escapes workload root: {compose_file} -> {resolved_compose}",
|
||||
)
|
||||
|
||||
try:
|
||||
content = compose_file.read_text(encoding="utf-8")
|
||||
@@ -324,50 +375,89 @@ def validate_compose_security(
|
||||
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):
|
||||
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 (
|
||||
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."
|
||||
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."
|
||||
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 (
|
||||
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."
|
||||
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()
|
||||
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()
|
||||
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'."
|
||||
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}."
|
||||
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}."
|
||||
return (
|
||||
False,
|
||||
f"Service '{svc_name}' specifies prohibited host device mount: {devices}.",
|
||||
)
|
||||
|
||||
sec_opts = svc.get("security_opt", [])
|
||||
if isinstance(sec_opts, str):
|
||||
@@ -375,7 +465,10 @@ def validate_compose_security(
|
||||
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}."
|
||||
return (
|
||||
False,
|
||||
f"Service '{svc_name}' specifies prohibited security_opt: {opt}.",
|
||||
)
|
||||
|
||||
raw_env_files = svc.get("env_file")
|
||||
if raw_env_files:
|
||||
@@ -402,13 +495,22 @@ def validate_compose_security(
|
||||
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}'."
|
||||
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}'."
|
||||
return (
|
||||
False,
|
||||
f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'.",
|
||||
)
|
||||
|
||||
volumes = svc.get("volumes", [])
|
||||
if isinstance(volumes, list):
|
||||
@@ -416,13 +518,19 @@ def validate_compose_security(
|
||||
host_path = ""
|
||||
if isinstance(vol, str):
|
||||
if "/var/run/docker.sock" in vol:
|
||||
return False, f"Service '{svc_name}' directly mounts Docker socket: {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}."
|
||||
return (
|
||||
False,
|
||||
f"Service '{svc_name}' directly mounts Docker socket: {src}.",
|
||||
)
|
||||
if vol.get("type") == "bind":
|
||||
host_path = src
|
||||
|
||||
@@ -430,12 +538,23 @@ def validate_compose_security(
|
||||
continue
|
||||
|
||||
# Declared top-level named volume without path separators
|
||||
if host_path in top_volumes and not (host_path.startswith((".", "/", "~")) or "/" in host_path or "\\" in host_path):
|
||||
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}'."
|
||||
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("~"):
|
||||
@@ -447,16 +566,20 @@ def validate_compose_security(
|
||||
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_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 (
|
||||
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.
|
||||
@@ -472,7 +595,10 @@ def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]:
|
||||
# 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)}"
|
||||
return (
|
||||
False,
|
||||
f"Unsupported deployment strategy '{strategy}'. Allowed strategies: {sorted(ALLOWED_STRATEGIES)}",
|
||||
)
|
||||
|
||||
# Validate actions if specified
|
||||
actions = deployment.get("actions")
|
||||
@@ -481,7 +607,10 @@ def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]:
|
||||
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 (
|
||||
False,
|
||||
f"Unsupported deployment action '{action}'. Allowed actions: {sorted(ALLOWED_ACTIONS)}",
|
||||
)
|
||||
|
||||
return True, ""
|
||||
|
||||
@@ -496,18 +625,26 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
||||
"""
|
||||
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}'")
|
||||
logger.info(
|
||||
f"Skipping deployment: pushed branch '{branch}' != target branch '{expected_branch}'"
|
||||
)
|
||||
return True
|
||||
|
||||
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 {}
|
||||
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})...")
|
||||
logger.info(
|
||||
f"🚀 Deploying '{target_dir.name}' at {target_dir} (branch: {expected_branch})..."
|
||||
)
|
||||
actions = deployment_config.get("actions", ["git_pull"])
|
||||
|
||||
try:
|
||||
@@ -517,8 +654,16 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
||||
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
|
||||
[
|
||||
"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.
|
||||
@@ -527,14 +672,28 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
||||
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}")
|
||||
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}")
|
||||
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"):
|
||||
@@ -559,49 +718,83 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
||||
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)
|
||||
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}")
|
||||
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(
|
||||
["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"],
|
||||
check=True
|
||||
[
|
||||
"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)
|
||||
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}")
|
||||
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
|
||||
logger.info(
|
||||
" ↳ [compose_build] Building & recreating containers..."
|
||||
)
|
||||
subprocess.run(
|
||||
["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"],
|
||||
check=True
|
||||
["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)
|
||||
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}")
|
||||
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
|
||||
check=True,
|
||||
)
|
||||
else:
|
||||
logger.error(f"❌ Unsupported or rejected deployment action '{action}'. Aborting deployment.")
|
||||
logger.error(
|
||||
f"❌ Unsupported or rejected deployment action '{action}'. Aborting deployment."
|
||||
)
|
||||
return False
|
||||
|
||||
idx += 1
|
||||
@@ -611,14 +804,20 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
||||
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:
|
||||
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
|
||||
payload: dict, event_type: str | None = None
|
||||
) -> tuple[bool, Path | None, dict, str, str]:
|
||||
"""
|
||||
Evaluate webhook deployment admission against strict policy gates:
|
||||
@@ -632,10 +831,22 @@ def admit_deployment(
|
||||
"""
|
||||
# 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."
|
||||
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."
|
||||
return (
|
||||
False,
|
||||
None,
|
||||
{},
|
||||
"",
|
||||
"Payload represents non-push event (pull_request/issue/release). Rejected.",
|
||||
)
|
||||
|
||||
# 2. Ref Admission
|
||||
ref = payload.get("ref", "")
|
||||
@@ -646,7 +857,13 @@ def admit_deployment(
|
||||
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."
|
||||
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:
|
||||
@@ -655,16 +872,34 @@ def admit_deployment(
|
||||
# 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."
|
||||
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."
|
||||
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."
|
||||
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"
|
||||
@@ -672,30 +907,55 @@ def admit_deployment(
|
||||
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 {}
|
||||
manifest = (
|
||||
yaml.safe_load(manifest_text)
|
||||
if yaml
|
||||
else parse_yaml_simple(manifest_text)
|
||||
) or {}
|
||||
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}",
|
||||
)
|
||||
|
||||
valid, err_msg = validate_manifest_deployment(manifest)
|
||||
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")
|
||||
if not isinstance(deployment_config, dict):
|
||||
deployment_config = {
|
||||
"branch": "main",
|
||||
"actions": ["git_pull", "compose_up"]
|
||||
}
|
||||
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 (
|
||||
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}'."
|
||||
return (
|
||||
True,
|
||||
target_dir,
|
||||
deployment_config,
|
||||
pushed_branch,
|
||||
f"Admitted for deployment on branch '{pushed_branch}'.",
|
||||
)
|
||||
|
||||
|
||||
def get_target_lock(target_name: str) -> Path:
|
||||
@@ -709,10 +969,7 @@ def get_pending_file(target_name: str) -> Path:
|
||||
|
||||
|
||||
def enqueue_deployment(
|
||||
target_dir: Path,
|
||||
deployment_config: dict,
|
||||
branch: str,
|
||||
commit_sha: str = ""
|
||||
target_dir: Path, deployment_config: dict, branch: str, commit_sha: str = ""
|
||||
) -> Path:
|
||||
"""
|
||||
Atomically enqueue a deployment request.
|
||||
@@ -732,7 +989,9 @@ def enqueue_deployment(
|
||||
|
||||
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).")
|
||||
logger.info(
|
||||
f"📥 Enqueued deployment for '{target_name}' (branch: {branch}, superseding previous pending)."
|
||||
)
|
||||
return pending_file
|
||||
|
||||
|
||||
@@ -749,7 +1008,9 @@ def run_target_worker(target_name: str) -> bool:
|
||||
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.")
|
||||
logger.info(
|
||||
f"Deployment worker for '{target_name}' is already active. Pending update will be picked up."
|
||||
)
|
||||
return True
|
||||
|
||||
overall_success = True
|
||||
@@ -783,9 +1044,13 @@ def run_target_worker(target_name: str) -> bool:
|
||||
"success": success,
|
||||
"timestamp": datetime.datetime.now(datetime.UTC).isoformat(),
|
||||
}
|
||||
status_file.write_text(json.dumps(status_data, indent=2), encoding="utf-8")
|
||||
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}")
|
||||
logger.warning(
|
||||
f"Failed to write deployment status file {status_file}: {e}"
|
||||
)
|
||||
|
||||
if not success:
|
||||
overall_success = False
|
||||
@@ -804,7 +1069,7 @@ def spawn_worker_async(target_name: str):
|
||||
cmd,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
start_new_session=True
|
||||
start_new_session=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -856,7 +1121,9 @@ def main():
|
||||
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}'")
|
||||
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.")
|
||||
@@ -887,21 +1154,27 @@ def main():
|
||||
logger.error(f"Invalid JSON payload: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
admitted, target_dir, deployment_config, branch, reason = admit_deployment(payload, event_type)
|
||||
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"
|
||||
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.")
|
||||
logger.info(
|
||||
f"🚀 Asynchronous deployment scheduled for '{target_dir.name}'. Returning HTTP 200."
|
||||
)
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
|
||||
+16
-10
@@ -19,6 +19,7 @@ from core_manifest import Manifest, RefType, SourceConfig
|
||||
|
||||
class ProvenanceStatus(str, Enum):
|
||||
"""Evaluation result of local state vs. upstream software provenance."""
|
||||
|
||||
SYNCED = "✓ Synced"
|
||||
UPDATE_AVAILABLE = "↓ Update Available"
|
||||
IMAGE_ONLY = "— Image-Only (Class B)"
|
||||
@@ -32,6 +33,7 @@ class ProvenanceStatus(str, Enum):
|
||||
@dataclass
|
||||
class CheckoutStatus:
|
||||
"""Axis 1: Local deployment checkout state."""
|
||||
|
||||
is_git: bool
|
||||
is_dirty: bool
|
||||
branch: str
|
||||
@@ -51,6 +53,7 @@ class CheckoutStatus:
|
||||
@dataclass
|
||||
class UpstreamProvenance:
|
||||
"""Axis 2: Upstream software provenance state."""
|
||||
|
||||
status: ProvenanceStatus
|
||||
remote_sha: str = ""
|
||||
target_ref: str = ""
|
||||
@@ -68,6 +71,7 @@ class UpstreamProvenance:
|
||||
@dataclass
|
||||
class TwoAxisStatus:
|
||||
"""Unified inspection combining local deployment and upstream provenance."""
|
||||
|
||||
app_name: str
|
||||
checkout: CheckoutStatus
|
||||
provenance: UpstreamProvenance
|
||||
@@ -198,12 +202,12 @@ def resolve_upstream_provenance(
|
||||
|
||||
# Commits pinned directly in manifest cannot be checked via ls-remote ref matching
|
||||
if source.ref_type == RefType.COMMIT:
|
||||
is_match = (
|
||||
local_commit and (
|
||||
source.ref.startswith(local_commit) or local_commit.startswith(source.ref)
|
||||
)
|
||||
is_match = local_commit and (
|
||||
source.ref.startswith(local_commit) or local_commit.startswith(source.ref)
|
||||
)
|
||||
status = (
|
||||
ProvenanceStatus.SYNCED if is_match else ProvenanceStatus.UPDATE_AVAILABLE
|
||||
)
|
||||
status = ProvenanceStatus.SYNCED if is_match else ProvenanceStatus.UPDATE_AVAILABLE
|
||||
return UpstreamProvenance(
|
||||
status=status,
|
||||
remote_sha=source.ref,
|
||||
@@ -248,10 +252,10 @@ def resolve_upstream_provenance(
|
||||
for line in proc.stdout.splitlines():
|
||||
parts = line.strip().split()
|
||||
if len(parts) >= 2 and (
|
||||
parts[1] == target_ref or
|
||||
parts[1] == f"refs/heads/{target_ref}" or
|
||||
parts[1] == f"refs/tags/{target_ref}" or
|
||||
parts[1] == f"refs/tags/{target_ref}^{{}}"
|
||||
parts[1] == target_ref
|
||||
or parts[1] == f"refs/heads/{target_ref}"
|
||||
or parts[1] == f"refs/tags/{target_ref}"
|
||||
or parts[1] == f"refs/tags/{target_ref}^{{}}"
|
||||
):
|
||||
remote_sha = parts[0]
|
||||
# Peaked tags (^{}) take precedence over lightweight tag refs
|
||||
@@ -271,7 +275,9 @@ def resolve_upstream_provenance(
|
||||
|
||||
# Compare local commit with remote SHA
|
||||
is_synced = False
|
||||
if local_commit and (remote_sha.startswith(local_commit) or local_commit.startswith(remote_sha[:7])):
|
||||
if local_commit and (
|
||||
remote_sha.startswith(local_commit) or local_commit.startswith(remote_sha[:7])
|
||||
):
|
||||
is_synced = True
|
||||
|
||||
status = ProvenanceStatus.SYNCED if is_synced else ProvenanceStatus.UPDATE_AVAILABLE
|
||||
|
||||
@@ -3,44 +3,41 @@ Security invariant tests for homelab GitOps execution and admission.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import gitops_dispatcher
|
||||
import pytest
|
||||
|
||||
# Add Core to path so scripts can be imported
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
|
||||
import gitops_dispatcher
|
||||
# Comment-out reason: testing pyproject-level pythonpath definition
|
||||
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
|
||||
|
||||
def test_custom_shell_action_is_rejected_without_execution(tmp_path: Path):
|
||||
"""Ensure that arbitrary 'custom' actions fail closed and never invoke a shell."""
|
||||
deployment_config = {
|
||||
"branch": "main",
|
||||
"actions": [
|
||||
{"custom": "touch /tmp/pwned"}
|
||||
]
|
||||
}
|
||||
deployment_config = {"branch": "main", "actions": [{"custom": "touch /tmp/pwned"}]}
|
||||
|
||||
with patch("subprocess.run") as mock_run:
|
||||
success = gitops_dispatcher.execute_deployment(tmp_path, deployment_config, branch="main")
|
||||
success = gitops_dispatcher.execute_deployment(
|
||||
tmp_path, deployment_config, branch="main"
|
||||
)
|
||||
|
||||
assert success is False, "execute_deployment must fail closed on 'custom' action"
|
||||
assert success is False, (
|
||||
"execute_deployment must fail closed on 'custom' action"
|
||||
)
|
||||
mock_run.assert_not_called()
|
||||
|
||||
|
||||
def test_unknown_action_is_rejected(tmp_path: Path):
|
||||
"""Ensure that unknown action strings fail closed and abort deployment."""
|
||||
deployment_config = {
|
||||
"branch": "main",
|
||||
"actions": ["malicious_or_unknown_action"]
|
||||
}
|
||||
deployment_config = {"branch": "main", "actions": ["malicious_or_unknown_action"]}
|
||||
|
||||
with patch("subprocess.run") as mock_run:
|
||||
success = gitops_dispatcher.execute_deployment(tmp_path, deployment_config, branch="main")
|
||||
success = gitops_dispatcher.execute_deployment(
|
||||
tmp_path, deployment_config, branch="main"
|
||||
)
|
||||
|
||||
assert success is False, "execute_deployment must reject unknown actions"
|
||||
mock_run.assert_not_called()
|
||||
@@ -48,14 +45,13 @@ def test_unknown_action_is_rejected(tmp_path: Path):
|
||||
|
||||
def test_allowed_actions_use_safe_argument_lists(tmp_path: Path):
|
||||
"""Ensure that allowed actions execute safely via argument lists without shell=True."""
|
||||
deployment_config = {
|
||||
"branch": "main",
|
||||
"actions": ["git_pull"]
|
||||
}
|
||||
deployment_config = {"branch": "main", "actions": ["git_pull"]}
|
||||
|
||||
with patch("subprocess.run") as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
success = gitops_dispatcher.execute_deployment(tmp_path, deployment_config, branch="main")
|
||||
success = gitops_dispatcher.execute_deployment(
|
||||
tmp_path, deployment_config, branch="main"
|
||||
)
|
||||
|
||||
assert success is True
|
||||
mock_run.assert_called_once()
|
||||
@@ -82,7 +78,9 @@ def test_resolve_repository_rejects_path_traversal(tmp_path: Path, monkeypatch):
|
||||
]
|
||||
|
||||
for payload in traversal_payloads:
|
||||
assert gitops_dispatcher.resolve_repository(payload) is None, f"Expected {payload} to be rejected"
|
||||
assert gitops_dispatcher.resolve_repository(payload) is None, (
|
||||
f"Expected {payload} to be rejected"
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_repository_rejects_unknown_repositories(tmp_path: Path, monkeypatch):
|
||||
@@ -120,14 +118,13 @@ def test_resolve_repository_resolves_valid_manifest(tmp_path: Path, monkeypatch)
|
||||
app_dir = sites_dir / "homelab-docs"
|
||||
app_dir.mkdir(parents=True)
|
||||
(app_dir / "app.yaml").write_text(
|
||||
"name: docs\naliases:\n - doc2site\n - notes\n",
|
||||
encoding="utf-8"
|
||||
"name: docs\naliases:\n - doc2site\n - notes\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
registry = tmp_path / "deployments.yaml"
|
||||
registry.write_text(
|
||||
f'schemaVersion: "1.0"\nrepositories:\n homelab-docs:\n path: "{app_dir}"\n aliases:\n - docs\n - doc2site\n - notes\n',
|
||||
encoding="utf-8"
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||
@@ -140,7 +137,6 @@ def test_resolve_repository_resolves_valid_manifest(tmp_path: Path, monkeypatch)
|
||||
assert gitops_dispatcher.resolve_repository("notes") == canonical
|
||||
|
||||
|
||||
|
||||
def test_resolve_repository_rejects_vault(tmp_path: Path, monkeypatch):
|
||||
"""Ensure data vault identities (Brain / second-brain) are not recognized by GitOps."""
|
||||
sites_dir = tmp_path / "Sites"
|
||||
@@ -189,7 +185,9 @@ repositories:
|
||||
assert "escaped-app" not in mapping
|
||||
|
||||
|
||||
def test_unregistered_sites_directory_rejected_when_registry_active(tmp_path: Path, monkeypatch):
|
||||
def test_unregistered_sites_directory_rejected_when_registry_active(
|
||||
tmp_path: Path, monkeypatch
|
||||
):
|
||||
"""Ensure unregistered directories in ~/Sites cannot be resolved when deployments.yaml is active."""
|
||||
sites_dir = tmp_path / "Sites"
|
||||
registered_dir = sites_dir / "homelab-docs"
|
||||
@@ -224,7 +222,9 @@ def test_missing_or_corrupt_registry_fails_closed(tmp_path: Path, monkeypatch):
|
||||
missing_registry = tmp_path / "nonexistent-deployments.yaml"
|
||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", missing_registry)
|
||||
monkeypatch.setattr(gitops_dispatcher, "CONFIG_DIR", tmp_path / "nonexistent-config")
|
||||
monkeypatch.setattr(
|
||||
gitops_dispatcher, "CONFIG_DIR", tmp_path / "nonexistent-config"
|
||||
)
|
||||
|
||||
# Missing registry must fail closed: empty mapping, no resolution
|
||||
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
|
||||
@@ -232,14 +232,15 @@ def test_missing_or_corrupt_registry_fails_closed(tmp_path: Path, monkeypatch):
|
||||
|
||||
# Corrupt YAML registry must also fail closed
|
||||
corrupt_registry = tmp_path / "corrupt-deployments.yaml"
|
||||
corrupt_registry.write_text("schemaVersion: 1.0\nrepositories: [bad list syntax", encoding="utf-8")
|
||||
corrupt_registry.write_text(
|
||||
"schemaVersion: 1.0\nrepositories: [bad list syntax", encoding="utf-8"
|
||||
)
|
||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", corrupt_registry)
|
||||
|
||||
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
|
||||
assert gitops_dispatcher.resolve_repository("valid") is None
|
||||
|
||||
|
||||
|
||||
def test_webhook_verification_valid_signature():
|
||||
"""Ensure valid HMAC-SHA256 signature passes verification."""
|
||||
import hashlib
|
||||
@@ -251,7 +252,10 @@ def test_webhook_verification_valid_signature():
|
||||
|
||||
assert gitops_dispatcher.verify_signature(body, expected_hex, secret) is True
|
||||
# Support sha256= prefix as well
|
||||
assert gitops_dispatcher.verify_signature(body, f"sha256={expected_hex}", secret) is True
|
||||
assert (
|
||||
gitops_dispatcher.verify_signature(body, f"sha256={expected_hex}", secret)
|
||||
is True
|
||||
)
|
||||
|
||||
|
||||
def test_webhook_verification_invalid_signature():
|
||||
@@ -316,7 +320,10 @@ def test_webhook_verification_malformed_signature():
|
||||
secret = b"supersecrettoken123"
|
||||
body = b'{"repository": {"name": "docs"}}'
|
||||
|
||||
assert gitops_dispatcher.verify_signature(body, "not-a-valid-hex-digest", secret) is False
|
||||
assert (
|
||||
gitops_dispatcher.verify_signature(body, "not-a-valid-hex-digest", secret)
|
||||
is False
|
||||
)
|
||||
assert gitops_dispatcher.verify_signature(body, "deadbeef", secret) is False
|
||||
assert gitops_dispatcher.verify_signature(body, "z" * 64, secret) is False
|
||||
|
||||
@@ -326,36 +333,35 @@ def test_admission_rejects_non_push_events(tmp_path: Path):
|
||||
payload_pr = {
|
||||
"ref": "refs/heads/main",
|
||||
"repository": {"name": "docs"},
|
||||
"pull_request": {"id": 1}
|
||||
"pull_request": {"id": 1},
|
||||
}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload_pr, event_type="push")
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||
payload_pr, event_type="push"
|
||||
)
|
||||
assert admitted is False
|
||||
assert "non-push event" in reason
|
||||
|
||||
payload_normal = {
|
||||
"ref": "refs/heads/main",
|
||||
"repository": {"name": "docs"}
|
||||
}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload_normal, event_type="pull_request")
|
||||
payload_normal = {"ref": "refs/heads/main", "repository": {"name": "docs"}}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||
payload_normal, event_type="pull_request"
|
||||
)
|
||||
assert admitted is False
|
||||
assert "Only 'push' is allowed" in reason
|
||||
|
||||
|
||||
def test_admission_rejects_tags_and_invalid_refs():
|
||||
"""Ensure tags or invalid ref structures are rejected from deployment."""
|
||||
tag_payload = {
|
||||
"ref": "refs/tags/v1.0.0",
|
||||
"repository": {"name": "docs"}
|
||||
}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(tag_payload, event_type="push")
|
||||
tag_payload = {"ref": "refs/tags/v1.0.0", "repository": {"name": "docs"}}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||
tag_payload, event_type="push"
|
||||
)
|
||||
assert admitted is False
|
||||
assert "Tag push" in reason
|
||||
|
||||
non_head_payload = {
|
||||
"ref": "refs/pull/42/head",
|
||||
"repository": {"name": "docs"}
|
||||
}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(non_head_payload, event_type="push")
|
||||
non_head_payload = {"ref": "refs/pull/42/head", "repository": {"name": "docs"}}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||
non_head_payload, event_type="push"
|
||||
)
|
||||
assert admitted is False
|
||||
assert "not a head branch" in reason
|
||||
|
||||
@@ -366,11 +372,10 @@ def test_admission_rejects_unknown_repository(tmp_path: Path, monkeypatch):
|
||||
sites_dir.mkdir()
|
||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||
|
||||
payload = {
|
||||
"ref": "refs/heads/main",
|
||||
"repository": {"name": "unregistered-app"}
|
||||
}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
||||
payload = {"ref": "refs/heads/main", "repository": {"name": "unregistered-app"}}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||
payload, event_type="push"
|
||||
)
|
||||
assert admitted is False
|
||||
assert "not recognized" in reason
|
||||
|
||||
@@ -381,8 +386,7 @@ def test_admission_rejects_branch_mismatch(tmp_path: Path, monkeypatch):
|
||||
app_dir = sites_dir / "homelab-docs"
|
||||
app_dir.mkdir(parents=True)
|
||||
(app_dir / "app.yaml").write_text(
|
||||
"name: docs\ndeployment:\n branch: production\n",
|
||||
encoding="utf-8"
|
||||
"name: docs\ndeployment:\n branch: production\n", encoding="utf-8"
|
||||
)
|
||||
registry = tmp_path / "deployments.yaml"
|
||||
registry.write_text(
|
||||
@@ -392,11 +396,10 @@ def test_admission_rejects_branch_mismatch(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||
|
||||
payload = {
|
||||
"ref": "refs/heads/staging",
|
||||
"repository": {"name": "docs"}
|
||||
}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
||||
payload = {"ref": "refs/heads/staging", "repository": {"name": "docs"}}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||
payload, event_type="push"
|
||||
)
|
||||
assert admitted is False
|
||||
assert "Branch mismatch" in reason
|
||||
|
||||
@@ -408,7 +411,7 @@ def test_admission_rejects_unsupported_strategy(tmp_path: Path, monkeypatch):
|
||||
app_dir.mkdir(parents=True)
|
||||
(app_dir / "app.yaml").write_text(
|
||||
"name: docs\ndeployment:\n branch: main\n strategy: kubernetes\n",
|
||||
encoding="utf-8"
|
||||
encoding="utf-8",
|
||||
)
|
||||
registry = tmp_path / "deployments.yaml"
|
||||
registry.write_text(
|
||||
@@ -418,11 +421,10 @@ def test_admission_rejects_unsupported_strategy(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||
|
||||
payload = {
|
||||
"ref": "refs/heads/main",
|
||||
"repository": {"name": "docs"}
|
||||
}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
||||
payload = {"ref": "refs/heads/main", "repository": {"name": "docs"}}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||
payload, event_type="push"
|
||||
)
|
||||
assert admitted is False
|
||||
assert "Unsupported deployment strategy" in reason
|
||||
|
||||
@@ -434,7 +436,7 @@ def test_admission_rejects_unsupported_actions(tmp_path: Path, monkeypatch):
|
||||
app_dir.mkdir(parents=True)
|
||||
(app_dir / "app.yaml").write_text(
|
||||
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n",
|
||||
encoding="utf-8"
|
||||
encoding="utf-8",
|
||||
)
|
||||
registry = tmp_path / "deployments.yaml"
|
||||
registry.write_text(
|
||||
@@ -444,11 +446,10 @@ def test_admission_rejects_unsupported_actions(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||
|
||||
payload = {
|
||||
"ref": "refs/heads/main",
|
||||
"repository": {"name": "docs"}
|
||||
}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
||||
payload = {"ref": "refs/heads/main", "repository": {"name": "docs"}}
|
||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||
payload, event_type="push"
|
||||
)
|
||||
assert admitted is False
|
||||
assert "Unsupported deployment action" in reason
|
||||
|
||||
@@ -460,7 +461,7 @@ def test_admission_admits_valid_push(tmp_path: Path, monkeypatch):
|
||||
app_dir.mkdir(parents=True)
|
||||
(app_dir / "app.yaml").write_text(
|
||||
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n",
|
||||
encoding="utf-8"
|
||||
encoding="utf-8",
|
||||
)
|
||||
registry = tmp_path / "deployments.yaml"
|
||||
registry.write_text(
|
||||
@@ -470,11 +471,10 @@ def test_admission_admits_valid_push(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||
|
||||
payload = {
|
||||
"ref": "refs/heads/main",
|
||||
"repository": {"name": "docs"}
|
||||
}
|
||||
admitted, target_dir, config, branch, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
||||
payload = {"ref": "refs/heads/main", "repository": {"name": "docs"}}
|
||||
admitted, target_dir, config, branch, reason = gitops_dispatcher.admit_deployment(
|
||||
payload, event_type="push"
|
||||
)
|
||||
assert admitted is True
|
||||
|
||||
assert "Admitted" in reason
|
||||
@@ -492,16 +492,22 @@ def test_enqueue_supersedes_pending_revision(tmp_path: Path, monkeypatch):
|
||||
target_dir.mkdir()
|
||||
|
||||
# Enqueue revision A
|
||||
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "A"}, "main")
|
||||
gitops_dispatcher.enqueue_deployment(
|
||||
target_dir, {"branch": "main", "rev": "A"}, "main"
|
||||
)
|
||||
pending_file = gitops_dispatcher.get_pending_file("app")
|
||||
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "A"
|
||||
|
||||
# Enqueue revision B (supersedes A)
|
||||
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "B"}, "main")
|
||||
gitops_dispatcher.enqueue_deployment(
|
||||
target_dir, {"branch": "main", "rev": "B"}, "main"
|
||||
)
|
||||
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "B"
|
||||
|
||||
# Enqueue revision C (supersedes B)
|
||||
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "C"}, "main")
|
||||
gitops_dispatcher.enqueue_deployment(
|
||||
target_dir, {"branch": "main", "rev": "C"}, "main"
|
||||
)
|
||||
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "C"
|
||||
|
||||
|
||||
@@ -538,20 +544,28 @@ def test_serialized_worker_race_superseding(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(gitops_dispatcher, "execute_deployment", mock_execute)
|
||||
|
||||
# 1. Enqueue A
|
||||
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "A"}, "main")
|
||||
gitops_dispatcher.enqueue_deployment(
|
||||
target_dir, {"branch": "main", "rev": "A"}, "main"
|
||||
)
|
||||
|
||||
# Start worker in thread (takes A)
|
||||
worker_thread = threading.Thread(target=gitops_dispatcher.run_target_worker, args=("app",))
|
||||
worker_thread = threading.Thread(
|
||||
target=gitops_dispatcher.run_target_worker, args=("app",)
|
||||
)
|
||||
worker_thread.start()
|
||||
|
||||
# Wait for A to start executing
|
||||
assert a_started_event.wait(timeout=2.0) is True
|
||||
|
||||
# 2. B arrives while A is running
|
||||
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "B"}, "main")
|
||||
gitops_dispatcher.enqueue_deployment(
|
||||
target_dir, {"branch": "main", "rev": "B"}, "main"
|
||||
)
|
||||
|
||||
# 3. C arrives while A is running (supersedes B)
|
||||
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "C"}, "main")
|
||||
gitops_dispatcher.enqueue_deployment(
|
||||
target_dir, {"branch": "main", "rev": "C"}, "main"
|
||||
)
|
||||
|
||||
# Let A complete
|
||||
b_and_c_enqueued_event.set()
|
||||
@@ -559,7 +573,9 @@ def test_serialized_worker_race_superseding(tmp_path: Path, monkeypatch):
|
||||
worker_thread.join(timeout=3.0)
|
||||
|
||||
# Verification: A was executed, B was superseded/skipped, C was executed!
|
||||
assert executed_revisions == ["A", "C"], f"Expected ['A', 'C'] but got {executed_revisions}"
|
||||
assert executed_revisions == ["A", "C"], (
|
||||
f"Expected ['A', 'C'] but got {executed_revisions}"
|
||||
)
|
||||
|
||||
|
||||
def test_post_pull_manifest_validation_rejects_unsupported_action(tmp_path: Path):
|
||||
@@ -570,24 +586,31 @@ def test_post_pull_manifest_validation_rejects_unsupported_action(tmp_path: Path
|
||||
app_dir = tmp_path / "app"
|
||||
app_dir.mkdir()
|
||||
manifest_file = app_dir / "app.yaml"
|
||||
manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n")
|
||||
(app_dir / "docker-compose.yml").write_text("version: '3'\nservices:\n web:\n image: nginx\n")
|
||||
manifest_file.write_text(
|
||||
"name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n"
|
||||
)
|
||||
(app_dir / "docker-compose.yml").write_text(
|
||||
"version: '3'\nservices:\n web:\n image: nginx\n"
|
||||
)
|
||||
|
||||
initial_config = {
|
||||
"branch": "main",
|
||||
"actions": ["git_pull", "compose_up"]
|
||||
}
|
||||
initial_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
|
||||
|
||||
def mock_pull(cmd, check=True):
|
||||
if "pull" in cmd:
|
||||
# Simulate git pull bringing in an invalid action in app.yaml
|
||||
manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n")
|
||||
manifest_file.write_text(
|
||||
"name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n"
|
||||
)
|
||||
return MagicMock(returncode=0)
|
||||
|
||||
with patch("subprocess.run", side_effect=mock_pull) as mock_run:
|
||||
success = gitops_dispatcher.execute_deployment(app_dir, initial_config, branch="main")
|
||||
success = gitops_dispatcher.execute_deployment(
|
||||
app_dir, initial_config, branch="main"
|
||||
)
|
||||
|
||||
assert success is False, "Deployment must fail closed when pulled revision has invalid actions"
|
||||
assert success is False, (
|
||||
"Deployment must fail closed when pulled revision has invalid actions"
|
||||
)
|
||||
# Only git pull was called; compose_up was never reached!
|
||||
calls = [c[0][0] for c in mock_run.call_args_list]
|
||||
assert len(calls) == 1
|
||||
@@ -602,24 +625,31 @@ def test_post_pull_manifest_validation_rejects_branch_policy_mismatch(tmp_path:
|
||||
app_dir = tmp_path / "app"
|
||||
app_dir.mkdir()
|
||||
manifest_file = app_dir / "app.yaml"
|
||||
manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n")
|
||||
(app_dir / "docker-compose.yml").write_text("version: '3'\nservices:\n web:\n image: nginx\n")
|
||||
manifest_file.write_text(
|
||||
"name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n"
|
||||
)
|
||||
(app_dir / "docker-compose.yml").write_text(
|
||||
"version: '3'\nservices:\n web:\n image: nginx\n"
|
||||
)
|
||||
|
||||
initial_config = {
|
||||
"branch": "main",
|
||||
"actions": ["git_pull", "compose_up"]
|
||||
}
|
||||
initial_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
|
||||
|
||||
def mock_pull(cmd, check=True):
|
||||
if "pull" in cmd:
|
||||
# Simulate git pull bringing in an app.yaml that targets 'staging', not 'main'
|
||||
manifest_file.write_text("name: app\ndeployment:\n branch: staging\n actions:\n - git_pull\n - compose_up\n")
|
||||
manifest_file.write_text(
|
||||
"name: app\ndeployment:\n branch: staging\n actions:\n - git_pull\n - compose_up\n"
|
||||
)
|
||||
return MagicMock(returncode=0)
|
||||
|
||||
with patch("subprocess.run", side_effect=mock_pull) as mock_run:
|
||||
success = gitops_dispatcher.execute_deployment(app_dir, initial_config, branch="main")
|
||||
success = gitops_dispatcher.execute_deployment(
|
||||
app_dir, initial_config, branch="main"
|
||||
)
|
||||
|
||||
assert success is False, "Deployment must fail closed on post-pull branch mismatch"
|
||||
assert success is False, (
|
||||
"Deployment must fail closed on post-pull branch mismatch"
|
||||
)
|
||||
calls = [c[0][0] for c in mock_run.call_args_list]
|
||||
assert len(calls) == 1
|
||||
assert "pull" in calls[0]
|
||||
@@ -633,22 +663,27 @@ def test_post_pull_manifest_adopts_updated_actions(tmp_path: Path):
|
||||
app_dir = tmp_path / "app"
|
||||
app_dir.mkdir()
|
||||
manifest_file = app_dir / "app.yaml"
|
||||
manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n")
|
||||
(app_dir / "docker-compose.yml").write_text("version: '3'\nservices:\n web:\n image: nginx\n")
|
||||
manifest_file.write_text(
|
||||
"name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n"
|
||||
)
|
||||
(app_dir / "docker-compose.yml").write_text(
|
||||
"version: '3'\nservices:\n web:\n image: nginx\n"
|
||||
)
|
||||
|
||||
initial_config = {
|
||||
"branch": "main",
|
||||
"actions": ["git_pull", "compose_up"]
|
||||
}
|
||||
initial_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
|
||||
|
||||
def mock_pull(cmd, check=True):
|
||||
if "pull" in cmd:
|
||||
# Revision updates action to compose_build
|
||||
manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_build\n")
|
||||
manifest_file.write_text(
|
||||
"name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_build\n"
|
||||
)
|
||||
return MagicMock(returncode=0)
|
||||
|
||||
with patch("subprocess.run", side_effect=mock_pull) as mock_run:
|
||||
success = gitops_dispatcher.execute_deployment(app_dir, initial_config, branch="main")
|
||||
success = gitops_dispatcher.execute_deployment(
|
||||
app_dir, initial_config, branch="main"
|
||||
)
|
||||
|
||||
assert success is True
|
||||
calls = [c[0][0] for c in mock_run.call_args_list]
|
||||
@@ -668,10 +703,7 @@ def test_worker_records_status_file(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(gitops_dispatcher, "execute_deployment", lambda t, c, b: True)
|
||||
|
||||
gitops_dispatcher.enqueue_deployment(
|
||||
target_dir,
|
||||
{"branch": "main"},
|
||||
"main",
|
||||
commit_sha="abcdef123456"
|
||||
target_dir, {"branch": "main"}, "main", commit_sha="abcdef123456"
|
||||
)
|
||||
|
||||
success = gitops_dispatcher.run_target_worker("app")
|
||||
@@ -690,12 +722,15 @@ def test_worker_records_status_file(tmp_path: Path, monkeypatch):
|
||||
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("""
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine:latest
|
||||
privileged: true
|
||||
""", encoding="utf-8")
|
||||
""",
|
||||
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
|
||||
@@ -705,19 +740,23 @@ 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("""
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine:latest
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
""", encoding="utf-8")
|
||||
""",
|
||||
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("""
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine:latest
|
||||
@@ -725,7 +764,9 @@ services:
|
||||
- type: bind
|
||||
source: /var/run/docker.sock
|
||||
target: /var/run/docker.sock
|
||||
""", encoding="utf-8")
|
||||
""",
|
||||
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
|
||||
@@ -734,12 +775,15 @@ services:
|
||||
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("""
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine:latest
|
||||
network_mode: host
|
||||
""", encoding="utf-8")
|
||||
""",
|
||||
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
|
||||
@@ -748,13 +792,16 @@ services:
|
||||
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("""
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine:latest
|
||||
volumes:
|
||||
- /etc/shadow:/etc/shadow:ro
|
||||
""", encoding="utf-8")
|
||||
""",
|
||||
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
|
||||
@@ -765,7 +812,8 @@ def test_validate_compose_security_allows_safe_compose(tmp_path: Path):
|
||||
data_dir = tmp_path / "data"
|
||||
data_dir.mkdir()
|
||||
compose_file = tmp_path / "docker-compose.yml"
|
||||
compose_file.write_text(f"""
|
||||
compose_file.write_text(
|
||||
f"""
|
||||
services:
|
||||
app:
|
||||
image: alpine:latest
|
||||
@@ -774,7 +822,9 @@ services:
|
||||
- named_vol:/var/log
|
||||
volumes:
|
||||
named_vol:
|
||||
""", encoding="utf-8")
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
||||
assert valid is True
|
||||
assert err is None
|
||||
@@ -788,11 +838,14 @@ def test_validate_compose_security_nonexistent_file(tmp_path: Path):
|
||||
assert err is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("malicious_volume", [
|
||||
"../../etc/passwd:/mnt/passwd:ro",
|
||||
"./../../Core/nixos/secrets.yaml:/secrets.yaml",
|
||||
"../other-workload/data:/data",
|
||||
])
|
||||
@pytest.mark.parametrize(
|
||||
"malicious_volume",
|
||||
[
|
||||
"../../etc/passwd:/mnt/passwd:ro",
|
||||
"./../../Core/nixos/secrets.yaml:/secrets.yaml",
|
||||
"../other-workload/data:/data",
|
||||
],
|
||||
)
|
||||
def test_validate_compose_security_blocks_relative_traversal(
|
||||
tmp_path: Path, malicious_volume: str
|
||||
):
|
||||
@@ -806,8 +859,12 @@ def test_validate_compose_security_blocks_relative_traversal(
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
|
||||
assert valid is False, f"Expected relative traversal '{malicious_volume}' to be rejected!"
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, app_dir, app_name="my-app"
|
||||
)
|
||||
assert valid is False, (
|
||||
f"Expected relative traversal '{malicious_volume}' to be rejected!"
|
||||
)
|
||||
assert err is not None and "prohibited host bind mount" in err
|
||||
|
||||
|
||||
@@ -831,27 +888,38 @@ def test_validate_compose_security_blocks_cross_tenant_state_mounts(
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, app_dir, app_name="my-app"
|
||||
)
|
||||
assert valid is False, "Expected cross-tenant state mount to be rejected!"
|
||||
assert err is not None and ("prohibited host bind mount" in err or "cross-tenant" in err.lower())
|
||||
assert err is not None and (
|
||||
"prohibited host bind mount" in err or "cross-tenant" in err.lower()
|
||||
)
|
||||
|
||||
# Authorized own state mount must pass
|
||||
compose_file.write_text(
|
||||
f"services:\n web:\n image: nginx\n volumes:\n - '{state_root}/my-app:/data'\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
valid_own, err_own = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
|
||||
assert valid_own is True, f"Own state mount should be permitted, got error: {err_own}"
|
||||
valid_own, err_own = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, app_dir, app_name="my-app"
|
||||
)
|
||||
assert valid_own is True, (
|
||||
f"Own state mount should be permitted, got error: {err_own}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("unsafe_directive", [
|
||||
"cap_add:\n - SYS_ADMIN",
|
||||
"pid: host",
|
||||
"ipc: host",
|
||||
"userns_mode: host",
|
||||
"devices:\n - /dev/sda:/dev/sda",
|
||||
"security_opt:\n - apparmor:unconfined",
|
||||
])
|
||||
@pytest.mark.parametrize(
|
||||
"unsafe_directive",
|
||||
[
|
||||
"cap_add:\n - SYS_ADMIN",
|
||||
"pid: host",
|
||||
"ipc: host",
|
||||
"userns_mode: host",
|
||||
"devices:\n - /dev/sda:/dev/sda",
|
||||
"security_opt:\n - apparmor:unconfined",
|
||||
],
|
||||
)
|
||||
def test_validate_compose_security_blocks_privilege_escalation_primitives(
|
||||
tmp_path: Path, unsafe_directive: str
|
||||
):
|
||||
@@ -861,7 +929,9 @@ def test_validate_compose_security_blocks_privilege_escalation_primitives(
|
||||
f"services:\n app:\n image: alpine\n {unsafe_directive}\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="app")
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, tmp_path, app_name="app"
|
||||
)
|
||||
assert valid is False, f"Directive should be blocked:\n{unsafe_directive}"
|
||||
assert err is not None
|
||||
|
||||
@@ -869,14 +939,19 @@ def test_validate_compose_security_blocks_privilege_escalation_primitives(
|
||||
def test_validate_compose_security_rejects_top_level_include(tmp_path: Path):
|
||||
"""Ensure top-level Compose include directives are rejected to prevent out-of-tree includes."""
|
||||
compose_file = tmp_path / "docker-compose.yml"
|
||||
compose_file.write_text("""
|
||||
compose_file.write_text(
|
||||
"""
|
||||
include:
|
||||
- /etc/shadow
|
||||
services:
|
||||
app:
|
||||
image: alpine
|
||||
""", encoding="utf-8")
|
||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="app")
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, tmp_path, app_name="app"
|
||||
)
|
||||
assert valid is False
|
||||
assert err is not None and "include" in err.lower()
|
||||
|
||||
@@ -891,7 +966,9 @@ def test_validate_compose_security_rejects_symlink_escape(tmp_path: Path):
|
||||
compose_link = app_dir / "docker-compose.yml"
|
||||
compose_link.symlink_to(outside_file)
|
||||
|
||||
valid, err = gitops_dispatcher.validate_compose_security(compose_link, app_dir, app_name="my-app")
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_link, app_dir, app_name="my-app"
|
||||
)
|
||||
assert valid is False
|
||||
assert err is not None and "symlink" in err.lower()
|
||||
|
||||
@@ -904,37 +981,52 @@ def test_validate_compose_security_rejects_escaping_env_file(tmp_path: Path):
|
||||
|
||||
# 1. Escaping absolute path
|
||||
compose_file = app_dir / "docker-compose.yml"
|
||||
compose_file.write_text("""
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine
|
||||
env_file: /run/secrets/homeserver.env
|
||||
""", encoding="utf-8")
|
||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, app_dir, app_name="my-app"
|
||||
)
|
||||
assert valid is False
|
||||
assert err is not None and "env_file" in err.lower()
|
||||
|
||||
# 2. Escaping relative path in list
|
||||
compose_file.write_text("""
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine
|
||||
env_file:
|
||||
- valid.env
|
||||
- ../../Core/.env
|
||||
""", encoding="utf-8")
|
||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, app_dir, app_name="my-app"
|
||||
)
|
||||
assert valid is False
|
||||
assert err is not None and "env_file" in err.lower()
|
||||
|
||||
# 3. Valid local env_file
|
||||
compose_file.write_text("""
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine
|
||||
env_file: valid.env
|
||||
""", encoding="utf-8")
|
||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, app_dir, app_name="my-app"
|
||||
)
|
||||
assert valid is True
|
||||
assert err is None
|
||||
|
||||
@@ -942,14 +1034,19 @@ services:
|
||||
def test_validate_compose_security_rejects_undeclared_named_volumes(tmp_path: Path):
|
||||
"""Ensure ambiguous volume paths not declared in top-level volumes are rejected."""
|
||||
compose_file = tmp_path / "docker-compose.yml"
|
||||
compose_file.write_text("""
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine
|
||||
volumes:
|
||||
- rogue_named_volume:/data
|
||||
""", encoding="utf-8")
|
||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="my-app")
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, tmp_path, app_name="my-app"
|
||||
)
|
||||
assert valid is False
|
||||
assert err is not None and "undeclared" in err.lower()
|
||||
|
||||
@@ -957,20 +1054,17 @@ services:
|
||||
def test_validate_compose_security_handles_string_security_opt(tmp_path: Path):
|
||||
"""Ensure security_opt specified as string instead of list is strictly checked."""
|
||||
compose_file = tmp_path / "docker-compose.yml"
|
||||
compose_file.write_text("""
|
||||
compose_file.write_text(
|
||||
"""
|
||||
services:
|
||||
app:
|
||||
image: alpine
|
||||
security_opt: "apparmor:unconfined"
|
||||
""", encoding="utf-8")
|
||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="my-app")
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
valid, err = gitops_dispatcher.validate_compose_security(
|
||||
compose_file, tmp_path, app_name="my-app"
|
||||
)
|
||||
assert valid is False
|
||||
assert err is not None and "security_opt" in err.lower()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -10,11 +10,11 @@ from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
# Comment-out reason: testing pyproject-level pythonpath definition
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
|
||||
|
||||
def test_socket_proxy_is_strictly_read_only():
|
||||
|
||||
"""Ensure socket-proxy container blocks state-modifying requests (POST=0, DELETE=0)."""
|
||||
compose_path = CORE_ROOT / "docker-compose.yml"
|
||||
with open(compose_path, encoding="utf-8") as f:
|
||||
@@ -47,8 +47,12 @@ def test_no_direct_docker_sock_mounts_except_socket_proxy():
|
||||
volumes = svc.get("volumes", [])
|
||||
for vol in volumes:
|
||||
if isinstance(vol, str) and "/var/run/docker.sock" in vol:
|
||||
assert name == "socket-proxy", f"Service '{name}' directly mounts docker.sock!"
|
||||
assert vol.endswith(":ro"), "socket-proxy docker.sock mount must be read-only (:ro)"
|
||||
assert name == "socket-proxy", (
|
||||
f"Service '{name}' directly mounts docker.sock!"
|
||||
)
|
||||
assert vol.endswith(":ro"), (
|
||||
"socket-proxy docker.sock mount must be read-only (:ro)"
|
||||
)
|
||||
|
||||
|
||||
def test_no_privileged_containers():
|
||||
@@ -60,7 +64,9 @@ def test_no_privileged_containers():
|
||||
services = compose.get("services", {})
|
||||
for name, svc in services.items():
|
||||
privileged = svc.get("privileged", False)
|
||||
assert privileged is not True, f"Service '{name}' is configured as privileged: true!"
|
||||
assert privileged is not True, (
|
||||
f"Service '{name}' is configured as privileged: true!"
|
||||
)
|
||||
|
||||
|
||||
def test_no_shell_true_in_core_scripts():
|
||||
@@ -78,10 +84,14 @@ def test_portainer_is_deprecated_and_absent():
|
||||
compose = yaml.safe_load(f)
|
||||
|
||||
services = compose.get("services", {})
|
||||
assert "portainer" not in services, "Deprecated service 'portainer' must not exist in docker-compose.yml"
|
||||
assert "portainer" not in services, (
|
||||
"Deprecated service 'portainer' must not exist in docker-compose.yml"
|
||||
)
|
||||
|
||||
volumes = compose.get("volumes", {}) or {}
|
||||
assert "portainer_data" not in volumes, "Deprecated volume 'portainer_data' must not exist in docker-compose.yml"
|
||||
assert "portainer_data" not in volumes, (
|
||||
"Deprecated volume 'portainer_data' must not exist in docker-compose.yml"
|
||||
)
|
||||
|
||||
|
||||
def test_no_eval_in_appctl_script():
|
||||
@@ -113,7 +123,9 @@ env:
|
||||
"""
|
||||
|
||||
(app_dir / "app.yaml").write_text(app_yaml.strip(), encoding="utf-8")
|
||||
(app_dir / "docker-compose.yml").write_text("services:\n web:\n image: nginx\n", encoding="utf-8")
|
||||
(app_dir / "docker-compose.yml").write_text(
|
||||
"services:\n web:\n image: nginx\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
# 2. Setup mock docker binary to capture environment without requiring a running Docker daemon
|
||||
mock_bin = tmp_path / "bin"
|
||||
@@ -152,10 +164,13 @@ exit 0
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
# 4. Assertions: command substitution was not executed, script ran, and mock docker received literal value
|
||||
assert not canary.exists(), "Command substitution was executed on the host during environment setup!"
|
||||
assert res.returncode == 0, f"appctl config failed: {res.stderr}\nStdout: {res.stdout}"
|
||||
assert not canary.exists(), (
|
||||
"Command substitution was executed on the host during environment setup!"
|
||||
)
|
||||
assert res.returncode == 0, (
|
||||
f"appctl config failed: {res.stderr}\nStdout: {res.stdout}"
|
||||
)
|
||||
assert "MOCK_DOCKER_COMPOSE_CONFIG" in res.stdout
|
||||
assert f"CAPTURED_INJECTION={payload}" in res.stdout
|
||||
assert "CAPTURED_NORMAL=safe_value" in res.stdout
|
||||
@@ -182,16 +197,17 @@ def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests(
|
||||
for file_path in candidate_files:
|
||||
if (
|
||||
file_path.is_file()
|
||||
and file_path.suffix in (".py", ".sh", ".bash", ".yml", ".yaml", ".md", ".nix", "")
|
||||
and file_path.suffix
|
||||
in (".py", ".sh", ".bash", ".yml", ".yaml", ".md", ".nix", "")
|
||||
and file_path.name != "test_security_invariants.py"
|
||||
):
|
||||
content = file_path.read_text(encoding="utf-8", errors="ignore")
|
||||
for term in forbidden:
|
||||
if term in content:
|
||||
violations.append(f"{file_path.relative_to(CORE_ROOT)}: contains prohibited literal '{term}'")
|
||||
|
||||
assert not violations, "Platform genericism violations detected:\n" + "\n".join(violations)
|
||||
|
||||
|
||||
|
||||
violations.append(
|
||||
f"{file_path.relative_to(CORE_ROOT)}: contains prohibited literal '{term}'"
|
||||
)
|
||||
|
||||
assert not violations, "Platform genericism violations detected:\n" + "\n".join(
|
||||
violations
|
||||
)
|
||||
@@ -36,7 +36,9 @@ def test_required_architectural_paths_exist():
|
||||
|
||||
pre_commit = CORE_ROOT / ".githooks" / "pre-commit"
|
||||
assert pre_commit.is_file(), ".githooks/pre-commit must be a regular file"
|
||||
assert os.access(pre_commit, os.X_OK), ".githooks/pre-commit must be marked executable"
|
||||
assert os.access(pre_commit, os.X_OK), (
|
||||
".githooks/pre-commit must be marked executable"
|
||||
)
|
||||
|
||||
|
||||
def test_deprecated_legacy_structures_are_absent():
|
||||
@@ -61,4 +63,7 @@ def test_unlicense_preserved():
|
||||
unlicense = CORE_ROOT / "UNLICENSE"
|
||||
assert unlicense.is_file(), "UNLICENSE file must be present"
|
||||
content = unlicense.read_text(encoding="utf-8")
|
||||
assert "This is free and unencumbered software released into the public domain." in content
|
||||
assert (
|
||||
"This is free and unencumbered software released into the public domain."
|
||||
in content
|
||||
)
|
||||
@@ -1,20 +1,19 @@
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import appctl_engine as engine
|
||||
import pytest
|
||||
|
||||
# Import appctl engine
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
|
||||
import appctl_engine as engine
|
||||
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
|
||||
|
||||
@dataclass
|
||||
class AppFactory:
|
||||
"""Helper class to generate mock app directories and configurations"""
|
||||
|
||||
sites_dir: Path
|
||||
|
||||
def create(
|
||||
@@ -28,9 +27,12 @@ class AppFactory:
|
||||
if manifest_yaml:
|
||||
(app_dir / "app.yaml").write_text(manifest_yaml, encoding="utf-8")
|
||||
if has_compose:
|
||||
(app_dir / "docker-compose.yml").write_text("services: {}\n", encoding="utf-8")
|
||||
(app_dir / "docker-compose.yml").write_text(
|
||||
"services: {}\n", encoding="utf-8"
|
||||
)
|
||||
return app_dir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
"""Fixture that creates an isolated Sites directory and points engine.SITES_DIR to it"""
|
||||
@@ -39,23 +41,24 @@ def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "mydomain.test")
|
||||
return sites
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app_factory(mock_sites_dir: Path) -> AppFactory:
|
||||
"""Fixture that provides the AppFactory instance to test"""
|
||||
return AppFactory(mock_sites_dir)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_core_dir(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch
|
||||
) -> Path:
|
||||
def mock_core_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
"""Fixture that creates an isolated Core directory and points engine.CORE_DIR to it"""
|
||||
core = tmp_path / "CORE"
|
||||
core.mkdir(parents=True, exist_ok=True)
|
||||
return core
|
||||
|
||||
|
||||
## GREEN TEST: Existing implementation should not break
|
||||
|
||||
|
||||
def test_resolve_app_hierarchy(app_factory: AppFactory):
|
||||
"""Ensure resolution follows: Canonical Name > Alias > Dir Name > Prefix"""
|
||||
app_factory.create(
|
||||
@@ -73,6 +76,7 @@ def test_resolve_app_hierarchy(app_factory: AppFactory):
|
||||
assert engine.resolve_app("homelab-jellyfin", apps) is not None
|
||||
assert engine.resolve_app("unknown", apps) is None
|
||||
|
||||
|
||||
def test_manifest_data_overrides_default_values(app_factory: AppFactory):
|
||||
"""Ensure app.yaml values successfully override the system defaults"""
|
||||
app_factory.create(
|
||||
@@ -84,7 +88,7 @@ def test_manifest_data_overrides_default_values(app_factory: AppFactory):
|
||||
visible: false
|
||||
networks:
|
||||
- custom-net
|
||||
"""
|
||||
""",
|
||||
)
|
||||
|
||||
apps = engine.get_sites_apps()
|
||||
@@ -95,6 +99,7 @@ def test_manifest_data_overrides_default_values(app_factory: AppFactory):
|
||||
assert app.auth is False
|
||||
assert app.networks == ["custom-net"]
|
||||
|
||||
|
||||
def test_sites_app_normalization(app_factory: AppFactory):
|
||||
"""Ensure missing or badly typed manifest fields are safely normalized"""
|
||||
app_factory.create(
|
||||
@@ -106,7 +111,7 @@ def test_sites_app_normalization(app_factory: AppFactory):
|
||||
auth: "False" # should evaluate based on boolean casting
|
||||
homepage:
|
||||
weight: "99" # this should be casted as an int
|
||||
"""
|
||||
""",
|
||||
)
|
||||
apps = engine.get_sites_apps()
|
||||
app = engine.resolve_app("testapp", apps)
|
||||
@@ -131,7 +136,7 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
||||
type: git
|
||||
url: https://git.example.com/operator/bitetrack.git
|
||||
ref: v1.2.0
|
||||
"""
|
||||
""",
|
||||
)
|
||||
# 2. Source-backed app with default ref (main)
|
||||
app_factory.create(
|
||||
@@ -140,14 +145,14 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
||||
name: doc2site
|
||||
source:
|
||||
url: https://git.example.com/operator/doc2site.git
|
||||
"""
|
||||
""",
|
||||
)
|
||||
# 3. Image-only app (no source block)
|
||||
app_factory.create(
|
||||
dir_name="homelab-jellyfin",
|
||||
manifest_yaml="""
|
||||
name: jellyfin
|
||||
"""
|
||||
""",
|
||||
)
|
||||
|
||||
apps = engine.get_sites_apps()
|
||||
@@ -177,7 +182,7 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
||||
name: malformed
|
||||
source:
|
||||
url: file:///etc/passwd
|
||||
"""
|
||||
""",
|
||||
)
|
||||
apps_updated = engine.get_sites_apps()
|
||||
malformed = engine.resolve_app("malformed", apps_updated)
|
||||
@@ -189,8 +194,10 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
||||
|
||||
## RED TESTS: TDD Goals for next implementation
|
||||
|
||||
|
||||
def test_docker_status_parser_running(monkeypatch):
|
||||
"""Ensure get_docker_status reports running compose stack when all containers are running."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
if "ps" in args:
|
||||
@@ -207,6 +214,7 @@ def test_docker_status_parser_running(monkeypatch):
|
||||
|
||||
def test_docker_status_parser_stopped(monkeypatch):
|
||||
"""Ensure get_docker_status reports stopped when no containers exist."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
if "ps" in args:
|
||||
@@ -221,6 +229,7 @@ def test_docker_status_parser_stopped(monkeypatch):
|
||||
|
||||
def test_docker_status_parser_degraded(monkeypatch):
|
||||
"""Ensure get_docker_status reports degraded when partial containers are running."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
if "ps" in args:
|
||||
@@ -244,6 +253,7 @@ def test_docker_status_parser_not_stack(tmp_path: Path):
|
||||
|
||||
def test_docker_status_single_container(monkeypatch):
|
||||
"""Ensure get_docker_status inspects single Core container by name."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
if "authelia" in args:
|
||||
@@ -260,6 +270,7 @@ def test_docker_status_single_container(monkeypatch):
|
||||
|
||||
def test_docker_status_error_handling(monkeypatch):
|
||||
"""Ensure get_docker_status handles subprocess failures gracefully."""
|
||||
|
||||
def mock_err(*args, **kwargs):
|
||||
raise OSError("Docker socket unreachable")
|
||||
|
||||
@@ -269,6 +280,7 @@ def test_docker_status_error_handling(monkeypatch):
|
||||
|
||||
def test_docker_image_revision_extraction(monkeypatch):
|
||||
"""Ensure get_docker_image_revision extracts org.opencontainers.image.revision."""
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
if "ps" in args:
|
||||
@@ -278,7 +290,10 @@ def test_docker_image_revision_extraction(monkeypatch):
|
||||
return mock
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_image_revision("/fake/dir") == "9d82577f489f0d478e465a36077538d0ded16ba5"
|
||||
assert (
|
||||
engine.get_docker_image_revision("/fake/dir")
|
||||
== "9d82577f489f0d478e465a36077538d0ded16ba5"
|
||||
)
|
||||
|
||||
def mock_run_empty(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
@@ -293,9 +308,8 @@ def test_docker_image_revision_extraction(monkeypatch):
|
||||
|
||||
|
||||
def test_homepage_sync_groups_and_sorts_correctly(
|
||||
mock_core_dir: Path,
|
||||
app_factory: AppFactory,
|
||||
monkeypatch):
|
||||
mock_core_dir: Path, app_factory: AppFactory, monkeypatch
|
||||
):
|
||||
"""
|
||||
TDD Goal: Port `cmd_sync_homepage` to V2 using the new Dataclass structure.
|
||||
It must group by `homepage.group` and sort by `homepage.weight`.
|
||||
@@ -312,7 +326,7 @@ def test_homepage_sync_groups_and_sorts_correctly(
|
||||
title: App1
|
||||
group: Group B
|
||||
weight: 20
|
||||
"""
|
||||
""",
|
||||
)
|
||||
|
||||
app_factory.create(
|
||||
@@ -324,7 +338,7 @@ def test_homepage_sync_groups_and_sorts_correctly(
|
||||
title: App2
|
||||
group: Group A
|
||||
weight: 10
|
||||
"""
|
||||
""",
|
||||
)
|
||||
|
||||
monkeypatch.setattr(engine, "get_core_services", list)
|
||||
@@ -334,8 +348,10 @@ def test_homepage_sync_groups_and_sorts_correctly(
|
||||
assert output_file.exists(), "The services.yaml file must be generated"
|
||||
|
||||
content = output_file.read_text()
|
||||
assert content.find("- Group A") < content.find("- Group B") # Group A should appear before Group B
|
||||
assert "App2" in content # App 2 is in the file
|
||||
assert content.find("- Group A") < content.find(
|
||||
"- Group B"
|
||||
) # Group A should appear before Group B
|
||||
assert "App2" in content # App 2 is in the file
|
||||
|
||||
|
||||
def test_homepage_sync_core_services_domain_isolation(
|
||||
@@ -380,7 +396,9 @@ def test_resolve_core_stack_type():
|
||||
assert traefik.container == "traefik"
|
||||
|
||||
|
||||
def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(app_factory: AppFactory):
|
||||
def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(
|
||||
app_factory: AppFactory,
|
||||
):
|
||||
"""Ensure manifest parsing uses core_manifest and catches invalid env keys."""
|
||||
app_factory.create(
|
||||
dir_name="homelab-badenv",
|
||||
@@ -397,7 +415,9 @@ def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(app_facto
|
||||
assert "Invalid or reserved environment variable key" in app.manifest_error
|
||||
|
||||
|
||||
def test_cmd_resolve_fails_closed_on_manifest_error(app_factory: AppFactory, capsys: pytest.CaptureFixture):
|
||||
def test_cmd_resolve_fails_closed_on_manifest_error(
|
||||
app_factory: AppFactory, capsys: pytest.CaptureFixture
|
||||
):
|
||||
"""Ensure cmd_resolve exits with non-zero on workload with manifest errors."""
|
||||
app_factory.create(
|
||||
dir_name="homelab-corrupt",
|
||||
@@ -449,7 +469,9 @@ def test_unification_uses_core_manifest_dataclasses(app_factory: AppFactory):
|
||||
assert app.source.transport == core_manifest.TransportScheme.HTTPS
|
||||
|
||||
|
||||
def test_cmd_list_flags_manifest_error(app_factory: AppFactory, capsys: pytest.CaptureFixture):
|
||||
def test_cmd_list_flags_manifest_error(
|
||||
app_factory: AppFactory, capsys: pytest.CaptureFixture
|
||||
):
|
||||
"""Ensure cmd_list flags workloads with manifest errors instead of swallowing them."""
|
||||
app_factory.create(
|
||||
dir_name="homelab-broken",
|
||||
@@ -462,4 +484,3 @@ def test_cmd_list_flags_manifest_error(app_factory: AppFactory, capsys: pytest.C
|
||||
engine.cmd_list([])
|
||||
captured = capsys.readouterr()
|
||||
assert "Manifest Error" in captured.out
|
||||
|
||||
@@ -2,15 +2,13 @@
|
||||
Unit test suite for scripts/core_manifest.py (Schema v1.0 & Parser Library).
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
# Add scripts directory to path
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
|
||||
# # Add scripts directory to path
|
||||
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
from core_manifest import (
|
||||
Manifest,
|
||||
ManifestValidationError,
|
||||
@@ -24,13 +22,17 @@ from core_manifest import (
|
||||
|
||||
def test_validate_transport_https():
|
||||
|
||||
scheme, url = validate_transport("https://git.example.com/operator/homelab-snappymail.git")
|
||||
scheme, url = validate_transport(
|
||||
"https://git.example.com/operator/homelab-snappymail.git"
|
||||
)
|
||||
assert scheme == TransportScheme.HTTPS
|
||||
assert url == "https://git.example.com/operator/homelab-snappymail.git"
|
||||
|
||||
|
||||
def test_validate_transport_ssh():
|
||||
scheme, url = validate_transport("ssh://git@git.example.com:2223/operator/homelab-docs.git")
|
||||
scheme, url = validate_transport(
|
||||
"ssh://git@git.example.com:2223/operator/homelab-docs.git"
|
||||
)
|
||||
assert scheme == TransportScheme.SSH
|
||||
assert url == "ssh://git@git.example.com:2223/operator/homelab-docs.git"
|
||||
|
||||
@@ -41,21 +43,29 @@ def test_validate_transport_git_scp():
|
||||
assert url == "git@github.com:operator/custom-workload.git"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("insecure_url", [
|
||||
"http://insecure.example.com/repo.git",
|
||||
"http://github.com/repo.git",
|
||||
])
|
||||
@pytest.mark.parametrize(
|
||||
"insecure_url",
|
||||
[
|
||||
"http://insecure.example.com/repo.git",
|
||||
"http://github.com/repo.git",
|
||||
],
|
||||
)
|
||||
def test_validate_transport_rejects_http(insecure_url: str):
|
||||
with pytest.raises(ManifestValidationError, match="Insecure HTTP source URL rejected"):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="Insecure HTTP source URL rejected"
|
||||
):
|
||||
validate_transport(insecure_url)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("traversal_url", [
|
||||
"../../etc/shadow",
|
||||
"/home/operator/secret",
|
||||
"~/vault",
|
||||
"file:///etc/passwd",
|
||||
])
|
||||
@pytest.mark.parametrize(
|
||||
"traversal_url",
|
||||
[
|
||||
"../../etc/shadow",
|
||||
"/home/operator/secret",
|
||||
"~/vault",
|
||||
"file:///etc/passwd",
|
||||
],
|
||||
)
|
||||
def test_validate_transport_rejects_paths_and_traversal(traversal_url: str):
|
||||
with pytest.raises(ManifestValidationError):
|
||||
validate_transport(traversal_url)
|
||||
@@ -64,7 +74,10 @@ def test_validate_transport_rejects_paths_and_traversal(traversal_url: str):
|
||||
def test_classify_ref_branches():
|
||||
assert classify_ref("main") == (RefType.BRANCH, "main")
|
||||
assert classify_ref("refs/heads/develop") == (RefType.BRANCH, "develop")
|
||||
assert classify_ref("feat/manifest-engine") == (RefType.BRANCH, "feat/manifest-engine")
|
||||
assert classify_ref("feat/manifest-engine") == (
|
||||
RefType.BRANCH,
|
||||
"feat/manifest-engine",
|
||||
)
|
||||
assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0")
|
||||
|
||||
|
||||
@@ -145,7 +158,9 @@ deployment:
|
||||
|
||||
|
||||
def test_parse_manifest_rejects_missing_name():
|
||||
with pytest.raises(ManifestValidationError, match="missing mandatory string field 'name'"):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="missing mandatory string field 'name'"
|
||||
):
|
||||
parse_manifest("domain: test.example.com\n")
|
||||
|
||||
|
||||
@@ -162,7 +177,9 @@ deployment:
|
||||
- compose_up
|
||||
- rm_rf_root
|
||||
"""
|
||||
with pytest.raises(ManifestValidationError, match="Prohibited deployment action 'rm_rf_root'"):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="Prohibited deployment action 'rm_rf_root'"
|
||||
):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
|
||||
@@ -172,7 +189,9 @@ name: "app"
|
||||
deployment:
|
||||
strategy: "swarm"
|
||||
"""
|
||||
with pytest.raises(ManifestValidationError, match="Unsupported deployment strategy 'swarm'"):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="Unsupported deployment strategy 'swarm'"
|
||||
):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
|
||||
@@ -185,24 +204,29 @@ def test_parse_manifest_from_path(tmp_path: Path):
|
||||
assert manifest.is_internal is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid_key", [
|
||||
"123_BAD",
|
||||
"INVALID-KEY",
|
||||
"FOO;BAR",
|
||||
"KEY WITH SPACE",
|
||||
"PATH",
|
||||
"LD_PRELOAD",
|
||||
"IFS",
|
||||
"CORE_DIR",
|
||||
"SITES_DIR",
|
||||
])
|
||||
@pytest.mark.parametrize(
|
||||
"invalid_key",
|
||||
[
|
||||
"123_BAD",
|
||||
"INVALID-KEY",
|
||||
"FOO;BAR",
|
||||
"KEY WITH SPACE",
|
||||
"PATH",
|
||||
"LD_PRELOAD",
|
||||
"IFS",
|
||||
"CORE_DIR",
|
||||
"SITES_DIR",
|
||||
],
|
||||
)
|
||||
def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str):
|
||||
raw_yaml = f"""
|
||||
name: "app"
|
||||
env:
|
||||
"{invalid_key}": "some_value"
|
||||
"""
|
||||
with pytest.raises(ManifestValidationError, match="Invalid or reserved environment variable key"):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="Invalid or reserved environment variable key"
|
||||
):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
|
||||
@@ -226,7 +250,9 @@ def test_parse_manifest_rejects_extra_fields():
|
||||
name: "app"
|
||||
unrecognized_field: "should_fail"
|
||||
"""
|
||||
with pytest.raises(ManifestValidationError, match="unrecognized or forbidden field"):
|
||||
with pytest.raises(
|
||||
ManifestValidationError, match="unrecognized or forbidden field"
|
||||
):
|
||||
parse_manifest(raw_yaml)
|
||||
|
||||
|
||||
@@ -259,5 +285,3 @@ description: "Pydantic serialization test"
|
||||
assert dumped["name"] == "serialized-app"
|
||||
assert dumped["schemaVersion"] == "1.0"
|
||||
assert manifest.to_dict()["name"] == "serialized-app"
|
||||
|
||||
|
||||
@@ -4,14 +4,12 @@ Unit test suite for scripts/provenance.py (Two-Axis Inspection & Provenance Reso
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
# Add scripts directory to path
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
|
||||
# # Add scripts directory to path
|
||||
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||
from core_manifest import Manifest, RefType, SourceConfig, TransportScheme
|
||||
from provenance import (
|
||||
ProvenanceStatus,
|
||||
@@ -43,12 +41,28 @@ def test_get_local_checkout_status_clean_repo(tmp_path: Path):
|
||||
app_dir = tmp_path / "git_app"
|
||||
app_dir.mkdir()
|
||||
env = _clean_git_env()
|
||||
subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env)
|
||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env)
|
||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "init", "-b", "main"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "config", "user.email", "test@example.com"],
|
||||
check=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env
|
||||
)
|
||||
(app_dir / "file.txt").write_text("hello", encoding="utf-8")
|
||||
subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env)
|
||||
subprocess.run(["git", "-C", str(app_dir), "commit", "-m", "init"], check=True, capture_output=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "commit", "-m", "init"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
status = get_local_checkout_status(app_dir)
|
||||
assert status.is_git is True
|
||||
@@ -62,12 +76,28 @@ def test_get_local_checkout_status_dirty_repo(tmp_path: Path):
|
||||
app_dir = tmp_path / "git_dirty_app"
|
||||
app_dir.mkdir()
|
||||
env = _clean_git_env()
|
||||
subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env)
|
||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env)
|
||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "init", "-b", "main"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "config", "user.email", "test@example.com"],
|
||||
check=True,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env
|
||||
)
|
||||
(app_dir / "file.txt").write_text("hello", encoding="utf-8")
|
||||
subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env)
|
||||
subprocess.run(["git", "-C", str(app_dir), "commit", "-m", "init"], check=True, capture_output=True, env=env)
|
||||
subprocess.run(
|
||||
["git", "-C", str(app_dir), "commit", "-m", "init"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
# Modify file to create dirty state
|
||||
(app_dir / "file.txt").write_text("modified", encoding="utf-8")
|
||||
@@ -131,7 +161,10 @@ def test_resolve_upstream_provenance_timeout():
|
||||
transport=TransportScheme.HTTPS,
|
||||
)
|
||||
|
||||
with patch("subprocess.run", side_effect=subprocess.TimeoutExpired(cmd=["git"], timeout=10.0)):
|
||||
with patch(
|
||||
"subprocess.run",
|
||||
side_effect=subprocess.TimeoutExpired(cmd=["git"], timeout=10.0),
|
||||
):
|
||||
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
|
||||
|
||||
assert prov.status == ProvenanceStatus.TIMEOUT
|
||||
@@ -183,13 +216,17 @@ def test_inspect_workload_two_axis(tmp_path: Path):
|
||||
)
|
||||
|
||||
# Without fetch_upstream: Axis 2 returns UNKNOWN
|
||||
status_no_fetch = inspect_workload_two_axis(tmp_path, manifest, fetch_upstream=False)
|
||||
status_no_fetch = inspect_workload_two_axis(
|
||||
tmp_path, manifest, fetch_upstream=False
|
||||
)
|
||||
assert status_no_fetch.provenance.status == ProvenanceStatus.UNKNOWN
|
||||
assert "Pass --fetch" in status_no_fetch.provenance.message
|
||||
|
||||
# With fetch_upstream: Axis 2 queries remote
|
||||
with patch("provenance.resolve_upstream_provenance") as mock_resolve:
|
||||
mock_resolve.return_value = MagicMock(status=ProvenanceStatus.SYNCED)
|
||||
status_fetch = inspect_workload_two_axis(tmp_path, manifest, fetch_upstream=True)
|
||||
status_fetch = inspect_workload_two_axis(
|
||||
tmp_path, manifest, fetch_upstream=True
|
||||
)
|
||||
assert status_fetch.provenance.status == ProvenanceStatus.SYNCED
|
||||
mock_resolve.assert_called_once()
|
||||
Reference in new issue
Block a user