style: format python files with ruff
This commit is contained in:
1 parent
51c43f71ff
commit
dc880928a9
11 files changed
+1089
-466
No files matched your search
@@ -28,7 +28,7 @@ PROVIDERS = [
|
|||||||
"https://api.ipify.org",
|
"https://api.ipify.org",
|
||||||
"https://ifconfig.me/ip",
|
"https://ifconfig.me/ip",
|
||||||
"https://icanhazip.com",
|
"https://icanhazip.com",
|
||||||
"https://wtfismyip.com/text"
|
"https://wtfismyip.com/text",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -78,14 +78,11 @@ def get_public_ip():
|
|||||||
for provider in PROVIDERS:
|
for provider in PROVIDERS:
|
||||||
try:
|
try:
|
||||||
req = urllib.request.Request(
|
req = urllib.request.Request(
|
||||||
provider,
|
provider, headers={"User-Agent": "Mozilla/5.0 (NixOS WAN Monitor)"}
|
||||||
headers={
|
|
||||||
'User-Agent': 'Mozilla/5.0 (NixOS WAN Monitor)'
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
# Fetch with 5s timeout to avoid hanging the systemd service
|
# Fetch with 5s timeout to avoid hanging the systemd service
|
||||||
with urllib.request.urlopen(req, timeout=5) as response:
|
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):
|
if is_valid_public_ipv4(ip):
|
||||||
return ip
|
return ip
|
||||||
else:
|
else:
|
||||||
@@ -94,8 +91,7 @@ def get_public_ip():
|
|||||||
errors.append(f"{provider}: {e!s}")
|
errors.append(f"{provider}: {e!s}")
|
||||||
|
|
||||||
print(
|
print(
|
||||||
f"Error: All IP discovery providers failed. Details: {errors}",
|
f"Error: All IP discovery providers failed. Details: {errors}", file=sys.stderr
|
||||||
file=sys.stderr
|
|
||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -132,11 +128,7 @@ def record_ip(ip, status, details=None):
|
|||||||
Appends a new event entry into the JSONLines history registry.
|
Appends a new event entry into the JSONLines history registry.
|
||||||
"""
|
"""
|
||||||
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
|
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
|
||||||
entry = {
|
entry = {"timestamp": datetime.now(tz=UTC).isoformat(), "ip": ip, "status": status}
|
||||||
"timestamp": datetime.now(tz=UTC).isoformat(),
|
|
||||||
"ip": ip,
|
|
||||||
"status": status
|
|
||||||
}
|
|
||||||
if details:
|
if details:
|
||||||
entry["details"] = details
|
entry["details"] = details
|
||||||
try:
|
try:
|
||||||
@@ -164,10 +156,7 @@ def trigger_ddclient():
|
|||||||
if res.returncode == 0:
|
if res.returncode == 0:
|
||||||
return True, None
|
return True, None
|
||||||
else:
|
else:
|
||||||
err_msg = (
|
err_msg = f"systemctl exited with {res.returncode}: {res.stderr.strip()}"
|
||||||
f"systemctl exited with {res.returncode}: "
|
|
||||||
f"{res.stderr.strip()}"
|
|
||||||
)
|
|
||||||
return False, err_msg
|
return False, err_msg
|
||||||
except (OSError, subprocess.SubprocessError) as e:
|
except (OSError, subprocess.SubprocessError) as e:
|
||||||
return False, str(e)
|
return False, str(e)
|
||||||
|
|||||||
+144
-50
@@ -33,7 +33,8 @@ from provenance import (
|
|||||||
|
|
||||||
# Dynamic Environment Paths
|
# Dynamic Environment Paths
|
||||||
CORE_DIR = os.environ.get(
|
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(
|
SITES_DIR = os.environ.get(
|
||||||
@@ -78,12 +79,19 @@ class App:
|
|||||||
name: str # Canonical identifier (e.g., "traefik", "jellyfin")
|
name: str # Canonical identifier (e.g., "traefik", "jellyfin")
|
||||||
description: str = "" # Human-readable summary for dashboards and CLI info
|
description: str = "" # Human-readable summary for dashboards and CLI info
|
||||||
domain: str = "" # Routing FQDN (e.g., "auth.example.com") or "internal".
|
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).
|
dir_path: str = (
|
||||||
|
"" # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
|
||||||
|
)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def is_internal(self) -> bool:
|
def is_internal(self) -> bool:
|
||||||
"""Returns True if the service does not expose a public TLS endpoint."""
|
"""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]:
|
def to_dict(self) -> dict[str, Any]:
|
||||||
"""Serialize for JSON consumption by scripts/appctl"""
|
"""Serialize for JSON consumption by scripts/appctl"""
|
||||||
@@ -104,12 +112,16 @@ class CoreService(App):
|
|||||||
@dataclass
|
@dataclass
|
||||||
class SitesApp(App):
|
class SitesApp(App):
|
||||||
dir_name: str = "" # directory name in ~/Sites (e.g., "homelab-vaultwarden")
|
dir_name: str = "" # directory name in ~/Sites (e.g., "homelab-vaultwarden")
|
||||||
source: SourceConfig | None = None # Upstream source provenance (None = Class B Image-Only)
|
source: SourceConfig | None = (
|
||||||
|
None # Upstream source provenance (None = Class B Image-Only)
|
||||||
|
)
|
||||||
aliases: list[str] = field(default_factory=list) # CLI resolution aliases
|
aliases: list[str] = field(default_factory=list) # CLI resolution aliases
|
||||||
visible: bool = True # Defines whether the icon is visible in Homepage
|
visible: bool = True # Defines whether the icon is visible in Homepage
|
||||||
auth: bool = True # Authelia protection guard indicator
|
auth: bool = True # Authelia protection guard indicator
|
||||||
has_compose: bool = False # Whether a docker-compose.yml exists
|
has_compose: bool = False # Whether a docker-compose.yml exists
|
||||||
networks: list[str] = field(default_factory=lambda: ["proxy-net"]) # Docker network attachments
|
networks: list[str] = field(
|
||||||
|
default_factory=lambda: ["proxy-net"]
|
||||||
|
) # Docker network attachments
|
||||||
env: dict[str, Any] = field(default_factory=dict) # Environment variable overrides
|
env: dict[str, Any] = field(default_factory=dict) # Environment variable overrides
|
||||||
homepage: HomepageConfig | None = None # Dashboard Card Configuration
|
homepage: HomepageConfig | None = None # Dashboard Card Configuration
|
||||||
manifest_error: str | None = None # Captured syntax/loading errors
|
manifest_error: str | None = None # Captured syntax/loading errors
|
||||||
@@ -121,15 +133,21 @@ class SitesApp(App):
|
|||||||
data = asdict(self)
|
data = asdict(self)
|
||||||
data.pop("manifest_obj", None)
|
data.pop("manifest_obj", None)
|
||||||
if self.source is not 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:
|
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")
|
data["type"] = getattr(self, "app_type", "app")
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def sites_app_from_manifest(
|
def sites_app_from_manifest(
|
||||||
app_dir: str,
|
app_dir: str,
|
||||||
manifest: Manifest | dict[str, Any] | None = None,
|
manifest: Manifest | dict[str, Any] | None = None,
|
||||||
@@ -139,10 +157,9 @@ def sites_app_from_manifest(
|
|||||||
raw_dir_name = os.path.basename(app_dir)
|
raw_dir_name = os.path.basename(app_dir)
|
||||||
|
|
||||||
if isinstance(manifest, Manifest):
|
if isinstance(manifest, Manifest):
|
||||||
has_compose = (
|
has_compose = os.path.isfile(
|
||||||
os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or
|
os.path.join(app_dir, "docker-compose.yaml")
|
||||||
os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
|
) or os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
|
||||||
)
|
|
||||||
canonical_name = manifest.name
|
canonical_name = manifest.name
|
||||||
domain = manifest.domain or f"{canonical_name}.{HOMELAB_DOMAIN}"
|
domain = manifest.domain or f"{canonical_name}.{HOMELAB_DOMAIN}"
|
||||||
return SitesApp(
|
return SitesApp(
|
||||||
@@ -169,7 +186,9 @@ def sites_app_from_manifest(
|
|||||||
return sites_app_from_manifest(app_dir, parsed, manifest_error)
|
return sites_app_from_manifest(app_dir, parsed, manifest_error)
|
||||||
except ManifestValidationError as err:
|
except ManifestValidationError as err:
|
||||||
manifest_error = f"{manifest_error}; {err}" if manifest_error else str(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(
|
return SitesApp(
|
||||||
name=canonical_name,
|
name=canonical_name,
|
||||||
dir_name=raw_dir_name,
|
dir_name=raw_dir_name,
|
||||||
@@ -217,7 +236,13 @@ def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]:
|
|||||||
try:
|
try:
|
||||||
manifest_obj = parse_manifest(manifest_file)
|
manifest_obj = parse_manifest(manifest_file)
|
||||||
apps.append(sites_app_from_manifest(app_dir=app_dir, manifest=manifest_obj))
|
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
|
raw_data = None
|
||||||
with (
|
with (
|
||||||
contextlib.suppress(Exception),
|
contextlib.suppress(Exception),
|
||||||
@@ -328,7 +353,9 @@ def resolve_app(
|
|||||||
Priority: Canonical Name > Alias > Dir Name > Stripped 'homelab-' Prefix > Core Services.
|
Priority: Canonical Name > Alias > Dir Name > Stripped 'homelab-' Prefix > Core Services.
|
||||||
"""
|
"""
|
||||||
if apps is None:
|
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()
|
query_clean = query.strip().lower()
|
||||||
|
|
||||||
@@ -389,7 +416,11 @@ def get_docker_status(
|
|||||||
return "🔴 Stopped"
|
return "🔴 Stopped"
|
||||||
|
|
||||||
path = Path(dir_path)
|
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"
|
return "⚪ Not Stack"
|
||||||
|
|
||||||
res = subprocess.run(
|
res = subprocess.run(
|
||||||
@@ -465,7 +496,9 @@ def get_docker_image_revision(
|
|||||||
return None
|
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."""
|
"""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:
|
if not domain or domain == "internal" or domain.endswith(".local") or ":" in domain:
|
||||||
return {
|
return {
|
||||||
@@ -492,9 +525,9 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
|
|||||||
days_remaining = None
|
days_remaining = None
|
||||||
formatted_expiry = "-"
|
formatted_expiry = "-"
|
||||||
if not_after_str:
|
if not_after_str:
|
||||||
expiry_dt = datetime.datetime.strptime(not_after_str, "%b %d %H:%M:%S %Y %Z").replace(
|
expiry_dt = datetime.datetime.strptime(
|
||||||
tzinfo=datetime.UTC
|
not_after_str, "%b %d %H:%M:%S %Y %Z"
|
||||||
)
|
).replace(tzinfo=datetime.UTC)
|
||||||
now_dt = datetime.datetime.now(datetime.UTC)
|
now_dt = datetime.datetime.now(datetime.UTC)
|
||||||
days_remaining = (expiry_dt - now_dt).days
|
days_remaining = (expiry_dt - now_dt).days
|
||||||
formatted_expiry = expiry_dt.strftime("%Y-%m-%d")
|
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]
|
entry = rdn[0]
|
||||||
if isinstance(entry, (list, tuple)) and len(entry) >= 2:
|
if isinstance(entry, (list, tuple)) and len(entry) >= 2:
|
||||||
issuer_dict[str(entry[0])] = str(entry[1])
|
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_dict: dict[str, str] = {}
|
||||||
subject_raw = cert.get("subject")
|
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_dict[str(entry[0])] = str(entry[1])
|
||||||
subject = str(subject_dict.get("commonName") or domain)
|
subject = str(subject_dict.get("commonName") or domain)
|
||||||
|
|
||||||
|
|
||||||
if days_remaining is not None:
|
if days_remaining is not None:
|
||||||
if days_remaining < 0:
|
if days_remaining < 0:
|
||||||
status = f"🔴 Expired ({abs(days_remaining)}d ago)"
|
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,
|
"formatted_expiry": formatted_expiry,
|
||||||
"error": None,
|
"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 {
|
return {
|
||||||
"domain": domain,
|
"domain": domain,
|
||||||
"status": "🔴 Failed",
|
"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]]:
|
def check_all_ssl_certs(domains: list[str]) -> dict[str, dict[str, Any]]:
|
||||||
"""Check multiple domains concurrently with ThreadPoolExecutor."""
|
"""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]] = {}
|
results: dict[str, dict[str, Any]] = {}
|
||||||
if not valid_domains:
|
if not valid_domains:
|
||||||
return results
|
return results
|
||||||
|
|
||||||
with ThreadPoolExecutor(max_workers=min(len(valid_domains), 8)) as executor:
|
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():
|
for future, d in future_to_domain.items():
|
||||||
with contextlib.suppress(subprocess.SubprocessError, OSError):
|
with contextlib.suppress(subprocess.SubprocessError, OSError):
|
||||||
results[d] = future.result()
|
results[d] = future.result()
|
||||||
@@ -591,7 +640,8 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
|||||||
groups[core_group] = []
|
groups[core_group] = []
|
||||||
for svc in core_services:
|
for svc in core_services:
|
||||||
if not svc.is_internal:
|
if not svc.is_internal:
|
||||||
groups[core_group].append({
|
groups[core_group].append(
|
||||||
|
{
|
||||||
"title": svc.name.title(),
|
"title": svc.name.title(),
|
||||||
"icon": getattr(svc, "icon", "default.png"),
|
"icon": getattr(svc, "icon", "default.png"),
|
||||||
"href": f"https://{svc.domain}",
|
"href": f"https://{svc.domain}",
|
||||||
@@ -599,7 +649,8 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
|||||||
"server": "my-docker",
|
"server": "my-docker",
|
||||||
"container": getattr(svc, "container", svc.name),
|
"container": getattr(svc, "container", svc.name),
|
||||||
"weight": getattr(svc, "weight", 50),
|
"weight": getattr(svc, "weight", 50),
|
||||||
})
|
}
|
||||||
|
)
|
||||||
|
|
||||||
# 2. Add Sites applications
|
# 2. Add Sites applications
|
||||||
icons_dir = os.path.join(hp_dir, "icons")
|
icons_dir = os.path.join(hp_dir, "icons")
|
||||||
@@ -633,7 +684,8 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
|||||||
if matched_icon:
|
if matched_icon:
|
||||||
icon = f"/icons/{matched_icon}"
|
icon = f"/icons/{matched_icon}"
|
||||||
|
|
||||||
groups[group_name].append({
|
groups[group_name].append(
|
||||||
|
{
|
||||||
"title": card_title,
|
"title": card_title,
|
||||||
"icon": icon,
|
"icon": icon,
|
||||||
"href": f"https://{app.domain}",
|
"href": f"https://{app.domain}",
|
||||||
@@ -641,7 +693,8 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None:
|
|||||||
"server": "my-docker",
|
"server": "my-docker",
|
||||||
"container": container,
|
"container": container,
|
||||||
"weight": weight,
|
"weight": weight,
|
||||||
})
|
}
|
||||||
|
)
|
||||||
|
|
||||||
# Preferred group order
|
# Preferred group order
|
||||||
preferred_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:
|
with open(services_yaml_path, "w", encoding="utf-8") as f:
|
||||||
f.write(content)
|
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}")
|
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)
|
ssl_data = check_all_ssl_certs(domains_to_check)
|
||||||
|
|
||||||
if show_ssl:
|
if show_ssl:
|
||||||
print(f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}")
|
print(
|
||||||
print(f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}")
|
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
print(f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}")
|
print(
|
||||||
print(f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}")
|
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}"
|
||||||
|
)
|
||||||
|
|
||||||
for app in apps:
|
for app in apps:
|
||||||
app_path = Path(app.dir_path)
|
app_path = Path(app.dir_path)
|
||||||
@@ -713,7 +776,9 @@ def cmd_list(args: list[str]) -> None:
|
|||||||
dep_str = "⚠️ Manifest Error"
|
dep_str = "⚠️ Manifest Error"
|
||||||
prov_str = "⚠️ Invalid Manifest"
|
prov_str = "⚠️ Invalid Manifest"
|
||||||
else:
|
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(
|
two_axis = inspect_workload_two_axis(
|
||||||
app_dir=app_path,
|
app_dir=app_path,
|
||||||
manifest=manifest_obj,
|
manifest=manifest_obj,
|
||||||
@@ -726,9 +791,13 @@ def cmd_list(args: list[str]) -> None:
|
|||||||
if show_ssl:
|
if show_ssl:
|
||||||
cert_info = ssl_data.get(app.domain, check_ssl_cert(app.domain))
|
cert_info = ssl_data.get(app.domain, check_ssl_cert(app.domain))
|
||||||
cert_badge = cert_info.get("status", "-")
|
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:
|
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:
|
if show_core:
|
||||||
core_path = Path(CORE_DIR)
|
core_path = Path(CORE_DIR)
|
||||||
@@ -736,11 +805,19 @@ def cmd_list(args: list[str]) -> None:
|
|||||||
core_dep_str = core_checkout.status_label
|
core_dep_str = core_checkout.status_label
|
||||||
print()
|
print()
|
||||||
if show_ssl:
|
if show_ssl:
|
||||||
print(f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}")
|
print(
|
||||||
print(f"{'------------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}")
|
f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
f"{'------------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
print(f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}")
|
print(
|
||||||
print(f"{'------------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}")
|
f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
f"{'------------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}"
|
||||||
|
)
|
||||||
|
|
||||||
core_services = get_core_services()
|
core_services = get_core_services()
|
||||||
for i, svc in enumerate(core_services):
|
for i, svc in enumerate(core_services):
|
||||||
@@ -749,9 +826,13 @@ def cmd_list(args: list[str]) -> None:
|
|||||||
if show_ssl:
|
if show_ssl:
|
||||||
cert_info = ssl_data.get(svc.domain, check_ssl_cert(svc.domain))
|
cert_info = ssl_data.get(svc.domain, check_ssl_cert(svc.domain))
|
||||||
cert_badge = cert_info.get("status", "-")
|
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:
|
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:
|
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"Directory: {app.dir_path}")
|
||||||
print(f"Domain: {app.domain}")
|
print(f"Domain: {app.domain}")
|
||||||
print(f"Container: {app.container}")
|
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}")
|
print(f"Description: {app.description}")
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -791,7 +874,9 @@ def cmd_info(args: list[str]) -> None:
|
|||||||
print(f"Description: {app.description}")
|
print(f"Description: {app.description}")
|
||||||
if app.aliases:
|
if app.aliases:
|
||||||
print(f"Aliases: {', '.join(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"Networks: {', '.join(app.networks)}")
|
||||||
print(f"Auth Protected: {app.auth}")
|
print(f"Auth Protected: {app.auth}")
|
||||||
print(f"Dashboard: {'Visible' if app.visible else 'Hidden'}")
|
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:
|
if two_axis.checkout.is_git:
|
||||||
print(f" Branch: {two_axis.checkout.branch}")
|
print(f" Branch: {two_axis.checkout.branch}")
|
||||||
print(f" Commit SHA: {two_axis.checkout.commit_sha}")
|
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}")
|
print(f" Docker Status: {two_axis.docker_status}")
|
||||||
if two_axis.image_revision:
|
if two_axis.image_revision:
|
||||||
print(f" Image Revision:{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:
|
if not app:
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
if isinstance(app, SitesApp) and app.manifest_error:
|
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)
|
sys.exit(1)
|
||||||
print(json.dumps(app.to_dict()))
|
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"Subject: {cert_info['subject']}")
|
||||||
print(f"Expiration: {cert_info['not_after']}")
|
print(f"Expiration: {cert_info['not_after']}")
|
||||||
if cert_info["days_remaining"] is not None:
|
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"]:
|
if cert_info["error"]:
|
||||||
print(f"Details/Error: {cert_info['error']}")
|
print(f"Details/Error: {cert_info['error']}")
|
||||||
print()
|
print()
|
||||||
@@ -896,7 +988,9 @@ def cmd_ssl(args: list[str]) -> None:
|
|||||||
|
|
||||||
for name, domain in services_to_check:
|
for name, domain in services_to_check:
|
||||||
info = ssl_results.get(domain, check_ssl_cert(domain))
|
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:
|
def cmd_complete(args: list[str]) -> None:
|
||||||
|
|||||||
+87
-23
@@ -36,9 +36,9 @@ class ManifestValidationError(Exception):
|
|||||||
"""Raised when an application manifest violates schema or security constraints."""
|
"""Raised when an application manifest violates schema or security constraints."""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class RefType(str, Enum):
|
class RefType(str, Enum):
|
||||||
"""Semantic classification of an upstream git reference."""
|
"""Semantic classification of an upstream git reference."""
|
||||||
|
|
||||||
BRANCH = "branch" # Moving branch (e.g. main, master, develop, release/v1)
|
BRANCH = "branch" # Moving branch (e.g. main, master, develop, release/v1)
|
||||||
TAG = "tag" # Pinned release tag (e.g. v1.0.0, 2.3.1)
|
TAG = "tag" # Pinned release tag (e.g. v1.0.0, 2.3.1)
|
||||||
COMMIT = "commit" # Immutable commit SHA (40-character hex)
|
COMMIT = "commit" # Immutable commit SHA (40-character hex)
|
||||||
@@ -47,6 +47,7 @@ class RefType(str, Enum):
|
|||||||
|
|
||||||
class TransportScheme(str, Enum):
|
class TransportScheme(str, Enum):
|
||||||
"""Supported secure git network transports."""
|
"""Supported secure git network transports."""
|
||||||
|
|
||||||
HTTPS = "https"
|
HTTPS = "https"
|
||||||
SSH = "ssh"
|
SSH = "ssh"
|
||||||
GIT_SCP = "git_scp"
|
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}$")
|
COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$")
|
||||||
SHORT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,12}$")
|
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._-]*)$")
|
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_]*$")
|
ENV_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
|
||||||
RESERVED_ENV_KEYS = {
|
RESERVED_ENV_KEYS = {
|
||||||
"PATH", "LD_PRELOAD", "IFS", "SHELL", "USER",
|
"PATH",
|
||||||
"CORE_DIR", "SITES_DIR", "ENV_FILE", "HOMESERVER_ENV"
|
"LD_PRELOAD",
|
||||||
|
"IFS",
|
||||||
|
"SHELL",
|
||||||
|
"USER",
|
||||||
|
"CORE_DIR",
|
||||||
|
"SITES_DIR",
|
||||||
|
"ENV_FILE",
|
||||||
|
"HOMESERVER_ENV",
|
||||||
}
|
}
|
||||||
|
|
||||||
ALLOWED_STRATEGIES = {"compose"}
|
ALLOWED_STRATEGIES = {"compose"}
|
||||||
@@ -80,35 +90,49 @@ def validate_transport(url: str) -> tuple[TransportScheme, str]:
|
|||||||
|
|
||||||
# Reject path traversal / directory escapes
|
# Reject path traversal / directory escapes
|
||||||
if ".." in clean_url or "\\" in clean_url or clean_url.startswith(("/", "~")):
|
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
|
# 1. HTTPS transport
|
||||||
if clean_url.startswith("https://"):
|
if clean_url.startswith("https://"):
|
||||||
parsed = urlparse(clean_url)
|
parsed = urlparse(clean_url)
|
||||||
if not parsed.netloc:
|
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 == "/":
|
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
|
return TransportScheme.HTTPS, clean_url
|
||||||
|
|
||||||
# 2. Standard SSH transport (ssh://[user@]host[:port]/path)
|
# 2. Standard SSH transport (ssh://[user@]host[:port]/path)
|
||||||
if clean_url.startswith("ssh://"):
|
if clean_url.startswith("ssh://"):
|
||||||
parsed = urlparse(clean_url)
|
parsed = urlparse(clean_url)
|
||||||
if not parsed.netloc:
|
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 == "/":
|
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
|
return TransportScheme.SSH, clean_url
|
||||||
|
|
||||||
# 3. SCP-style SSH transport (git@host:owner/repo.git)
|
# 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):
|
if SCP_URL_RE.match(clean_url):
|
||||||
return TransportScheme.GIT_SCP, clean_url
|
return TransportScheme.GIT_SCP, clean_url
|
||||||
raise ManifestValidationError(f"Malformed SCP-style source URL: '{clean_url}'")
|
raise ManifestValidationError(f"Malformed SCP-style source URL: '{clean_url}'")
|
||||||
|
|
||||||
# Reject plaintext HTTP or unsupported schemes
|
# Reject plaintext HTTP or unsupported schemes
|
||||||
if clean_url.startswith("http://"):
|
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(
|
raise ManifestValidationError(
|
||||||
f"Invalid source.url scheme: '{clean_url}'. "
|
f"Invalid source.url scheme: '{clean_url}'. "
|
||||||
@@ -141,7 +165,16 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]:
|
|||||||
return RefType.TAG, ref
|
return RefType.TAG, ref
|
||||||
|
|
||||||
# Standard branch naming patterns
|
# 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
|
return RefType.BRANCH, ref
|
||||||
|
|
||||||
if ref.startswith(("feat/", "fix/", "release/", "chore/", "refactor/")):
|
if ref.startswith(("feat/", "fix/", "release/", "chore/", "refactor/")):
|
||||||
@@ -153,6 +186,7 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]:
|
|||||||
|
|
||||||
class SourceConfig(BaseModel):
|
class SourceConfig(BaseModel):
|
||||||
"""Upstream source provenance descriptor."""
|
"""Upstream source provenance descriptor."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="forbid")
|
model_config = ConfigDict(extra="forbid")
|
||||||
|
|
||||||
url: str
|
url: str
|
||||||
@@ -167,7 +201,9 @@ class SourceConfig(BaseModel):
|
|||||||
if isinstance(data, dict):
|
if isinstance(data, dict):
|
||||||
src_type = str(data.get("type", "git")).strip().lower()
|
src_type = str(data.get("type", "git")).strip().lower()
|
||||||
if src_type != "git":
|
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
|
data["type"] = src_type
|
||||||
|
|
||||||
raw_url = data.get("url")
|
raw_url = data.get("url")
|
||||||
@@ -198,6 +234,7 @@ class SourceConfig(BaseModel):
|
|||||||
|
|
||||||
class DeploymentConfig(BaseModel):
|
class DeploymentConfig(BaseModel):
|
||||||
"""Continuous deployment strategy and action policy."""
|
"""Continuous deployment strategy and action policy."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="forbid")
|
model_config = ConfigDict(extra="forbid")
|
||||||
|
|
||||||
strategy: str = "compose"
|
strategy: str = "compose"
|
||||||
@@ -237,6 +274,7 @@ class DeploymentConfig(BaseModel):
|
|||||||
|
|
||||||
class HomepageConfig(BaseModel):
|
class HomepageConfig(BaseModel):
|
||||||
"""Dashboard card metadata for Homepage."""
|
"""Dashboard card metadata for Homepage."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="forbid")
|
model_config = ConfigDict(extra="forbid")
|
||||||
|
|
||||||
title: str
|
title: str
|
||||||
@@ -262,6 +300,7 @@ class Manifest(BaseModel):
|
|||||||
Authoritative Workload Manifest Model (Schema v1.0).
|
Authoritative Workload Manifest Model (Schema v1.0).
|
||||||
Represents the full contract declared in a workload's app.yaml.
|
Represents the full contract declared in a workload's app.yaml.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="forbid", populate_by_name=True)
|
model_config = ConfigDict(extra="forbid", populate_by_name=True)
|
||||||
|
|
||||||
name: str
|
name: str
|
||||||
@@ -282,8 +321,14 @@ class Manifest(BaseModel):
|
|||||||
def prepare_manifest(cls, data: Any) -> Any:
|
def prepare_manifest(cls, data: Any) -> Any:
|
||||||
if isinstance(data, dict):
|
if isinstance(data, dict):
|
||||||
raw_name = data.get("name")
|
raw_name = data.get("name")
|
||||||
if raw_name is None or not isinstance(raw_name, str) or not raw_name.strip():
|
if (
|
||||||
raise ManifestValidationError("Manifest is missing mandatory string field 'name'.")
|
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()
|
clean_name = raw_name.strip()
|
||||||
if not NAME_RE.match(clean_name):
|
if not NAME_RE.match(clean_name):
|
||||||
raise ManifestValidationError(
|
raise ManifestValidationError(
|
||||||
@@ -359,7 +404,12 @@ class Manifest(BaseModel):
|
|||||||
@property
|
@property
|
||||||
def is_internal(self) -> bool:
|
def is_internal(self) -> bool:
|
||||||
"""True if the workload does not expose a public TLS endpoint."""
|
"""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]:
|
def to_dict(self) -> dict[str, Any]:
|
||||||
data: dict[str, Any] = {
|
data: dict[str, Any] = {
|
||||||
@@ -401,23 +451,35 @@ def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest:
|
|||||||
try:
|
try:
|
||||||
content = raw_input.read_text(encoding="utf-8")
|
content = raw_input.read_text(encoding="utf-8")
|
||||||
except OSError as e:
|
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:
|
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:
|
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):
|
elif isinstance(raw_input, str):
|
||||||
try:
|
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:
|
except Exception as e:
|
||||||
raise ManifestValidationError(f"YAML parsing error: {e}") from e
|
raise ManifestValidationError(f"YAML parsing error: {e}") from e
|
||||||
elif isinstance(raw_input, dict):
|
elif isinstance(raw_input, dict):
|
||||||
data = raw_input
|
data = raw_input
|
||||||
else:
|
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):
|
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:
|
try:
|
||||||
return Manifest.model_validate(data)
|
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, ")
|
msg = msg.removeprefix("Value error, ")
|
||||||
loc = ".".join(str(p) for p in first_error.get("loc", []))
|
loc = ".".join(str(p) for p in first_error.get("loc", []))
|
||||||
if loc and first_error.get("type") == "extra_forbidden":
|
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
|
raise ManifestValidationError(msg) from e
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+388
-115
@@ -27,15 +27,23 @@ except ImportError:
|
|||||||
|
|
||||||
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
|
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))
|
CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent))
|
||||||
CONFIG_DIR = Path(os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab")))
|
CONFIG_DIR = Path(
|
||||||
DEPLOYMENTS_FILE = Path(os.environ.get("HOMELAB_DEPLOYMENTS_FILE", CORE_DIR / "config" / "deployments.yaml"))
|
os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab"))
|
||||||
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"))
|
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(
|
logging.basicConfig(
|
||||||
level=logging.INFO,
|
level=logging.INFO,
|
||||||
format="%(asctime)s [%(levelname)s] [GitOps] %(message)s",
|
format="%(asctime)s [%(levelname)s] [GitOps] %(message)s",
|
||||||
handlers=[logging.StreamHandler(sys.stdout)]
|
handlers=[logging.StreamHandler(sys.stdout)],
|
||||||
)
|
)
|
||||||
logger = logging.getLogger("gitops_dispatcher")
|
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.
|
Load webhook shared secret from projected secret file or environment.
|
||||||
Never hardcoded in code or repository manifests.
|
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():
|
if path.is_file():
|
||||||
try:
|
try:
|
||||||
return path.read_bytes().strip()
|
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.
|
Fail-closed: missing signature, malformed signature, empty secret, or mismatch returns False.
|
||||||
"""
|
"""
|
||||||
if not secret:
|
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
|
return False
|
||||||
|
|
||||||
if not signature or not isinstance(signature, str):
|
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=")
|
cleaned_signature = cleaned_signature.removeprefix("sha256=")
|
||||||
|
|
||||||
# SHA256 hex digest is exactly 64 hexadecimal characters
|
# 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.")
|
logger.error("Authentication failed: Malformed signature format.")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -109,7 +123,9 @@ def parse_yaml_simple(text: str) -> dict:
|
|||||||
item = stripped[2:].strip().strip("\"'")
|
item = stripped[2:].strip().strip("\"'")
|
||||||
if current_section:
|
if current_section:
|
||||||
if current_subsection and isinstance(data.get(current_section), dict):
|
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] = []
|
||||||
data[current_section][current_subsection].append(item)
|
data[current_section][current_subsection].append(item)
|
||||||
else:
|
else:
|
||||||
@@ -161,16 +177,26 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
|
|||||||
"""
|
"""
|
||||||
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():
|
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
|
return mapping
|
||||||
|
|
||||||
yaml_errors = (yaml.YAMLError,) if yaml is not None else ()
|
yaml_errors = (yaml.YAMLError,) if yaml is not None else ()
|
||||||
try:
|
try:
|
||||||
content = registry_file.read_text(encoding="utf-8")
|
content = registry_file.read_text(encoding="utf-8")
|
||||||
registry = (yaml.safe_load(content) if yaml else parse_yaml_simple(content)) or {}
|
registry = (
|
||||||
repo_entries = registry.get("repositories", registry) if isinstance(registry, dict) else {}
|
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):
|
if isinstance(repo_entries, dict):
|
||||||
for reg_name, entry in repo_entries.items():
|
for reg_name, entry in repo_entries.items():
|
||||||
if not isinstance(entry, dict):
|
if not isinstance(entry, dict):
|
||||||
@@ -190,20 +216,31 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
|
|||||||
if isinstance(alias, str) and alias.strip():
|
if isinstance(alias, str) and alias.strip():
|
||||||
mapping[alias.strip()] = p
|
mapping[alias.strip()] = p
|
||||||
else:
|
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:
|
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 {}
|
return {}
|
||||||
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError, TypeError, *yaml_errors) as e:
|
except (
|
||||||
logger.critical(f"Failed to parse authoritative registry {registry_file}: {e}. Failing closed.")
|
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 {}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return mapping
|
return mapping
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_repository(repo_name: str) -> Path | None:
|
def resolve_repository(repo_name: str) -> Path | None:
|
||||||
"""
|
"""
|
||||||
Resolve a logical repository identity to a trusted local directory.
|
Resolve a logical repository identity to a trusted local directory.
|
||||||
@@ -218,14 +255,18 @@ def resolve_repository(repo_name: str) -> Path | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
if ".." in cleaned_name or "/" in cleaned_name or "\\" in cleaned_name:
|
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
|
return None
|
||||||
|
|
||||||
trusted_mapping = get_trusted_repository_mapping()
|
trusted_mapping = get_trusted_repository_mapping()
|
||||||
target = trusted_mapping.get(cleaned_name)
|
target = trusted_mapping.get(cleaned_name)
|
||||||
|
|
||||||
if not target:
|
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
|
return None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -235,12 +276,18 @@ def resolve_repository(repo_name: str) -> Path | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
if not canonical_target.is_dir():
|
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
|
return None
|
||||||
|
|
||||||
# Defense-in-depth: check allowed root containment strictly within SITES_DIR
|
# 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())):
|
if not (
|
||||||
logger.warning(f"Resolved path '{canonical_target}' escapes allowed SITES_DIR root for repository '{cleaned_name}'.")
|
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 None
|
||||||
|
|
||||||
return canonical_target
|
return canonical_target
|
||||||
@@ -260,16 +307,17 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
|
|||||||
if manifest_file.is_file():
|
if manifest_file.is_file():
|
||||||
try:
|
try:
|
||||||
manifest_text = manifest_file.read_text(encoding="utf-8")
|
manifest_text = manifest_file.read_text(encoding="utf-8")
|
||||||
manifest = (yaml.safe_load(manifest_text) if yaml else parse_yaml_simple(manifest_text)) or {}
|
manifest = (
|
||||||
|
yaml.safe_load(manifest_text)
|
||||||
|
if yaml
|
||||||
|
else parse_yaml_simple(manifest_text)
|
||||||
|
) or {}
|
||||||
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
||||||
logger.warning(f"Failed to parse {manifest_file}: {e}")
|
logger.warning(f"Failed to parse {manifest_file}: {e}")
|
||||||
|
|
||||||
deployment_config = manifest.get("deployment")
|
deployment_config = manifest.get("deployment")
|
||||||
if not isinstance(deployment_config, dict):
|
if not isinstance(deployment_config, dict):
|
||||||
deployment_config = {
|
deployment_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
|
||||||
"branch": "main",
|
|
||||||
"actions": ["git_pull", "compose_up"]
|
|
||||||
}
|
|
||||||
|
|
||||||
return target_dir, deployment_config
|
return target_dir, deployment_config
|
||||||
|
|
||||||
@@ -309,7 +357,10 @@ def validate_compose_security(
|
|||||||
if compose_file.is_symlink():
|
if compose_file.is_symlink():
|
||||||
resolved_compose = compose_file.resolve()
|
resolved_compose = compose_file.resolve()
|
||||||
if not resolved_compose.is_relative_to(canonical_allowed_root):
|
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:
|
try:
|
||||||
content = compose_file.read_text(encoding="utf-8")
|
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}"
|
return False, f"Failed to parse compose YAML {compose_file}: {e}"
|
||||||
else:
|
else:
|
||||||
# Fallback regex inspection if yaml module is not present
|
# 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."
|
return False, "Privileged mode is prohibited in workload compose files."
|
||||||
if "/var/run/docker.sock" in content:
|
if "/var/run/docker.sock" in content:
|
||||||
return False, "Docker socket mounts are prohibited in workload compose files."
|
return (
|
||||||
if re.search(r"^\s*network_mode:\s*[\"']?host[\"']?", content, re.MULTILINE | re.IGNORECASE):
|
False,
|
||||||
return False, "Host networking (network_mode: host) is prohibited in workload compose files."
|
"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):
|
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):
|
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):
|
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
|
return True, None
|
||||||
|
|
||||||
if not isinstance(data, dict):
|
if not isinstance(data, dict):
|
||||||
return False, f"Invalid compose root in {compose_file}: expected mapping"
|
return False, f"Invalid compose root in {compose_file}: expected mapping"
|
||||||
|
|
||||||
if "include" in data:
|
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")
|
services = data.get("services")
|
||||||
if not isinstance(services, dict):
|
if not isinstance(services, dict):
|
||||||
return True, None
|
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_app_name = app_name or allowed_root.name
|
||||||
target_state_root = (state_root / target_app_name).resolve()
|
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():
|
for svc_name, svc in services.items():
|
||||||
if not isinstance(svc, dict):
|
if not isinstance(svc, dict):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if svc.get("privileged") is True:
|
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")
|
cap_add = svc.get("cap_add")
|
||||||
if 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")
|
devices = svc.get("devices")
|
||||||
if 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", [])
|
sec_opts = svc.get("security_opt", [])
|
||||||
if isinstance(sec_opts, str):
|
if isinstance(sec_opts, str):
|
||||||
@@ -375,7 +465,10 @@ def validate_compose_security(
|
|||||||
if isinstance(sec_opts, list):
|
if isinstance(sec_opts, list):
|
||||||
for opt in sec_opts:
|
for opt in sec_opts:
|
||||||
if any(bad in str(opt).lower() for bad in ("unconfined", "disable")):
|
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")
|
raw_env_files = svc.get("env_file")
|
||||||
if raw_env_files:
|
if raw_env_files:
|
||||||
@@ -402,13 +495,22 @@ def validate_compose_security(
|
|||||||
else:
|
else:
|
||||||
resolved_env = (allowed_root / clean_env).resolve()
|
resolved_env = (allowed_root / clean_env).resolve()
|
||||||
|
|
||||||
if not (allowed_root.is_dir() and resolved_env.is_relative_to(canonical_allowed_root)):
|
if not (
|
||||||
return False, f"Service '{svc_name}' specifies prohibited env_file escaping workload root: '{clean_env}'."
|
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"):
|
for ns_key in ("network_mode", "pid", "ipc", "uts", "userns_mode"):
|
||||||
val = str(svc.get(ns_key, "")).strip().lower()
|
val = str(svc.get(ns_key, "")).strip().lower()
|
||||||
if val in PROHIBITED_HOST_NAMESPACES:
|
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", [])
|
volumes = svc.get("volumes", [])
|
||||||
if isinstance(volumes, list):
|
if isinstance(volumes, list):
|
||||||
@@ -416,13 +518,19 @@ def validate_compose_security(
|
|||||||
host_path = ""
|
host_path = ""
|
||||||
if isinstance(vol, str):
|
if isinstance(vol, str):
|
||||||
if "/var/run/docker.sock" in vol:
|
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:
|
if ":" in vol:
|
||||||
host_path = vol.split(":")[0].strip()
|
host_path = vol.split(":")[0].strip()
|
||||||
elif isinstance(vol, dict):
|
elif isinstance(vol, dict):
|
||||||
src = str(vol.get("source", ""))
|
src = str(vol.get("source", ""))
|
||||||
if "/var/run/docker.sock" in src:
|
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":
|
if vol.get("type") == "bind":
|
||||||
host_path = src
|
host_path = src
|
||||||
|
|
||||||
@@ -430,12 +538,23 @@ def validate_compose_security(
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
# Declared top-level named volume without path separators
|
# 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
|
continue
|
||||||
|
|
||||||
# Undeclared named volumes or bare identifiers not starting with ., /, ~ or containing / are prohibited
|
# 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):
|
if not (
|
||||||
return False, f"Service '{svc_name}' specifies undeclared named volume or ambiguous path: '{host_path}'."
|
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
|
# Host bind mount evaluation
|
||||||
if host_path.startswith("~"):
|
if host_path.startswith("~"):
|
||||||
@@ -447,16 +566,20 @@ def validate_compose_security(
|
|||||||
expanded = (allowed_root / host_path).resolve()
|
expanded = (allowed_root / host_path).resolve()
|
||||||
|
|
||||||
# Containment check: strictly within workload directory or dedicated state root
|
# 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)
|
is_in_own_state = expanded.is_relative_to(target_state_root)
|
||||||
|
|
||||||
if not (is_in_workload or is_in_own_state):
|
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
|
return True, None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]:
|
def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]:
|
||||||
"""
|
"""
|
||||||
Validate deployment policy inside app.yaml.
|
Validate deployment policy inside app.yaml.
|
||||||
@@ -472,7 +595,10 @@ def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]:
|
|||||||
# Validate strategy if specified
|
# Validate strategy if specified
|
||||||
strategy = deployment.get("strategy")
|
strategy = deployment.get("strategy")
|
||||||
if strategy is not None and strategy not in ALLOWED_STRATEGIES:
|
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
|
# Validate actions if specified
|
||||||
actions = deployment.get("actions")
|
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."
|
return False, "Field 'deployment.actions' must be a list of strings."
|
||||||
for action in actions:
|
for action in actions:
|
||||||
if not isinstance(action, str) or action not in ALLOWED_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, ""
|
return True, ""
|
||||||
|
|
||||||
@@ -496,18 +625,26 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
|||||||
"""
|
"""
|
||||||
expected_branch = deployment_config.get("branch", "main")
|
expected_branch = deployment_config.get("branch", "main")
|
||||||
if branch and branch != expected_branch:
|
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
|
return True
|
||||||
|
|
||||||
canonical_app_name = target_dir.name.removeprefix("homelab-")
|
canonical_app_name = target_dir.name.removeprefix("homelab-")
|
||||||
manifest_file = target_dir / "app.yaml"
|
manifest_file = target_dir / "app.yaml"
|
||||||
if manifest_file.is_file():
|
if manifest_file.is_file():
|
||||||
with contextlib.suppress(Exception):
|
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"):
|
if isinstance(pre_manifest, dict) and pre_manifest.get("name"):
|
||||||
canonical_app_name = str(pre_manifest["name"]).strip()
|
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"])
|
actions = deployment_config.get("actions", ["git_pull"])
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -517,8 +654,16 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
|||||||
if action == "git_pull":
|
if action == "git_pull":
|
||||||
logger.info(f" ↳ [git_pull] Pulling latest '{expected_branch}'...")
|
logger.info(f" ↳ [git_pull] Pulling latest '{expected_branch}'...")
|
||||||
subprocess.run(
|
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:
|
# Revision-consistent manifest validation:
|
||||||
# The working tree has now advanced to the deployed revision.
|
# 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():
|
if manifest_file.is_file():
|
||||||
try:
|
try:
|
||||||
manifest_text = manifest_file.read_text(encoding="utf-8")
|
manifest_text = manifest_file.read_text(encoding="utf-8")
|
||||||
fresh_manifest = (yaml.safe_load(manifest_text) if yaml else parse_yaml_simple(manifest_text)) or {}
|
fresh_manifest = (
|
||||||
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
yaml.safe_load(manifest_text)
|
||||||
logger.error(f"❌ Post-pull manifest parse failure in {manifest_file}: {e}")
|
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
|
return False
|
||||||
|
|
||||||
valid, err_msg = validate_manifest_deployment(fresh_manifest)
|
valid, err_msg = validate_manifest_deployment(fresh_manifest)
|
||||||
if not valid:
|
if not valid:
|
||||||
logger.error(f"❌ Post-pull manifest validation failed for '{target_dir.name}': {err_msg}")
|
logger.error(
|
||||||
|
f"❌ Post-pull manifest validation failed for '{target_dir.name}': {err_msg}"
|
||||||
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if isinstance(fresh_manifest, dict) and fresh_manifest.get("name"):
|
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():
|
if not compose_file.is_file():
|
||||||
compose_file = target_dir / "docker-compose.yaml"
|
compose_file = target_dir / "docker-compose.yaml"
|
||||||
if compose_file.is_file():
|
if compose_file.is_file():
|
||||||
valid_sec, sec_err = validate_compose_security(compose_file, target_dir, 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:
|
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
|
return False
|
||||||
logger.info(" ↳ [compose_up] Recreating containers (docker compose up -d)...")
|
logger.info(
|
||||||
|
" ↳ [compose_up] Recreating containers (docker compose up -d)..."
|
||||||
|
)
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"],
|
[
|
||||||
check=True
|
"docker",
|
||||||
|
"compose",
|
||||||
|
"-f",
|
||||||
|
str(compose_file),
|
||||||
|
"up",
|
||||||
|
"-d",
|
||||||
|
"--remove-orphans",
|
||||||
|
],
|
||||||
|
check=True,
|
||||||
)
|
)
|
||||||
elif action == "compose_build":
|
elif action == "compose_build":
|
||||||
compose_file = target_dir / "docker-compose.yml"
|
compose_file = target_dir / "docker-compose.yml"
|
||||||
if not compose_file.is_file():
|
if not compose_file.is_file():
|
||||||
compose_file = target_dir / "docker-compose.yaml"
|
compose_file = target_dir / "docker-compose.yaml"
|
||||||
if compose_file.is_file():
|
if compose_file.is_file():
|
||||||
valid_sec, sec_err = validate_compose_security(compose_file, target_dir, 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:
|
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
|
return False
|
||||||
logger.info(" ↳ [compose_build] Building & recreating containers...")
|
logger.info(
|
||||||
subprocess.run(
|
" ↳ [compose_build] Building & recreating containers..."
|
||||||
["docker", "compose", "-f", str(compose_file), "build"],
|
|
||||||
check=True
|
|
||||||
)
|
)
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"],
|
["docker", "compose", "-f", str(compose_file), "build"],
|
||||||
check=True
|
check=True,
|
||||||
|
)
|
||||||
|
subprocess.run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"compose",
|
||||||
|
"-f",
|
||||||
|
str(compose_file),
|
||||||
|
"up",
|
||||||
|
"-d",
|
||||||
|
"--remove-orphans",
|
||||||
|
],
|
||||||
|
check=True,
|
||||||
)
|
)
|
||||||
elif action == "compose_restart":
|
elif action == "compose_restart":
|
||||||
compose_file = target_dir / "docker-compose.yml"
|
compose_file = target_dir / "docker-compose.yml"
|
||||||
if not compose_file.is_file():
|
if not compose_file.is_file():
|
||||||
compose_file = target_dir / "docker-compose.yaml"
|
compose_file = target_dir / "docker-compose.yaml"
|
||||||
if compose_file.is_file():
|
if compose_file.is_file():
|
||||||
valid_sec, sec_err = validate_compose_security(compose_file, target_dir, 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:
|
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
|
return False
|
||||||
logger.info(" ↳ [compose_restart] Restarting containers...")
|
logger.info(" ↳ [compose_restart] Restarting containers...")
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
["docker", "compose", "-f", str(compose_file), "restart"],
|
["docker", "compose", "-f", str(compose_file), "restart"],
|
||||||
check=True
|
check=True,
|
||||||
)
|
)
|
||||||
else:
|
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
|
return False
|
||||||
|
|
||||||
idx += 1
|
idx += 1
|
||||||
@@ -611,14 +804,20 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
|||||||
except subprocess.CalledProcessError as e:
|
except subprocess.CalledProcessError as e:
|
||||||
logger.error(f"❌ Deployment step failed with exit code {e.returncode}: {e}")
|
logger.error(f"❌ Deployment step failed with exit code {e.returncode}: {e}")
|
||||||
return False
|
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}")
|
logger.error(f"❌ Unexpected deployment error: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def admit_deployment(
|
def admit_deployment(
|
||||||
payload: dict,
|
payload: dict, event_type: str | None = None
|
||||||
event_type: str | None = None
|
|
||||||
) -> tuple[bool, Path | None, dict, str, str]:
|
) -> tuple[bool, Path | None, dict, str, str]:
|
||||||
"""
|
"""
|
||||||
Evaluate webhook deployment admission against strict policy gates:
|
Evaluate webhook deployment admission against strict policy gates:
|
||||||
@@ -632,10 +831,22 @@ def admit_deployment(
|
|||||||
"""
|
"""
|
||||||
# 1. Event Admission
|
# 1. Event Admission
|
||||||
if event_type and event_type.strip().lower() != "push":
|
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:
|
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
|
# 2. Ref Admission
|
||||||
ref = payload.get("ref", "")
|
ref = payload.get("ref", "")
|
||||||
@@ -646,7 +857,13 @@ def admit_deployment(
|
|||||||
return False, None, {}, "", f"Tag push '{ref}' is not deployable."
|
return False, None, {}, "", f"Tag push '{ref}' is not deployable."
|
||||||
|
|
||||||
if not ref.startswith("refs/heads/"):
|
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/")
|
pushed_branch = ref.removeprefix("refs/heads/")
|
||||||
if not pushed_branch:
|
if not pushed_branch:
|
||||||
@@ -655,16 +872,34 @@ def admit_deployment(
|
|||||||
# 3. Repository Admission
|
# 3. Repository Admission
|
||||||
repo_field = payload.get("repository")
|
repo_field = payload.get("repository")
|
||||||
if not isinstance(repo_field, dict):
|
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")
|
repo_name = repo_field.get("name")
|
||||||
if not isinstance(repo_name, str) or not repo_name.strip():
|
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()
|
repo_name = repo_name.strip()
|
||||||
target_dir = resolve_repository(repo_name)
|
target_dir = resolve_repository(repo_name)
|
||||||
if not target_dir:
|
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
|
# 4. Manifest & Strategy Validation
|
||||||
manifest_file = target_dir / "app.yaml"
|
manifest_file = target_dir / "app.yaml"
|
||||||
@@ -672,30 +907,55 @@ def admit_deployment(
|
|||||||
if manifest_file.is_file():
|
if manifest_file.is_file():
|
||||||
try:
|
try:
|
||||||
manifest_text = manifest_file.read_text(encoding="utf-8")
|
manifest_text = manifest_file.read_text(encoding="utf-8")
|
||||||
manifest = (yaml.safe_load(manifest_text) if yaml else parse_yaml_simple(manifest_text)) or {}
|
manifest = (
|
||||||
|
yaml.safe_load(manifest_text)
|
||||||
|
if yaml
|
||||||
|
else parse_yaml_simple(manifest_text)
|
||||||
|
) or {}
|
||||||
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
||||||
return False, None, {}, pushed_branch, f"Failed to parse manifest {manifest_file}: {e}"
|
return (
|
||||||
|
False,
|
||||||
|
None,
|
||||||
|
{},
|
||||||
|
pushed_branch,
|
||||||
|
f"Failed to parse manifest {manifest_file}: {e}",
|
||||||
|
)
|
||||||
|
|
||||||
valid, err_msg = validate_manifest_deployment(manifest)
|
valid, err_msg = validate_manifest_deployment(manifest)
|
||||||
if not valid:
|
if not valid:
|
||||||
return False, None, {}, pushed_branch, f"Manifest validation error: {err_msg}"
|
return (
|
||||||
|
False,
|
||||||
|
None,
|
||||||
|
{},
|
||||||
|
pushed_branch,
|
||||||
|
f"Manifest validation error: {err_msg}",
|
||||||
|
)
|
||||||
|
|
||||||
deployment_config = manifest.get("deployment")
|
deployment_config = manifest.get("deployment")
|
||||||
if not isinstance(deployment_config, dict):
|
if not isinstance(deployment_config, dict):
|
||||||
deployment_config = {
|
deployment_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
|
||||||
"branch": "main",
|
|
||||||
"actions": ["git_pull", "compose_up"]
|
|
||||||
}
|
|
||||||
|
|
||||||
# 5. Branch Policy Admission
|
# 5. Branch Policy Admission
|
||||||
expected_branch = deployment_config.get("branch", "main")
|
expected_branch = deployment_config.get("branch", "main")
|
||||||
if pushed_branch != expected_branch:
|
if pushed_branch != expected_branch:
|
||||||
return False, target_dir, deployment_config, pushed_branch, (
|
return (
|
||||||
|
False,
|
||||||
|
target_dir,
|
||||||
|
deployment_config,
|
||||||
|
pushed_branch,
|
||||||
|
(
|
||||||
f"Branch mismatch: pushed branch '{pushed_branch}' does not match "
|
f"Branch mismatch: pushed branch '{pushed_branch}' does not match "
|
||||||
f"declared target branch '{expected_branch}'."
|
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:
|
def get_target_lock(target_name: str) -> Path:
|
||||||
@@ -709,10 +969,7 @@ def get_pending_file(target_name: str) -> Path:
|
|||||||
|
|
||||||
|
|
||||||
def enqueue_deployment(
|
def enqueue_deployment(
|
||||||
target_dir: Path,
|
target_dir: Path, deployment_config: dict, branch: str, commit_sha: str = ""
|
||||||
deployment_config: dict,
|
|
||||||
branch: str,
|
|
||||||
commit_sha: str = ""
|
|
||||||
) -> Path:
|
) -> Path:
|
||||||
"""
|
"""
|
||||||
Atomically enqueue a deployment request.
|
Atomically enqueue a deployment request.
|
||||||
@@ -732,7 +989,9 @@ def enqueue_deployment(
|
|||||||
|
|
||||||
temp_file.write_text(json.dumps(data), encoding="utf-8")
|
temp_file.write_text(json.dumps(data), encoding="utf-8")
|
||||||
temp_file.replace(pending_file)
|
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
|
return pending_file
|
||||||
|
|
||||||
|
|
||||||
@@ -749,7 +1008,9 @@ def run_target_worker(target_name: str) -> bool:
|
|||||||
try:
|
try:
|
||||||
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
except (BlockingIOError, OSError):
|
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
|
return True
|
||||||
|
|
||||||
overall_success = True
|
overall_success = True
|
||||||
@@ -783,9 +1044,13 @@ def run_target_worker(target_name: str) -> bool:
|
|||||||
"success": success,
|
"success": success,
|
||||||
"timestamp": datetime.datetime.now(datetime.UTC).isoformat(),
|
"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:
|
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:
|
if not success:
|
||||||
overall_success = False
|
overall_success = False
|
||||||
@@ -804,7 +1069,7 @@ def spawn_worker_async(target_name: str):
|
|||||||
cmd,
|
cmd,
|
||||||
stdout=subprocess.DEVNULL,
|
stdout=subprocess.DEVNULL,
|
||||||
stderr=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")
|
b_idx = sys.argv.index("--branch")
|
||||||
if b_idx + 1 < len(sys.argv):
|
if b_idx + 1 < len(sys.argv):
|
||||||
branch = sys.argv[b_idx + 1].replace("refs/heads/", "")
|
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)
|
target_dir, deployment_config = resolve_target(repo_name)
|
||||||
if not target_dir or not target_dir.is_dir():
|
if not target_dir or not target_dir.is_dir():
|
||||||
logger.error(f"Target repository '{repo_name}' could not be resolved.")
|
logger.error(f"Target repository '{repo_name}' could not be resolved.")
|
||||||
@@ -887,21 +1154,27 @@ def main():
|
|||||||
logger.error(f"Invalid JSON payload: {e}")
|
logger.error(f"Invalid JSON payload: {e}")
|
||||||
sys.exit(1)
|
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:
|
if not admitted:
|
||||||
logger.warning(f"🚫 Webhook admission rejected: {reason}")
|
logger.warning(f"🚫 Webhook admission rejected: {reason}")
|
||||||
# Branch mismatch on valid push is benign skip; other violations fail closed
|
# Branch mismatch on valid push is benign skip; other violations fail closed
|
||||||
sys.exit(0 if "Branch mismatch" in reason else 1)
|
sys.exit(0 if "Branch mismatch" in reason else 1)
|
||||||
|
|
||||||
logger.info(f"✅ Webhook admission passed: {reason}")
|
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", "")
|
commit_sha = payload.get("after", "")
|
||||||
if not commit_sha and isinstance(payload.get("head_commit"), dict):
|
if not commit_sha and isinstance(payload.get("head_commit"), dict):
|
||||||
commit_sha = payload.get("head_commit", {}).get("id", "")
|
commit_sha = payload.get("head_commit", {}).get("id", "")
|
||||||
|
|
||||||
enqueue_deployment(target_dir, deployment_config, branch, commit_sha=commit_sha)
|
enqueue_deployment(target_dir, deployment_config, branch, commit_sha=commit_sha)
|
||||||
spawn_worker_async(target_dir.name)
|
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)
|
sys.exit(0)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+14
-8
@@ -19,6 +19,7 @@ from core_manifest import Manifest, RefType, SourceConfig
|
|||||||
|
|
||||||
class ProvenanceStatus(str, Enum):
|
class ProvenanceStatus(str, Enum):
|
||||||
"""Evaluation result of local state vs. upstream software provenance."""
|
"""Evaluation result of local state vs. upstream software provenance."""
|
||||||
|
|
||||||
SYNCED = "✓ Synced"
|
SYNCED = "✓ Synced"
|
||||||
UPDATE_AVAILABLE = "↓ Update Available"
|
UPDATE_AVAILABLE = "↓ Update Available"
|
||||||
IMAGE_ONLY = "— Image-Only (Class B)"
|
IMAGE_ONLY = "— Image-Only (Class B)"
|
||||||
@@ -32,6 +33,7 @@ class ProvenanceStatus(str, Enum):
|
|||||||
@dataclass
|
@dataclass
|
||||||
class CheckoutStatus:
|
class CheckoutStatus:
|
||||||
"""Axis 1: Local deployment checkout state."""
|
"""Axis 1: Local deployment checkout state."""
|
||||||
|
|
||||||
is_git: bool
|
is_git: bool
|
||||||
is_dirty: bool
|
is_dirty: bool
|
||||||
branch: str
|
branch: str
|
||||||
@@ -51,6 +53,7 @@ class CheckoutStatus:
|
|||||||
@dataclass
|
@dataclass
|
||||||
class UpstreamProvenance:
|
class UpstreamProvenance:
|
||||||
"""Axis 2: Upstream software provenance state."""
|
"""Axis 2: Upstream software provenance state."""
|
||||||
|
|
||||||
status: ProvenanceStatus
|
status: ProvenanceStatus
|
||||||
remote_sha: str = ""
|
remote_sha: str = ""
|
||||||
target_ref: str = ""
|
target_ref: str = ""
|
||||||
@@ -68,6 +71,7 @@ class UpstreamProvenance:
|
|||||||
@dataclass
|
@dataclass
|
||||||
class TwoAxisStatus:
|
class TwoAxisStatus:
|
||||||
"""Unified inspection combining local deployment and upstream provenance."""
|
"""Unified inspection combining local deployment and upstream provenance."""
|
||||||
|
|
||||||
app_name: str
|
app_name: str
|
||||||
checkout: CheckoutStatus
|
checkout: CheckoutStatus
|
||||||
provenance: UpstreamProvenance
|
provenance: UpstreamProvenance
|
||||||
@@ -198,12 +202,12 @@ def resolve_upstream_provenance(
|
|||||||
|
|
||||||
# Commits pinned directly in manifest cannot be checked via ls-remote ref matching
|
# Commits pinned directly in manifest cannot be checked via ls-remote ref matching
|
||||||
if source.ref_type == RefType.COMMIT:
|
if source.ref_type == RefType.COMMIT:
|
||||||
is_match = (
|
is_match = local_commit and (
|
||||||
local_commit and (
|
|
||||||
source.ref.startswith(local_commit) or local_commit.startswith(source.ref)
|
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(
|
return UpstreamProvenance(
|
||||||
status=status,
|
status=status,
|
||||||
remote_sha=source.ref,
|
remote_sha=source.ref,
|
||||||
@@ -248,10 +252,10 @@ def resolve_upstream_provenance(
|
|||||||
for line in proc.stdout.splitlines():
|
for line in proc.stdout.splitlines():
|
||||||
parts = line.strip().split()
|
parts = line.strip().split()
|
||||||
if len(parts) >= 2 and (
|
if len(parts) >= 2 and (
|
||||||
parts[1] == target_ref or
|
parts[1] == target_ref
|
||||||
parts[1] == f"refs/heads/{target_ref}" or
|
or parts[1] == f"refs/heads/{target_ref}"
|
||||||
parts[1] == f"refs/tags/{target_ref}" or
|
or parts[1] == f"refs/tags/{target_ref}"
|
||||||
parts[1] == f"refs/tags/{target_ref}^{{}}"
|
or parts[1] == f"refs/tags/{target_ref}^{{}}"
|
||||||
):
|
):
|
||||||
remote_sha = parts[0]
|
remote_sha = parts[0]
|
||||||
# Peaked tags (^{}) take precedence over lightweight tag refs
|
# Peaked tags (^{}) take precedence over lightweight tag refs
|
||||||
@@ -271,7 +275,9 @@ def resolve_upstream_provenance(
|
|||||||
|
|
||||||
# Compare local commit with remote SHA
|
# Compare local commit with remote SHA
|
||||||
is_synced = False
|
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
|
is_synced = True
|
||||||
|
|
||||||
status = ProvenanceStatus.SYNCED if is_synced else ProvenanceStatus.UPDATE_AVAILABLE
|
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 json
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import gitops_dispatcher
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
# Add Core to path so scripts can be imported
|
# Add Core to path so scripts can be imported
|
||||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
# Comment-out reason: testing pyproject-level pythonpath definition
|
||||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||||
|
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||||
import gitops_dispatcher
|
|
||||||
|
|
||||||
|
|
||||||
def test_custom_shell_action_is_rejected_without_execution(tmp_path: Path):
|
def test_custom_shell_action_is_rejected_without_execution(tmp_path: Path):
|
||||||
"""Ensure that arbitrary 'custom' actions fail closed and never invoke a shell."""
|
"""Ensure that arbitrary 'custom' actions fail closed and never invoke a shell."""
|
||||||
deployment_config = {
|
deployment_config = {"branch": "main", "actions": [{"custom": "touch /tmp/pwned"}]}
|
||||||
"branch": "main",
|
|
||||||
"actions": [
|
|
||||||
{"custom": "touch /tmp/pwned"}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
with patch("subprocess.run") as mock_run:
|
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()
|
mock_run.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
def test_unknown_action_is_rejected(tmp_path: Path):
|
def test_unknown_action_is_rejected(tmp_path: Path):
|
||||||
"""Ensure that unknown action strings fail closed and abort deployment."""
|
"""Ensure that unknown action strings fail closed and abort deployment."""
|
||||||
deployment_config = {
|
deployment_config = {"branch": "main", "actions": ["malicious_or_unknown_action"]}
|
||||||
"branch": "main",
|
|
||||||
"actions": ["malicious_or_unknown_action"]
|
|
||||||
}
|
|
||||||
|
|
||||||
with patch("subprocess.run") as mock_run:
|
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"
|
assert success is False, "execute_deployment must reject unknown actions"
|
||||||
mock_run.assert_not_called()
|
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):
|
def test_allowed_actions_use_safe_argument_lists(tmp_path: Path):
|
||||||
"""Ensure that allowed actions execute safely via argument lists without shell=True."""
|
"""Ensure that allowed actions execute safely via argument lists without shell=True."""
|
||||||
deployment_config = {
|
deployment_config = {"branch": "main", "actions": ["git_pull"]}
|
||||||
"branch": "main",
|
|
||||||
"actions": ["git_pull"]
|
|
||||||
}
|
|
||||||
|
|
||||||
with patch("subprocess.run") as mock_run:
|
with patch("subprocess.run") as mock_run:
|
||||||
mock_run.return_value = MagicMock(returncode=0)
|
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
|
assert success is True
|
||||||
mock_run.assert_called_once()
|
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:
|
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):
|
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 = sites_dir / "homelab-docs"
|
||||||
app_dir.mkdir(parents=True)
|
app_dir.mkdir(parents=True)
|
||||||
(app_dir / "app.yaml").write_text(
|
(app_dir / "app.yaml").write_text(
|
||||||
"name: docs\naliases:\n - doc2site\n - notes\n",
|
"name: docs\naliases:\n - doc2site\n - notes\n", encoding="utf-8"
|
||||||
encoding="utf-8"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
registry = tmp_path / "deployments.yaml"
|
registry = tmp_path / "deployments.yaml"
|
||||||
registry.write_text(
|
registry.write_text(
|
||||||
f'schemaVersion: "1.0"\nrepositories:\n homelab-docs:\n path: "{app_dir}"\n aliases:\n - docs\n - doc2site\n - notes\n',
|
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)
|
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
|
assert gitops_dispatcher.resolve_repository("notes") == canonical
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_resolve_repository_rejects_vault(tmp_path: Path, monkeypatch):
|
def test_resolve_repository_rejects_vault(tmp_path: Path, monkeypatch):
|
||||||
"""Ensure data vault identities (Brain / second-brain) are not recognized by GitOps."""
|
"""Ensure data vault identities (Brain / second-brain) are not recognized by GitOps."""
|
||||||
sites_dir = tmp_path / "Sites"
|
sites_dir = tmp_path / "Sites"
|
||||||
@@ -189,7 +185,9 @@ repositories:
|
|||||||
assert "escaped-app" not in mapping
|
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."""
|
"""Ensure unregistered directories in ~/Sites cannot be resolved when deployments.yaml is active."""
|
||||||
sites_dir = tmp_path / "Sites"
|
sites_dir = tmp_path / "Sites"
|
||||||
registered_dir = sites_dir / "homelab-docs"
|
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"
|
missing_registry = tmp_path / "nonexistent-deployments.yaml"
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", missing_registry)
|
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
|
# Missing registry must fail closed: empty mapping, no resolution
|
||||||
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
|
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 YAML registry must also fail closed
|
||||||
corrupt_registry = tmp_path / "corrupt-deployments.yaml"
|
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)
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", corrupt_registry)
|
||||||
|
|
||||||
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
|
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
|
||||||
assert gitops_dispatcher.resolve_repository("valid") is None
|
assert gitops_dispatcher.resolve_repository("valid") is None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_webhook_verification_valid_signature():
|
def test_webhook_verification_valid_signature():
|
||||||
"""Ensure valid HMAC-SHA256 signature passes verification."""
|
"""Ensure valid HMAC-SHA256 signature passes verification."""
|
||||||
import hashlib
|
import hashlib
|
||||||
@@ -251,7 +252,10 @@ def test_webhook_verification_valid_signature():
|
|||||||
|
|
||||||
assert gitops_dispatcher.verify_signature(body, expected_hex, secret) is True
|
assert gitops_dispatcher.verify_signature(body, expected_hex, secret) is True
|
||||||
# Support sha256= prefix as well
|
# 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():
|
def test_webhook_verification_invalid_signature():
|
||||||
@@ -316,7 +320,10 @@ def test_webhook_verification_malformed_signature():
|
|||||||
secret = b"supersecrettoken123"
|
secret = b"supersecrettoken123"
|
||||||
body = b'{"repository": {"name": "docs"}}'
|
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, "deadbeef", secret) is False
|
||||||
assert gitops_dispatcher.verify_signature(body, "z" * 64, 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 = {
|
payload_pr = {
|
||||||
"ref": "refs/heads/main",
|
"ref": "refs/heads/main",
|
||||||
"repository": {"name": "docs"},
|
"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 admitted is False
|
||||||
assert "non-push event" in reason
|
assert "non-push event" in reason
|
||||||
|
|
||||||
payload_normal = {
|
payload_normal = {"ref": "refs/heads/main", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/heads/main",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
payload_normal, event_type="pull_request"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload_normal, event_type="pull_request")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "Only 'push' is allowed" in reason
|
assert "Only 'push' is allowed" in reason
|
||||||
|
|
||||||
|
|
||||||
def test_admission_rejects_tags_and_invalid_refs():
|
def test_admission_rejects_tags_and_invalid_refs():
|
||||||
"""Ensure tags or invalid ref structures are rejected from deployment."""
|
"""Ensure tags or invalid ref structures are rejected from deployment."""
|
||||||
tag_payload = {
|
tag_payload = {"ref": "refs/tags/v1.0.0", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/tags/v1.0.0",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
tag_payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(tag_payload, event_type="push")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "Tag push" in reason
|
assert "Tag push" in reason
|
||||||
|
|
||||||
non_head_payload = {
|
non_head_payload = {"ref": "refs/pull/42/head", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/pull/42/head",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
non_head_payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(non_head_payload, event_type="push")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "not a head branch" in reason
|
assert "not a head branch" in reason
|
||||||
|
|
||||||
@@ -366,11 +372,10 @@ def test_admission_rejects_unknown_repository(tmp_path: Path, monkeypatch):
|
|||||||
sites_dir.mkdir()
|
sites_dir.mkdir()
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
|
||||||
payload = {
|
payload = {"ref": "refs/heads/main", "repository": {"name": "unregistered-app"}}
|
||||||
"ref": "refs/heads/main",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "unregistered-app"}
|
payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "not recognized" in reason
|
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 = sites_dir / "homelab-docs"
|
||||||
app_dir.mkdir(parents=True)
|
app_dir.mkdir(parents=True)
|
||||||
(app_dir / "app.yaml").write_text(
|
(app_dir / "app.yaml").write_text(
|
||||||
"name: docs\ndeployment:\n branch: production\n",
|
"name: docs\ndeployment:\n branch: production\n", encoding="utf-8"
|
||||||
encoding="utf-8"
|
|
||||||
)
|
)
|
||||||
registry = tmp_path / "deployments.yaml"
|
registry = tmp_path / "deployments.yaml"
|
||||||
registry.write_text(
|
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, "SITES_DIR", sites_dir)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {"ref": "refs/heads/staging", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/heads/staging",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "Branch mismatch" in reason
|
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.mkdir(parents=True)
|
||||||
(app_dir / "app.yaml").write_text(
|
(app_dir / "app.yaml").write_text(
|
||||||
"name: docs\ndeployment:\n branch: main\n strategy: kubernetes\n",
|
"name: docs\ndeployment:\n branch: main\n strategy: kubernetes\n",
|
||||||
encoding="utf-8"
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
registry = tmp_path / "deployments.yaml"
|
registry = tmp_path / "deployments.yaml"
|
||||||
registry.write_text(
|
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, "SITES_DIR", sites_dir)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {"ref": "refs/heads/main", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/heads/main",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "Unsupported deployment strategy" in reason
|
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.mkdir(parents=True)
|
||||||
(app_dir / "app.yaml").write_text(
|
(app_dir / "app.yaml").write_text(
|
||||||
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n",
|
"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 = tmp_path / "deployments.yaml"
|
||||||
registry.write_text(
|
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, "SITES_DIR", sites_dir)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {"ref": "refs/heads/main", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/heads/main",
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
|
||||||
assert admitted is False
|
assert admitted is False
|
||||||
assert "Unsupported deployment action" in reason
|
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.mkdir(parents=True)
|
||||||
(app_dir / "app.yaml").write_text(
|
(app_dir / "app.yaml").write_text(
|
||||||
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n",
|
"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 = tmp_path / "deployments.yaml"
|
||||||
registry.write_text(
|
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, "SITES_DIR", sites_dir)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {"ref": "refs/heads/main", "repository": {"name": "docs"}}
|
||||||
"ref": "refs/heads/main",
|
admitted, target_dir, config, branch, reason = gitops_dispatcher.admit_deployment(
|
||||||
"repository": {"name": "docs"}
|
payload, event_type="push"
|
||||||
}
|
)
|
||||||
admitted, target_dir, config, branch, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
|
||||||
assert admitted is True
|
assert admitted is True
|
||||||
|
|
||||||
assert "Admitted" in reason
|
assert "Admitted" in reason
|
||||||
@@ -492,16 +492,22 @@ def test_enqueue_supersedes_pending_revision(tmp_path: Path, monkeypatch):
|
|||||||
target_dir.mkdir()
|
target_dir.mkdir()
|
||||||
|
|
||||||
# Enqueue revision A
|
# 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")
|
pending_file = gitops_dispatcher.get_pending_file("app")
|
||||||
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "A"
|
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "A"
|
||||||
|
|
||||||
# Enqueue revision B (supersedes 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"
|
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "B"
|
||||||
|
|
||||||
# Enqueue revision C (supersedes 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"
|
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)
|
monkeypatch.setattr(gitops_dispatcher, "execute_deployment", mock_execute)
|
||||||
|
|
||||||
# 1. Enqueue A
|
# 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)
|
# 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()
|
worker_thread.start()
|
||||||
|
|
||||||
# Wait for A to start executing
|
# Wait for A to start executing
|
||||||
assert a_started_event.wait(timeout=2.0) is True
|
assert a_started_event.wait(timeout=2.0) is True
|
||||||
|
|
||||||
# 2. B arrives while A is running
|
# 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)
|
# 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
|
# Let A complete
|
||||||
b_and_c_enqueued_event.set()
|
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)
|
worker_thread.join(timeout=3.0)
|
||||||
|
|
||||||
# Verification: A was executed, B was superseded/skipped, C was executed!
|
# 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):
|
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 = tmp_path / "app"
|
||||||
app_dir.mkdir()
|
app_dir.mkdir()
|
||||||
manifest_file = app_dir / "app.yaml"
|
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")
|
manifest_file.write_text(
|
||||||
(app_dir / "docker-compose.yml").write_text("version: '3'\nservices:\n web:\n image: nginx\n")
|
"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 = {
|
initial_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
|
||||||
"branch": "main",
|
|
||||||
"actions": ["git_pull", "compose_up"]
|
|
||||||
}
|
|
||||||
|
|
||||||
def mock_pull(cmd, check=True):
|
def mock_pull(cmd, check=True):
|
||||||
if "pull" in cmd:
|
if "pull" in cmd:
|
||||||
# Simulate git pull bringing in an invalid action in app.yaml
|
# 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)
|
return MagicMock(returncode=0)
|
||||||
|
|
||||||
with patch("subprocess.run", side_effect=mock_pull) as mock_run:
|
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!
|
# Only git pull was called; compose_up was never reached!
|
||||||
calls = [c[0][0] for c in mock_run.call_args_list]
|
calls = [c[0][0] for c in mock_run.call_args_list]
|
||||||
assert len(calls) == 1
|
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 = tmp_path / "app"
|
||||||
app_dir.mkdir()
|
app_dir.mkdir()
|
||||||
manifest_file = app_dir / "app.yaml"
|
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")
|
manifest_file.write_text(
|
||||||
(app_dir / "docker-compose.yml").write_text("version: '3'\nservices:\n web:\n image: nginx\n")
|
"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 = {
|
initial_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
|
||||||
"branch": "main",
|
|
||||||
"actions": ["git_pull", "compose_up"]
|
|
||||||
}
|
|
||||||
|
|
||||||
def mock_pull(cmd, check=True):
|
def mock_pull(cmd, check=True):
|
||||||
if "pull" in cmd:
|
if "pull" in cmd:
|
||||||
# Simulate git pull bringing in an app.yaml that targets 'staging', not 'main'
|
# 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)
|
return MagicMock(returncode=0)
|
||||||
|
|
||||||
with patch("subprocess.run", side_effect=mock_pull) as mock_run:
|
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]
|
calls = [c[0][0] for c in mock_run.call_args_list]
|
||||||
assert len(calls) == 1
|
assert len(calls) == 1
|
||||||
assert "pull" in calls[0]
|
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 = tmp_path / "app"
|
||||||
app_dir.mkdir()
|
app_dir.mkdir()
|
||||||
manifest_file = app_dir / "app.yaml"
|
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")
|
manifest_file.write_text(
|
||||||
(app_dir / "docker-compose.yml").write_text("version: '3'\nservices:\n web:\n image: nginx\n")
|
"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 = {
|
initial_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
|
||||||
"branch": "main",
|
|
||||||
"actions": ["git_pull", "compose_up"]
|
|
||||||
}
|
|
||||||
|
|
||||||
def mock_pull(cmd, check=True):
|
def mock_pull(cmd, check=True):
|
||||||
if "pull" in cmd:
|
if "pull" in cmd:
|
||||||
# Revision updates action to compose_build
|
# 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)
|
return MagicMock(returncode=0)
|
||||||
|
|
||||||
with patch("subprocess.run", side_effect=mock_pull) as mock_run:
|
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
|
assert success is True
|
||||||
calls = [c[0][0] for c in mock_run.call_args_list]
|
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)
|
monkeypatch.setattr(gitops_dispatcher, "execute_deployment", lambda t, c, b: True)
|
||||||
|
|
||||||
gitops_dispatcher.enqueue_deployment(
|
gitops_dispatcher.enqueue_deployment(
|
||||||
target_dir,
|
target_dir, {"branch": "main"}, "main", commit_sha="abcdef123456"
|
||||||
{"branch": "main"},
|
|
||||||
"main",
|
|
||||||
commit_sha="abcdef123456"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
success = gitops_dispatcher.run_target_worker("app")
|
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):
|
def test_validate_compose_security_rejects_privileged(tmp_path: Path):
|
||||||
"""Ensure docker-compose with privileged: true fails pre-flight validation."""
|
"""Ensure docker-compose with privileged: true fails pre-flight validation."""
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine:latest
|
image: alpine:latest
|
||||||
privileged: true
|
privileged: true
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "privileged: true" in err
|
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."""
|
"""Ensure docker-compose with /var/run/docker.sock mount fails validation."""
|
||||||
# Test string syntax
|
# Test string syntax
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine:latest
|
image: alpine:latest
|
||||||
volumes:
|
volumes:
|
||||||
- /var/run/docker.sock:/var/run/docker.sock
|
- /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)
|
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "Docker socket" in err
|
assert err is not None and "Docker socket" in err
|
||||||
|
|
||||||
# Test dict / long syntax
|
# Test dict / long syntax
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine:latest
|
image: alpine:latest
|
||||||
@@ -725,7 +764,9 @@ services:
|
|||||||
- type: bind
|
- type: bind
|
||||||
source: /var/run/docker.sock
|
source: /var/run/docker.sock
|
||||||
target: /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)
|
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "Docker socket" in err
|
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):
|
def test_validate_compose_security_rejects_host_network(tmp_path: Path):
|
||||||
"""Ensure docker-compose with network_mode: host fails pre-flight validation."""
|
"""Ensure docker-compose with network_mode: host fails pre-flight validation."""
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine:latest
|
image: alpine:latest
|
||||||
network_mode: host
|
network_mode: host
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "network_mode: host" in err
|
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):
|
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."""
|
"""Ensure host bind mounts outside workload directory or state root are rejected."""
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine:latest
|
image: alpine:latest
|
||||||
volumes:
|
volumes:
|
||||||
- /etc/shadow:/etc/shadow:ro
|
- /etc/shadow:/etc/shadow:ro
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
||||||
assert valid is False
|
assert valid is False
|
||||||
assert err is not None and "prohibited host bind mount" in err
|
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 = tmp_path / "data"
|
||||||
data_dir.mkdir()
|
data_dir.mkdir()
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text(f"""
|
compose_file.write_text(
|
||||||
|
f"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine:latest
|
image: alpine:latest
|
||||||
@@ -774,7 +822,9 @@ services:
|
|||||||
- named_vol:/var/log
|
- named_vol:/var/log
|
||||||
volumes:
|
volumes:
|
||||||
named_vol:
|
named_vol:
|
||||||
""", encoding="utf-8")
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
|
||||||
assert valid is True
|
assert valid is True
|
||||||
assert err is None
|
assert err is None
|
||||||
@@ -788,11 +838,14 @@ def test_validate_compose_security_nonexistent_file(tmp_path: Path):
|
|||||||
assert err is None
|
assert err is None
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("malicious_volume", [
|
@pytest.mark.parametrize(
|
||||||
|
"malicious_volume",
|
||||||
|
[
|
||||||
"../../etc/passwd:/mnt/passwd:ro",
|
"../../etc/passwd:/mnt/passwd:ro",
|
||||||
"./../../Core/nixos/secrets.yaml:/secrets.yaml",
|
"./../../Core/nixos/secrets.yaml:/secrets.yaml",
|
||||||
"../other-workload/data:/data",
|
"../other-workload/data:/data",
|
||||||
])
|
],
|
||||||
|
)
|
||||||
def test_validate_compose_security_blocks_relative_traversal(
|
def test_validate_compose_security_blocks_relative_traversal(
|
||||||
tmp_path: Path, malicious_volume: str
|
tmp_path: Path, malicious_volume: str
|
||||||
):
|
):
|
||||||
@@ -806,8 +859,12 @@ def test_validate_compose_security_blocks_relative_traversal(
|
|||||||
encoding="utf-8",
|
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(
|
||||||
assert valid is False, f"Expected relative traversal '{malicious_volume}' to be rejected!"
|
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
|
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",
|
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 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
|
# Authorized own state mount must pass
|
||||||
compose_file.write_text(
|
compose_file.write_text(
|
||||||
f"services:\n web:\n image: nginx\n volumes:\n - '{state_root}/my-app:/data'\n",
|
f"services:\n web:\n image: nginx\n volumes:\n - '{state_root}/my-app:/data'\n",
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
valid_own, err_own = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
|
valid_own, err_own = gitops_dispatcher.validate_compose_security(
|
||||||
assert valid_own is True, f"Own state mount should be permitted, got error: {err_own}"
|
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", [
|
@pytest.mark.parametrize(
|
||||||
|
"unsafe_directive",
|
||||||
|
[
|
||||||
"cap_add:\n - SYS_ADMIN",
|
"cap_add:\n - SYS_ADMIN",
|
||||||
"pid: host",
|
"pid: host",
|
||||||
"ipc: host",
|
"ipc: host",
|
||||||
"userns_mode: host",
|
"userns_mode: host",
|
||||||
"devices:\n - /dev/sda:/dev/sda",
|
"devices:\n - /dev/sda:/dev/sda",
|
||||||
"security_opt:\n - apparmor:unconfined",
|
"security_opt:\n - apparmor:unconfined",
|
||||||
])
|
],
|
||||||
|
)
|
||||||
def test_validate_compose_security_blocks_privilege_escalation_primitives(
|
def test_validate_compose_security_blocks_privilege_escalation_primitives(
|
||||||
tmp_path: Path, unsafe_directive: str
|
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",
|
f"services:\n app:\n image: alpine\n {unsafe_directive}\n",
|
||||||
encoding="utf-8",
|
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 valid is False, f"Directive should be blocked:\n{unsafe_directive}"
|
||||||
assert err is not None
|
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):
|
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."""
|
"""Ensure top-level Compose include directives are rejected to prevent out-of-tree includes."""
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
include:
|
include:
|
||||||
- /etc/shadow
|
- /etc/shadow
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine
|
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 valid is False
|
||||||
assert err is not None and "include" in err.lower()
|
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 = app_dir / "docker-compose.yml"
|
||||||
compose_link.symlink_to(outside_file)
|
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 valid is False
|
||||||
assert err is not None and "symlink" in err.lower()
|
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
|
# 1. Escaping absolute path
|
||||||
compose_file = app_dir / "docker-compose.yml"
|
compose_file = app_dir / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine
|
image: alpine
|
||||||
env_file: /run/secrets/homeserver.env
|
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 valid is False
|
||||||
assert err is not None and "env_file" in err.lower()
|
assert err is not None and "env_file" in err.lower()
|
||||||
|
|
||||||
# 2. Escaping relative path in list
|
# 2. Escaping relative path in list
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine
|
image: alpine
|
||||||
env_file:
|
env_file:
|
||||||
- valid.env
|
- valid.env
|
||||||
- ../../Core/.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 valid is False
|
||||||
assert err is not None and "env_file" in err.lower()
|
assert err is not None and "env_file" in err.lower()
|
||||||
|
|
||||||
# 3. Valid local env_file
|
# 3. Valid local env_file
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine
|
image: alpine
|
||||||
env_file: valid.env
|
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 valid is True
|
||||||
assert err is None
|
assert err is None
|
||||||
|
|
||||||
@@ -942,14 +1034,19 @@ services:
|
|||||||
def test_validate_compose_security_rejects_undeclared_named_volumes(tmp_path: Path):
|
def test_validate_compose_security_rejects_undeclared_named_volumes(tmp_path: Path):
|
||||||
"""Ensure ambiguous volume paths not declared in top-level volumes are rejected."""
|
"""Ensure ambiguous volume paths not declared in top-level volumes are rejected."""
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine
|
image: alpine
|
||||||
volumes:
|
volumes:
|
||||||
- rogue_named_volume:/data
|
- 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 valid is False
|
||||||
assert err is not None and "undeclared" in err.lower()
|
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):
|
def test_validate_compose_security_handles_string_security_opt(tmp_path: Path):
|
||||||
"""Ensure security_opt specified as string instead of list is strictly checked."""
|
"""Ensure security_opt specified as string instead of list is strictly checked."""
|
||||||
compose_file = tmp_path / "docker-compose.yml"
|
compose_file = tmp_path / "docker-compose.yml"
|
||||||
compose_file.write_text("""
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: alpine
|
image: alpine
|
||||||
security_opt: "apparmor:unconfined"
|
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 valid is False
|
||||||
assert err is not None and "security_opt" in err.lower()
|
assert err is not None and "security_opt" in err.lower()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -10,11 +10,11 @@ from pathlib import Path
|
|||||||
|
|
||||||
import yaml
|
import yaml
|
||||||
|
|
||||||
|
# Comment-out reason: testing pyproject-level pythonpath definition
|
||||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||||
|
|
||||||
|
|
||||||
def test_socket_proxy_is_strictly_read_only():
|
def test_socket_proxy_is_strictly_read_only():
|
||||||
|
|
||||||
"""Ensure socket-proxy container blocks state-modifying requests (POST=0, DELETE=0)."""
|
"""Ensure socket-proxy container blocks state-modifying requests (POST=0, DELETE=0)."""
|
||||||
compose_path = CORE_ROOT / "docker-compose.yml"
|
compose_path = CORE_ROOT / "docker-compose.yml"
|
||||||
with open(compose_path, encoding="utf-8") as f:
|
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", [])
|
volumes = svc.get("volumes", [])
|
||||||
for vol in volumes:
|
for vol in volumes:
|
||||||
if isinstance(vol, str) and "/var/run/docker.sock" in vol:
|
if isinstance(vol, str) and "/var/run/docker.sock" in vol:
|
||||||
assert name == "socket-proxy", f"Service '{name}' directly mounts docker.sock!"
|
assert name == "socket-proxy", (
|
||||||
assert vol.endswith(":ro"), "socket-proxy docker.sock mount must be read-only (:ro)"
|
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():
|
def test_no_privileged_containers():
|
||||||
@@ -60,7 +64,9 @@ def test_no_privileged_containers():
|
|||||||
services = compose.get("services", {})
|
services = compose.get("services", {})
|
||||||
for name, svc in services.items():
|
for name, svc in services.items():
|
||||||
privileged = svc.get("privileged", False)
|
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():
|
def test_no_shell_true_in_core_scripts():
|
||||||
@@ -78,10 +84,14 @@ def test_portainer_is_deprecated_and_absent():
|
|||||||
compose = yaml.safe_load(f)
|
compose = yaml.safe_load(f)
|
||||||
|
|
||||||
services = compose.get("services", {})
|
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 {}
|
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():
|
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 / "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
|
# 2. Setup mock docker binary to capture environment without requiring a running Docker daemon
|
||||||
mock_bin = tmp_path / "bin"
|
mock_bin = tmp_path / "bin"
|
||||||
@@ -152,10 +164,13 @@ exit 0
|
|||||||
check=False,
|
check=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# 4. Assertions: command substitution was not executed, script ran, and mock docker received literal value
|
# 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 not canary.exists(), (
|
||||||
assert res.returncode == 0, f"appctl config failed: {res.stderr}\nStdout: {res.stdout}"
|
"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 "MOCK_DOCKER_COMPOSE_CONFIG" in res.stdout
|
||||||
assert f"CAPTURED_INJECTION={payload}" in res.stdout
|
assert f"CAPTURED_INJECTION={payload}" in res.stdout
|
||||||
assert "CAPTURED_NORMAL=safe_value" 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:
|
for file_path in candidate_files:
|
||||||
if (
|
if (
|
||||||
file_path.is_file()
|
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"
|
and file_path.name != "test_security_invariants.py"
|
||||||
):
|
):
|
||||||
content = file_path.read_text(encoding="utf-8", errors="ignore")
|
content = file_path.read_text(encoding="utf-8", errors="ignore")
|
||||||
for term in forbidden:
|
for term in forbidden:
|
||||||
if term in content:
|
if term in content:
|
||||||
violations.append(f"{file_path.relative_to(CORE_ROOT)}: contains prohibited literal '{term}'")
|
violations.append(
|
||||||
|
f"{file_path.relative_to(CORE_ROOT)}: contains prohibited literal '{term}'"
|
||||||
assert not violations, "Platform genericism violations detected:\n" + "\n".join(violations)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
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"
|
pre_commit = CORE_ROOT / ".githooks" / "pre-commit"
|
||||||
assert pre_commit.is_file(), ".githooks/pre-commit must be a regular file"
|
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():
|
def test_deprecated_legacy_structures_are_absent():
|
||||||
@@ -61,4 +63,7 @@ def test_unlicense_preserved():
|
|||||||
unlicense = CORE_ROOT / "UNLICENSE"
|
unlicense = CORE_ROOT / "UNLICENSE"
|
||||||
assert unlicense.is_file(), "UNLICENSE file must be present"
|
assert unlicense.is_file(), "UNLICENSE file must be present"
|
||||||
content = unlicense.read_text(encoding="utf-8")
|
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 dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import MagicMock
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import appctl_engine as engine
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
# Import appctl engine
|
# Import appctl engine
|
||||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||||
|
|
||||||
import appctl_engine as engine
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class AppFactory:
|
class AppFactory:
|
||||||
"""Helper class to generate mock app directories and configurations"""
|
"""Helper class to generate mock app directories and configurations"""
|
||||||
|
|
||||||
sites_dir: Path
|
sites_dir: Path
|
||||||
|
|
||||||
def create(
|
def create(
|
||||||
@@ -28,9 +27,12 @@ class AppFactory:
|
|||||||
if manifest_yaml:
|
if manifest_yaml:
|
||||||
(app_dir / "app.yaml").write_text(manifest_yaml, encoding="utf-8")
|
(app_dir / "app.yaml").write_text(manifest_yaml, encoding="utf-8")
|
||||||
if has_compose:
|
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
|
return app_dir
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
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"""
|
"""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")
|
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "mydomain.test")
|
||||||
return sites
|
return sites
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def app_factory(mock_sites_dir: Path) -> AppFactory:
|
def app_factory(mock_sites_dir: Path) -> AppFactory:
|
||||||
"""Fixture that provides the AppFactory instance to test"""
|
"""Fixture that provides the AppFactory instance to test"""
|
||||||
return AppFactory(mock_sites_dir)
|
return AppFactory(mock_sites_dir)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def mock_core_dir(
|
def mock_core_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||||
tmp_path: Path,
|
|
||||||
monkeypatch: pytest.MonkeyPatch
|
|
||||||
) -> Path:
|
|
||||||
"""Fixture that creates an isolated Core directory and points engine.CORE_DIR to it"""
|
"""Fixture that creates an isolated Core directory and points engine.CORE_DIR to it"""
|
||||||
core = tmp_path / "CORE"
|
core = tmp_path / "CORE"
|
||||||
core.mkdir(parents=True, exist_ok=True)
|
core.mkdir(parents=True, exist_ok=True)
|
||||||
return core
|
return core
|
||||||
|
|
||||||
|
|
||||||
## GREEN TEST: Existing implementation should not break
|
## GREEN TEST: Existing implementation should not break
|
||||||
|
|
||||||
|
|
||||||
def test_resolve_app_hierarchy(app_factory: AppFactory):
|
def test_resolve_app_hierarchy(app_factory: AppFactory):
|
||||||
"""Ensure resolution follows: Canonical Name > Alias > Dir Name > Prefix"""
|
"""Ensure resolution follows: Canonical Name > Alias > Dir Name > Prefix"""
|
||||||
app_factory.create(
|
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("homelab-jellyfin", apps) is not None
|
||||||
assert engine.resolve_app("unknown", apps) is None
|
assert engine.resolve_app("unknown", apps) is None
|
||||||
|
|
||||||
|
|
||||||
def test_manifest_data_overrides_default_values(app_factory: AppFactory):
|
def test_manifest_data_overrides_default_values(app_factory: AppFactory):
|
||||||
"""Ensure app.yaml values successfully override the system defaults"""
|
"""Ensure app.yaml values successfully override the system defaults"""
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
@@ -84,7 +88,7 @@ def test_manifest_data_overrides_default_values(app_factory: AppFactory):
|
|||||||
visible: false
|
visible: false
|
||||||
networks:
|
networks:
|
||||||
- custom-net
|
- custom-net
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
apps = engine.get_sites_apps()
|
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.auth is False
|
||||||
assert app.networks == ["custom-net"]
|
assert app.networks == ["custom-net"]
|
||||||
|
|
||||||
|
|
||||||
def test_sites_app_normalization(app_factory: AppFactory):
|
def test_sites_app_normalization(app_factory: AppFactory):
|
||||||
"""Ensure missing or badly typed manifest fields are safely normalized"""
|
"""Ensure missing or badly typed manifest fields are safely normalized"""
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
@@ -106,7 +111,7 @@ def test_sites_app_normalization(app_factory: AppFactory):
|
|||||||
auth: "False" # should evaluate based on boolean casting
|
auth: "False" # should evaluate based on boolean casting
|
||||||
homepage:
|
homepage:
|
||||||
weight: "99" # this should be casted as an int
|
weight: "99" # this should be casted as an int
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
apps = engine.get_sites_apps()
|
apps = engine.get_sites_apps()
|
||||||
app = engine.resolve_app("testapp", apps)
|
app = engine.resolve_app("testapp", apps)
|
||||||
@@ -131,7 +136,7 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
|||||||
type: git
|
type: git
|
||||||
url: https://git.example.com/operator/bitetrack.git
|
url: https://git.example.com/operator/bitetrack.git
|
||||||
ref: v1.2.0
|
ref: v1.2.0
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
# 2. Source-backed app with default ref (main)
|
# 2. Source-backed app with default ref (main)
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
@@ -140,14 +145,14 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
|||||||
name: doc2site
|
name: doc2site
|
||||||
source:
|
source:
|
||||||
url: https://git.example.com/operator/doc2site.git
|
url: https://git.example.com/operator/doc2site.git
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
# 3. Image-only app (no source block)
|
# 3. Image-only app (no source block)
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
dir_name="homelab-jellyfin",
|
dir_name="homelab-jellyfin",
|
||||||
manifest_yaml="""
|
manifest_yaml="""
|
||||||
name: jellyfin
|
name: jellyfin
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
apps = engine.get_sites_apps()
|
apps = engine.get_sites_apps()
|
||||||
@@ -177,7 +182,7 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
|
|||||||
name: malformed
|
name: malformed
|
||||||
source:
|
source:
|
||||||
url: file:///etc/passwd
|
url: file:///etc/passwd
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
apps_updated = engine.get_sites_apps()
|
apps_updated = engine.get_sites_apps()
|
||||||
malformed = engine.resolve_app("malformed", apps_updated)
|
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
|
## RED TESTS: TDD Goals for next implementation
|
||||||
|
|
||||||
|
|
||||||
def test_docker_status_parser_running(monkeypatch):
|
def test_docker_status_parser_running(monkeypatch):
|
||||||
"""Ensure get_docker_status reports running compose stack when all containers are running."""
|
"""Ensure get_docker_status reports running compose stack when all containers are running."""
|
||||||
|
|
||||||
def mock_run(args, **kwargs):
|
def mock_run(args, **kwargs):
|
||||||
mock = MagicMock()
|
mock = MagicMock()
|
||||||
if "ps" in args:
|
if "ps" in args:
|
||||||
@@ -207,6 +214,7 @@ def test_docker_status_parser_running(monkeypatch):
|
|||||||
|
|
||||||
def test_docker_status_parser_stopped(monkeypatch):
|
def test_docker_status_parser_stopped(monkeypatch):
|
||||||
"""Ensure get_docker_status reports stopped when no containers exist."""
|
"""Ensure get_docker_status reports stopped when no containers exist."""
|
||||||
|
|
||||||
def mock_run(args, **kwargs):
|
def mock_run(args, **kwargs):
|
||||||
mock = MagicMock()
|
mock = MagicMock()
|
||||||
if "ps" in args:
|
if "ps" in args:
|
||||||
@@ -221,6 +229,7 @@ def test_docker_status_parser_stopped(monkeypatch):
|
|||||||
|
|
||||||
def test_docker_status_parser_degraded(monkeypatch):
|
def test_docker_status_parser_degraded(monkeypatch):
|
||||||
"""Ensure get_docker_status reports degraded when partial containers are running."""
|
"""Ensure get_docker_status reports degraded when partial containers are running."""
|
||||||
|
|
||||||
def mock_run(args, **kwargs):
|
def mock_run(args, **kwargs):
|
||||||
mock = MagicMock()
|
mock = MagicMock()
|
||||||
if "ps" in args:
|
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):
|
def test_docker_status_single_container(monkeypatch):
|
||||||
"""Ensure get_docker_status inspects single Core container by name."""
|
"""Ensure get_docker_status inspects single Core container by name."""
|
||||||
|
|
||||||
def mock_run(args, **kwargs):
|
def mock_run(args, **kwargs):
|
||||||
mock = MagicMock()
|
mock = MagicMock()
|
||||||
if "authelia" in args:
|
if "authelia" in args:
|
||||||
@@ -260,6 +270,7 @@ def test_docker_status_single_container(monkeypatch):
|
|||||||
|
|
||||||
def test_docker_status_error_handling(monkeypatch):
|
def test_docker_status_error_handling(monkeypatch):
|
||||||
"""Ensure get_docker_status handles subprocess failures gracefully."""
|
"""Ensure get_docker_status handles subprocess failures gracefully."""
|
||||||
|
|
||||||
def mock_err(*args, **kwargs):
|
def mock_err(*args, **kwargs):
|
||||||
raise OSError("Docker socket unreachable")
|
raise OSError("Docker socket unreachable")
|
||||||
|
|
||||||
@@ -269,6 +280,7 @@ def test_docker_status_error_handling(monkeypatch):
|
|||||||
|
|
||||||
def test_docker_image_revision_extraction(monkeypatch):
|
def test_docker_image_revision_extraction(monkeypatch):
|
||||||
"""Ensure get_docker_image_revision extracts org.opencontainers.image.revision."""
|
"""Ensure get_docker_image_revision extracts org.opencontainers.image.revision."""
|
||||||
|
|
||||||
def mock_run(args, **kwargs):
|
def mock_run(args, **kwargs):
|
||||||
mock = MagicMock()
|
mock = MagicMock()
|
||||||
if "ps" in args:
|
if "ps" in args:
|
||||||
@@ -278,7 +290,10 @@ def test_docker_image_revision_extraction(monkeypatch):
|
|||||||
return mock
|
return mock
|
||||||
|
|
||||||
monkeypatch.setattr("subprocess.run", mock_run)
|
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):
|
def mock_run_empty(args, **kwargs):
|
||||||
mock = MagicMock()
|
mock = MagicMock()
|
||||||
@@ -293,9 +308,8 @@ def test_docker_image_revision_extraction(monkeypatch):
|
|||||||
|
|
||||||
|
|
||||||
def test_homepage_sync_groups_and_sorts_correctly(
|
def test_homepage_sync_groups_and_sorts_correctly(
|
||||||
mock_core_dir: Path,
|
mock_core_dir: Path, app_factory: AppFactory, monkeypatch
|
||||||
app_factory: AppFactory,
|
):
|
||||||
monkeypatch):
|
|
||||||
"""
|
"""
|
||||||
TDD Goal: Port `cmd_sync_homepage` to V2 using the new Dataclass structure.
|
TDD Goal: Port `cmd_sync_homepage` to V2 using the new Dataclass structure.
|
||||||
It must group by `homepage.group` and sort by `homepage.weight`.
|
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
|
title: App1
|
||||||
group: Group B
|
group: Group B
|
||||||
weight: 20
|
weight: 20
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
@@ -324,7 +338,7 @@ def test_homepage_sync_groups_and_sorts_correctly(
|
|||||||
title: App2
|
title: App2
|
||||||
group: Group A
|
group: Group A
|
||||||
weight: 10
|
weight: 10
|
||||||
"""
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
monkeypatch.setattr(engine, "get_core_services", list)
|
monkeypatch.setattr(engine, "get_core_services", list)
|
||||||
@@ -334,7 +348,9 @@ def test_homepage_sync_groups_and_sorts_correctly(
|
|||||||
assert output_file.exists(), "The services.yaml file must be generated"
|
assert output_file.exists(), "The services.yaml file must be generated"
|
||||||
|
|
||||||
content = output_file.read_text()
|
content = output_file.read_text()
|
||||||
assert content.find("- Group A") < content.find("- Group B") # Group A should appear before Group B
|
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 "App2" in content # App 2 is in the file
|
||||||
|
|
||||||
|
|
||||||
@@ -380,7 +396,9 @@ def test_resolve_core_stack_type():
|
|||||||
assert traefik.container == "traefik"
|
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."""
|
"""Ensure manifest parsing uses core_manifest and catches invalid env keys."""
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
dir_name="homelab-badenv",
|
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
|
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."""
|
"""Ensure cmd_resolve exits with non-zero on workload with manifest errors."""
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
dir_name="homelab-corrupt",
|
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
|
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."""
|
"""Ensure cmd_list flags workloads with manifest errors instead of swallowing them."""
|
||||||
app_factory.create(
|
app_factory.create(
|
||||||
dir_name="homelab-broken",
|
dir_name="homelab-broken",
|
||||||
@@ -462,4 +484,3 @@ def test_cmd_list_flags_manifest_error(app_factory: AppFactory, capsys: pytest.C
|
|||||||
engine.cmd_list([])
|
engine.cmd_list([])
|
||||||
captured = capsys.readouterr()
|
captured = capsys.readouterr()
|
||||||
assert "Manifest Error" in captured.out
|
assert "Manifest Error" in captured.out
|
||||||
|
|
||||||
@@ -2,15 +2,13 @@
|
|||||||
Unit test suite for scripts/core_manifest.py (Schema v1.0 & Parser Library).
|
Unit test suite for scripts/core_manifest.py (Schema v1.0 & Parser Library).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
# Add scripts directory to path
|
# # Add scripts directory to path
|
||||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||||
|
|
||||||
from core_manifest import (
|
from core_manifest import (
|
||||||
Manifest,
|
Manifest,
|
||||||
ManifestValidationError,
|
ManifestValidationError,
|
||||||
@@ -24,13 +22,17 @@ from core_manifest import (
|
|||||||
|
|
||||||
def test_validate_transport_https():
|
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 scheme == TransportScheme.HTTPS
|
||||||
assert url == "https://git.example.com/operator/homelab-snappymail.git"
|
assert url == "https://git.example.com/operator/homelab-snappymail.git"
|
||||||
|
|
||||||
|
|
||||||
def test_validate_transport_ssh():
|
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 scheme == TransportScheme.SSH
|
||||||
assert url == "ssh://git@git.example.com:2223/operator/homelab-docs.git"
|
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"
|
assert url == "git@github.com:operator/custom-workload.git"
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("insecure_url", [
|
@pytest.mark.parametrize(
|
||||||
|
"insecure_url",
|
||||||
|
[
|
||||||
"http://insecure.example.com/repo.git",
|
"http://insecure.example.com/repo.git",
|
||||||
"http://github.com/repo.git",
|
"http://github.com/repo.git",
|
||||||
])
|
],
|
||||||
|
)
|
||||||
def test_validate_transport_rejects_http(insecure_url: str):
|
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)
|
validate_transport(insecure_url)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("traversal_url", [
|
@pytest.mark.parametrize(
|
||||||
|
"traversal_url",
|
||||||
|
[
|
||||||
"../../etc/shadow",
|
"../../etc/shadow",
|
||||||
"/home/operator/secret",
|
"/home/operator/secret",
|
||||||
"~/vault",
|
"~/vault",
|
||||||
"file:///etc/passwd",
|
"file:///etc/passwd",
|
||||||
])
|
],
|
||||||
|
)
|
||||||
def test_validate_transport_rejects_paths_and_traversal(traversal_url: str):
|
def test_validate_transport_rejects_paths_and_traversal(traversal_url: str):
|
||||||
with pytest.raises(ManifestValidationError):
|
with pytest.raises(ManifestValidationError):
|
||||||
validate_transport(traversal_url)
|
validate_transport(traversal_url)
|
||||||
@@ -64,7 +74,10 @@ def test_validate_transport_rejects_paths_and_traversal(traversal_url: str):
|
|||||||
def test_classify_ref_branches():
|
def test_classify_ref_branches():
|
||||||
assert classify_ref("main") == (RefType.BRANCH, "main")
|
assert classify_ref("main") == (RefType.BRANCH, "main")
|
||||||
assert classify_ref("refs/heads/develop") == (RefType.BRANCH, "develop")
|
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")
|
assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0")
|
||||||
|
|
||||||
|
|
||||||
@@ -145,7 +158,9 @@ deployment:
|
|||||||
|
|
||||||
|
|
||||||
def test_parse_manifest_rejects_missing_name():
|
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")
|
parse_manifest("domain: test.example.com\n")
|
||||||
|
|
||||||
|
|
||||||
@@ -162,7 +177,9 @@ deployment:
|
|||||||
- compose_up
|
- compose_up
|
||||||
- rm_rf_root
|
- 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)
|
parse_manifest(raw_yaml)
|
||||||
|
|
||||||
|
|
||||||
@@ -172,7 +189,9 @@ name: "app"
|
|||||||
deployment:
|
deployment:
|
||||||
strategy: "swarm"
|
strategy: "swarm"
|
||||||
"""
|
"""
|
||||||
with pytest.raises(ManifestValidationError, match="Unsupported deployment strategy 'swarm'"):
|
with pytest.raises(
|
||||||
|
ManifestValidationError, match="Unsupported deployment strategy 'swarm'"
|
||||||
|
):
|
||||||
parse_manifest(raw_yaml)
|
parse_manifest(raw_yaml)
|
||||||
|
|
||||||
|
|
||||||
@@ -185,7 +204,9 @@ def test_parse_manifest_from_path(tmp_path: Path):
|
|||||||
assert manifest.is_internal is True
|
assert manifest.is_internal is True
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("invalid_key", [
|
@pytest.mark.parametrize(
|
||||||
|
"invalid_key",
|
||||||
|
[
|
||||||
"123_BAD",
|
"123_BAD",
|
||||||
"INVALID-KEY",
|
"INVALID-KEY",
|
||||||
"FOO;BAR",
|
"FOO;BAR",
|
||||||
@@ -195,14 +216,17 @@ def test_parse_manifest_from_path(tmp_path: Path):
|
|||||||
"IFS",
|
"IFS",
|
||||||
"CORE_DIR",
|
"CORE_DIR",
|
||||||
"SITES_DIR",
|
"SITES_DIR",
|
||||||
])
|
],
|
||||||
|
)
|
||||||
def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str):
|
def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str):
|
||||||
raw_yaml = f"""
|
raw_yaml = f"""
|
||||||
name: "app"
|
name: "app"
|
||||||
env:
|
env:
|
||||||
"{invalid_key}": "some_value"
|
"{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)
|
parse_manifest(raw_yaml)
|
||||||
|
|
||||||
|
|
||||||
@@ -226,7 +250,9 @@ def test_parse_manifest_rejects_extra_fields():
|
|||||||
name: "app"
|
name: "app"
|
||||||
unrecognized_field: "should_fail"
|
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)
|
parse_manifest(raw_yaml)
|
||||||
|
|
||||||
|
|
||||||
@@ -259,5 +285,3 @@ description: "Pydantic serialization test"
|
|||||||
assert dumped["name"] == "serialized-app"
|
assert dumped["name"] == "serialized-app"
|
||||||
assert dumped["schemaVersion"] == "1.0"
|
assert dumped["schemaVersion"] == "1.0"
|
||||||
assert manifest.to_dict()["name"] == "serialized-app"
|
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 os
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
# Add scripts directory to path
|
# # Add scripts directory to path
|
||||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||||
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||||
|
|
||||||
from core_manifest import Manifest, RefType, SourceConfig, TransportScheme
|
from core_manifest import Manifest, RefType, SourceConfig, TransportScheme
|
||||||
from provenance import (
|
from provenance import (
|
||||||
ProvenanceStatus,
|
ProvenanceStatus,
|
||||||
@@ -43,12 +41,28 @@ def test_get_local_checkout_status_clean_repo(tmp_path: Path):
|
|||||||
app_dir = tmp_path / "git_app"
|
app_dir = tmp_path / "git_app"
|
||||||
app_dir.mkdir()
|
app_dir.mkdir()
|
||||||
env = _clean_git_env()
|
env = _clean_git_env()
|
||||||
subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env)
|
subprocess.run(
|
||||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env)
|
["git", "-C", str(app_dir), "init", "-b", "main"],
|
||||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env)
|
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")
|
(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), "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)
|
status = get_local_checkout_status(app_dir)
|
||||||
assert status.is_git is True
|
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 = tmp_path / "git_dirty_app"
|
||||||
app_dir.mkdir()
|
app_dir.mkdir()
|
||||||
env = _clean_git_env()
|
env = _clean_git_env()
|
||||||
subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env)
|
subprocess.run(
|
||||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env)
|
["git", "-C", str(app_dir), "init", "-b", "main"],
|
||||||
subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env)
|
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")
|
(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), "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
|
# Modify file to create dirty state
|
||||||
(app_dir / "file.txt").write_text("modified", encoding="utf-8")
|
(app_dir / "file.txt").write_text("modified", encoding="utf-8")
|
||||||
@@ -131,7 +161,10 @@ def test_resolve_upstream_provenance_timeout():
|
|||||||
transport=TransportScheme.HTTPS,
|
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)
|
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
|
||||||
|
|
||||||
assert prov.status == ProvenanceStatus.TIMEOUT
|
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
|
# 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 status_no_fetch.provenance.status == ProvenanceStatus.UNKNOWN
|
||||||
assert "Pass --fetch" in status_no_fetch.provenance.message
|
assert "Pass --fetch" in status_no_fetch.provenance.message
|
||||||
|
|
||||||
# With fetch_upstream: Axis 2 queries remote
|
# With fetch_upstream: Axis 2 queries remote
|
||||||
with patch("provenance.resolve_upstream_provenance") as mock_resolve:
|
with patch("provenance.resolve_upstream_provenance") as mock_resolve:
|
||||||
mock_resolve.return_value = MagicMock(status=ProvenanceStatus.SYNCED)
|
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
|
assert status_fetch.provenance.status == ProvenanceStatus.SYNCED
|
||||||
mock_resolve.assert_called_once()
|
mock_resolve.assert_called_once()
|
||||||
Reference in new issue
Block a user