From dc880928a9fc9504e09915389e449290a1de432a Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 16 Oct 2026 23:21:34 -0500 Subject: [PATCH 01/43] style: format python files with ruff --- nixos/scripts/monitor.py | 23 +- scripts/appctl_engine.py | 252 ++++++--- scripts/core_manifest.py | 118 +++- scripts/gitops_dispatcher.py | 507 ++++++++++++++---- scripts/provenance.py | 26 +- tests/security/test_gitops_security.py | 450 ++++++++++------ tests/security/test_security_invariants.py | 50 +- tests/structural/test_repository_structure.py | 9 +- tests/unit/test_appctl_engine.py | 77 ++- tests/unit/test_core_manifest.py | 98 ++-- tests/unit/test_provenance.py | 69 ++- 11 files changed, 1151 insertions(+), 528 deletions(-) diff --git a/nixos/scripts/monitor.py b/nixos/scripts/monitor.py index cd141ad..f368c3e 100644 --- a/nixos/scripts/monitor.py +++ b/nixos/scripts/monitor.py @@ -28,7 +28,7 @@ PROVIDERS = [ "https://api.ipify.org", "https://ifconfig.me/ip", "https://icanhazip.com", - "https://wtfismyip.com/text" + "https://wtfismyip.com/text", ] @@ -78,14 +78,11 @@ def get_public_ip(): for provider in PROVIDERS: try: req = urllib.request.Request( - provider, - headers={ - 'User-Agent': 'Mozilla/5.0 (NixOS WAN Monitor)' - } + provider, headers={"User-Agent": "Mozilla/5.0 (NixOS WAN Monitor)"} ) # Fetch with 5s timeout to avoid hanging the systemd service with urllib.request.urlopen(req, timeout=5) as response: - ip = response.read().decode('utf-8').strip() + ip = response.read().decode("utf-8").strip() if is_valid_public_ipv4(ip): return ip else: @@ -94,8 +91,7 @@ def get_public_ip(): errors.append(f"{provider}: {e!s}") print( - f"Error: All IP discovery providers failed. Details: {errors}", - file=sys.stderr + f"Error: All IP discovery providers failed. Details: {errors}", file=sys.stderr ) return None @@ -132,11 +128,7 @@ def record_ip(ip, status, details=None): Appends a new event entry into the JSONLines history registry. """ os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True) - entry = { - "timestamp": datetime.now(tz=UTC).isoformat(), - "ip": ip, - "status": status - } + entry = {"timestamp": datetime.now(tz=UTC).isoformat(), "ip": ip, "status": status} if details: entry["details"] = details try: @@ -164,10 +156,7 @@ def trigger_ddclient(): if res.returncode == 0: return True, None else: - err_msg = ( - f"systemctl exited with {res.returncode}: " - f"{res.stderr.strip()}" - ) + err_msg = f"systemctl exited with {res.returncode}: {res.stderr.strip()}" return False, err_msg except (OSError, subprocess.SubprocessError) as e: return False, str(e) diff --git a/scripts/appctl_engine.py b/scripts/appctl_engine.py index cca2924..cc722f0 100755 --- a/scripts/appctl_engine.py +++ b/scripts/appctl_engine.py @@ -33,7 +33,8 @@ from provenance import ( # Dynamic Environment Paths CORE_DIR = os.environ.get( - "CORE_DIR", os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "CORE_DIR", + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ) SITES_DIR = os.environ.get( @@ -75,15 +76,22 @@ ManifestError = ManifestValidationError @dataclass class App: - name: str # Canonical identifier (e.g., "traefik", "jellyfin") - description: str = "" # Human-readable summary for dashboards and CLI info - domain: str = "" # Routing FQDN (e.g., "auth.example.com") or "internal". - dir_path: str = "" # Filesystem directory (CORE_DIR for Core, or ~/Sites/ for Sites). + name: str # Canonical identifier (e.g., "traefik", "jellyfin") + description: str = "" # Human-readable summary for dashboards and CLI info + domain: str = "" # Routing FQDN (e.g., "auth.example.com") or "internal". + dir_path: str = ( + "" # Filesystem directory (CORE_DIR for Core, or ~/Sites/ for Sites). + ) @property def is_internal(self) -> bool: """Returns True if the service does not expose a public TLS endpoint.""" - return not self.domain or self.domain == "internal" or self.domain.endswith(".local") or ":" in self.domain + return ( + not self.domain + or self.domain == "internal" + or self.domain.endswith(".local") + or ":" in self.domain + ) def to_dict(self) -> dict[str, Any]: """Serialize for JSON consumption by scripts/appctl""" @@ -94,26 +102,30 @@ class App: @dataclass class CoreService(App): - container: str = "" # Target container name inside Core's docker-compose.yml - weight: int = 50 # Homepage ordering weight - icon: str = "default.png" # Dashboard icon filename + container: str = "" # Target container name inside Core's docker-compose.yml + weight: int = 50 # Homepage ordering weight + icon: str = "default.png" # Dashboard icon filename app_type: str = "core_service" dir_path: str = CORE_DIR @dataclass class SitesApp(App): - dir_name: str = "" # directory name in ~/Sites (e.g., "homelab-vaultwarden") - source: SourceConfig | None = None # Upstream source provenance (None = Class B Image-Only) - aliases: list[str] = field(default_factory=list) # CLI resolution aliases - visible: bool = True # Defines whether the icon is visible in Homepage - auth: bool = True # Authelia protection guard indicator - has_compose: bool = False # Whether a docker-compose.yml exists - networks: list[str] = field(default_factory=lambda: ["proxy-net"]) # Docker network attachments - env: dict[str, Any] = field(default_factory=dict) # Environment variable overrides - homepage: HomepageConfig | None = None # Dashboard Card Configuration - manifest_error: str | None = None # Captured syntax/loading errors - manifest_obj: Manifest | None = None # Parsed authoritative Manifest + dir_name: str = "" # directory name in ~/Sites (e.g., "homelab-vaultwarden") + source: SourceConfig | None = ( + None # Upstream source provenance (None = Class B Image-Only) + ) + aliases: list[str] = field(default_factory=list) # CLI resolution aliases + visible: bool = True # Defines whether the icon is visible in Homepage + auth: bool = True # Authelia protection guard indicator + has_compose: bool = False # Whether a docker-compose.yml exists + networks: list[str] = field( + default_factory=lambda: ["proxy-net"] + ) # Docker network attachments + env: dict[str, Any] = field(default_factory=dict) # Environment variable overrides + homepage: HomepageConfig | None = None # Dashboard Card Configuration + manifest_error: str | None = None # Captured syntax/loading errors + manifest_obj: Manifest | None = None # Parsed authoritative Manifest app_type: str = "app" def to_dict(self) -> dict[str, Any]: @@ -121,15 +133,21 @@ class SitesApp(App): data = asdict(self) data.pop("manifest_obj", None) if self.source is not None: - data["source"] = self.source.to_dict() if hasattr(self.source, "to_dict") else self.source.model_dump() + data["source"] = ( + self.source.to_dict() + if hasattr(self.source, "to_dict") + else self.source.model_dump() + ) if self.homepage is not None: - data["homepage"] = self.homepage.to_dict() if hasattr(self.homepage, "to_dict") else self.homepage.model_dump() + data["homepage"] = ( + self.homepage.to_dict() + if hasattr(self.homepage, "to_dict") + else self.homepage.model_dump() + ) data["type"] = getattr(self, "app_type", "app") return data - - def sites_app_from_manifest( app_dir: str, manifest: Manifest | dict[str, Any] | None = None, @@ -139,10 +157,9 @@ def sites_app_from_manifest( raw_dir_name = os.path.basename(app_dir) if isinstance(manifest, Manifest): - has_compose = ( - os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or - os.path.isfile(os.path.join(app_dir, "docker-compose.yml")) - ) + has_compose = os.path.isfile( + os.path.join(app_dir, "docker-compose.yaml") + ) or os.path.isfile(os.path.join(app_dir, "docker-compose.yml")) canonical_name = manifest.name domain = manifest.domain or f"{canonical_name}.{HOMELAB_DOMAIN}" return SitesApp( @@ -169,7 +186,9 @@ def sites_app_from_manifest( return sites_app_from_manifest(app_dir, parsed, manifest_error) except ManifestValidationError as err: manifest_error = f"{manifest_error}; {err}" if manifest_error else str(err) - canonical_name = str(manifest.get("name") or raw_dir_name.replace("homelab-", "")) + canonical_name = str( + manifest.get("name") or raw_dir_name.replace("homelab-", "") + ) return SitesApp( name=canonical_name, dir_name=raw_dir_name, @@ -217,7 +236,13 @@ def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]: try: manifest_obj = parse_manifest(manifest_file) apps.append(sites_app_from_manifest(app_dir=app_dir, manifest=manifest_obj)) - except (ManifestValidationError, yaml.YAMLError, OSError, ValueError, KeyError) as err: + except ( + ManifestValidationError, + yaml.YAMLError, + OSError, + ValueError, + KeyError, + ) as err: raw_data = None with ( contextlib.suppress(Exception), @@ -328,7 +353,9 @@ def resolve_app( Priority: Canonical Name > Alias > Dir Name > Stripped 'homelab-' Prefix > Core Services. """ if apps is None: - apps = get_sites_apps(sites_dir=sites_dir if sites_dir is not None else SITES_DIR) + apps = get_sites_apps( + sites_dir=sites_dir if sites_dir is not None else SITES_DIR + ) query_clean = query.strip().lower() @@ -389,7 +416,11 @@ def get_docker_status( return "🔴 Stopped" path = Path(dir_path) - if path.exists() and not (path / "docker-compose.yml").is_file() and not (path / "docker-compose.yaml").is_file(): + if ( + path.exists() + and not (path / "docker-compose.yml").is_file() + and not (path / "docker-compose.yaml").is_file() + ): return "⚪ Not Stack" res = subprocess.run( @@ -465,7 +496,9 @@ def get_docker_image_revision( return None -def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[str, Any]: +def check_ssl_cert( + domain: str, port: int = 443, timeout: float = 3.0 +) -> dict[str, Any]: """Inspect SSL/TLS certificate for a domain using standard library ssl and socket.""" if not domain or domain == "internal" or domain.endswith(".local") or ":" in domain: return { @@ -492,9 +525,9 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s days_remaining = None formatted_expiry = "-" if not_after_str: - expiry_dt = datetime.datetime.strptime(not_after_str, "%b %d %H:%M:%S %Y %Z").replace( - tzinfo=datetime.UTC - ) + expiry_dt = datetime.datetime.strptime( + not_after_str, "%b %d %H:%M:%S %Y %Z" + ).replace(tzinfo=datetime.UTC) now_dt = datetime.datetime.now(datetime.UTC) days_remaining = (expiry_dt - now_dt).days formatted_expiry = expiry_dt.strftime("%Y-%m-%d") @@ -507,7 +540,11 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s entry = rdn[0] if isinstance(entry, (list, tuple)) and len(entry) >= 2: issuer_dict[str(entry[0])] = str(entry[1]) - issuer = str(issuer_dict.get("organizationName") or issuer_dict.get("commonName") or "Unknown") + issuer = str( + issuer_dict.get("organizationName") + or issuer_dict.get("commonName") + or "Unknown" + ) subject_dict: dict[str, str] = {} subject_raw = cert.get("subject") @@ -519,7 +556,6 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s subject_dict[str(entry[0])] = str(entry[1]) subject = str(subject_dict.get("commonName") or domain) - if days_remaining is not None: if days_remaining < 0: status = f"🔴 Expired ({abs(days_remaining)}d ago)" @@ -540,7 +576,14 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s "formatted_expiry": formatted_expiry, "error": None, } - except (ssl.SSLError, socket.gaierror, TimeoutError, ConnectionRefusedError, OSError, ValueError) as e: + except ( + ssl.SSLError, + socket.gaierror, + TimeoutError, + ConnectionRefusedError, + OSError, + ValueError, + ) as e: return { "domain": domain, "status": "🔴 Failed", @@ -555,13 +598,19 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s def check_all_ssl_certs(domains: list[str]) -> dict[str, dict[str, Any]]: """Check multiple domains concurrently with ThreadPoolExecutor.""" - valid_domains = [d for d in set(domains) if d and d != "internal" and not d.endswith(".local") and ":" not in d] + valid_domains = [ + d + for d in set(domains) + if d and d != "internal" and not d.endswith(".local") and ":" not in d + ] results: dict[str, dict[str, Any]] = {} if not valid_domains: return results with ThreadPoolExecutor(max_workers=min(len(valid_domains), 8)) as executor: - future_to_domain = {executor.submit(check_ssl_cert, d): d for d in valid_domains} + future_to_domain = { + executor.submit(check_ssl_cert, d): d for d in valid_domains + } for future, d in future_to_domain.items(): with contextlib.suppress(subprocess.SubprocessError, OSError): results[d] = future.result() @@ -591,15 +640,17 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None: groups[core_group] = [] for svc in core_services: if not svc.is_internal: - groups[core_group].append({ - "title": svc.name.title(), - "icon": getattr(svc, "icon", "default.png"), - "href": f"https://{svc.domain}", - "description": svc.description, - "server": "my-docker", - "container": getattr(svc, "container", svc.name), - "weight": getattr(svc, "weight", 50), - }) + groups[core_group].append( + { + "title": svc.name.title(), + "icon": getattr(svc, "icon", "default.png"), + "href": f"https://{svc.domain}", + "description": svc.description, + "server": "my-docker", + "container": getattr(svc, "container", svc.name), + "weight": getattr(svc, "weight", 50), + } + ) # 2. Add Sites applications icons_dir = os.path.join(hp_dir, "icons") @@ -633,15 +684,17 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None: if matched_icon: icon = f"/icons/{matched_icon}" - groups[group_name].append({ - "title": card_title, - "icon": icon, - "href": f"https://{app.domain}", - "description": desc, - "server": "my-docker", - "container": container, - "weight": weight, - }) + groups[group_name].append( + { + "title": card_title, + "icon": icon, + "href": f"https://{app.domain}", + "description": desc, + "server": "my-docker", + "container": container, + "weight": weight, + } + ) # Preferred group order preferred_order = [ @@ -678,7 +731,9 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None: with open(services_yaml_path, "w", encoding="utf-8") as f: f.write(content) - print(f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)") + print( + f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)" + ) print(f"📄 Generated {services_yaml_path}") @@ -699,11 +754,19 @@ def cmd_list(args: list[str]) -> None: ssl_data = check_all_ssl_certs(domains_to_check) if show_ssl: - print(f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}") - print(f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}") + print( + f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}" + ) + print( + f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}" + ) else: - print(f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}") - print(f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}") + print( + f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}" + ) + print( + f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}" + ) for app in apps: app_path = Path(app.dir_path) @@ -713,7 +776,9 @@ def cmd_list(args: list[str]) -> None: dep_str = "⚠️ Manifest Error" prov_str = "⚠️ Invalid Manifest" else: - manifest_obj = app.manifest_obj or Manifest(name=app.name, domain=app.domain) + manifest_obj = app.manifest_obj or Manifest( + name=app.name, domain=app.domain + ) two_axis = inspect_workload_two_axis( app_dir=app_path, manifest=manifest_obj, @@ -726,9 +791,13 @@ def cmd_list(args: list[str]) -> None: if show_ssl: cert_info = ssl_data.get(app.domain, check_ssl_cert(app.domain)) cert_badge = cert_info.get("status", "-") - print(f"{app.name:<16} {dep_str:<22} {prov_str:<22} {docker_status:<15} {app.domain:<28} {cert_badge}") + print( + f"{app.name:<16} {dep_str:<22} {prov_str:<22} {docker_status:<15} {app.domain:<28} {cert_badge}" + ) else: - print(f"{app.name:<16} {dep_str:<22} {prov_str:<24} {docker_status:<15} {app.domain:<28}") + print( + f"{app.name:<16} {dep_str:<22} {prov_str:<24} {docker_status:<15} {app.domain:<28}" + ) if show_core: core_path = Path(CORE_DIR) @@ -736,11 +805,19 @@ def cmd_list(args: list[str]) -> None: core_dep_str = core_checkout.status_label print() if show_ssl: - print(f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}") - print(f"{'------------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}") + print( + f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}" + ) + print( + f"{'------------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}" + ) else: - print(f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}") - print(f"{'------------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}") + print( + f"{'CORE SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN':<28}" + ) + print( + f"{'------------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------':<28}" + ) core_services = get_core_services() for i, svc in enumerate(core_services): @@ -749,9 +826,13 @@ def cmd_list(args: list[str]) -> None: if show_ssl: cert_info = ssl_data.get(svc.domain, check_ssl_cert(svc.domain)) cert_badge = cert_info.get("status", "-") - print(f"{svc.name:<16} {row_dep:<22} {'— Core Platform':<22} {svc_docker:<15} {svc.domain:<28} {cert_badge}") + print( + f"{svc.name:<16} {row_dep:<22} {'— Core Platform':<22} {svc_docker:<15} {svc.domain:<28} {cert_badge}" + ) else: - print(f"{svc.name:<16} {row_dep:<22} {'— Core Platform':<24} {svc_docker:<15} {svc.domain:<28}") + print( + f"{svc.name:<16} {row_dep:<22} {'— Core Platform':<24} {svc_docker:<15} {svc.domain:<28}" + ) def cmd_info(args: list[str]) -> None: @@ -775,7 +856,9 @@ def cmd_info(args: list[str]) -> None: print(f"Directory: {app.dir_path}") print(f"Domain: {app.domain}") print(f"Container: {app.container}") - print(f"Status: {get_docker_status(Path(app.dir_path), app.container)}") + print( + f"Status: {get_docker_status(Path(app.dir_path), app.container)}" + ) print(f"Description: {app.description}") return @@ -791,7 +874,9 @@ def cmd_info(args: list[str]) -> None: print(f"Description: {app.description}") if app.aliases: print(f"Aliases: {', '.join(app.aliases)}") - print(f"Class: {'Class A (Source-Backed)' if app.source else 'Class B (Image-Only)'}") + print( + f"Class: {'Class A (Source-Backed)' if app.source else 'Class B (Image-Only)'}" + ) print(f"Networks: {', '.join(app.networks)}") print(f"Auth Protected: {app.auth}") print(f"Dashboard: {'Visible' if app.visible else 'Hidden'}") @@ -816,7 +901,9 @@ def cmd_info(args: list[str]) -> None: if two_axis.checkout.is_git: print(f" Branch: {two_axis.checkout.branch}") print(f" Commit SHA: {two_axis.checkout.commit_sha}") - print(f" Checkout: {'* Dirty (Uncommitted changes)' if two_axis.checkout.is_dirty else '✓ Clean'}") + print( + f" Checkout: {'* Dirty (Uncommitted changes)' if two_axis.checkout.is_dirty else '✓ Clean'}" + ) print(f" Docker Status: {two_axis.docker_status}") if two_axis.image_revision: print(f" Image Revision:{two_axis.image_revision}") @@ -847,7 +934,10 @@ def cmd_resolve(args: list[str]) -> None: if not app: sys.exit(1) if isinstance(app, SitesApp) and app.manifest_error: - print(f"❌ Error: Workload '{app.name}' has invalid manifest: {app.manifest_error}", file=sys.stderr) + print( + f"❌ Error: Workload '{app.name}' has invalid manifest: {app.manifest_error}", + file=sys.stderr, + ) sys.exit(1) print(json.dumps(app.to_dict())) @@ -874,7 +964,9 @@ def cmd_ssl(args: list[str]) -> None: print(f"Subject: {cert_info['subject']}") print(f"Expiration: {cert_info['not_after']}") if cert_info["days_remaining"] is not None: - print(f"Days Remaining: {cert_info['days_remaining']} days ({cert_info['formatted_expiry']})") + print( + f"Days Remaining: {cert_info['days_remaining']} days ({cert_info['formatted_expiry']})" + ) if cert_info["error"]: print(f"Details/Error: {cert_info['error']}") print() @@ -896,7 +988,9 @@ def cmd_ssl(args: list[str]) -> None: for name, domain in services_to_check: info = ssl_results.get(domain, check_ssl_cert(domain)) - print(f"{name:<20} {domain:<30} {info['status']:<24} {info['issuer']:<20} {info['formatted_expiry']}") + print( + f"{name:<20} {domain:<30} {info['status']:<24} {info['issuer']:<20} {info['formatted_expiry']}" + ) def cmd_complete(args: list[str]) -> None: diff --git a/scripts/core_manifest.py b/scripts/core_manifest.py index 6fbccd4..9280c4b 100644 --- a/scripts/core_manifest.py +++ b/scripts/core_manifest.py @@ -36,17 +36,18 @@ class ManifestValidationError(Exception): """Raised when an application manifest violates schema or security constraints.""" - class RefType(str, Enum): """Semantic classification of an upstream git reference.""" - BRANCH = "branch" # Moving branch (e.g. main, master, develop, release/v1) - TAG = "tag" # Pinned release tag (e.g. v1.0.0, 2.3.1) - COMMIT = "commit" # Immutable commit SHA (40-character hex) + + BRANCH = "branch" # Moving branch (e.g. main, master, develop, release/v1) + TAG = "tag" # Pinned release tag (e.g. v1.0.0, 2.3.1) + COMMIT = "commit" # Immutable commit SHA (40-character hex) UNKNOWN = "unknown" class TransportScheme(str, Enum): """Supported secure git network transports.""" + HTTPS = "https" SSH = "ssh" GIT_SCP = "git_scp" @@ -57,11 +58,20 @@ NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]*$") COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$") SHORT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,12}$") SEMVER_TAG_RE = re.compile(r"^v?[0-9]+(\.[0-9]+)+([a-zA-Z0-9._-]*)$") -SCP_URL_RE = re.compile(r"^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:([0-9]+/)?([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+(\.git)?$") +SCP_URL_RE = re.compile( + r"^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:([0-9]+/)?([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+(\.git)?$" +) ENV_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$") RESERVED_ENV_KEYS = { - "PATH", "LD_PRELOAD", "IFS", "SHELL", "USER", - "CORE_DIR", "SITES_DIR", "ENV_FILE", "HOMESERVER_ENV" + "PATH", + "LD_PRELOAD", + "IFS", + "SHELL", + "USER", + "CORE_DIR", + "SITES_DIR", + "ENV_FILE", + "HOMESERVER_ENV", } ALLOWED_STRATEGIES = {"compose"} @@ -80,35 +90,49 @@ def validate_transport(url: str) -> tuple[TransportScheme, str]: # Reject path traversal / directory escapes if ".." in clean_url or "\\" in clean_url or clean_url.startswith(("/", "~")): - raise ManifestValidationError(f"Prohibited filesystem path or traversal in source URL: '{clean_url}'") + raise ManifestValidationError( + f"Prohibited filesystem path or traversal in source URL: '{clean_url}'" + ) # 1. HTTPS transport if clean_url.startswith("https://"): parsed = urlparse(clean_url) if not parsed.netloc: - raise ManifestValidationError(f"Malformed HTTPS source URL (missing host): '{clean_url}'") + raise ManifestValidationError( + f"Malformed HTTPS source URL (missing host): '{clean_url}'" + ) if not parsed.path or parsed.path == "/": - raise ManifestValidationError(f"Malformed HTTPS source URL (missing repository path): '{clean_url}'") + raise ManifestValidationError( + f"Malformed HTTPS source URL (missing repository path): '{clean_url}'" + ) return TransportScheme.HTTPS, clean_url # 2. Standard SSH transport (ssh://[user@]host[:port]/path) if clean_url.startswith("ssh://"): parsed = urlparse(clean_url) if not parsed.netloc: - raise ManifestValidationError(f"Malformed SSH source URL (missing host): '{clean_url}'") + raise ManifestValidationError( + f"Malformed SSH source URL (missing host): '{clean_url}'" + ) if not parsed.path or parsed.path == "/": - raise ManifestValidationError(f"Malformed SSH source URL (missing repository path): '{clean_url}'") + raise ManifestValidationError( + f"Malformed SSH source URL (missing repository path): '{clean_url}'" + ) return TransportScheme.SSH, clean_url # 3. SCP-style SSH transport (git@host:owner/repo.git) - if clean_url.startswith("git@") or ("@" in clean_url and ":" in clean_url and not clean_url.startswith("http")): + if clean_url.startswith("git@") or ( + "@" in clean_url and ":" in clean_url and not clean_url.startswith("http") + ): if SCP_URL_RE.match(clean_url): return TransportScheme.GIT_SCP, clean_url raise ManifestValidationError(f"Malformed SCP-style source URL: '{clean_url}'") # Reject plaintext HTTP or unsupported schemes if clean_url.startswith("http://"): - raise ManifestValidationError(f"Insecure HTTP source URL rejected (HTTPS or SSH required): '{clean_url}'") + raise ManifestValidationError( + f"Insecure HTTP source URL rejected (HTTPS or SSH required): '{clean_url}'" + ) raise ManifestValidationError( f"Invalid source.url scheme: '{clean_url}'. " @@ -141,7 +165,16 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]: return RefType.TAG, ref # Standard branch naming patterns - if ref in {"main", "master", "develop", "dev", "trunk", "staging", "prod", "production"}: + if ref in { + "main", + "master", + "develop", + "dev", + "trunk", + "staging", + "prod", + "production", + }: return RefType.BRANCH, ref if ref.startswith(("feat/", "fix/", "release/", "chore/", "refactor/")): @@ -153,6 +186,7 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]: class SourceConfig(BaseModel): """Upstream source provenance descriptor.""" + model_config = ConfigDict(extra="forbid") url: str @@ -167,7 +201,9 @@ class SourceConfig(BaseModel): if isinstance(data, dict): src_type = str(data.get("type", "git")).strip().lower() if src_type != "git": - raise ManifestValidationError(f"Unsupported source type '{src_type}'. Only 'git' is supported.") + raise ManifestValidationError( + f"Unsupported source type '{src_type}'. Only 'git' is supported." + ) data["type"] = src_type raw_url = data.get("url") @@ -198,6 +234,7 @@ class SourceConfig(BaseModel): class DeploymentConfig(BaseModel): """Continuous deployment strategy and action policy.""" + model_config = ConfigDict(extra="forbid") strategy: str = "compose" @@ -237,6 +274,7 @@ class DeploymentConfig(BaseModel): class HomepageConfig(BaseModel): """Dashboard card metadata for Homepage.""" + model_config = ConfigDict(extra="forbid") title: str @@ -262,6 +300,7 @@ class Manifest(BaseModel): Authoritative Workload Manifest Model (Schema v1.0). Represents the full contract declared in a workload's app.yaml. """ + model_config = ConfigDict(extra="forbid", populate_by_name=True) name: str @@ -282,8 +321,14 @@ class Manifest(BaseModel): def prepare_manifest(cls, data: Any) -> Any: if isinstance(data, dict): raw_name = data.get("name") - if raw_name is None or not isinstance(raw_name, str) or not raw_name.strip(): - raise ManifestValidationError("Manifest is missing mandatory string field 'name'.") + if ( + raw_name is None + or not isinstance(raw_name, str) + or not raw_name.strip() + ): + raise ManifestValidationError( + "Manifest is missing mandatory string field 'name'." + ) clean_name = raw_name.strip() if not NAME_RE.match(clean_name): raise ManifestValidationError( @@ -359,7 +404,12 @@ class Manifest(BaseModel): @property def is_internal(self) -> bool: """True if the workload does not expose a public TLS endpoint.""" - return not self.domain or self.domain == "internal" or self.domain.endswith(".local") or ":" in self.domain + return ( + not self.domain + or self.domain == "internal" + or self.domain.endswith(".local") + or ":" in self.domain + ) def to_dict(self) -> dict[str, Any]: data: dict[str, Any] = { @@ -387,7 +437,7 @@ class Manifest(BaseModel): def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest: """ Parse and strictly validate an app.yaml manifest into an authoritative Manifest object. - + Accepts: - Path object pointing to an app.yaml - Raw YAML string content @@ -401,23 +451,35 @@ def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest: try: content = raw_input.read_text(encoding="utf-8") except OSError as e: - raise ManifestValidationError(f"Failed to read manifest {raw_input}: {e}") from e + raise ManifestValidationError( + f"Failed to read manifest {raw_input}: {e}" + ) from e try: - data = (yaml.safe_load(content) if yaml else _parse_yaml_basic(content)) or {} + data = ( + yaml.safe_load(content) if yaml else _parse_yaml_basic(content) + ) or {} except Exception as e: - raise ManifestValidationError(f"YAML parsing error in {raw_input}: {e}") from e + raise ManifestValidationError( + f"YAML parsing error in {raw_input}: {e}" + ) from e elif isinstance(raw_input, str): try: - data = (yaml.safe_load(raw_input) if yaml else _parse_yaml_basic(raw_input)) or {} + data = ( + yaml.safe_load(raw_input) if yaml else _parse_yaml_basic(raw_input) + ) or {} except Exception as e: raise ManifestValidationError(f"YAML parsing error: {e}") from e elif isinstance(raw_input, dict): data = raw_input else: - raise ManifestValidationError(f"Invalid input type for manifest parsing: {type(raw_input)}") + raise ManifestValidationError( + f"Invalid input type for manifest parsing: {type(raw_input)}" + ) if not isinstance(data, dict): - raise ManifestValidationError("Manifest root must be a YAML dictionary mapping.") + raise ManifestValidationError( + "Manifest root must be a YAML dictionary mapping." + ) try: return Manifest.model_validate(data) @@ -433,7 +495,9 @@ def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest: msg = msg.removeprefix("Value error, ") loc = ".".join(str(p) for p in first_error.get("loc", [])) if loc and first_error.get("type") == "extra_forbidden": - raise ManifestValidationError(f"Manifest contains unrecognized or forbidden field '{loc}'.") from e + raise ManifestValidationError( + f"Manifest contains unrecognized or forbidden field '{loc}'." + ) from e raise ManifestValidationError(msg) from e diff --git a/scripts/gitops_dispatcher.py b/scripts/gitops_dispatcher.py index 143de42..04570b1 100755 --- a/scripts/gitops_dispatcher.py +++ b/scripts/gitops_dispatcher.py @@ -27,15 +27,23 @@ except ImportError: SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites"))) CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent)) -CONFIG_DIR = Path(os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab"))) -DEPLOYMENTS_FILE = Path(os.environ.get("HOMELAB_DEPLOYMENTS_FILE", CORE_DIR / "config" / "deployments.yaml")) -DEFAULT_SECRET_PATH = Path(os.environ.get("GITOPS_SECRET_FILE", "/run/secrets/gitops/webhook_secret")) -STATE_DIR = Path(os.environ.get("GITOPS_STATE_DIR", Path.home() / ".local/state/homelab/gitops")) +CONFIG_DIR = Path( + os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab")) +) +DEPLOYMENTS_FILE = Path( + os.environ.get("HOMELAB_DEPLOYMENTS_FILE", CORE_DIR / "config" / "deployments.yaml") +) +DEFAULT_SECRET_PATH = Path( + os.environ.get("GITOPS_SECRET_FILE", "/run/secrets/gitops/webhook_secret") +) +STATE_DIR = Path( + os.environ.get("GITOPS_STATE_DIR", Path.home() / ".local/state/homelab/gitops") +) logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] [GitOps] %(message)s", - handlers=[logging.StreamHandler(sys.stdout)] + handlers=[logging.StreamHandler(sys.stdout)], ) logger = logging.getLogger("gitops_dispatcher") @@ -45,7 +53,9 @@ def load_webhook_secret(secret_file: Path | None = None) -> bytes: Load webhook shared secret from projected secret file or environment. Never hardcoded in code or repository manifests. """ - path = secret_file or Path(os.environ.get("GITOPS_SECRET_FILE", DEFAULT_SECRET_PATH)) + path = secret_file or Path( + os.environ.get("GITOPS_SECRET_FILE", DEFAULT_SECRET_PATH) + ) if path.is_file(): try: return path.read_bytes().strip() @@ -68,7 +78,9 @@ def verify_signature(raw_body: bytes, signature: str | None, secret: bytes) -> b Fail-closed: missing signature, malformed signature, empty secret, or mismatch returns False. """ if not secret: - logger.error("Authentication failed: Webhook shared secret is empty or missing.") + logger.error( + "Authentication failed: Webhook shared secret is empty or missing." + ) return False if not signature or not isinstance(signature, str): @@ -79,7 +91,9 @@ def verify_signature(raw_body: bytes, signature: str | None, secret: bytes) -> b cleaned_signature = cleaned_signature.removeprefix("sha256=") # SHA256 hex digest is exactly 64 hexadecimal characters - if len(cleaned_signature) != 64 or not all(c in "0123456789abcdefABCDEF" for c in cleaned_signature): + if len(cleaned_signature) != 64 or not all( + c in "0123456789abcdefABCDEF" for c in cleaned_signature + ): logger.error("Authentication failed: Malformed signature format.") return False @@ -109,7 +123,9 @@ def parse_yaml_simple(text: str) -> dict: item = stripped[2:].strip().strip("\"'") if current_section: if current_subsection and isinstance(data.get(current_section), dict): - if not isinstance(data[current_section].get(current_subsection), list): + if not isinstance( + data[current_section].get(current_subsection), list + ): data[current_section][current_subsection] = [] data[current_section][current_subsection].append(item) else: @@ -161,16 +177,26 @@ def get_trusted_repository_mapping() -> dict[str, Path]: """ mapping: dict[str, Path] = {} - registry_file = DEPLOYMENTS_FILE if DEPLOYMENTS_FILE.is_file() else (CONFIG_DIR / "deployments.yaml") + registry_file = ( + DEPLOYMENTS_FILE + if DEPLOYMENTS_FILE.is_file() + else (CONFIG_DIR / "deployments.yaml") + ) if not registry_file.is_file(): - logger.error(f"Authoritative registry {registry_file} not found. Failing closed with zero admitted repositories.") + logger.error( + f"Authoritative registry {registry_file} not found. Failing closed with zero admitted repositories." + ) return mapping yaml_errors = (yaml.YAMLError,) if yaml is not None else () try: content = registry_file.read_text(encoding="utf-8") - registry = (yaml.safe_load(content) if yaml else parse_yaml_simple(content)) or {} - repo_entries = registry.get("repositories", registry) if isinstance(registry, dict) else {} + registry = ( + yaml.safe_load(content) if yaml else parse_yaml_simple(content) + ) or {} + repo_entries = ( + registry.get("repositories", registry) if isinstance(registry, dict) else {} + ) if isinstance(repo_entries, dict): for reg_name, entry in repo_entries.items(): if not isinstance(entry, dict): @@ -190,20 +216,31 @@ def get_trusted_repository_mapping() -> dict[str, Path]: if isinstance(alias, str) and alias.strip(): mapping[alias.strip()] = p else: - logger.warning(f"Rejecting out-of-bounds path in deployments.yaml for '{reg_name}': {p}") + logger.warning( + f"Rejecting out-of-bounds path in deployments.yaml for '{reg_name}': {p}" + ) else: - logger.error(f"Malformed repositories block in {registry_file}: expected dictionary mapping.") + logger.error( + f"Malformed repositories block in {registry_file}: expected dictionary mapping." + ) return {} - except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError, TypeError, *yaml_errors) as e: - logger.critical(f"Failed to parse authoritative registry {registry_file}: {e}. Failing closed.") + except ( + OSError, + UnicodeDecodeError, + ValueError, + KeyError, + AttributeError, + TypeError, + *yaml_errors, + ) as e: + logger.critical( + f"Failed to parse authoritative registry {registry_file}: {e}. Failing closed." + ) return {} - - return mapping - def resolve_repository(repo_name: str) -> Path | None: """ Resolve a logical repository identity to a trusted local directory. @@ -218,14 +255,18 @@ def resolve_repository(repo_name: str) -> Path | None: return None if ".." in cleaned_name or "/" in cleaned_name or "\\" in cleaned_name: - logger.warning(f"Path traversal characters detected in repository name: '{repo_name}'") + logger.warning( + f"Path traversal characters detected in repository name: '{repo_name}'" + ) return None trusted_mapping = get_trusted_repository_mapping() target = trusted_mapping.get(cleaned_name) if not target: - logger.warning(f"Repository '{cleaned_name}' is not in trusted repository registry.") + logger.warning( + f"Repository '{cleaned_name}' is not in trusted repository registry." + ) return None try: @@ -235,12 +276,18 @@ def resolve_repository(repo_name: str) -> Path | None: return None if not canonical_target.is_dir(): - logger.warning(f"Trusted repository target '{canonical_target}' does not exist or is not a directory.") + logger.warning( + f"Trusted repository target '{canonical_target}' does not exist or is not a directory." + ) return None # Defense-in-depth: check allowed root containment strictly within SITES_DIR - if not (SITES_DIR.is_dir() and canonical_target.is_relative_to(SITES_DIR.resolve())): - logger.warning(f"Resolved path '{canonical_target}' escapes allowed SITES_DIR root for repository '{cleaned_name}'.") + if not ( + SITES_DIR.is_dir() and canonical_target.is_relative_to(SITES_DIR.resolve()) + ): + logger.warning( + f"Resolved path '{canonical_target}' escapes allowed SITES_DIR root for repository '{cleaned_name}'." + ) return None return canonical_target @@ -260,16 +307,17 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]: if manifest_file.is_file(): try: manifest_text = manifest_file.read_text(encoding="utf-8") - manifest = (yaml.safe_load(manifest_text) if yaml else parse_yaml_simple(manifest_text)) or {} + manifest = ( + yaml.safe_load(manifest_text) + if yaml + else parse_yaml_simple(manifest_text) + ) or {} except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e: logger.warning(f"Failed to parse {manifest_file}: {e}") deployment_config = manifest.get("deployment") if not isinstance(deployment_config, dict): - deployment_config = { - "branch": "main", - "actions": ["git_pull", "compose_up"] - } + deployment_config = {"branch": "main", "actions": ["git_pull", "compose_up"]} return target_dir, deployment_config @@ -309,7 +357,10 @@ def validate_compose_security( if compose_file.is_symlink(): resolved_compose = compose_file.resolve() if not resolved_compose.is_relative_to(canonical_allowed_root): - return False, f"Compose file symlink escapes workload root: {compose_file} -> {resolved_compose}" + return ( + False, + f"Compose file symlink escapes workload root: {compose_file} -> {resolved_compose}", + ) try: content = compose_file.read_text(encoding="utf-8") @@ -324,50 +375,89 @@ def validate_compose_security( return False, f"Failed to parse compose YAML {compose_file}: {e}" else: # Fallback regex inspection if yaml module is not present - if re.search(r"^\s*privileged:\s*true\b", content, re.MULTILINE | re.IGNORECASE): + if re.search( + r"^\s*privileged:\s*true\b", content, re.MULTILINE | re.IGNORECASE + ): return False, "Privileged mode is prohibited in workload compose files." if "/var/run/docker.sock" in content: - return False, "Docker socket mounts are prohibited in workload compose files." - if re.search(r"^\s*network_mode:\s*[\"']?host[\"']?", content, re.MULTILINE | re.IGNORECASE): - return False, "Host networking (network_mode: host) is prohibited in workload compose files." + return ( + False, + "Docker socket mounts are prohibited in workload compose files.", + ) + if re.search( + r"^\s*network_mode:\s*[\"']?host[\"']?", + content, + re.MULTILINE | re.IGNORECASE, + ): + return ( + False, + "Host networking (network_mode: host) is prohibited in workload compose files.", + ) if re.search(r"^\s*cap_add:\s*", content, re.MULTILINE | re.IGNORECASE): - return False, "Linux capabilities (cap_add) are prohibited in workload compose files." + return ( + False, + "Linux capabilities (cap_add) are prohibited in workload compose files.", + ) if re.search(r"^\s*devices:\s*", content, re.MULTILINE | re.IGNORECASE): - return False, "Host device mounts (devices) are prohibited in workload compose files." + return ( + False, + "Host device mounts (devices) are prohibited in workload compose files.", + ) if re.search(r"^\s*include:\s*", content, re.MULTILINE | re.IGNORECASE): - return False, "Top-level include directives are prohibited in workload compose files." + return ( + False, + "Top-level include directives are prohibited in workload compose files.", + ) return True, None if not isinstance(data, dict): return False, f"Invalid compose root in {compose_file}: expected mapping" if "include" in data: - return False, "Top-level 'include' directives are prohibited in workload compose files." + return ( + False, + "Top-level 'include' directives are prohibited in workload compose files.", + ) services = data.get("services") if not isinstance(services, dict): return True, None - state_root = Path(os.environ.get("HOMELAB_STATE_ROOT", Path.home() / "var/lib/homelab")).resolve() + state_root = Path( + os.environ.get("HOMELAB_STATE_ROOT", Path.home() / "var/lib/homelab") + ).resolve() target_app_name = app_name or allowed_root.name target_state_root = (state_root / target_app_name).resolve() - top_volumes = set(data.get("volumes", {}).keys()) if isinstance(data.get("volumes"), dict) else set() + top_volumes = ( + set(data.get("volumes", {}).keys()) + if isinstance(data.get("volumes"), dict) + else set() + ) for svc_name, svc in services.items(): if not isinstance(svc, dict): continue if svc.get("privileged") is True: - return False, f"Service '{svc_name}' specifies prohibited 'privileged: true'." + return ( + False, + f"Service '{svc_name}' specifies prohibited 'privileged: true'.", + ) cap_add = svc.get("cap_add") if cap_add: - return False, f"Service '{svc_name}' specifies prohibited 'cap_add' capabilities: {cap_add}." + return ( + False, + f"Service '{svc_name}' specifies prohibited 'cap_add' capabilities: {cap_add}.", + ) devices = svc.get("devices") if devices: - return False, f"Service '{svc_name}' specifies prohibited host device mount: {devices}." + return ( + False, + f"Service '{svc_name}' specifies prohibited host device mount: {devices}.", + ) sec_opts = svc.get("security_opt", []) if isinstance(sec_opts, str): @@ -375,7 +465,10 @@ def validate_compose_security( if isinstance(sec_opts, list): for opt in sec_opts: if any(bad in str(opt).lower() for bad in ("unconfined", "disable")): - return False, f"Service '{svc_name}' specifies prohibited security_opt: {opt}." + return ( + False, + f"Service '{svc_name}' specifies prohibited security_opt: {opt}.", + ) raw_env_files = svc.get("env_file") if raw_env_files: @@ -402,13 +495,22 @@ def validate_compose_security( else: resolved_env = (allowed_root / clean_env).resolve() - if not (allowed_root.is_dir() and resolved_env.is_relative_to(canonical_allowed_root)): - return False, f"Service '{svc_name}' specifies prohibited env_file escaping workload root: '{clean_env}'." + if not ( + allowed_root.is_dir() + and resolved_env.is_relative_to(canonical_allowed_root) + ): + return ( + False, + f"Service '{svc_name}' specifies prohibited env_file escaping workload root: '{clean_env}'.", + ) for ns_key in ("network_mode", "pid", "ipc", "uts", "userns_mode"): val = str(svc.get(ns_key, "")).strip().lower() if val in PROHIBITED_HOST_NAMESPACES: - return False, f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'." + return ( + False, + f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'.", + ) volumes = svc.get("volumes", []) if isinstance(volumes, list): @@ -416,13 +518,19 @@ def validate_compose_security( host_path = "" if isinstance(vol, str): if "/var/run/docker.sock" in vol: - return False, f"Service '{svc_name}' directly mounts Docker socket: {vol}." + return ( + False, + f"Service '{svc_name}' directly mounts Docker socket: {vol}.", + ) if ":" in vol: host_path = vol.split(":")[0].strip() elif isinstance(vol, dict): src = str(vol.get("source", "")) if "/var/run/docker.sock" in src: - return False, f"Service '{svc_name}' directly mounts Docker socket: {src}." + return ( + False, + f"Service '{svc_name}' directly mounts Docker socket: {src}.", + ) if vol.get("type") == "bind": host_path = src @@ -430,12 +538,23 @@ def validate_compose_security( continue # Declared top-level named volume without path separators - if host_path in top_volumes and not (host_path.startswith((".", "/", "~")) or "/" in host_path or "\\" in host_path): + if host_path in top_volumes and not ( + host_path.startswith((".", "/", "~")) + or "/" in host_path + or "\\" in host_path + ): continue # Undeclared named volumes or bare identifiers not starting with ., /, ~ or containing / are prohibited - if not (host_path.startswith((".", "/", "~")) or "/" in host_path or "\\" in host_path): - return False, f"Service '{svc_name}' specifies undeclared named volume or ambiguous path: '{host_path}'." + if not ( + host_path.startswith((".", "/", "~")) + or "/" in host_path + or "\\" in host_path + ): + return ( + False, + f"Service '{svc_name}' specifies undeclared named volume or ambiguous path: '{host_path}'.", + ) # Host bind mount evaluation if host_path.startswith("~"): @@ -447,16 +566,20 @@ def validate_compose_security( expanded = (allowed_root / host_path).resolve() # Containment check: strictly within workload directory or dedicated state root - is_in_workload = allowed_root.is_dir() and expanded.is_relative_to(canonical_allowed_root) + is_in_workload = allowed_root.is_dir() and expanded.is_relative_to( + canonical_allowed_root + ) is_in_own_state = expanded.is_relative_to(target_state_root) if not (is_in_workload or is_in_own_state): - return False, f"Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'." + return ( + False, + f"Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'.", + ) return True, None - def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]: """ Validate deployment policy inside app.yaml. @@ -472,7 +595,10 @@ def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]: # Validate strategy if specified strategy = deployment.get("strategy") if strategy is not None and strategy not in ALLOWED_STRATEGIES: - return False, f"Unsupported deployment strategy '{strategy}'. Allowed strategies: {sorted(ALLOWED_STRATEGIES)}" + return ( + False, + f"Unsupported deployment strategy '{strategy}'. Allowed strategies: {sorted(ALLOWED_STRATEGIES)}", + ) # Validate actions if specified actions = deployment.get("actions") @@ -481,7 +607,10 @@ def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]: return False, "Field 'deployment.actions' must be a list of strings." for action in actions: if not isinstance(action, str) or action not in ALLOWED_ACTIONS: - return False, f"Unsupported deployment action '{action}'. Allowed actions: {sorted(ALLOWED_ACTIONS)}" + return ( + False, + f"Unsupported deployment action '{action}'. Allowed actions: {sorted(ALLOWED_ACTIONS)}", + ) return True, "" @@ -496,18 +625,26 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) - """ expected_branch = deployment_config.get("branch", "main") if branch and branch != expected_branch: - logger.info(f"Skipping deployment: pushed branch '{branch}' != target branch '{expected_branch}'") + logger.info( + f"Skipping deployment: pushed branch '{branch}' != target branch '{expected_branch}'" + ) return True canonical_app_name = target_dir.name.removeprefix("homelab-") manifest_file = target_dir / "app.yaml" if manifest_file.is_file(): with contextlib.suppress(Exception): - pre_manifest = (yaml.safe_load(manifest_file.read_text(encoding="utf-8")) if yaml else parse_yaml_simple(manifest_file.read_text(encoding="utf-8"))) or {} + pre_manifest = ( + yaml.safe_load(manifest_file.read_text(encoding="utf-8")) + if yaml + else parse_yaml_simple(manifest_file.read_text(encoding="utf-8")) + ) or {} if isinstance(pre_manifest, dict) and pre_manifest.get("name"): canonical_app_name = str(pre_manifest["name"]).strip() - logger.info(f"🚀 Deploying '{target_dir.name}' at {target_dir} (branch: {expected_branch})...") + logger.info( + f"🚀 Deploying '{target_dir.name}' at {target_dir} (branch: {expected_branch})..." + ) actions = deployment_config.get("actions", ["git_pull"]) try: @@ -517,8 +654,16 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) - if action == "git_pull": logger.info(f" ↳ [git_pull] Pulling latest '{expected_branch}'...") subprocess.run( - ["git", "-C", str(target_dir), "pull", "--ff-only", "origin", expected_branch], - check=True + [ + "git", + "-C", + str(target_dir), + "pull", + "--ff-only", + "origin", + expected_branch, + ], + check=True, ) # Revision-consistent manifest validation: # The working tree has now advanced to the deployed revision. @@ -527,14 +672,28 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) - if manifest_file.is_file(): try: manifest_text = manifest_file.read_text(encoding="utf-8") - fresh_manifest = (yaml.safe_load(manifest_text) if yaml else parse_yaml_simple(manifest_text)) or {} - except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e: - logger.error(f"❌ Post-pull manifest parse failure in {manifest_file}: {e}") + fresh_manifest = ( + yaml.safe_load(manifest_text) + if yaml + else parse_yaml_simple(manifest_text) + ) or {} + except ( + OSError, + UnicodeDecodeError, + ValueError, + KeyError, + AttributeError, + ) as e: + logger.error( + f"❌ Post-pull manifest parse failure in {manifest_file}: {e}" + ) return False valid, err_msg = validate_manifest_deployment(fresh_manifest) if not valid: - logger.error(f"❌ Post-pull manifest validation failed for '{target_dir.name}': {err_msg}") + logger.error( + f"❌ Post-pull manifest validation failed for '{target_dir.name}': {err_msg}" + ) return False if isinstance(fresh_manifest, dict) and fresh_manifest.get("name"): @@ -559,49 +718,83 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) - if not compose_file.is_file(): compose_file = target_dir / "docker-compose.yaml" if compose_file.is_file(): - valid_sec, sec_err = validate_compose_security(compose_file, target_dir, app_name=canonical_app_name) + valid_sec, sec_err = validate_compose_security( + compose_file, target_dir, app_name=canonical_app_name + ) if not valid_sec: - logger.error(f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}") + logger.error( + f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}" + ) return False - logger.info(" ↳ [compose_up] Recreating containers (docker compose up -d)...") + logger.info( + " ↳ [compose_up] Recreating containers (docker compose up -d)..." + ) subprocess.run( - ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"], - check=True + [ + "docker", + "compose", + "-f", + str(compose_file), + "up", + "-d", + "--remove-orphans", + ], + check=True, ) elif action == "compose_build": compose_file = target_dir / "docker-compose.yml" if not compose_file.is_file(): compose_file = target_dir / "docker-compose.yaml" if compose_file.is_file(): - valid_sec, sec_err = validate_compose_security(compose_file, target_dir, app_name=canonical_app_name) + valid_sec, sec_err = validate_compose_security( + compose_file, target_dir, app_name=canonical_app_name + ) if not valid_sec: - logger.error(f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}") + logger.error( + f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}" + ) return False - logger.info(" ↳ [compose_build] Building & recreating containers...") - subprocess.run( - ["docker", "compose", "-f", str(compose_file), "build"], - check=True + logger.info( + " ↳ [compose_build] Building & recreating containers..." ) subprocess.run( - ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"], - check=True + ["docker", "compose", "-f", str(compose_file), "build"], + check=True, + ) + subprocess.run( + [ + "docker", + "compose", + "-f", + str(compose_file), + "up", + "-d", + "--remove-orphans", + ], + check=True, ) elif action == "compose_restart": compose_file = target_dir / "docker-compose.yml" if not compose_file.is_file(): compose_file = target_dir / "docker-compose.yaml" if compose_file.is_file(): - valid_sec, sec_err = validate_compose_security(compose_file, target_dir, app_name=canonical_app_name) + valid_sec, sec_err = validate_compose_security( + compose_file, target_dir, app_name=canonical_app_name + ) if not valid_sec: - logger.error(f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}") + logger.error( + f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}" + ) return False logger.info(" ↳ [compose_restart] Restarting containers...") subprocess.run( ["docker", "compose", "-f", str(compose_file), "restart"], - check=True + check=True, ) else: - logger.error(f"❌ Unsupported or rejected deployment action '{action}'. Aborting deployment.") + logger.error( + f"❌ Unsupported or rejected deployment action '{action}'. Aborting deployment." + ) return False idx += 1 @@ -611,14 +804,20 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) - except subprocess.CalledProcessError as e: logger.error(f"❌ Deployment step failed with exit code {e.returncode}: {e}") return False - except (subprocess.SubprocessError, OSError, KeyError, TypeError, ValueError, RuntimeError) as e: + except ( + subprocess.SubprocessError, + OSError, + KeyError, + TypeError, + ValueError, + RuntimeError, + ) as e: logger.error(f"❌ Unexpected deployment error: {e}") return False def admit_deployment( - payload: dict, - event_type: str | None = None + payload: dict, event_type: str | None = None ) -> tuple[bool, Path | None, dict, str, str]: """ Evaluate webhook deployment admission against strict policy gates: @@ -632,10 +831,22 @@ def admit_deployment( """ # 1. Event Admission if event_type and event_type.strip().lower() != "push": - return False, None, {}, "", f"Event '{event_type}' is not eligible for deployment. Only 'push' is allowed." + return ( + False, + None, + {}, + "", + f"Event '{event_type}' is not eligible for deployment. Only 'push' is allowed.", + ) if "pull_request" in payload or "issue" in payload or "release" in payload: - return False, None, {}, "", "Payload represents non-push event (pull_request/issue/release). Rejected." + return ( + False, + None, + {}, + "", + "Payload represents non-push event (pull_request/issue/release). Rejected.", + ) # 2. Ref Admission ref = payload.get("ref", "") @@ -646,7 +857,13 @@ def admit_deployment( return False, None, {}, "", f"Tag push '{ref}' is not deployable." if not ref.startswith("refs/heads/"): - return False, None, {}, "", f"Ref '{ref}' is not a head branch. Only 'refs/heads/*' is supported." + return ( + False, + None, + {}, + "", + f"Ref '{ref}' is not a head branch. Only 'refs/heads/*' is supported.", + ) pushed_branch = ref.removeprefix("refs/heads/") if not pushed_branch: @@ -655,16 +872,34 @@ def admit_deployment( # 3. Repository Admission repo_field = payload.get("repository") if not isinstance(repo_field, dict): - return False, None, {}, pushed_branch, "Missing or invalid 'repository' object in payload." + return ( + False, + None, + {}, + pushed_branch, + "Missing or invalid 'repository' object in payload.", + ) repo_name = repo_field.get("name") if not isinstance(repo_name, str) or not repo_name.strip(): - return False, None, {}, pushed_branch, "Missing or empty repository name in payload." + return ( + False, + None, + {}, + pushed_branch, + "Missing or empty repository name in payload.", + ) repo_name = repo_name.strip() target_dir = resolve_repository(repo_name) if not target_dir: - return False, None, {}, pushed_branch, f"Repository '{repo_name}' is not recognized in trusted registry." + return ( + False, + None, + {}, + pushed_branch, + f"Repository '{repo_name}' is not recognized in trusted registry.", + ) # 4. Manifest & Strategy Validation manifest_file = target_dir / "app.yaml" @@ -672,30 +907,55 @@ def admit_deployment( if manifest_file.is_file(): try: manifest_text = manifest_file.read_text(encoding="utf-8") - manifest = (yaml.safe_load(manifest_text) if yaml else parse_yaml_simple(manifest_text)) or {} + manifest = ( + yaml.safe_load(manifest_text) + if yaml + else parse_yaml_simple(manifest_text) + ) or {} except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e: - return False, None, {}, pushed_branch, f"Failed to parse manifest {manifest_file}: {e}" + return ( + False, + None, + {}, + pushed_branch, + f"Failed to parse manifest {manifest_file}: {e}", + ) valid, err_msg = validate_manifest_deployment(manifest) if not valid: - return False, None, {}, pushed_branch, f"Manifest validation error: {err_msg}" + return ( + False, + None, + {}, + pushed_branch, + f"Manifest validation error: {err_msg}", + ) deployment_config = manifest.get("deployment") if not isinstance(deployment_config, dict): - deployment_config = { - "branch": "main", - "actions": ["git_pull", "compose_up"] - } + deployment_config = {"branch": "main", "actions": ["git_pull", "compose_up"]} # 5. Branch Policy Admission expected_branch = deployment_config.get("branch", "main") if pushed_branch != expected_branch: - return False, target_dir, deployment_config, pushed_branch, ( - f"Branch mismatch: pushed branch '{pushed_branch}' does not match " - f"declared target branch '{expected_branch}'." + return ( + False, + target_dir, + deployment_config, + pushed_branch, + ( + f"Branch mismatch: pushed branch '{pushed_branch}' does not match " + f"declared target branch '{expected_branch}'." + ), ) - return True, target_dir, deployment_config, pushed_branch, f"Admitted for deployment on branch '{pushed_branch}'." + return ( + True, + target_dir, + deployment_config, + pushed_branch, + f"Admitted for deployment on branch '{pushed_branch}'.", + ) def get_target_lock(target_name: str) -> Path: @@ -709,10 +969,7 @@ def get_pending_file(target_name: str) -> Path: def enqueue_deployment( - target_dir: Path, - deployment_config: dict, - branch: str, - commit_sha: str = "" + target_dir: Path, deployment_config: dict, branch: str, commit_sha: str = "" ) -> Path: """ Atomically enqueue a deployment request. @@ -732,7 +989,9 @@ def enqueue_deployment( temp_file.write_text(json.dumps(data), encoding="utf-8") temp_file.replace(pending_file) - logger.info(f"📥 Enqueued deployment for '{target_name}' (branch: {branch}, superseding previous pending).") + logger.info( + f"📥 Enqueued deployment for '{target_name}' (branch: {branch}, superseding previous pending)." + ) return pending_file @@ -749,7 +1008,9 @@ def run_target_worker(target_name: str) -> bool: try: fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except (BlockingIOError, OSError): - logger.info(f"Deployment worker for '{target_name}' is already active. Pending update will be picked up.") + logger.info( + f"Deployment worker for '{target_name}' is already active. Pending update will be picked up." + ) return True overall_success = True @@ -783,9 +1044,13 @@ def run_target_worker(target_name: str) -> bool: "success": success, "timestamp": datetime.datetime.now(datetime.UTC).isoformat(), } - status_file.write_text(json.dumps(status_data, indent=2), encoding="utf-8") + status_file.write_text( + json.dumps(status_data, indent=2), encoding="utf-8" + ) except OSError as e: - logger.warning(f"Failed to write deployment status file {status_file}: {e}") + logger.warning( + f"Failed to write deployment status file {status_file}: {e}" + ) if not success: overall_success = False @@ -804,7 +1069,7 @@ def spawn_worker_async(target_name: str): cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, - start_new_session=True + start_new_session=True, ) @@ -856,7 +1121,9 @@ def main(): b_idx = sys.argv.index("--branch") if b_idx + 1 < len(sys.argv): branch = sys.argv[b_idx + 1].replace("refs/heads/", "") - logger.info(f"Local manual trigger: repository='{repo_name}', branch='{branch}'") + logger.info( + f"Local manual trigger: repository='{repo_name}', branch='{branch}'" + ) target_dir, deployment_config = resolve_target(repo_name) if not target_dir or not target_dir.is_dir(): logger.error(f"Target repository '{repo_name}' could not be resolved.") @@ -887,21 +1154,27 @@ def main(): logger.error(f"Invalid JSON payload: {e}") sys.exit(1) - admitted, target_dir, deployment_config, branch, reason = admit_deployment(payload, event_type) + admitted, target_dir, deployment_config, branch, reason = admit_deployment( + payload, event_type + ) if not admitted: logger.warning(f"🚫 Webhook admission rejected: {reason}") # Branch mismatch on valid push is benign skip; other violations fail closed sys.exit(0 if "Branch mismatch" in reason else 1) logger.info(f"✅ Webhook admission passed: {reason}") - assert target_dir is not None, "admitted deployment must have a valid target directory" + assert target_dir is not None, ( + "admitted deployment must have a valid target directory" + ) commit_sha = payload.get("after", "") if not commit_sha and isinstance(payload.get("head_commit"), dict): commit_sha = payload.get("head_commit", {}).get("id", "") enqueue_deployment(target_dir, deployment_config, branch, commit_sha=commit_sha) spawn_worker_async(target_dir.name) - logger.info(f"🚀 Asynchronous deployment scheduled for '{target_dir.name}'. Returning HTTP 200.") + logger.info( + f"🚀 Asynchronous deployment scheduled for '{target_dir.name}'. Returning HTTP 200." + ) sys.exit(0) diff --git a/scripts/provenance.py b/scripts/provenance.py index ae1602a..4673f74 100644 --- a/scripts/provenance.py +++ b/scripts/provenance.py @@ -19,6 +19,7 @@ from core_manifest import Manifest, RefType, SourceConfig class ProvenanceStatus(str, Enum): """Evaluation result of local state vs. upstream software provenance.""" + SYNCED = "✓ Synced" UPDATE_AVAILABLE = "↓ Update Available" IMAGE_ONLY = "— Image-Only (Class B)" @@ -32,6 +33,7 @@ class ProvenanceStatus(str, Enum): @dataclass class CheckoutStatus: """Axis 1: Local deployment checkout state.""" + is_git: bool is_dirty: bool branch: str @@ -51,6 +53,7 @@ class CheckoutStatus: @dataclass class UpstreamProvenance: """Axis 2: Upstream software provenance state.""" + status: ProvenanceStatus remote_sha: str = "" target_ref: str = "" @@ -68,6 +71,7 @@ class UpstreamProvenance: @dataclass class TwoAxisStatus: """Unified inspection combining local deployment and upstream provenance.""" + app_name: str checkout: CheckoutStatus provenance: UpstreamProvenance @@ -198,12 +202,12 @@ def resolve_upstream_provenance( # Commits pinned directly in manifest cannot be checked via ls-remote ref matching if source.ref_type == RefType.COMMIT: - is_match = ( - local_commit and ( - source.ref.startswith(local_commit) or local_commit.startswith(source.ref) - ) + is_match = local_commit and ( + source.ref.startswith(local_commit) or local_commit.startswith(source.ref) + ) + status = ( + ProvenanceStatus.SYNCED if is_match else ProvenanceStatus.UPDATE_AVAILABLE ) - status = ProvenanceStatus.SYNCED if is_match else ProvenanceStatus.UPDATE_AVAILABLE return UpstreamProvenance( status=status, remote_sha=source.ref, @@ -248,10 +252,10 @@ def resolve_upstream_provenance( for line in proc.stdout.splitlines(): parts = line.strip().split() if len(parts) >= 2 and ( - parts[1] == target_ref or - parts[1] == f"refs/heads/{target_ref}" or - parts[1] == f"refs/tags/{target_ref}" or - parts[1] == f"refs/tags/{target_ref}^{{}}" + parts[1] == target_ref + or parts[1] == f"refs/heads/{target_ref}" + or parts[1] == f"refs/tags/{target_ref}" + or parts[1] == f"refs/tags/{target_ref}^{{}}" ): remote_sha = parts[0] # Peaked tags (^{}) take precedence over lightweight tag refs @@ -271,7 +275,9 @@ def resolve_upstream_provenance( # Compare local commit with remote SHA is_synced = False - if local_commit and (remote_sha.startswith(local_commit) or local_commit.startswith(remote_sha[:7])): + if local_commit and ( + remote_sha.startswith(local_commit) or local_commit.startswith(remote_sha[:7]) + ): is_synced = True status = ProvenanceStatus.SYNCED if is_synced else ProvenanceStatus.UPDATE_AVAILABLE diff --git a/tests/security/test_gitops_security.py b/tests/security/test_gitops_security.py index 6777335..29eb91f 100644 --- a/tests/security/test_gitops_security.py +++ b/tests/security/test_gitops_security.py @@ -3,44 +3,41 @@ Security invariant tests for homelab GitOps execution and admission. """ import json -import sys from pathlib import Path from unittest.mock import MagicMock, patch +import gitops_dispatcher import pytest # Add Core to path so scripts can be imported -CORE_ROOT = Path(__file__).resolve().parent.parent.parent -sys.path.insert(0, str(CORE_ROOT / "scripts")) - -import gitops_dispatcher +# Comment-out reason: testing pyproject-level pythonpath definition +# CORE_ROOT = Path(__file__).resolve().parent.parent.parent +# sys.path.insert(0, str(CORE_ROOT / "scripts")) def test_custom_shell_action_is_rejected_without_execution(tmp_path: Path): """Ensure that arbitrary 'custom' actions fail closed and never invoke a shell.""" - deployment_config = { - "branch": "main", - "actions": [ - {"custom": "touch /tmp/pwned"} - ] - } + deployment_config = {"branch": "main", "actions": [{"custom": "touch /tmp/pwned"}]} with patch("subprocess.run") as mock_run: - success = gitops_dispatcher.execute_deployment(tmp_path, deployment_config, branch="main") + success = gitops_dispatcher.execute_deployment( + tmp_path, deployment_config, branch="main" + ) - assert success is False, "execute_deployment must fail closed on 'custom' action" + assert success is False, ( + "execute_deployment must fail closed on 'custom' action" + ) mock_run.assert_not_called() def test_unknown_action_is_rejected(tmp_path: Path): """Ensure that unknown action strings fail closed and abort deployment.""" - deployment_config = { - "branch": "main", - "actions": ["malicious_or_unknown_action"] - } + deployment_config = {"branch": "main", "actions": ["malicious_or_unknown_action"]} with patch("subprocess.run") as mock_run: - success = gitops_dispatcher.execute_deployment(tmp_path, deployment_config, branch="main") + success = gitops_dispatcher.execute_deployment( + tmp_path, deployment_config, branch="main" + ) assert success is False, "execute_deployment must reject unknown actions" mock_run.assert_not_called() @@ -48,14 +45,13 @@ def test_unknown_action_is_rejected(tmp_path: Path): def test_allowed_actions_use_safe_argument_lists(tmp_path: Path): """Ensure that allowed actions execute safely via argument lists without shell=True.""" - deployment_config = { - "branch": "main", - "actions": ["git_pull"] - } + deployment_config = {"branch": "main", "actions": ["git_pull"]} with patch("subprocess.run") as mock_run: mock_run.return_value = MagicMock(returncode=0) - success = gitops_dispatcher.execute_deployment(tmp_path, deployment_config, branch="main") + success = gitops_dispatcher.execute_deployment( + tmp_path, deployment_config, branch="main" + ) assert success is True mock_run.assert_called_once() @@ -82,7 +78,9 @@ def test_resolve_repository_rejects_path_traversal(tmp_path: Path, monkeypatch): ] for payload in traversal_payloads: - assert gitops_dispatcher.resolve_repository(payload) is None, f"Expected {payload} to be rejected" + assert gitops_dispatcher.resolve_repository(payload) is None, ( + f"Expected {payload} to be rejected" + ) def test_resolve_repository_rejects_unknown_repositories(tmp_path: Path, monkeypatch): @@ -120,14 +118,13 @@ def test_resolve_repository_resolves_valid_manifest(tmp_path: Path, monkeypatch) app_dir = sites_dir / "homelab-docs" app_dir.mkdir(parents=True) (app_dir / "app.yaml").write_text( - "name: docs\naliases:\n - doc2site\n - notes\n", - encoding="utf-8" + "name: docs\naliases:\n - doc2site\n - notes\n", encoding="utf-8" ) registry = tmp_path / "deployments.yaml" registry.write_text( f'schemaVersion: "1.0"\nrepositories:\n homelab-docs:\n path: "{app_dir}"\n aliases:\n - docs\n - doc2site\n - notes\n', - encoding="utf-8" + encoding="utf-8", ) monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir) @@ -140,7 +137,6 @@ def test_resolve_repository_resolves_valid_manifest(tmp_path: Path, monkeypatch) assert gitops_dispatcher.resolve_repository("notes") == canonical - def test_resolve_repository_rejects_vault(tmp_path: Path, monkeypatch): """Ensure data vault identities (Brain / second-brain) are not recognized by GitOps.""" sites_dir = tmp_path / "Sites" @@ -189,7 +185,9 @@ repositories: assert "escaped-app" not in mapping -def test_unregistered_sites_directory_rejected_when_registry_active(tmp_path: Path, monkeypatch): +def test_unregistered_sites_directory_rejected_when_registry_active( + tmp_path: Path, monkeypatch +): """Ensure unregistered directories in ~/Sites cannot be resolved when deployments.yaml is active.""" sites_dir = tmp_path / "Sites" registered_dir = sites_dir / "homelab-docs" @@ -224,7 +222,9 @@ def test_missing_or_corrupt_registry_fails_closed(tmp_path: Path, monkeypatch): missing_registry = tmp_path / "nonexistent-deployments.yaml" monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir) monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", missing_registry) - monkeypatch.setattr(gitops_dispatcher, "CONFIG_DIR", tmp_path / "nonexistent-config") + monkeypatch.setattr( + gitops_dispatcher, "CONFIG_DIR", tmp_path / "nonexistent-config" + ) # Missing registry must fail closed: empty mapping, no resolution assert gitops_dispatcher.get_trusted_repository_mapping() == {} @@ -232,14 +232,15 @@ def test_missing_or_corrupt_registry_fails_closed(tmp_path: Path, monkeypatch): # Corrupt YAML registry must also fail closed corrupt_registry = tmp_path / "corrupt-deployments.yaml" - corrupt_registry.write_text("schemaVersion: 1.0\nrepositories: [bad list syntax", encoding="utf-8") + corrupt_registry.write_text( + "schemaVersion: 1.0\nrepositories: [bad list syntax", encoding="utf-8" + ) monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", corrupt_registry) assert gitops_dispatcher.get_trusted_repository_mapping() == {} assert gitops_dispatcher.resolve_repository("valid") is None - def test_webhook_verification_valid_signature(): """Ensure valid HMAC-SHA256 signature passes verification.""" import hashlib @@ -251,7 +252,10 @@ def test_webhook_verification_valid_signature(): assert gitops_dispatcher.verify_signature(body, expected_hex, secret) is True # Support sha256= prefix as well - assert gitops_dispatcher.verify_signature(body, f"sha256={expected_hex}", secret) is True + assert ( + gitops_dispatcher.verify_signature(body, f"sha256={expected_hex}", secret) + is True + ) def test_webhook_verification_invalid_signature(): @@ -316,7 +320,10 @@ def test_webhook_verification_malformed_signature(): secret = b"supersecrettoken123" body = b'{"repository": {"name": "docs"}}' - assert gitops_dispatcher.verify_signature(body, "not-a-valid-hex-digest", secret) is False + assert ( + gitops_dispatcher.verify_signature(body, "not-a-valid-hex-digest", secret) + is False + ) assert gitops_dispatcher.verify_signature(body, "deadbeef", secret) is False assert gitops_dispatcher.verify_signature(body, "z" * 64, secret) is False @@ -326,36 +333,35 @@ def test_admission_rejects_non_push_events(tmp_path: Path): payload_pr = { "ref": "refs/heads/main", "repository": {"name": "docs"}, - "pull_request": {"id": 1} + "pull_request": {"id": 1}, } - admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload_pr, event_type="push") + admitted, _, _, _, reason = gitops_dispatcher.admit_deployment( + payload_pr, event_type="push" + ) assert admitted is False assert "non-push event" in reason - payload_normal = { - "ref": "refs/heads/main", - "repository": {"name": "docs"} - } - admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload_normal, event_type="pull_request") + payload_normal = {"ref": "refs/heads/main", "repository": {"name": "docs"}} + admitted, _, _, _, reason = gitops_dispatcher.admit_deployment( + payload_normal, event_type="pull_request" + ) assert admitted is False assert "Only 'push' is allowed" in reason def test_admission_rejects_tags_and_invalid_refs(): """Ensure tags or invalid ref structures are rejected from deployment.""" - tag_payload = { - "ref": "refs/tags/v1.0.0", - "repository": {"name": "docs"} - } - admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(tag_payload, event_type="push") + tag_payload = {"ref": "refs/tags/v1.0.0", "repository": {"name": "docs"}} + admitted, _, _, _, reason = gitops_dispatcher.admit_deployment( + tag_payload, event_type="push" + ) assert admitted is False assert "Tag push" in reason - non_head_payload = { - "ref": "refs/pull/42/head", - "repository": {"name": "docs"} - } - admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(non_head_payload, event_type="push") + non_head_payload = {"ref": "refs/pull/42/head", "repository": {"name": "docs"}} + admitted, _, _, _, reason = gitops_dispatcher.admit_deployment( + non_head_payload, event_type="push" + ) assert admitted is False assert "not a head branch" in reason @@ -366,11 +372,10 @@ def test_admission_rejects_unknown_repository(tmp_path: Path, monkeypatch): sites_dir.mkdir() monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir) - payload = { - "ref": "refs/heads/main", - "repository": {"name": "unregistered-app"} - } - admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push") + payload = {"ref": "refs/heads/main", "repository": {"name": "unregistered-app"}} + admitted, _, _, _, reason = gitops_dispatcher.admit_deployment( + payload, event_type="push" + ) assert admitted is False assert "not recognized" in reason @@ -381,8 +386,7 @@ def test_admission_rejects_branch_mismatch(tmp_path: Path, monkeypatch): app_dir = sites_dir / "homelab-docs" app_dir.mkdir(parents=True) (app_dir / "app.yaml").write_text( - "name: docs\ndeployment:\n branch: production\n", - encoding="utf-8" + "name: docs\ndeployment:\n branch: production\n", encoding="utf-8" ) registry = tmp_path / "deployments.yaml" registry.write_text( @@ -392,11 +396,10 @@ def test_admission_rejects_branch_mismatch(tmp_path: Path, monkeypatch): monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir) monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry) - payload = { - "ref": "refs/heads/staging", - "repository": {"name": "docs"} - } - admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push") + payload = {"ref": "refs/heads/staging", "repository": {"name": "docs"}} + admitted, _, _, _, reason = gitops_dispatcher.admit_deployment( + payload, event_type="push" + ) assert admitted is False assert "Branch mismatch" in reason @@ -408,7 +411,7 @@ def test_admission_rejects_unsupported_strategy(tmp_path: Path, monkeypatch): app_dir.mkdir(parents=True) (app_dir / "app.yaml").write_text( "name: docs\ndeployment:\n branch: main\n strategy: kubernetes\n", - encoding="utf-8" + encoding="utf-8", ) registry = tmp_path / "deployments.yaml" registry.write_text( @@ -418,11 +421,10 @@ def test_admission_rejects_unsupported_strategy(tmp_path: Path, monkeypatch): monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir) monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry) - payload = { - "ref": "refs/heads/main", - "repository": {"name": "docs"} - } - admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push") + payload = {"ref": "refs/heads/main", "repository": {"name": "docs"}} + admitted, _, _, _, reason = gitops_dispatcher.admit_deployment( + payload, event_type="push" + ) assert admitted is False assert "Unsupported deployment strategy" in reason @@ -434,7 +436,7 @@ def test_admission_rejects_unsupported_actions(tmp_path: Path, monkeypatch): app_dir.mkdir(parents=True) (app_dir / "app.yaml").write_text( "name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n", - encoding="utf-8" + encoding="utf-8", ) registry = tmp_path / "deployments.yaml" registry.write_text( @@ -444,11 +446,10 @@ def test_admission_rejects_unsupported_actions(tmp_path: Path, monkeypatch): monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir) monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry) - payload = { - "ref": "refs/heads/main", - "repository": {"name": "docs"} - } - admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push") + payload = {"ref": "refs/heads/main", "repository": {"name": "docs"}} + admitted, _, _, _, reason = gitops_dispatcher.admit_deployment( + payload, event_type="push" + ) assert admitted is False assert "Unsupported deployment action" in reason @@ -460,7 +461,7 @@ def test_admission_admits_valid_push(tmp_path: Path, monkeypatch): app_dir.mkdir(parents=True) (app_dir / "app.yaml").write_text( "name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n", - encoding="utf-8" + encoding="utf-8", ) registry = tmp_path / "deployments.yaml" registry.write_text( @@ -470,11 +471,10 @@ def test_admission_admits_valid_push(tmp_path: Path, monkeypatch): monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir) monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry) - payload = { - "ref": "refs/heads/main", - "repository": {"name": "docs"} - } - admitted, target_dir, config, branch, reason = gitops_dispatcher.admit_deployment(payload, event_type="push") + payload = {"ref": "refs/heads/main", "repository": {"name": "docs"}} + admitted, target_dir, config, branch, reason = gitops_dispatcher.admit_deployment( + payload, event_type="push" + ) assert admitted is True assert "Admitted" in reason @@ -492,16 +492,22 @@ def test_enqueue_supersedes_pending_revision(tmp_path: Path, monkeypatch): target_dir.mkdir() # Enqueue revision A - gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "A"}, "main") + gitops_dispatcher.enqueue_deployment( + target_dir, {"branch": "main", "rev": "A"}, "main" + ) pending_file = gitops_dispatcher.get_pending_file("app") assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "A" # Enqueue revision B (supersedes A) - gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "B"}, "main") + gitops_dispatcher.enqueue_deployment( + target_dir, {"branch": "main", "rev": "B"}, "main" + ) assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "B" # Enqueue revision C (supersedes B) - gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "C"}, "main") + gitops_dispatcher.enqueue_deployment( + target_dir, {"branch": "main", "rev": "C"}, "main" + ) assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "C" @@ -538,20 +544,28 @@ def test_serialized_worker_race_superseding(tmp_path: Path, monkeypatch): monkeypatch.setattr(gitops_dispatcher, "execute_deployment", mock_execute) # 1. Enqueue A - gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "A"}, "main") + gitops_dispatcher.enqueue_deployment( + target_dir, {"branch": "main", "rev": "A"}, "main" + ) # Start worker in thread (takes A) - worker_thread = threading.Thread(target=gitops_dispatcher.run_target_worker, args=("app",)) + worker_thread = threading.Thread( + target=gitops_dispatcher.run_target_worker, args=("app",) + ) worker_thread.start() # Wait for A to start executing assert a_started_event.wait(timeout=2.0) is True # 2. B arrives while A is running - gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "B"}, "main") + gitops_dispatcher.enqueue_deployment( + target_dir, {"branch": "main", "rev": "B"}, "main" + ) # 3. C arrives while A is running (supersedes B) - gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "C"}, "main") + gitops_dispatcher.enqueue_deployment( + target_dir, {"branch": "main", "rev": "C"}, "main" + ) # Let A complete b_and_c_enqueued_event.set() @@ -559,7 +573,9 @@ def test_serialized_worker_race_superseding(tmp_path: Path, monkeypatch): worker_thread.join(timeout=3.0) # Verification: A was executed, B was superseded/skipped, C was executed! - assert executed_revisions == ["A", "C"], f"Expected ['A', 'C'] but got {executed_revisions}" + assert executed_revisions == ["A", "C"], ( + f"Expected ['A', 'C'] but got {executed_revisions}" + ) def test_post_pull_manifest_validation_rejects_unsupported_action(tmp_path: Path): @@ -570,24 +586,31 @@ def test_post_pull_manifest_validation_rejects_unsupported_action(tmp_path: Path app_dir = tmp_path / "app" app_dir.mkdir() manifest_file = app_dir / "app.yaml" - manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n") - (app_dir / "docker-compose.yml").write_text("version: '3'\nservices:\n web:\n image: nginx\n") + manifest_file.write_text( + "name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n" + ) + (app_dir / "docker-compose.yml").write_text( + "version: '3'\nservices:\n web:\n image: nginx\n" + ) - initial_config = { - "branch": "main", - "actions": ["git_pull", "compose_up"] - } + initial_config = {"branch": "main", "actions": ["git_pull", "compose_up"]} def mock_pull(cmd, check=True): if "pull" in cmd: # Simulate git pull bringing in an invalid action in app.yaml - manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n") + manifest_file.write_text( + "name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n" + ) return MagicMock(returncode=0) with patch("subprocess.run", side_effect=mock_pull) as mock_run: - success = gitops_dispatcher.execute_deployment(app_dir, initial_config, branch="main") + success = gitops_dispatcher.execute_deployment( + app_dir, initial_config, branch="main" + ) - assert success is False, "Deployment must fail closed when pulled revision has invalid actions" + assert success is False, ( + "Deployment must fail closed when pulled revision has invalid actions" + ) # Only git pull was called; compose_up was never reached! calls = [c[0][0] for c in mock_run.call_args_list] assert len(calls) == 1 @@ -602,24 +625,31 @@ def test_post_pull_manifest_validation_rejects_branch_policy_mismatch(tmp_path: app_dir = tmp_path / "app" app_dir.mkdir() manifest_file = app_dir / "app.yaml" - manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n") - (app_dir / "docker-compose.yml").write_text("version: '3'\nservices:\n web:\n image: nginx\n") + manifest_file.write_text( + "name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n" + ) + (app_dir / "docker-compose.yml").write_text( + "version: '3'\nservices:\n web:\n image: nginx\n" + ) - initial_config = { - "branch": "main", - "actions": ["git_pull", "compose_up"] - } + initial_config = {"branch": "main", "actions": ["git_pull", "compose_up"]} def mock_pull(cmd, check=True): if "pull" in cmd: # Simulate git pull bringing in an app.yaml that targets 'staging', not 'main' - manifest_file.write_text("name: app\ndeployment:\n branch: staging\n actions:\n - git_pull\n - compose_up\n") + manifest_file.write_text( + "name: app\ndeployment:\n branch: staging\n actions:\n - git_pull\n - compose_up\n" + ) return MagicMock(returncode=0) with patch("subprocess.run", side_effect=mock_pull) as mock_run: - success = gitops_dispatcher.execute_deployment(app_dir, initial_config, branch="main") + success = gitops_dispatcher.execute_deployment( + app_dir, initial_config, branch="main" + ) - assert success is False, "Deployment must fail closed on post-pull branch mismatch" + assert success is False, ( + "Deployment must fail closed on post-pull branch mismatch" + ) calls = [c[0][0] for c in mock_run.call_args_list] assert len(calls) == 1 assert "pull" in calls[0] @@ -633,22 +663,27 @@ def test_post_pull_manifest_adopts_updated_actions(tmp_path: Path): app_dir = tmp_path / "app" app_dir.mkdir() manifest_file = app_dir / "app.yaml" - manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n") - (app_dir / "docker-compose.yml").write_text("version: '3'\nservices:\n web:\n image: nginx\n") + manifest_file.write_text( + "name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n" + ) + (app_dir / "docker-compose.yml").write_text( + "version: '3'\nservices:\n web:\n image: nginx\n" + ) - initial_config = { - "branch": "main", - "actions": ["git_pull", "compose_up"] - } + initial_config = {"branch": "main", "actions": ["git_pull", "compose_up"]} def mock_pull(cmd, check=True): if "pull" in cmd: # Revision updates action to compose_build - manifest_file.write_text("name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_build\n") + manifest_file.write_text( + "name: app\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_build\n" + ) return MagicMock(returncode=0) with patch("subprocess.run", side_effect=mock_pull) as mock_run: - success = gitops_dispatcher.execute_deployment(app_dir, initial_config, branch="main") + success = gitops_dispatcher.execute_deployment( + app_dir, initial_config, branch="main" + ) assert success is True calls = [c[0][0] for c in mock_run.call_args_list] @@ -668,10 +703,7 @@ def test_worker_records_status_file(tmp_path: Path, monkeypatch): monkeypatch.setattr(gitops_dispatcher, "execute_deployment", lambda t, c, b: True) gitops_dispatcher.enqueue_deployment( - target_dir, - {"branch": "main"}, - "main", - commit_sha="abcdef123456" + target_dir, {"branch": "main"}, "main", commit_sha="abcdef123456" ) success = gitops_dispatcher.run_target_worker("app") @@ -690,12 +722,15 @@ def test_worker_records_status_file(tmp_path: Path, monkeypatch): def test_validate_compose_security_rejects_privileged(tmp_path: Path): """Ensure docker-compose with privileged: true fails pre-flight validation.""" compose_file = tmp_path / "docker-compose.yml" - compose_file.write_text(""" + compose_file.write_text( + """ services: app: image: alpine:latest privileged: true -""", encoding="utf-8") +""", + encoding="utf-8", + ) valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path) assert valid is False assert err is not None and "privileged: true" in err @@ -705,19 +740,23 @@ def test_validate_compose_security_rejects_docker_socket_mount(tmp_path: Path): """Ensure docker-compose with /var/run/docker.sock mount fails validation.""" # Test string syntax compose_file = tmp_path / "docker-compose.yml" - compose_file.write_text(""" + compose_file.write_text( + """ services: app: image: alpine:latest volumes: - /var/run/docker.sock:/var/run/docker.sock -""", encoding="utf-8") +""", + encoding="utf-8", + ) valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path) assert valid is False assert err is not None and "Docker socket" in err # Test dict / long syntax - compose_file.write_text(""" + compose_file.write_text( + """ services: app: image: alpine:latest @@ -725,7 +764,9 @@ services: - type: bind source: /var/run/docker.sock target: /var/run/docker.sock -""", encoding="utf-8") +""", + encoding="utf-8", + ) valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path) assert valid is False assert err is not None and "Docker socket" in err @@ -734,12 +775,15 @@ services: def test_validate_compose_security_rejects_host_network(tmp_path: Path): """Ensure docker-compose with network_mode: host fails pre-flight validation.""" compose_file = tmp_path / "docker-compose.yml" - compose_file.write_text(""" + compose_file.write_text( + """ services: app: image: alpine:latest network_mode: host -""", encoding="utf-8") +""", + encoding="utf-8", + ) valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path) assert valid is False assert err is not None and "network_mode: host" in err @@ -748,13 +792,16 @@ services: def test_validate_compose_security_rejects_out_of_bounds_host_bind(tmp_path: Path): """Ensure host bind mounts outside workload directory or state root are rejected.""" compose_file = tmp_path / "docker-compose.yml" - compose_file.write_text(""" + compose_file.write_text( + """ services: app: image: alpine:latest volumes: - /etc/shadow:/etc/shadow:ro -""", encoding="utf-8") +""", + encoding="utf-8", + ) valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path) assert valid is False assert err is not None and "prohibited host bind mount" in err @@ -765,7 +812,8 @@ def test_validate_compose_security_allows_safe_compose(tmp_path: Path): data_dir = tmp_path / "data" data_dir.mkdir() compose_file = tmp_path / "docker-compose.yml" - compose_file.write_text(f""" + compose_file.write_text( + f""" services: app: image: alpine:latest @@ -774,7 +822,9 @@ services: - named_vol:/var/log volumes: named_vol: -""", encoding="utf-8") +""", + encoding="utf-8", + ) valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path) assert valid is True assert err is None @@ -788,11 +838,14 @@ def test_validate_compose_security_nonexistent_file(tmp_path: Path): assert err is None -@pytest.mark.parametrize("malicious_volume", [ - "../../etc/passwd:/mnt/passwd:ro", - "./../../Core/nixos/secrets.yaml:/secrets.yaml", - "../other-workload/data:/data", -]) +@pytest.mark.parametrize( + "malicious_volume", + [ + "../../etc/passwd:/mnt/passwd:ro", + "./../../Core/nixos/secrets.yaml:/secrets.yaml", + "../other-workload/data:/data", + ], +) def test_validate_compose_security_blocks_relative_traversal( tmp_path: Path, malicious_volume: str ): @@ -806,8 +859,12 @@ def test_validate_compose_security_blocks_relative_traversal( encoding="utf-8", ) - valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app") - assert valid is False, f"Expected relative traversal '{malicious_volume}' to be rejected!" + valid, err = gitops_dispatcher.validate_compose_security( + compose_file, app_dir, app_name="my-app" + ) + assert valid is False, ( + f"Expected relative traversal '{malicious_volume}' to be rejected!" + ) assert err is not None and "prohibited host bind mount" in err @@ -831,27 +888,38 @@ def test_validate_compose_security_blocks_cross_tenant_state_mounts( encoding="utf-8", ) - valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app") + valid, err = gitops_dispatcher.validate_compose_security( + compose_file, app_dir, app_name="my-app" + ) assert valid is False, "Expected cross-tenant state mount to be rejected!" - assert err is not None and ("prohibited host bind mount" in err or "cross-tenant" in err.lower()) + assert err is not None and ( + "prohibited host bind mount" in err or "cross-tenant" in err.lower() + ) # Authorized own state mount must pass compose_file.write_text( f"services:\n web:\n image: nginx\n volumes:\n - '{state_root}/my-app:/data'\n", encoding="utf-8", ) - valid_own, err_own = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app") - assert valid_own is True, f"Own state mount should be permitted, got error: {err_own}" + valid_own, err_own = gitops_dispatcher.validate_compose_security( + compose_file, app_dir, app_name="my-app" + ) + assert valid_own is True, ( + f"Own state mount should be permitted, got error: {err_own}" + ) -@pytest.mark.parametrize("unsafe_directive", [ - "cap_add:\n - SYS_ADMIN", - "pid: host", - "ipc: host", - "userns_mode: host", - "devices:\n - /dev/sda:/dev/sda", - "security_opt:\n - apparmor:unconfined", -]) +@pytest.mark.parametrize( + "unsafe_directive", + [ + "cap_add:\n - SYS_ADMIN", + "pid: host", + "ipc: host", + "userns_mode: host", + "devices:\n - /dev/sda:/dev/sda", + "security_opt:\n - apparmor:unconfined", + ], +) def test_validate_compose_security_blocks_privilege_escalation_primitives( tmp_path: Path, unsafe_directive: str ): @@ -861,7 +929,9 @@ def test_validate_compose_security_blocks_privilege_escalation_primitives( f"services:\n app:\n image: alpine\n {unsafe_directive}\n", encoding="utf-8", ) - valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="app") + valid, err = gitops_dispatcher.validate_compose_security( + compose_file, tmp_path, app_name="app" + ) assert valid is False, f"Directive should be blocked:\n{unsafe_directive}" assert err is not None @@ -869,14 +939,19 @@ def test_validate_compose_security_blocks_privilege_escalation_primitives( def test_validate_compose_security_rejects_top_level_include(tmp_path: Path): """Ensure top-level Compose include directives are rejected to prevent out-of-tree includes.""" compose_file = tmp_path / "docker-compose.yml" - compose_file.write_text(""" + compose_file.write_text( + """ include: - /etc/shadow services: app: image: alpine -""", encoding="utf-8") - valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="app") +""", + encoding="utf-8", + ) + valid, err = gitops_dispatcher.validate_compose_security( + compose_file, tmp_path, app_name="app" + ) assert valid is False assert err is not None and "include" in err.lower() @@ -891,7 +966,9 @@ def test_validate_compose_security_rejects_symlink_escape(tmp_path: Path): compose_link = app_dir / "docker-compose.yml" compose_link.symlink_to(outside_file) - valid, err = gitops_dispatcher.validate_compose_security(compose_link, app_dir, app_name="my-app") + valid, err = gitops_dispatcher.validate_compose_security( + compose_link, app_dir, app_name="my-app" + ) assert valid is False assert err is not None and "symlink" in err.lower() @@ -904,37 +981,52 @@ def test_validate_compose_security_rejects_escaping_env_file(tmp_path: Path): # 1. Escaping absolute path compose_file = app_dir / "docker-compose.yml" - compose_file.write_text(""" + compose_file.write_text( + """ services: app: image: alpine env_file: /run/secrets/homeserver.env -""", encoding="utf-8") - valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app") +""", + encoding="utf-8", + ) + valid, err = gitops_dispatcher.validate_compose_security( + compose_file, app_dir, app_name="my-app" + ) assert valid is False assert err is not None and "env_file" in err.lower() # 2. Escaping relative path in list - compose_file.write_text(""" + compose_file.write_text( + """ services: app: image: alpine env_file: - valid.env - ../../Core/.env -""", encoding="utf-8") - valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app") +""", + encoding="utf-8", + ) + valid, err = gitops_dispatcher.validate_compose_security( + compose_file, app_dir, app_name="my-app" + ) assert valid is False assert err is not None and "env_file" in err.lower() # 3. Valid local env_file - compose_file.write_text(""" + compose_file.write_text( + """ services: app: image: alpine env_file: valid.env -""", encoding="utf-8") - valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app") +""", + encoding="utf-8", + ) + valid, err = gitops_dispatcher.validate_compose_security( + compose_file, app_dir, app_name="my-app" + ) assert valid is True assert err is None @@ -942,14 +1034,19 @@ services: def test_validate_compose_security_rejects_undeclared_named_volumes(tmp_path: Path): """Ensure ambiguous volume paths not declared in top-level volumes are rejected.""" compose_file = tmp_path / "docker-compose.yml" - compose_file.write_text(""" + compose_file.write_text( + """ services: app: image: alpine volumes: - rogue_named_volume:/data -""", encoding="utf-8") - valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="my-app") +""", + encoding="utf-8", + ) + valid, err = gitops_dispatcher.validate_compose_security( + compose_file, tmp_path, app_name="my-app" + ) assert valid is False assert err is not None and "undeclared" in err.lower() @@ -957,20 +1054,17 @@ services: def test_validate_compose_security_handles_string_security_opt(tmp_path: Path): """Ensure security_opt specified as string instead of list is strictly checked.""" compose_file = tmp_path / "docker-compose.yml" - compose_file.write_text(""" + compose_file.write_text( + """ services: app: image: alpine security_opt: "apparmor:unconfined" -""", encoding="utf-8") - valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="my-app") +""", + encoding="utf-8", + ) + valid, err = gitops_dispatcher.validate_compose_security( + compose_file, tmp_path, app_name="my-app" + ) assert valid is False assert err is not None and "security_opt" in err.lower() - - - - - - - - diff --git a/tests/security/test_security_invariants.py b/tests/security/test_security_invariants.py index ba093dc..9cd6c28 100644 --- a/tests/security/test_security_invariants.py +++ b/tests/security/test_security_invariants.py @@ -10,11 +10,11 @@ from pathlib import Path import yaml +# Comment-out reason: testing pyproject-level pythonpath definition CORE_ROOT = Path(__file__).resolve().parent.parent.parent def test_socket_proxy_is_strictly_read_only(): - """Ensure socket-proxy container blocks state-modifying requests (POST=0, DELETE=0).""" compose_path = CORE_ROOT / "docker-compose.yml" with open(compose_path, encoding="utf-8") as f: @@ -47,8 +47,12 @@ def test_no_direct_docker_sock_mounts_except_socket_proxy(): volumes = svc.get("volumes", []) for vol in volumes: if isinstance(vol, str) and "/var/run/docker.sock" in vol: - assert name == "socket-proxy", f"Service '{name}' directly mounts docker.sock!" - assert vol.endswith(":ro"), "socket-proxy docker.sock mount must be read-only (:ro)" + assert name == "socket-proxy", ( + f"Service '{name}' directly mounts docker.sock!" + ) + assert vol.endswith(":ro"), ( + "socket-proxy docker.sock mount must be read-only (:ro)" + ) def test_no_privileged_containers(): @@ -60,7 +64,9 @@ def test_no_privileged_containers(): services = compose.get("services", {}) for name, svc in services.items(): privileged = svc.get("privileged", False) - assert privileged is not True, f"Service '{name}' is configured as privileged: true!" + assert privileged is not True, ( + f"Service '{name}' is configured as privileged: true!" + ) def test_no_shell_true_in_core_scripts(): @@ -78,10 +84,14 @@ def test_portainer_is_deprecated_and_absent(): compose = yaml.safe_load(f) services = compose.get("services", {}) - assert "portainer" not in services, "Deprecated service 'portainer' must not exist in docker-compose.yml" + assert "portainer" not in services, ( + "Deprecated service 'portainer' must not exist in docker-compose.yml" + ) volumes = compose.get("volumes", {}) or {} - assert "portainer_data" not in volumes, "Deprecated volume 'portainer_data' must not exist in docker-compose.yml" + assert "portainer_data" not in volumes, ( + "Deprecated volume 'portainer_data' must not exist in docker-compose.yml" + ) def test_no_eval_in_appctl_script(): @@ -113,7 +123,9 @@ env: """ (app_dir / "app.yaml").write_text(app_yaml.strip(), encoding="utf-8") - (app_dir / "docker-compose.yml").write_text("services:\n web:\n image: nginx\n", encoding="utf-8") + (app_dir / "docker-compose.yml").write_text( + "services:\n web:\n image: nginx\n", encoding="utf-8" + ) # 2. Setup mock docker binary to capture environment without requiring a running Docker daemon mock_bin = tmp_path / "bin" @@ -152,10 +164,13 @@ exit 0 check=False, ) - # 4. Assertions: command substitution was not executed, script ran, and mock docker received literal value - assert not canary.exists(), "Command substitution was executed on the host during environment setup!" - assert res.returncode == 0, f"appctl config failed: {res.stderr}\nStdout: {res.stdout}" + assert not canary.exists(), ( + "Command substitution was executed on the host during environment setup!" + ) + assert res.returncode == 0, ( + f"appctl config failed: {res.stderr}\nStdout: {res.stdout}" + ) assert "MOCK_DOCKER_COMPOSE_CONFIG" in res.stdout assert f"CAPTURED_INJECTION={payload}" in res.stdout assert "CAPTURED_NORMAL=safe_value" in res.stdout @@ -182,16 +197,17 @@ def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests( for file_path in candidate_files: if ( file_path.is_file() - and file_path.suffix in (".py", ".sh", ".bash", ".yml", ".yaml", ".md", ".nix", "") + and file_path.suffix + in (".py", ".sh", ".bash", ".yml", ".yaml", ".md", ".nix", "") and file_path.name != "test_security_invariants.py" ): content = file_path.read_text(encoding="utf-8", errors="ignore") for term in forbidden: if term in content: - violations.append(f"{file_path.relative_to(CORE_ROOT)}: contains prohibited literal '{term}'") - - assert not violations, "Platform genericism violations detected:\n" + "\n".join(violations) - - - + violations.append( + f"{file_path.relative_to(CORE_ROOT)}: contains prohibited literal '{term}'" + ) + assert not violations, "Platform genericism violations detected:\n" + "\n".join( + violations + ) diff --git a/tests/structural/test_repository_structure.py b/tests/structural/test_repository_structure.py index f971683..f0a6656 100644 --- a/tests/structural/test_repository_structure.py +++ b/tests/structural/test_repository_structure.py @@ -36,7 +36,9 @@ def test_required_architectural_paths_exist(): pre_commit = CORE_ROOT / ".githooks" / "pre-commit" assert pre_commit.is_file(), ".githooks/pre-commit must be a regular file" - assert os.access(pre_commit, os.X_OK), ".githooks/pre-commit must be marked executable" + assert os.access(pre_commit, os.X_OK), ( + ".githooks/pre-commit must be marked executable" + ) def test_deprecated_legacy_structures_are_absent(): @@ -61,4 +63,7 @@ def test_unlicense_preserved(): unlicense = CORE_ROOT / "UNLICENSE" assert unlicense.is_file(), "UNLICENSE file must be present" content = unlicense.read_text(encoding="utf-8") - assert "This is free and unencumbered software released into the public domain." in content + assert ( + "This is free and unencumbered software released into the public domain." + in content + ) diff --git a/tests/unit/test_appctl_engine.py b/tests/unit/test_appctl_engine.py index 98b8f86..2666dea 100644 --- a/tests/unit/test_appctl_engine.py +++ b/tests/unit/test_appctl_engine.py @@ -1,20 +1,19 @@ -import sys from dataclasses import dataclass from pathlib import Path from unittest.mock import MagicMock +import appctl_engine as engine import pytest # Import appctl engine -CORE_ROOT = Path(__file__).resolve().parent.parent.parent -sys.path.insert(0, str(CORE_ROOT / "scripts")) - -import appctl_engine as engine +# CORE_ROOT = Path(__file__).resolve().parent.parent.parent +# sys.path.insert(0, str(CORE_ROOT / "scripts")) @dataclass class AppFactory: """Helper class to generate mock app directories and configurations""" + sites_dir: Path def create( @@ -28,9 +27,12 @@ class AppFactory: if manifest_yaml: (app_dir / "app.yaml").write_text(manifest_yaml, encoding="utf-8") if has_compose: - (app_dir / "docker-compose.yml").write_text("services: {}\n", encoding="utf-8") + (app_dir / "docker-compose.yml").write_text( + "services: {}\n", encoding="utf-8" + ) return app_dir + @pytest.fixture def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: """Fixture that creates an isolated Sites directory and points engine.SITES_DIR to it""" @@ -39,23 +41,24 @@ def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "mydomain.test") return sites + @pytest.fixture def app_factory(mock_sites_dir: Path) -> AppFactory: """Fixture that provides the AppFactory instance to test""" return AppFactory(mock_sites_dir) + @pytest.fixture -def mock_core_dir( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch -) -> Path: +def mock_core_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: """Fixture that creates an isolated Core directory and points engine.CORE_DIR to it""" core = tmp_path / "CORE" core.mkdir(parents=True, exist_ok=True) return core + ## GREEN TEST: Existing implementation should not break + def test_resolve_app_hierarchy(app_factory: AppFactory): """Ensure resolution follows: Canonical Name > Alias > Dir Name > Prefix""" app_factory.create( @@ -73,6 +76,7 @@ def test_resolve_app_hierarchy(app_factory: AppFactory): assert engine.resolve_app("homelab-jellyfin", apps) is not None assert engine.resolve_app("unknown", apps) is None + def test_manifest_data_overrides_default_values(app_factory: AppFactory): """Ensure app.yaml values successfully override the system defaults""" app_factory.create( @@ -84,7 +88,7 @@ def test_manifest_data_overrides_default_values(app_factory: AppFactory): visible: false networks: - custom-net - """ + """, ) apps = engine.get_sites_apps() @@ -95,6 +99,7 @@ def test_manifest_data_overrides_default_values(app_factory: AppFactory): assert app.auth is False assert app.networks == ["custom-net"] + def test_sites_app_normalization(app_factory: AppFactory): """Ensure missing or badly typed manifest fields are safely normalized""" app_factory.create( @@ -106,7 +111,7 @@ def test_sites_app_normalization(app_factory: AppFactory): auth: "False" # should evaluate based on boolean casting homepage: weight: "99" # this should be casted as an int - """ + """, ) apps = engine.get_sites_apps() app = engine.resolve_app("testapp", apps) @@ -131,7 +136,7 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory): type: git url: https://git.example.com/operator/bitetrack.git ref: v1.2.0 - """ + """, ) # 2. Source-backed app with default ref (main) app_factory.create( @@ -140,14 +145,14 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory): name: doc2site source: url: https://git.example.com/operator/doc2site.git - """ + """, ) # 3. Image-only app (no source block) app_factory.create( dir_name="homelab-jellyfin", manifest_yaml=""" name: jellyfin - """ + """, ) apps = engine.get_sites_apps() @@ -177,7 +182,7 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory): name: malformed source: url: file:///etc/passwd - """ + """, ) apps_updated = engine.get_sites_apps() malformed = engine.resolve_app("malformed", apps_updated) @@ -189,8 +194,10 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory): ## RED TESTS: TDD Goals for next implementation + def test_docker_status_parser_running(monkeypatch): """Ensure get_docker_status reports running compose stack when all containers are running.""" + def mock_run(args, **kwargs): mock = MagicMock() if "ps" in args: @@ -207,6 +214,7 @@ def test_docker_status_parser_running(monkeypatch): def test_docker_status_parser_stopped(monkeypatch): """Ensure get_docker_status reports stopped when no containers exist.""" + def mock_run(args, **kwargs): mock = MagicMock() if "ps" in args: @@ -221,6 +229,7 @@ def test_docker_status_parser_stopped(monkeypatch): def test_docker_status_parser_degraded(monkeypatch): """Ensure get_docker_status reports degraded when partial containers are running.""" + def mock_run(args, **kwargs): mock = MagicMock() if "ps" in args: @@ -244,6 +253,7 @@ def test_docker_status_parser_not_stack(tmp_path: Path): def test_docker_status_single_container(monkeypatch): """Ensure get_docker_status inspects single Core container by name.""" + def mock_run(args, **kwargs): mock = MagicMock() if "authelia" in args: @@ -260,6 +270,7 @@ def test_docker_status_single_container(monkeypatch): def test_docker_status_error_handling(monkeypatch): """Ensure get_docker_status handles subprocess failures gracefully.""" + def mock_err(*args, **kwargs): raise OSError("Docker socket unreachable") @@ -269,6 +280,7 @@ def test_docker_status_error_handling(monkeypatch): def test_docker_image_revision_extraction(monkeypatch): """Ensure get_docker_image_revision extracts org.opencontainers.image.revision.""" + def mock_run(args, **kwargs): mock = MagicMock() if "ps" in args: @@ -278,7 +290,10 @@ def test_docker_image_revision_extraction(monkeypatch): return mock monkeypatch.setattr("subprocess.run", mock_run) - assert engine.get_docker_image_revision("/fake/dir") == "9d82577f489f0d478e465a36077538d0ded16ba5" + assert ( + engine.get_docker_image_revision("/fake/dir") + == "9d82577f489f0d478e465a36077538d0ded16ba5" + ) def mock_run_empty(args, **kwargs): mock = MagicMock() @@ -293,9 +308,8 @@ def test_docker_image_revision_extraction(monkeypatch): def test_homepage_sync_groups_and_sorts_correctly( - mock_core_dir: Path, - app_factory: AppFactory, - monkeypatch): + mock_core_dir: Path, app_factory: AppFactory, monkeypatch +): """ TDD Goal: Port `cmd_sync_homepage` to V2 using the new Dataclass structure. It must group by `homepage.group` and sort by `homepage.weight`. @@ -312,7 +326,7 @@ def test_homepage_sync_groups_and_sorts_correctly( title: App1 group: Group B weight: 20 - """ + """, ) app_factory.create( @@ -324,7 +338,7 @@ def test_homepage_sync_groups_and_sorts_correctly( title: App2 group: Group A weight: 10 - """ + """, ) monkeypatch.setattr(engine, "get_core_services", list) @@ -334,8 +348,10 @@ def test_homepage_sync_groups_and_sorts_correctly( assert output_file.exists(), "The services.yaml file must be generated" content = output_file.read_text() - assert content.find("- Group A") < content.find("- Group B") # Group A should appear before Group B - assert "App2" in content # App 2 is in the file + assert content.find("- Group A") < content.find( + "- Group B" + ) # Group A should appear before Group B + assert "App2" in content # App 2 is in the file def test_homepage_sync_core_services_domain_isolation( @@ -380,7 +396,9 @@ def test_resolve_core_stack_type(): assert traefik.container == "traefik" -def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(app_factory: AppFactory): +def test_manifest_parsing_delegates_to_core_manifest_and_validates_env( + app_factory: AppFactory, +): """Ensure manifest parsing uses core_manifest and catches invalid env keys.""" app_factory.create( dir_name="homelab-badenv", @@ -397,7 +415,9 @@ def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(app_facto assert "Invalid or reserved environment variable key" in app.manifest_error -def test_cmd_resolve_fails_closed_on_manifest_error(app_factory: AppFactory, capsys: pytest.CaptureFixture): +def test_cmd_resolve_fails_closed_on_manifest_error( + app_factory: AppFactory, capsys: pytest.CaptureFixture +): """Ensure cmd_resolve exits with non-zero on workload with manifest errors.""" app_factory.create( dir_name="homelab-corrupt", @@ -449,7 +469,9 @@ def test_unification_uses_core_manifest_dataclasses(app_factory: AppFactory): assert app.source.transport == core_manifest.TransportScheme.HTTPS -def test_cmd_list_flags_manifest_error(app_factory: AppFactory, capsys: pytest.CaptureFixture): +def test_cmd_list_flags_manifest_error( + app_factory: AppFactory, capsys: pytest.CaptureFixture +): """Ensure cmd_list flags workloads with manifest errors instead of swallowing them.""" app_factory.create( dir_name="homelab-broken", @@ -462,4 +484,3 @@ def test_cmd_list_flags_manifest_error(app_factory: AppFactory, capsys: pytest.C engine.cmd_list([]) captured = capsys.readouterr() assert "Manifest Error" in captured.out - diff --git a/tests/unit/test_core_manifest.py b/tests/unit/test_core_manifest.py index a85092a..d16eb78 100644 --- a/tests/unit/test_core_manifest.py +++ b/tests/unit/test_core_manifest.py @@ -2,15 +2,13 @@ Unit test suite for scripts/core_manifest.py (Schema v1.0 & Parser Library). """ -import sys from pathlib import Path import pytest -# Add scripts directory to path -CORE_ROOT = Path(__file__).resolve().parent.parent.parent -sys.path.insert(0, str(CORE_ROOT / "scripts")) - +# # Add scripts directory to path +# CORE_ROOT = Path(__file__).resolve().parent.parent.parent +# sys.path.insert(0, str(CORE_ROOT / "scripts")) from core_manifest import ( Manifest, ManifestValidationError, @@ -24,13 +22,17 @@ from core_manifest import ( def test_validate_transport_https(): - scheme, url = validate_transport("https://git.example.com/operator/homelab-snappymail.git") + scheme, url = validate_transport( + "https://git.example.com/operator/homelab-snappymail.git" + ) assert scheme == TransportScheme.HTTPS assert url == "https://git.example.com/operator/homelab-snappymail.git" def test_validate_transport_ssh(): - scheme, url = validate_transport("ssh://git@git.example.com:2223/operator/homelab-docs.git") + scheme, url = validate_transport( + "ssh://git@git.example.com:2223/operator/homelab-docs.git" + ) assert scheme == TransportScheme.SSH assert url == "ssh://git@git.example.com:2223/operator/homelab-docs.git" @@ -41,21 +43,29 @@ def test_validate_transport_git_scp(): assert url == "git@github.com:operator/custom-workload.git" -@pytest.mark.parametrize("insecure_url", [ - "http://insecure.example.com/repo.git", - "http://github.com/repo.git", -]) +@pytest.mark.parametrize( + "insecure_url", + [ + "http://insecure.example.com/repo.git", + "http://github.com/repo.git", + ], +) def test_validate_transport_rejects_http(insecure_url: str): - with pytest.raises(ManifestValidationError, match="Insecure HTTP source URL rejected"): + with pytest.raises( + ManifestValidationError, match="Insecure HTTP source URL rejected" + ): validate_transport(insecure_url) -@pytest.mark.parametrize("traversal_url", [ - "../../etc/shadow", - "/home/operator/secret", - "~/vault", - "file:///etc/passwd", -]) +@pytest.mark.parametrize( + "traversal_url", + [ + "../../etc/shadow", + "/home/operator/secret", + "~/vault", + "file:///etc/passwd", + ], +) def test_validate_transport_rejects_paths_and_traversal(traversal_url: str): with pytest.raises(ManifestValidationError): validate_transport(traversal_url) @@ -64,7 +74,10 @@ def test_validate_transport_rejects_paths_and_traversal(traversal_url: str): def test_classify_ref_branches(): assert classify_ref("main") == (RefType.BRANCH, "main") assert classify_ref("refs/heads/develop") == (RefType.BRANCH, "develop") - assert classify_ref("feat/manifest-engine") == (RefType.BRANCH, "feat/manifest-engine") + assert classify_ref("feat/manifest-engine") == ( + RefType.BRANCH, + "feat/manifest-engine", + ) assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0") @@ -145,7 +158,9 @@ deployment: def test_parse_manifest_rejects_missing_name(): - with pytest.raises(ManifestValidationError, match="missing mandatory string field 'name'"): + with pytest.raises( + ManifestValidationError, match="missing mandatory string field 'name'" + ): parse_manifest("domain: test.example.com\n") @@ -162,7 +177,9 @@ deployment: - compose_up - rm_rf_root """ - with pytest.raises(ManifestValidationError, match="Prohibited deployment action 'rm_rf_root'"): + with pytest.raises( + ManifestValidationError, match="Prohibited deployment action 'rm_rf_root'" + ): parse_manifest(raw_yaml) @@ -172,7 +189,9 @@ name: "app" deployment: strategy: "swarm" """ - with pytest.raises(ManifestValidationError, match="Unsupported deployment strategy 'swarm'"): + with pytest.raises( + ManifestValidationError, match="Unsupported deployment strategy 'swarm'" + ): parse_manifest(raw_yaml) @@ -185,24 +204,29 @@ def test_parse_manifest_from_path(tmp_path: Path): assert manifest.is_internal is True -@pytest.mark.parametrize("invalid_key", [ - "123_BAD", - "INVALID-KEY", - "FOO;BAR", - "KEY WITH SPACE", - "PATH", - "LD_PRELOAD", - "IFS", - "CORE_DIR", - "SITES_DIR", -]) +@pytest.mark.parametrize( + "invalid_key", + [ + "123_BAD", + "INVALID-KEY", + "FOO;BAR", + "KEY WITH SPACE", + "PATH", + "LD_PRELOAD", + "IFS", + "CORE_DIR", + "SITES_DIR", + ], +) def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str): raw_yaml = f""" name: "app" env: "{invalid_key}": "some_value" """ - with pytest.raises(ManifestValidationError, match="Invalid or reserved environment variable key"): + with pytest.raises( + ManifestValidationError, match="Invalid or reserved environment variable key" + ): parse_manifest(raw_yaml) @@ -226,7 +250,9 @@ def test_parse_manifest_rejects_extra_fields(): name: "app" unrecognized_field: "should_fail" """ - with pytest.raises(ManifestValidationError, match="unrecognized or forbidden field"): + with pytest.raises( + ManifestValidationError, match="unrecognized or forbidden field" + ): parse_manifest(raw_yaml) @@ -259,5 +285,3 @@ description: "Pydantic serialization test" assert dumped["name"] == "serialized-app" assert dumped["schemaVersion"] == "1.0" assert manifest.to_dict()["name"] == "serialized-app" - - diff --git a/tests/unit/test_provenance.py b/tests/unit/test_provenance.py index b828325..a068658 100644 --- a/tests/unit/test_provenance.py +++ b/tests/unit/test_provenance.py @@ -4,14 +4,12 @@ Unit test suite for scripts/provenance.py (Two-Axis Inspection & Provenance Reso import os import subprocess -import sys from pathlib import Path from unittest.mock import MagicMock, patch -# Add scripts directory to path -CORE_ROOT = Path(__file__).resolve().parent.parent.parent -sys.path.insert(0, str(CORE_ROOT / "scripts")) - +# # Add scripts directory to path +# CORE_ROOT = Path(__file__).resolve().parent.parent.parent +# sys.path.insert(0, str(CORE_ROOT / "scripts")) from core_manifest import Manifest, RefType, SourceConfig, TransportScheme from provenance import ( ProvenanceStatus, @@ -43,12 +41,28 @@ def test_get_local_checkout_status_clean_repo(tmp_path: Path): app_dir = tmp_path / "git_app" app_dir.mkdir() env = _clean_git_env() - subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env) - subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env) - subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env) + subprocess.run( + ["git", "-C", str(app_dir), "init", "-b", "main"], + check=True, + capture_output=True, + env=env, + ) + subprocess.run( + ["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], + check=True, + env=env, + ) + subprocess.run( + ["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env + ) (app_dir / "file.txt").write_text("hello", encoding="utf-8") subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env) - subprocess.run(["git", "-C", str(app_dir), "commit", "-m", "init"], check=True, capture_output=True, env=env) + subprocess.run( + ["git", "-C", str(app_dir), "commit", "-m", "init"], + check=True, + capture_output=True, + env=env, + ) status = get_local_checkout_status(app_dir) assert status.is_git is True @@ -62,12 +76,28 @@ def test_get_local_checkout_status_dirty_repo(tmp_path: Path): app_dir = tmp_path / "git_dirty_app" app_dir.mkdir() env = _clean_git_env() - subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env) - subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env) - subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env) + subprocess.run( + ["git", "-C", str(app_dir), "init", "-b", "main"], + check=True, + capture_output=True, + env=env, + ) + subprocess.run( + ["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], + check=True, + env=env, + ) + subprocess.run( + ["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env + ) (app_dir / "file.txt").write_text("hello", encoding="utf-8") subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env) - subprocess.run(["git", "-C", str(app_dir), "commit", "-m", "init"], check=True, capture_output=True, env=env) + subprocess.run( + ["git", "-C", str(app_dir), "commit", "-m", "init"], + check=True, + capture_output=True, + env=env, + ) # Modify file to create dirty state (app_dir / "file.txt").write_text("modified", encoding="utf-8") @@ -131,7 +161,10 @@ def test_resolve_upstream_provenance_timeout(): transport=TransportScheme.HTTPS, ) - with patch("subprocess.run", side_effect=subprocess.TimeoutExpired(cmd=["git"], timeout=10.0)): + with patch( + "subprocess.run", + side_effect=subprocess.TimeoutExpired(cmd=["git"], timeout=10.0), + ): prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0) assert prov.status == ProvenanceStatus.TIMEOUT @@ -183,13 +216,17 @@ def test_inspect_workload_two_axis(tmp_path: Path): ) # Without fetch_upstream: Axis 2 returns UNKNOWN - status_no_fetch = inspect_workload_two_axis(tmp_path, manifest, fetch_upstream=False) + status_no_fetch = inspect_workload_two_axis( + tmp_path, manifest, fetch_upstream=False + ) assert status_no_fetch.provenance.status == ProvenanceStatus.UNKNOWN assert "Pass --fetch" in status_no_fetch.provenance.message # With fetch_upstream: Axis 2 queries remote with patch("provenance.resolve_upstream_provenance") as mock_resolve: mock_resolve.return_value = MagicMock(status=ProvenanceStatus.SYNCED) - status_fetch = inspect_workload_two_axis(tmp_path, manifest, fetch_upstream=True) + status_fetch = inspect_workload_two_axis( + tmp_path, manifest, fetch_upstream=True + ) assert status_fetch.provenance.status == ProvenanceStatus.SYNCED mock_resolve.assert_called_once() From e23ff941d812e7c5106a3a1cbbada94e7748f576 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 13:04:25 -0500 Subject: [PATCH 02/43] docs(p4): add ADR-0001 and ADR-0002 architecture records and update roadmap --- ROADMAP.md | 30 ++-- .../0001-3tier-architecture-and-provenance.md | 99 +++++++++++++ .../0002-appctl-control-plane-architecture.md | 140 ++++++++++++++++++ docs/decisions/README.md | 50 +++---- docs/plans/p4-readiness-plan.md | 4 +- 5 files changed, 279 insertions(+), 44 deletions(-) create mode 100644 docs/decisions/0001-3tier-architecture-and-provenance.md create mode 100644 docs/decisions/0002-appctl-control-plane-architecture.md diff --git a/ROADMAP.md b/ROADMAP.md index 5ab6358..c9ec57a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,34 +1,36 @@ # 🗺️ Homelab Core & Appctl Engineering Roadmap -This document serves as the repository-facing projection of the authoritative **Homelab Architecture Consolidation & Control Plane Roadmap (v5)**. +This document serves as the repository-facing projection of the authoritative **Homelab Architecture Consolidation & Control Plane Roadmap (v6)** and the locked Milestone P4 boundary specification ([`docs/plans/p4-readiness-plan.md`](docs/plans/p4-readiness-plan.md)). It describes the implementation trajectory and phased engineering milestones for transitioning Homelab Core into a unified platform driven by the `appctl` Operational Control Plane. -> **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index (Control Plane Architecture, 3-Tier Provenance Model, and Pydantic v2 Runtime Validation). +> **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index ([ADR-0001: 3-Tier Provenance Model](docs/decisions/0001-3tier-architecture-and-provenance.md), [ADR-0002: Operational Control Plane Architecture](docs/decisions/0002-appctl-control-plane-architecture.md), and [ADR-0003: Pydantic v2 Runtime Validation](docs/decisions/0003-pydantic-v2-runtime-validation.md)). --- ## 🎯 Architectural Invariants Governing Execution 1. **Git is the Authoritative Source of Deployment State**: All workload configurations are versioned in Git. `appctl` reconciles desired Git state into running containers. -2. **One Logical API Across Dual Transports**: The control-plane API is a single logical command-oriented contract. Unix domain socket (`/run/homelab/appctl.sock`) on the host and HTTP for network clients are transport details. -3. **Host Access Does Not Confer Authority**: Entering via SSH does not bypass authentication. Every mutating operation requires an explicit, authenticated user-scoped token. -4. **Separation of Intent from Implementation**: `DeploymentModel` captures implementation-agnostic intent; concrete platform descriptors (`app.yaml` + Compose) are materialized and enforced by `appctl`. -5. **AI Authoring Boundary**: AI agents act strictly as proposal generators (`DeploymentProposal`). Humans approve the intent (`DeploymentModel`). The AI possesses zero execution authority. -6. **Secret Reference Invariant**: Deployment definitions store secret references (`secretKeyRef`), never plaintext material, resolved at runtime via `SecretProvider`. -7. **Clean State Root**: Mutable application runtime data resides strictly under `~/var/lib/homelab//`, isolated from Git repositories. +2. **One Logical API Across Dual Transports (`DEC-01`)**: The control-plane API is a single logical HTTP/1.1 command contract (`POST /v1/operations` + `GET /v1/health`) served identically over Unix domain socket (`/run/homelab/appctl.sock`) and loopback TCP (`127.0.0.1:9001`). +3. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**: Entering via SSH does not bypass authentication. Every mutating operation and sensitive read (`workload.config`, `workload.logs`) requires an explicit Bearer token; tokenless local UDS calls fall back via `SO_PEERCRED` strictly to `homelab-viewer` read-only inspection. +4. **Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)**: `homelab-appctl.service` executes as isolated user `homelab-appctl:homelab-operators` with mode `0600` append-only `/var/log/homelab/appctl/audit.jsonl`. Mutating operations abort immediately (`500 ERR_EXECUTION_FAILED`) if the pre-execution `DISPATCHED` audit write fails. +5. **Unified Execution, Pre-Flight & Pure-Python Environment (`DEC-04`, `DEC-05`)**: Both CLI and GitOps worker paths execute through the daemon, enforcing Pydantic v2 manifest validation, `validate_compose_security()` AST checks, and inert pure-Python `.env` assembly (no shell `source` or `eval`). +6. **Separation of Intent from Implementation**: `DeploymentModel` captures implementation-agnostic intent; concrete platform descriptors (`app.yaml` + Compose) are materialized and enforced by `appctl`. +7. **AI Authoring Boundary**: AI agents act strictly as proposal generators (`DeploymentProposal`). Humans approve the intent (`DeploymentModel`). The AI possesses zero execution authority. +8. **Secret Reference Invariant**: Deployment definitions store secret references (`secretKeyRef`), never plaintext material, resolved at runtime via `SecretProvider`. +9. **Clean State Root**: Mutable application runtime data resides strictly under `~/var/lib/homelab//`, isolated from Git repositories. --- ## 🔍 Current Implementation Baseline vs. Target Architecture -| Architectural Area | Current Implementation Baseline (Milestone P3) | Target Architecture (Roadmap v5) | +| Architectural Area | Current Implementation Baseline (Milestone P3) | Target Architecture (Roadmap v6) | | :--- | :--- | :--- | -| **`appctl` Architecture** | Bash CLI wrapper (`scripts/appctl`) driving local subprocesses (`docker compose`, `git`) and Python engine. | Dedicated daemon service (`homelab-appctl.service`) exposing one logical API over Unix socket and HTTP. | -| **Operational Auth** | Host Unix permissions; sourcing runtime secrets from `/run/secrets/`. | Mandatory auth middleware in daemon (P4 admission gate); LLDAP directory RBAC, user-scoped API tokens, and Authelia ForwardAuth (P5). | -| **Metadata & Schema Engine** | Unified engine (`scripts/appctl_engine.py`) with two-axis provenance and fail-closed Pydantic v2 schema v1.0 parser (`scripts/core_manifest.py`). | Control-plane daemon invokes `core_manifest.py` / `appctl_engine.py` through a stable internal Python interface. | +| **`appctl` Architecture** | Bash CLI wrapper (`scripts/appctl`) driving local subprocesses (`docker compose`, `git`) and Python engine. | Dedicated daemon service (`homelab-appctl.service`, user `homelab-appctl`) exposing `POST /v1/operations` over Unix socket and HTTP. | +| **Operational Auth** | Host Unix permissions; sourcing runtime secrets from `/run/secrets/`. | Mandatory SHA-256 Bearer token + 3-role RBAC + UDS `SO_PEERCRED` viewer fallback (P4); LLDAP directory RBAC & Authelia ForwardAuth (P5). | +| **Metadata & Schema Engine** | Unified engine (`scripts/appctl_engine.py`) with two-axis provenance and fail-closed Pydantic v2 schema v1.0 parser (`scripts/core_manifest.py`). | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | | **Deployment Model** | Direct authoring of `app.yaml` and `docker-compose.yml` in `~/Sites//`. | 5-stage lifecycle (planned in P6): `DeploymentProposal` $\to$ operator-approved `DeploymentModel` in Git $\to$ `appctl` materialization. | -| **GitOps Engine** | Webhook dispatcher (`scripts/gitops_dispatcher.py`) with HMAC-SHA256 auth, Compose AST security validator, and `flock` serialization. | Integrated into control-plane admission, invoking central reconciliation endpoints. | +| **GitOps Engine** | Webhook dispatcher (`scripts/gitops_dispatcher.py`) with HMAC-SHA256 auth, Compose AST security validator, and `flock` serialization. | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | | **Secret Distribution** | Age-encrypted `nixos/secrets.yaml` decrypted by `sops-nix` to tmpfs `/run/secrets/`. | Host secrets remain in `sops-nix`; workload secrets referenced by key and projected via `SecretProvider` (planned in P5). | | **Dashboard** | `appctl sync` compiles `config/homepage/services.yaml` from `app.yaml` manifests. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for management (planned in P7). | @@ -55,7 +57,7 @@ It describes the implementation trajectory and phased engineering milestones for **Status**: ✅ **Completed** * Merged `refactor/appctl-rework` and `main` into a unified architectural baseline (commit `2297cd5`). * Modernized metadata engine with strongly-typed models (`SitesApp`, `CoreService`, `SourceConfig`) and Docker status inspection. -* Formalized the control-plane ADR and Roadmap v5; marked legacy roadmaps as superseded. +* Formalized the control-plane ADR and consolidated roadmap; marked legacy roadmaps as superseded. * Verified test suite and NixOS flake sandbox evaluation. --- diff --git a/docs/decisions/0001-3tier-architecture-and-provenance.md b/docs/decisions/0001-3tier-architecture-and-provenance.md new file mode 100644 index 0000000..018ae75 --- /dev/null +++ b/docs/decisions/0001-3tier-architecture-and-provenance.md @@ -0,0 +1,99 @@ +--- +type: decision +status: accepted +project: homelab-core +date: 2026-09-28 +tags: [architecture, homelab, provenance, gitops, state, kiss] +--- + +# ADR 0001: Homelab 3-Tier Architecture & Deployment Provenance Model + +## Context and Problem Statement + +Homelab Core operates as a dedicated NixOS appliance hosting self-hosted productivity services and independent backend engineering projects. In early platform iterations (v1 through v3), several structural tensions emerged: + +1. **Application & Deployment Coupling**: Custom applications co-located application source trees with host-specific Traefik labels, Docker bridge networks, and host path mounts inside individual Git repositories in `~/Sites/`. +2. **Repository Inflation**: Third-party off-the-shelf applications (`jellyfin`, `stirling`, `snappymail`) required standalone Git repositories simply to store a minimal Compose file and manifest. +3. **Ambiguous Freshness**: Local Git status checks in `~/Sites/` could only report whether deployment descriptors had uncommitted edits, never whether running containers matched current upstream application source code. +4. **Mutable State Entanglement**: Application databases, caches, and runtime state lived inside or adjacent to version-controlled Git working trees (`Core/config/` and `Sites//data`), risking dirty checkouts, accidental secret/state commits, or data loss during branch operations. +5. **Orchestrator Sprawl Risk**: Scaling operational scripts threatened to introduce secondary distributed infrastructure (queues, databases, message brokers) around basic single-node container deployments. + +The central architectural question is: **How should Homelab Core structure application source code, deployment configuration, runtime state, and platform orchestration to maintain strict separation of concerns, verifiable provenance, and linear KISS operations?** + +## Decision Drivers + +* **Clean Separation of Concerns**: Application software projects must be developable, testable, and publishable independently of Homelab Core infrastructure, domains, or bridge networks. +* **Workload Simplicity**: Off-the-shelf third-party applications should not incur standalone source repository overhead. +* **Verifiable Two-Axis Provenance**: Operators must be able to independently verify local deployment configuration freshness (`~/Sites/`) versus upstream software code freshness (`source.url` vs. running container image). +* **KISS Primitives & Minimal Control Paths**: Operational reconciliation must remain bounded, deterministic, and linear without distributed brokers, queues, or deployment databases. +* **Filesystem State Hygiene**: Mutable runtime data must never reside inside version-controlled Git trees. + +## Considered Options + +* **Option 1: Monolithic / Single-Repo Deployment (Status Quo v1–v3)**: Co-locate application source code, Dockerfiles, Compose files, and mutable runtime state inside a single Git repository per application. +* **Option 2: Miniature Cloud Platform**: Introduce message brokers (RabbitMQ/Redis), a deployment state database, multi-environment controllers, and asynchronous rollback daemons. +* **Option 3: Bounded 3-Tier Platform with OCI Provenance Labels & Linear Control Path (Adopted)**: Decouple Software, Deployment, and Platform tiers; connect them via OCI image artifacts carrying source revision labels and content-addressed digests; enforce two-axis provenance inspection, linear reconciliation, and isolated host state roots. + +## Decision Outcome + +Chosen option: **Option 3: Bounded 3-Tier Platform with OCI Provenance Labels & Linear Control Path**, because it resolves source-deployment coupling and provenance ambiguity while retaining a strictly bounded, single-appliance operational footprint. + +### Summary of Architectural Commitments + +1. **3-Tier Separation of Concerns**: + * **Tier 1 — Software Layer (Application Repositories)**: Standalone Git repositories owning application source code, tests, Dockerfiles, and CI workflows. Zero Homelab infrastructure coupling. + * **Intermediate Provenance Artifacts**: OCI container images produced by CI act as immutable provenance objects identified by their OCI digest and carrying source commit metadata via the `org.opencontainers.image.revision` label. + * **Tier 2 — Deployment Layer (`~/Sites` Workload Plane)**: Declarative catalog in `~/Sites/` owning workload-specific `app.yaml` manifests and `docker-compose.yml` topologies. + * **Tier 3 — Platform Layer (Homelab Core Appliance)**: Declarative NixOS host foundation (`~/Core`) owning edge ingress (`traefik`), SSO/directory (`authelia`, `lldap`), mail (`stalwart`), monitoring (`dozzle`, `diun`), and operational controllers (`appctl`, `gitops_dispatcher`). +2. **Two Workload Deployment Classes**: + * **Class A (Source-Backed)**: Declares an explicit upstream `source:` block (`source.url`, `source.ref`) in `app.yaml`; tracks upstream Git revisions against running container OCI labels. + * **Class B (Image-Only)**: Standard third-party workloads omitting `source:`; deployment freshness relies on container registry image tags and content-addressed digests. +3. **Two Operational Inspection Axes (`scripts/provenance.py`)**: + * **Axis 1 (Local Deployment Checkout)**: Evaluates local `~/Sites/` working-tree cleanliness (`✓ Synced`, `* Dirty`, `⬆ Ahead`, `⬇ Behind`). + * **Axis 2 (Upstream Software Provenance)**: Independently resolves upstream remote revisions via bounded `git ls-remote` (10-second timeout during `--fetch`) against running container revision labels. +4. **Minimal Linear Reconciliation Path**: + * The deployment lifecycle remains strictly linear: + $$\text{Source Push} \longrightarrow \text{CI Build} \longrightarrow \text{GitOps Ingress} \longrightarrow \text{appctl Reconcile} \longrightarrow \text{Compose Up}$$ + * Secondary message queues, brokers, and deployment databases are rejected. +5. **Isolated Persistent State Root**: + * Mutable application runtime state (databases, caches, uploads, dynamic configs) resides strictly under `~/var/lib/homelab//`, isolated from version-controlled Git repositories. + +## Pros and Cons of the Options + +### Option 1: Monolithic / Single-Repo Deployment +* Good, because it requires only a single Git repository per custom application. +* Bad, because host-specific routing labels and bridge networks leak into application source repositories, preventing clean open-sourcing or reuse. +* Bad, because off-the-shelf tools require artificial wrapper repositories. +* Bad, because a single commit SHA conflates software code revisions with deployment configuration edits. +* Bad, because mutable state co-located in `Sites//data` creates dirty Git trees and risks accidental commits or data loss. + +### Option 2: Miniature Cloud Platform +* Good, because it mirrors enterprise Kubernetes / ArgoCD continuous deployment pipelines. +* Bad, because running distributed brokers, queues, and state databases on a single appliance introduces disproportionate operational overhead and failure modes. +* Bad, because it violates the KISS principle. + +### Option 3: Bounded 3-Tier Platform with OCI Provenance Labels (Adopted) +* Good, because custom software is completely decoupled from homelab infrastructure and remains portable and instance-agnostic. +* Good, because off-the-shelf software incurs zero source repository overhead. +* Good, because two-axis inspection resolves local configuration status and upstream code provenance unambiguously. +* Good, because runtime state is cleanly isolated under `~/var/lib/homelab//`. +* Bad, because custom applications manage source code and Sites deployment manifests as separate concerns. +* Bad, because verifying remote revisions without local clones (`git ls-remote`) evaluates commit equality (`HEAD` match) rather than full commit ancestry distance. + +## Consequences + +### Positive Consequences +* **Independent Software Lifecycle**: Custom applications can be developed, tested, and published without exposing homelab domains, secrets, or network topologies. +* **Precise Diagnostic Truth**: Operators and `appctl` can distinguish between uncommitted local deployment edits (`* Dirty`) and upstream software updates (`git ls-remote`). +* **Zero-Data-Loss State Isolation**: Proven during the Milestone P1 SnappyMail migration, moving persistent runtime data to `~/var/lib/homelab//` keeps Git trees pure and backups deterministic. +* **Operational Restraint**: Preserves a linear, local reconciliation path without distributed state stores. + +### Negative Consequences & Accepted Trade-offs +* **Dual Repositories for Custom Workloads**: Deploying a custom application separates upstream source CI from the `~/Sites/` deployment manifest. +* **Commit Equality Without Ancestry Graph**: Remote `git ls-remote` queries confirm whether the deployed revision matches upstream `HEAD`, without computing commit ahead/behind counts on uncloned source repos. + +## More Information + +* **Architecture Specification**: [`docs/architecture.md`](../architecture.md) +* **Secrets & State Contract**: [`docs/secrets-and-state.md`](../secrets-and-state.md) +* **Governing Roadmap**: [`ROADMAP.md`](../../ROADMAP.md) (Milestones P1 & P3) diff --git a/docs/decisions/0002-appctl-control-plane-architecture.md b/docs/decisions/0002-appctl-control-plane-architecture.md new file mode 100644 index 0000000..7a7f462 --- /dev/null +++ b/docs/decisions/0002-appctl-control-plane-architecture.md @@ -0,0 +1,140 @@ +--- +type: decision +status: accepted +project: homelab-core +date: 2026-10-07 +tags: [architecture, homelab, appctl, control-plane, security, rbac, audit, gitops] +--- + +# ADR 0002: Homelab Operational Control Plane & Deployment Model Architecture + +## Context and Problem Statement + +Homelab Core historically relied on `appctl` as a procedural Bash CLI wrapper (`scripts/appctl`) coupled with a Python metadata helper (`scripts/appctl_engine.py`). Operational commands (`up`, `down`, `restart`, `update`, `logs`, `config`, `sync`) executed as local subprocesses in the operator's shell session, sourcing environment files directly from `/run/secrets/` and `$APP_DIR/.env`. + +As the platform matured and AI coding agents began operating inside developer SSH sessions, this script-based model exposed five architectural and security liabilities: + +1. **Conflated Host & Control Plane Authority**: Entering the server via SSH granted full operational mutation authority. Any unprivileged process or AI coding agent running under the operator's UID could invoke `appctl` to mutate containers, inspect secrets, or alter routing with zero authentication. +2. **Duplicated Execution & Pre-Flight Drift**: The local CLI (`scripts/appctl`) and the GitOps webhook worker (`scripts/gitops_dispatcher.py`) maintained separate implementations of `git pull` and `docker compose`, with the CLI path bypassing Compose AST security validation and sourcing `.env` files via shell `source`. +3. **Absence of Tamper-Evident Auditability**: Operational actions produced only ephemeral terminal output with no centralized, append-only audit log recording principal identity, transport, origin, target revision, and outcome. +4. **Secret Lifecycle Coupling**: Workload secrets were broadly sourced into parent shell environments or coupled to static SOPS rebuilds rather than resolved via scoped references. +5. **Manual Workload Authoring Friction**: Onboarding workloads required handwriting boilerplate descriptors without a structured boundary separating AI-generated proposals (`DeploymentProposal`) from human-approved declarative intent (`DeploymentModel`). + +The central architectural question is: **How should Homelab Core transition `appctl` into an authoritative, fail-closed operational control plane with strict privilege isolation, unified execution, mandatory token authorization, and safe deployment authoring without introducing distributed cloud complexity?** + +## Decision Drivers + +* **Control Plane Centralization**: Exactly one authoritative execution pipeline for all workload and platform operations across CLI, GitOps, and future web clients. +* **Host Access Does Not Confer Mutation Authority**: Entering the host via SSH must not bypass control-plane authentication. Every mutating action and sensitive read requires cryptographic token verification. +* **OS Privilege Isolation**: The control plane daemon, token store, and audit log must be isolated under a dedicated system identity (`homelab-appctl`) inaccessible to unprivileged operator shell processes and AI sessions. +* **Unified Pre-Flight & Inert Environment Assembly**: Eliminate shell `eval` and `source`; enforce Pydantic v2 schema validation ([ADR-0003](0003-pydantic-v2-runtime-validation.md)) and Compose AST security checks before every Compose invocation. +* **Declarative Git Ground Truth & AI Boundary**: Git remains the sole authoritative source of deployment state; AI agents act strictly as upstream proposal generators (`DeploymentProposal`) with zero execution authority. +* **KISS Primitives**: Preserve synchronous, linear execution using local `flock` serialization and HTTP/1.1 without external message brokers or databases. + +## Considered Options + +* **Option 1: Status Quo with Modernized Local CLI**: Modernize `appctl_engine.py` into a type-safe Python CLI while keeping execution in-process inside the caller's SSH session. +* **Option 2: Cloud-Native Micro-Platform (Kubernetes / Nomad / ArgoCD)**: Replace `appctl` and Docker Compose with enterprise cluster orchestration and distributed control loops. +* **Option 3: Authoritative `homelab-appctl.service` Daemon with Single Command Router & Stable Deployment Model (Adopted)**: Evolve `appctl` into an isolated systemd daemon exposing one logical HTTP/1.1 command API (`POST /v1/operations`) across Unix domain socket and TCP, backed by mandatory Bearer token auth, 3-role RBAC, fail-closed audit logging, and a 5-stage `DeploymentModel` lifecycle. + +## Decision Outcome + +Chosen option: **Option 3: Authoritative `homelab-appctl.service` Daemon with Single Command Router & Stable Deployment Model**, because it enforces an OS-level security boundary between operator sessions and platform execution, unifies CLI and GitOps codepaths behind a single fail-closed pipeline, and establishes a clean roadmap for directory-backed identity (P5) and human-gated AI deployment authoring (P6). + +### Summary of Architectural Commitments (Reconciled with Pre-P4 Locked Decisions `DEC-01`–`DEC-05`) + +```text + Clients (CLI / GitOps Worker / Future Web UI) + │ + POST /v1/operations + GET /v1/health + (One Logical HTTP/1.1 Command Contract) + │ + ┌─────────────────────┴─────────────────────┐ + ▼ ▼ + Unix Domain Socket (/run/homelab/appctl.sock) HTTP Listener (127.0.0.1:9001) + mode 0660 (homelab-appctl:homelab-operators) (Loopback in P4) + │ │ + └─────────────────────┬─────────────────────┘ + ▼ + ┌───────────────────────────────────────────────┐ + │ Unified Fail-Closed Pipeline (homelab-appctl)│ + │ 1. Pydantic v2 Validator (extra="forbid", 64K)│ + │ 2. Auth & 3-Role RBAC Gate (Bearer / PeerCred)│ + │ 3. Per-Target flock (/var/lib/homelab/appctl) │ + │ 4. Pre-Exec Audit Disk Guard (DISPATCHED) │ + │ 5. Pre-Flight (Manifest + Compose AST + .env) │ + │ 6. Subprocess Execution (Fixed argv, 256K cap)│ + │ 7. Post-Exec Audit Record (COMPLETED / FAILED)│ + └───────────────────────────────────────────────┘ +``` + +#### 1. One Logical Command API Across Dual Transports (`DEC-01`) +* `appctl` runs as a dedicated systemd daemon (`homelab-appctl.service`) speaking standard **HTTP/1.1** over both a local Unix Domain Socket (`/run/homelab/appctl.sock`) and a TCP listener (`127.0.0.1:9001` in P4). +* All 13 canonical domain operations (`workload.list`, `workload.get`, `workload.resolve`, `platform.ssl`, `platform.health`, `workload.config`, `workload.logs`, `workload.deploy`, `workload.stop`, `workload.restart`, `workload.pull`, `workload.update`, `platform.sync_homepage`) dispatch through a **single canonical endpoint**: `POST /v1/operations` (plus `GET /v1/health` for liveness). Multi-route REST aliases are rejected. +* `scripts/appctl` acts as a thin HTTP/1.1 UDS client with zero local Docker or Git execution logic. + +#### 2. Host Access Does Not Confer Mutation Authority & 3-Role RBAC (`DEC-02`) +* Entering via SSH confers zero control-plane mutation authority. Every mutating operation, every sensitive read (`workload.config`, `workload.logs`), and every HTTP request requires an explicit Bearer token validated via constant-time SHA-256 comparison (`hmac.compare_digest`) against `/run/secrets/appctl/tokens.json` (`0400`). +* **UDS `SO_PEERCRED` Viewer Fallback**: Unauthenticated local Unix socket calls extract kernel peer credentials (`SO_PEERCRED`) and fall back strictly to `homelab-viewer` privileges for non-sensitive reads (`list`, `get`, `resolve`, `ssl`, `health`), preserving zero-friction CLI inspection and shell tab-completion while blocking all mutations and secret dumps (`401`/`403`). +* **3-Role Authorization Hierarchy**: + * `homelab-admin`: Full access across `core`, `core_service`, and all valid `~/Sites/` workloads. + * `homelab-operator`: Mutations and sensitive reads strictly restricted to workloads admitted in `Core/config/deployments.yaml` (used by `gitops-dispatcher`). Denied (`403`) on `core`, `core_service`, and unregistered Sites directories. + * `homelab-viewer`: Non-sensitive read-only operations only. +* *(Milestone P5 expands this gate with LLDAP directory group mapping and authenticated Traefik/Authelia ForwardAuth proxy headers).* + +#### 3. Dedicated Service Identity, OS Isolation & Fail-Closed Audit Guard (`DEC-03`) +* The daemon executes as system user `homelab-appctl` (`Group = "homelab-operators"`, `SupplementaryGroups = [ "docker" ]`), with declarative recursive POSIX ACLs (`systemd.tmpfiles.rules`) granting shared read/write access on `~/Sites`, `~/var/lib/homelab`, and `~/Core/config/homepage`. +* **Append-Only Audit Telemetry (`/var/log/homelab/appctl/audit.jsonl`, mode `0600`)**: Records `DISPATCHED`, `COMPLETED`, `FAILED`, and `DENIED` lifecycle events with `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, `commit_sha`, and secret-redacted `parameters`/`result`. +* **Fail-Closed Disk Guard**: Mutating operations must write and flush a `DISPATCHED` audit record **before** invoking any Docker or Git subprocess. If the audit write fails (`OSError`), the mutation aborts immediately with `500 ERR_EXECUTION_FAILED`. + +#### 4. GitOps Execution Unification (`DEC-04`) +* `scripts/gitops_dispatcher.py` retains webhook HTTP ingress (port 9000), HMAC-SHA256 verification, `config/deployments.yaml` admission, and the commit-superseding `.pending.json` queue. +* The background worker delegates deployment execution to the daemon's `workload.update` operation over `/run/homelab/appctl.sock` using its `homelab-operator` Bearer token, eliminating duplicated `git pull` and `docker compose` execution codepaths. + +#### 5. Unified Pre-Flight & Pure-Python Environment Assembly (`DEC-05`) +* Shell `eval` and `source` are completely eliminated. Subprocess environments are assembled in memory via an inert pure-Python `KEY=VALUE` reader enforcing `ENV_KEY_RE`, `RESERVED_ENV_KEYS`, and canonical domain precedence (`HOMELAB_DOMAIN` $\to$ `DOMAIN_SUFFIX` $\to$ `DOMAIN`). +* Every workload mutation and `workload.config` call enforces path containment, `core_manifest.parse_manifest()`, and `validate_compose_security()` pre-flight inspection before invoking Docker Compose. + +#### 6. Declarative Git Truth, Five-Stage Deployment Model & AI Boundary (P5–P7 Trajectory) +* **Git is Authoritative**: Approved deployment definitions are versioned in Git; `appctl` reconciles desired Git state into running containers. +* **Five-Stage Model Lifecycle (P6)**: + $$\text{Repository} \xrightarrow{\text{Investigation}} \text{Application Profile} \xrightarrow{\text{Proposal}} \text{DeploymentProposal} \xrightarrow{\text{Human Selection}} \text{DeploymentModel (Git)} \xrightarrow{\text{appctl Materialize}} \text{Deployment Definition} \xrightarrow{\text{Reconcile}} \text{Containers}$$ +* **AI Authoring Boundary (P6)**: AI agents act strictly as upstream `DeploymentProposal` generators with zero execution or mutation authority. +* **Secret Reference Invariant (P5)**: Manifests reference secrets by key (`secretKeyRef`) resolved at runtime via `SecretProvider`, never storing plaintext credentials in Git. +* **Client Decoupling (P7)**: Homepage remains a read-only status portal; interactive web management belongs to a dedicated Operations UI client consuming `POST /v1/operations`. + +## Pros and Cons of the Options + +### Option 1: Status Quo with Local CLI Modernization +* Good, because it requires no background daemon or socket listener. +* Bad, because every process running under the operator's SSH UID retains full unauthenticated mutation authority over containers and secrets. +* Bad, because CLI and GitOps execution remain split across separate processes without unified lock management or tamper-evident auditing. + +### Option 2: Cloud-Native Micro-Platform +* Good, because Kubernetes/ArgoCD provide built-in API servers and RBAC. +* Bad, because cluster control planes impose heavy resource and operational complexity disproportionate to a single-node NixOS appliance. + +### Option 3: Authoritative `homelab-appctl.service` Daemon (Adopted) +* Good, because it isolates operational authority, secrets (`/run/secrets/appctl/tokens.json`), and audit logs (`/var/log/homelab/appctl/audit.jsonl`) under `homelab-appctl`. +* Good, because `POST /v1/operations` guarantees 100% contract parity across UDS and HTTP transports. +* Good, because `SO_PEERCRED` viewer fallback preserves ergonomic local read commands (`appctl list`, `appctl info`) while requiring tokens for mutations and secret reads. +* Bad, because it introduces a core systemd daemon and requires provisioning SOPS-managed API tokens for mutating CLI and GitOps operations. + +## Consequences + +### Positive Consequences +* **Defense-in-Depth Against Session Compromise**: Unprivileged scripts or AI coding agents in the operator's shell cannot mutate infrastructure, read `tokens.json`, or alter `audit.jsonl`. +* **Single Execution Truth**: Interactive CLI commands and automated GitOps webhooks execute through the exact same pre-flight validator, lock manager, and environment builder. +* **Deterministic Concurrency**: Per-target non-blocking `flock` locks (`/var/lib/homelab/appctl/locks/.lock`) prevent overlapping mutations (`409 ERR_CONCURRENT_MUTATION`). + +### Negative Consequences & Accepted Trade-offs +* **Daemon Dependency**: Normal operational commands depend on `homelab-appctl.service` availability (emergency host recovery remains possible for human administrators via `sudo`). +* **Token Provisioning**: Mutating CLI invocations require `APPCTL_TOKEN` / token configuration rather than relying on ambient SSH user identity. + +## More Information + +* **P4 Readiness & Boundary Specification**: [`docs/plans/p4-readiness-plan.md`](../plans/p4-readiness-plan.md) +* **Companion ADRs**: + * [ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model](0001-3tier-architecture-and-provenance.md) + * [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md) +* **Governing Roadmap**: [`ROADMAP.md`](../../ROADMAP.md) (Milestones P4–P7) diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 8151774..e60cdde 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -2,7 +2,7 @@ This document serves as the authoritative repository index for Architectural Decision Records (ADRs) governing **Homelab Core** and the **`appctl` Operational Control Plane**. -Repository-level architectural decisions are recorded in `docs/decisions/` using the MADR 4.0 specification. Foundational platform ADRs (0001 and 0002) are summarized inline below alongside full MADR records (0003+). +Repository-level architectural decisions are recorded in `docs/decisions/` using the MADR 4.0 specification (`NNNN-slug.md`). --- @@ -11,15 +11,14 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using | Decision Record | Status | Date | Scope & One-Line Purpose | | :--- | :--- | :--- | :--- | | [**ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. | -| [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](#homelab-operational-control-plane--deployment-model-architecture) | `accepted` | 2026-10-07 | Establishes `appctl` as the central operational control plane daemon, one logical API across dual transports (Unix socket and HTTP), explicit token authentication on host, Git as authoritative deployment state, the 5-stage model lifecycle, AI proposal boundaries, and append-only audit telemetry. | -| [**ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model**](#homelab-3-tier-architecture--deployment-provenance-model) | `accepted` | 2026-09-28 | Establishes 3-tier separation (Software, OCI Artifact, Sites Deployment, Core Platform), two workload classes (Source-Backed vs. Image-Only), isolated state root (`~/var/lib/homelab//`), and two operational inspection axes. | - +| [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and the 5-stage `DeploymentModel` lifecycle. | +| [**ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model**](0001-3tier-architecture-and-provenance.md) | `accepted` | 2026-09-28 | Establishes 3-tier separation (Software, OCI Artifact, Sites Deployment, Core Platform), two workload classes (Source-Backed vs. Image-Only), isolated state root (`~/var/lib/homelab//`), and two operational inspection axes. | --- ## 🧭 Summaries of Governing Decisions -### Centralized Runtime Validation & Serialization via Pydantic v2 +### [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md) * **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md) * **Status**: `accepted` (Active) * **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Milestone P4) @@ -30,27 +29,21 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using 4. **Secret-Safe Error Transformation**: Transport-level conversion of `ValidationError` into standard `ERR_VALIDATION_FAILED` (400) with raw input values redacted. 5. **Dual-Transport Parity**: Identical validated models across Unix domain socket and HTTP transports. -### Homelab Operational Control Plane & Deployment Model Architecture - -* **Decision ID**: `ADR-0002` -* **Status**: `accepted` (Active) -* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v5) +### [ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture](0002-appctl-control-plane-architecture.md) +* **Canonical Document**: [`0002-appctl-control-plane-architecture.md`](0002-appctl-control-plane-architecture.md) +* **Status**: `accepted` (Active — Reconciled with Pre-P4 Locked Decisions `DEC-01`–`DEC-05`) +* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v6) * **Core Commitments**: - 1. **Control Plane Daemon**: `appctl` transitions from a collection of local shell scripts into the authoritative platform service (`homelab-appctl.service`). - 2. **One Logical API Across Dual Transports**: Command-oriented operations exposed over a Unix domain socket (`/run/homelab/appctl.sock`) on host and an HTTP listener for network clients. - 3. **Explicit Token Authentication Everywhere**: Host SSH access does not confer appctl authority; every mutating operation requires an explicit, authenticated user-scoped token. - 4. **Git as Authoritative Deployment State**: Approved `DeploymentModels` are committed to Git. `appctl` acts as the reconciliation engine, validating the model, materializing platform descriptors (`app.yaml` + Compose), and reconciling running containers. - 5. **Five-Stage Deployment Model Lifecycle**: Separates factual `ApplicationProfile`, candidate `DeploymentProposal`, validated `DeploymentModel` (in Git), materialized `Deployment Definition`, and runtime `Reconciliation`. - 6. **AI Proposal Boundary**: AI agents act strictly as proposal generators with zero mutation or execution authority. After human approval into a `DeploymentModel`, the AI is completely out of the loop. - 7. **Secret Reference Invariant**: Manifests contain secret references (`secretKeyRef`), never secret material, resolved at runtime via `SecretProvider`. - 8. **Append-Only Audit Log**: Audit entries capture `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, and `result`. + 1. **One Logical Command API Across Dual Transports (`DEC-01`)**: `homelab-appctl.service` exposes `POST /v1/operations` (13 canonical domain operations) and `GET /v1/health` over HTTP/1.1 on `/run/homelab/appctl.sock` and `127.0.0.1:9001`. + 2. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**: Every mutating operation and sensitive read (`workload.config`, `workload.logs`) requires an authenticated SHA-256 Bearer token (`/run/secrets/appctl/tokens.json`); tokenless UDS calls fall back via `SO_PEERCRED` strictly to `homelab-viewer` read-only inspection. + 3. **Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)**: Daemon executes as `homelab-appctl:homelab-operators` with mode `0600` append-only `/var/log/homelab/appctl/audit.jsonl` and a pre-execution `DISPATCHED` disk guard. + 4. **GitOps Worker Unification & Pure-Python Pre-Flight (`DEC-04`, `DEC-05`)**: `gitops_dispatcher.py` worker delegates `workload.update` to the daemon; shell `source`/`eval` are replaced with pure-Python `.env` parsing and mandatory `validate_compose_security()` pre-flight checks. + 5. **Git Truth, Five-Stage Deployment Model & AI Boundary (P5–P7)**: Git remains authoritative deployment state; separates `ApplicationProfile` $\to$ `DeploymentProposal` (AI) $\to$ `DeploymentModel` (human-approved in Git) $\to$ materialized descriptors; resolves workload secrets via `SecretProvider` (`secretKeyRef`). ---- - -### Homelab 3-Tier Architecture & Deployment Provenance Model -* **Decision ID**: `ADR-0001` +### [ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model](0001-3tier-architecture-and-provenance.md) +* **Canonical Document**: [`0001-3tier-architecture-and-provenance.md`](0001-3tier-architecture-and-provenance.md) * **Status**: `accepted` (Active) -* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v5) +* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v6) * **Core Commitments**: 1. **3-Tier Separation of Concerns**: * *Tier 1 (Software Layer)*: Upstream application repositories owning code, tests, and CI. Zero Homelab infrastructure coupling. @@ -67,9 +60,10 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using ## 📜 Superseded Historical Decisions & Lineage -The following historical plans and design iterations have been formally superseded by the active ADRs and Roadmap v5: +The following historical plans and design iterations have been formally superseded by the active ADRs and Roadmap v6: -* **Roadmap v4 & v3** (`architecture-consolidation-roadmap-v4.md`): Superseded by Roadmap v5. -* **appctl-v2 Modernization Plan** (`appctl-engine-v2-refactoring.md`): Scaffolded and absorbed into Roadmap v5 Phases P0 and P3. -* **Smart Selective Deployment Pipeline Plan** (`smart-deployment-pipeline.md`): Absorbed into Roadmap v5 Phase P4 control-plane reconciliation. -* **Architecture Implementation Guide v3** (`architecture-consolidation-implementation-guide-v3.md`): Superseded by Roadmap v5. +* **Roadmap v5 (`architecture-consolidation-roadmap-v5.md`)**: Superseded by Roadmap v6 (`DEC-01`–`DEC-05` pre-P4 boundary lock). +* **Roadmap v4, v3, v2 & v1** (`architecture-consolidation-roadmap-v4.md`): Superseded by Roadmap v5/v6. +* **appctl-v2 Modernization Plan** (`appctl-engine-v2-refactoring.md`): Scaffolded and absorbed into Roadmap Phases P0 and P3. +* **Smart Selective Deployment Pipeline Plan** (`smart-deployment-pipeline.md`): Absorbed into Phase P4 control-plane reconciliation. +* **Architecture Implementation Guide v3 & v2** (`architecture-consolidation-implementation-guide-v3.md`): Superseded by unified Roadmap v4–v6. diff --git a/docs/plans/p4-readiness-plan.md b/docs/plans/p4-readiness-plan.md index f26071c..b10822f 100644 --- a/docs/plans/p4-readiness-plan.md +++ b/docs/plans/p4-readiness-plan.md @@ -2,7 +2,7 @@ **Status**: ✅ **Approved & Locked (Pre-P4 Security Gate Complete; Ready for Daemon Implementation)** **Target Milestone**: [Milestone P4: Appctl Control Plane Daemon & API](../../ROADMAP.md#milestone-p4-appctl-control-plane-daemon--command-oriented-api) -**Governing ADR**: [`homelab-appctl-control-plane-architecture.md`](../decisions/README.md) +**Governing ADR**: [`0002-appctl-control-plane-architecture.md`](../decisions/0002-appctl-control-plane-architecture.md) --- @@ -97,7 +97,7 @@ This plan resolves the six architectural prerequisites necessary to implement P4 1. **HTTP/1.1 Over Both Transports**: Both the local Unix Domain Socket (`/run/homelab/appctl.sock`) and the loopback TCP listener (`127.0.0.1:9001`) speak standard **HTTP/1.1** and traverse a single shared request pipeline (Body Size Limit $\to$ JSON Parse $\to$ Pydantic v2 Validate $\to$ Auth/RBAC Gate $\to$ Target Resolution & Lock $\to$ Pre-Execution Audit $\to$ Execution $\to$ Post-Execution Audit). 2. **Single Canonical Operation Endpoint**: - - `POST /v1/operations`: Dispatches all 12 canonical domain operations (both read-only and mutating). + - `POST /v1/operations`: Dispatches all 13 canonical domain operations (both read-only and mutating). - `GET /v1/health`: Convenience liveness probe that internally dispatches `platform.health`. - No multi-route REST aliases (`GET /workloads`, `POST /operations/deploy`, etc.) are exposed in P4, eliminating URL-vs-body ambiguity. 3. **Bounded Non-Streaming Logs**: `workload.logs` is strictly non-streaming in P4 (`tail: StrictInt` bounded `1..1000`, default `100`). Live streaming (`--follow` / SSE) is deferred to Milestone P7. From b5a3db6f1b60379f093bacb1c5841bf9f66a6238 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 13:04:36 -0500 Subject: [PATCH 03/43] feat(appctl): implement Pydantic v2 API contracts and compose_pull action --- pyproject.toml | 6 + scripts/appctl_contracts.py | 319 ++++++++++++++ scripts/core_manifest.py | 2 +- tests/unit/test_appctl_contracts.py | 657 ++++++++++++++++++++++++++++ todo.txt | 2 +- 5 files changed, 984 insertions(+), 2 deletions(-) create mode 100644 scripts/appctl_contracts.py create mode 100644 tests/unit/test_appctl_contracts.py diff --git a/pyproject.toml b/pyproject.toml index a715c3e..6dfa6a2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,3 +14,9 @@ extraPaths = ["scripts"] venvPath = "." venv = ".venv" +[tool.pytest.ini_options] +# Automatically adds app modules and script hooks to the sys.venvPath +pythonpath = [ + ".", + "scripts" +] diff --git a/scripts/appctl_contracts.py b/scripts/appctl_contracts.py new file mode 100644 index 0000000..1a0eaa7 --- /dev/null +++ b/scripts/appctl_contracts.py @@ -0,0 +1,319 @@ +""" +appctl_contracts.py — Authoritative Control Plane API Contracts & Schema Validation + +Defines the wire protocol and Pydantic v2 domain schemas for homelab-appctl.service: +- Canonical 13 domain operations (workload.*, platform.*) +- Fail-closed strict typing (ConfigDict(extra="forbid", strict=True)) +- Operation-specific parameter models (DeployParams, UpdateParams, LogsParams, ListParams, GetParams) +- Closed 6-code error taxonomy mapped to HTTP/1.1 semantics +- Information-disclosure-preventing error sanitizer (stripping input and url) +- Dual-transport request/response models +""" + +from __future__ import annotations + +from enum import StrEnum +from typing import Annotated, Any, Literal + +from pydantic import ( + BaseModel, + BeforeValidator, + ConfigDict, + Field, + StrictBool, + StrictInt, + StrictStr, + ValidationError, + field_validator, + model_validator, +) + + +class StrictModel(BaseModel): + """Base model propagating strict validation across all control plane models — ADR-0003.""" + + model_config = ConfigDict(extra="forbid", strict=True) + + +class OperationType(StrEnum): + """The 13 canonical domain operations exposed by homelab-appctl.service.""" + + # Read-Only Operations + WORKLOAD_LIST = "workload.list" + WORKLOAD_GET = "workload.get" + WORKLOAD_RESOLVE = "workload.resolve" + PLATFORM_SSL = "platform.ssl" + PLATFORM_HEALTH = "platform.health" + WORKLOAD_CONFIG = "workload.config" + WORKLOAD_LOGS = "workload.logs" + + # Mutating Operations + WORKLOAD_DEPLOY = "workload.deploy" + WORKLOAD_STOP = "workload.stop" + WORKLOAD_RESTART = "workload.restart" + WORKLOAD_UPDATE = "workload.update" + WORKLOAD_PULL = "workload.pull" + PLATFORM_SYNC_HOMEPAGE = "platform.sync_homepage" + + +# Backward-compatibility alias +WorkloadAction = OperationType +CanonicalOperation = OperationType + +MUTATING_OPERATIONS: frozenset[OperationType] = frozenset({ + OperationType.WORKLOAD_DEPLOY, + OperationType.WORKLOAD_STOP, + OperationType.WORKLOAD_RESTART, + OperationType.WORKLOAD_UPDATE, + OperationType.WORKLOAD_PULL, + OperationType.PLATFORM_SYNC_HOMEPAGE, +}) + +READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset({ + OperationType.WORKLOAD_LIST, + OperationType.WORKLOAD_GET, + OperationType.WORKLOAD_RESOLVE, + OperationType.PLATFORM_SSL, + OperationType.PLATFORM_HEALTH, + OperationType.WORKLOAD_CONFIG, + OperationType.WORKLOAD_LOGS, +}) + +SENSITIVE_READ_OPERATIONS: frozenset[OperationType] = frozenset({ + OperationType.WORKLOAD_CONFIG, + OperationType.WORKLOAD_LOGS, +}) + +TARGET_REQUIRED_OPERATIONS: frozenset[OperationType] = frozenset({ + OperationType.WORKLOAD_GET, + OperationType.WORKLOAD_RESOLVE, + OperationType.WORKLOAD_CONFIG, + OperationType.WORKLOAD_LOGS, + OperationType.WORKLOAD_DEPLOY, + OperationType.WORKLOAD_STOP, + OperationType.WORKLOAD_RESTART, + OperationType.WORKLOAD_UPDATE, + OperationType.WORKLOAD_PULL, +}) + + +def _coerce_operation(v: Any) -> Any: + if isinstance(v, str): + try: + return OperationType(v) + except ValueError: + return v + return v + + +FlexibleOperationType = Annotated[ + OperationType, + BeforeValidator(_coerce_operation), +] +FlexibleWorkloadAction = FlexibleOperationType + + +class ErrorCode(StrEnum): + """Canonical 6-code error taxonomy for homelab-appctl.service.""" + + ERR_VALIDATION_FAILED = "ERR_VALIDATION_FAILED" + ERR_AUTH_REQUIRED = "ERR_AUTH_REQUIRED" + ERR_PERMISSION_DENIED = "ERR_PERMISSION_DENIED" + ERR_TARGET_NOT_FOUND = "ERR_TARGET_NOT_FOUND" + ERR_CONCURRENT_MUTATION = "ERR_CONCURRENT_MUTATION" + ERR_EXECUTION_FAILED = "ERR_EXECUTION_FAILED" + + @property + def http_status(self) -> int: + return ERROR_HTTP_STATUS[self] + + +ERROR_HTTP_STATUS: dict[ErrorCode, int] = { + ErrorCode.ERR_VALIDATION_FAILED: 400, + ErrorCode.ERR_AUTH_REQUIRED: 401, + ErrorCode.ERR_PERMISSION_DENIED: 403, + ErrorCode.ERR_TARGET_NOT_FOUND: 404, + ErrorCode.ERR_CONCURRENT_MUTATION: 409, + ErrorCode.ERR_EXECUTION_FAILED: 500, +} + + +def _coerce_error_code(v: Any) -> Any: + if isinstance(v, str): + try: + return ErrorCode(v) + except ValueError: + return v + return v + + +FlexibleErrorCode = Annotated[ + ErrorCode, + BeforeValidator(_coerce_error_code), +] + + +class DeployParams(StrictModel): + """Parameters for workload.deploy.""" + + recreate: StrictBool = True + remove_orphans: StrictBool = True + build: StrictBool = False + + +class UpdateParams(StrictModel): + """Parameters for workload.update.""" + + expected_branch: Annotated[StrictStr, Field(min_length=1)] | None = None + build: StrictBool = False + + +class LogsParams(StrictModel): + """Parameters for workload.logs.""" + + tail: StrictInt = Field(default=100, ge=1, le=1000) + + +class ListParams(StrictModel): + """Parameters for workload.list.""" + + fetch: StrictBool = False + core: StrictBool = False + ssl: StrictBool = False + + +class GetParams(StrictModel): + """Parameters for workload.get.""" + + ssl: StrictBool = False + + +class EmptyParams(StrictModel): + """Parameters model for operations that accept no arguments.""" + + +OPERATION_PARAMS_MAP: dict[OperationType, type[StrictModel]] = { + OperationType.WORKLOAD_DEPLOY: DeployParams, + OperationType.WORKLOAD_UPDATE: UpdateParams, + OperationType.WORKLOAD_LOGS: LogsParams, + OperationType.WORKLOAD_LIST: ListParams, + OperationType.WORKLOAD_GET: GetParams, + OperationType.WORKLOAD_STOP: EmptyParams, + OperationType.WORKLOAD_RESTART: EmptyParams, + OperationType.WORKLOAD_PULL: EmptyParams, + OperationType.WORKLOAD_RESOLVE: EmptyParams, + OperationType.PLATFORM_SSL: EmptyParams, + OperationType.PLATFORM_HEALTH: EmptyParams, + OperationType.WORKLOAD_CONFIG: EmptyParams, + OperationType.PLATFORM_SYNC_HOMEPAGE: EmptyParams, +} + + +class OperationError(StrictModel): + """Standardized error payload returned in failed OperationResponse payloads.""" + + code: FlexibleErrorCode + message: StrictStr + details: list[dict[str, Any]] | None = None + + +def sanitize_validation_error(exc: ValidationError) -> OperationError: + """ + Format and sanitize a Pydantic ValidationError into an OperationError with ERR_VALIDATION_FAILED, + stripping raw user input and documentation URLs to prevent information disclosure. + """ + raw_details = exc.errors(include_input=False, include_url=False) + clean_details: list[dict[str, Any]] = [] + for d in raw_details: + clean_details.append({ + "type": d.get("type"), + "loc": list(d.get("loc", ())), + "msg": d.get("msg"), + }) + return OperationError( + code=ErrorCode.ERR_VALIDATION_FAILED, + message="Request payload validation failed", + details=clean_details, + ) + + +class OperationRequest(StrictModel): + """Defines the body requirements of an HTTP/1.1 operation request.""" + + model_config = ConfigDict(extra="forbid", strict=True, populate_by_name=True) + + version: Literal["1.0"] = "1.0" + operation: FlexibleOperationType = Field(alias="action") + target: Annotated[StrictStr, Field(min_length=1)] | None = None + parameters: dict[str, Any] = Field(default_factory=dict, alias="params") + + @property + def action(self) -> OperationType: + return self.operation + + @property + def params(self) -> dict[str, Any]: + return self.parameters + + @field_validator("parameters", mode="before") + @classmethod + def _coerce_parameters(cls, v: Any) -> Any: + if isinstance(v, BaseModel): + return v.model_dump() + return v + + @model_validator(mode="after") + def validate_request(self) -> OperationRequest: + if self.operation in TARGET_REQUIRED_OPERATIONS and not self.target: + raise ValueError(f"Operation '{self.operation.value}' requires a non-empty target") + param_model = OPERATION_PARAMS_MAP.get(self.operation, EmptyParams) + param_model.model_validate(self.parameters) + return self + + def parse_parameters(self) -> StrictModel: + """Parse and return the typed parameter model for this operation.""" + param_model = OPERATION_PARAMS_MAP.get(self.operation, EmptyParams) + return param_model.model_validate(self.parameters) + + +class OperationResponse(StrictModel): + """Defines the standard response payload for control plane operations.""" + + model_config = ConfigDict(extra="forbid", strict=True, populate_by_name=True) + + version: Literal["1.0"] = "1.0" + success: StrictBool | None = None + status: Literal["success", "error"] | None = None + operation_id: StrictStr = Field(min_length=1) + operation: FlexibleOperationType = Field(alias="action") + target: StrictStr | None = None + output: StrictStr = "" + result: dict[str, Any] | None = None + error: OperationError | None = None + timestamp: StrictStr | None = None + duration_ms: StrictInt | None = None + + @property + def action(self) -> OperationType: + return self.operation + + @model_validator(mode="after") + def check_consistency(self) -> OperationResponse: + if self.success is None and self.status is None: + raise ValueError("Either 'success' or 'status' must be provided") + if self.success is None and self.status is not None: + self.success = self.status == "success" + elif self.status is None and self.success is not None: + self.status = "success" if self.success else "error" + elif ( + self.success is not None + and self.status is not None + and (self.status == "success") != self.success + ): + raise ValueError("'status' and 'success' must agree") + + if self.success and self.error is not None: + raise ValueError("Successful operation cannot contain an error") + if not self.success and self.error is None: + raise ValueError("Failed operation must contain an error") + return self diff --git a/scripts/core_manifest.py b/scripts/core_manifest.py index 9280c4b..41eb0e2 100644 --- a/scripts/core_manifest.py +++ b/scripts/core_manifest.py @@ -75,7 +75,7 @@ RESERVED_ENV_KEYS = { } ALLOWED_STRATEGIES = {"compose"} -ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"} +ALLOWED_ACTIONS = {"git_pull", "compose_pull", "compose_up", "compose_build", "compose_restart"} def validate_transport(url: str) -> tuple[TransportScheme, str]: diff --git a/tests/unit/test_appctl_contracts.py b/tests/unit/test_appctl_contracts.py new file mode 100644 index 0000000..a76c79b --- /dev/null +++ b/tests/unit/test_appctl_contracts.py @@ -0,0 +1,657 @@ +""" +tests/unit/test_appctl_contracts.py — Unit Tests for Control Plane API Contracts (P4 Slice 1) + +Behavior-driven test naming convention: +test___ +""" + +from __future__ import annotations + +import pytest +from appctl_contracts import ( + MUTATING_OPERATIONS, + READ_ONLY_OPERATIONS, + TARGET_REQUIRED_OPERATIONS, + DeployParams, + EmptyParams, + ErrorCode, + GetParams, + ListParams, + LogsParams, + OperationError, + OperationRequest, + OperationResponse, + OperationType, + UpdateParams, + sanitize_validation_error, +) +from core_manifest import ALLOWED_ACTIONS, Manifest +from pydantic import BaseModel, ValidationError + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def get_validation_error_locs(data: dict) -> list[str | int]: + with pytest.raises(ValidationError) as exc_info: + OperationRequest.model_validate(data) + return [err["loc"][0] for err in exc_info.value.errors()] + + +# --------------------------------------------------------------------------- +# Canonical 13 Operations +# --------------------------------------------------------------------------- + + +def test_operation_type_contains_exactly_13_canonical_operations(): + assert len(OperationType) == 13 + expected = { + "workload.list", + "workload.get", + "workload.resolve", + "platform.ssl", + "platform.health", + "workload.config", + "workload.logs", + "workload.deploy", + "workload.stop", + "workload.restart", + "workload.update", + "workload.pull", + "platform.sync_homepage", + } + assert {op.value for op in OperationType} == expected + + +def test_operation_sets_partition_canonical_operations(): + assert MUTATING_OPERATIONS | READ_ONLY_OPERATIONS == set(OperationType) + assert MUTATING_OPERATIONS.isdisjoint(READ_ONLY_OPERATIONS) + + +@pytest.mark.parametrize("op", list(OperationType)) +def test_operation_request_accepts_all_canonical_operations(op: OperationType): + target = "jellyfin" if op in TARGET_REQUIRED_OPERATIONS else None + request = { + "version": "1.0", + "operation": op.value, + "target": target, + "parameters": {}, + } + validated = OperationRequest.model_validate(request) + assert validated.operation == op + assert validated.action == op + + +def test_operation_request_rejects_unknown_operation(): + request = { + "version": "1.0", + "operation": "workload.unknown_action", + "target": "jellyfin", + "parameters": {}, + } + locs = get_validation_error_locs(request) + assert "operation" in locs + + +def test_operation_request_rejects_empty_operation(): + request = { + "version": "1.0", + "operation": "", + "target": "jellyfin", + "parameters": {}, + } + locs = get_validation_error_locs(request) + assert "operation" in locs + + +def test_operation_request_rejects_non_string_operation(): + request = { + "version": "1.0", + "operation": 12345, + "target": "jellyfin", + "parameters": {}, + } + locs = get_validation_error_locs(request) + assert "operation" in locs + + +# --------------------------------------------------------------------------- +# Version "1.0" +# --------------------------------------------------------------------------- + + +def test_operation_request_accepts_default_and_explicit_version_1_0(): + # Explicit "1.0" + r1 = OperationRequest.model_validate({ + "version": "1.0", + "operation": "platform.health", + }) + assert r1.version == "1.0" + + # Default "1.0" + r2 = OperationRequest.model_validate({ + "operation": "platform.health", + }) + assert r2.version == "1.0" + + +def test_operation_request_rejects_non_1_0_version(): + for bad_ver in ["2.0", "0.9", "1.1", ""]: + request = { + "version": bad_ver, + "operation": "platform.health", + } + locs = get_validation_error_locs(request) + assert "version" in locs + + +def test_operation_request_rejects_numeric_version(): + request = { + "version": 1.0, + "operation": "platform.health", + } + locs = get_validation_error_locs(request) + assert "version" in locs + + +# --------------------------------------------------------------------------- +# Target Validation +# --------------------------------------------------------------------------- + + +def test_operation_request_rejects_empty_target(): + request = { + "version": "1.0", + "operation": "workload.deploy", + "target": "", + "parameters": {}, + } + locs = get_validation_error_locs(request) + assert "target" in locs + + +@pytest.mark.parametrize("op", list(TARGET_REQUIRED_OPERATIONS)) +def test_operation_request_rejects_missing_target_when_required(op: OperationType): + request = { + "version": "1.0", + "operation": op.value, + "target": None, + "parameters": {}, + } + with pytest.raises(ValidationError) as exc_info: + OperationRequest.model_validate(request) + assert "requires a non-empty target" in str(exc_info.value) + + +@pytest.mark.parametrize("op", [ + OperationType.WORKLOAD_LIST, + OperationType.PLATFORM_HEALTH, + OperationType.PLATFORM_SYNC_HOMEPAGE, +]) +def test_operation_request_accepts_missing_target_when_optional(op: OperationType): + request = { + "version": "1.0", + "operation": op.value, + "parameters": {}, + } + validated = OperationRequest.model_validate(request) + assert validated.target is None + + +# --------------------------------------------------------------------------- +# Parameter Models & Bounds Validation +# --------------------------------------------------------------------------- + + +def test_deploy_params_defaults_and_explicit_bounds(): + # Defaults + p_default = DeployParams() + assert p_default.recreate is True + assert p_default.remove_orphans is True + assert p_default.build is False + + # Explicit + p_custom = DeployParams(recreate=False, remove_orphans=False, build=True) + assert p_custom.recreate is False + assert p_custom.remove_orphans is False + assert p_custom.build is True + + +def test_deploy_params_rejects_non_strict_types(): + for bad_bool in ["true", "false", 1, 0, None, [True]]: + with pytest.raises(ValidationError): + DeployParams(recreate=bad_bool) # type: ignore[arg-type] + with pytest.raises(ValidationError): + DeployParams(remove_orphans=bad_bool) # type: ignore[arg-type] + with pytest.raises(ValidationError): + DeployParams(build=bad_bool) # type: ignore[arg-type] + + +def test_deploy_params_rejects_extra_fields(): + with pytest.raises(ValidationError): + DeployParams.model_validate({"recreate": True, "unexpected": "extra"}) + + +def test_update_params_defaults_and_explicit(): + # Defaults + p_default = UpdateParams() + assert p_default.expected_branch is None + assert p_default.build is False + + # Explicit + p_custom = UpdateParams(expected_branch="main", build=True) + assert p_custom.expected_branch == "main" + assert p_custom.build is True + + +def test_update_params_rejects_empty_branch_and_non_strict_types(): + with pytest.raises(ValidationError): + UpdateParams(expected_branch="") # min_length=1 + + with pytest.raises(ValidationError): + UpdateParams(expected_branch=123) # type: ignore[arg-type] + + with pytest.raises(ValidationError): + UpdateParams(build="true") # type: ignore[arg-type] + + with pytest.raises(ValidationError): + UpdateParams.model_validate({"build": False, "extra": "prohibited"}) + + +def test_logs_params_defaults_and_bounds(): + # Default + p_default = LogsParams() + assert p_default.tail == 100 + + # Bounds + assert LogsParams(tail=1).tail == 1 + assert LogsParams(tail=1000).tail == 1000 + assert LogsParams(tail=500).tail == 500 + + # Below minimum + with pytest.raises(ValidationError): + LogsParams(tail=0) + + # Above maximum + with pytest.raises(ValidationError): + LogsParams(tail=1001) + + # Non-strict integer (string / float) + with pytest.raises(ValidationError): + LogsParams(tail="100") # type: ignore[arg-type] + with pytest.raises(ValidationError): + LogsParams(tail=100.5) # type: ignore[arg-type] + + with pytest.raises(ValidationError): + LogsParams.model_validate({"tail": 50, "follow": True}) + + +def test_list_params_defaults_and_explicit(): + p_default = ListParams() + assert p_default.fetch is False + assert p_default.core is False + assert p_default.ssl is False + + p_custom = ListParams(fetch=True, core=True, ssl=True) + assert p_custom.fetch is True + assert p_custom.core is True + assert p_custom.ssl is True + + with pytest.raises(ValidationError): + ListParams(fetch="yes") # type: ignore[arg-type] + + with pytest.raises(ValidationError): + ListParams.model_validate({"fetch": False, "extra": 1}) + + +def test_get_params_defaults_and_explicit(): + p_default = GetParams() + assert p_default.ssl is False + + p_custom = GetParams(ssl=True) + assert p_custom.ssl is True + + with pytest.raises(ValidationError): + GetParams(ssl="true") # type: ignore[arg-type] + + +def test_empty_params_rejects_extra_fields(): + p = EmptyParams() + assert p.model_dump() == {} + + with pytest.raises(ValidationError): + EmptyParams.model_validate({"any_field": "disallowed"}) + + +def test_operation_request_validates_and_parses_operation_specific_params(): + # Deploy + req_deploy = OperationRequest.model_validate({ + "version": "1.0", + "operation": "workload.deploy", + "target": "snappymail", + "parameters": {"recreate": True, "build": True}, + }) + params = req_deploy.parse_parameters() + assert isinstance(params, DeployParams) + assert params.build is True + + # Logs + req_logs = OperationRequest.model_validate({ + "version": "1.0", + "operation": "workload.logs", + "target": "snappymail", + "parameters": {"tail": 250}, + }) + log_params = req_logs.parse_parameters() + assert isinstance(log_params, LogsParams) + assert log_params.tail == 250 + + # Stop (accepts EmptyParams) + req_stop = OperationRequest.model_validate({ + "version": "1.0", + "operation": "workload.stop", + "target": "snappymail", + "parameters": {}, + }) + assert isinstance(req_stop.parse_parameters(), EmptyParams) + + +def test_operation_request_rejects_invalid_params_for_operation(): + # Deploy with bad tail + with pytest.raises(ValidationError): + OperationRequest.model_validate({ + "version": "1.0", + "operation": "workload.deploy", + "target": "snappymail", + "parameters": {"tail": 50}, # Deploy does not accept tail + }) + + # Logs with out-of-bounds tail + with pytest.raises(ValidationError): + OperationRequest.model_validate({ + "version": "1.0", + "operation": "workload.logs", + "target": "snappymail", + "parameters": {"tail": 9999}, + }) + + # Stop with extra params + with pytest.raises(ValidationError): + OperationRequest.model_validate({ + "version": "1.0", + "operation": "workload.stop", + "target": "snappymail", + "parameters": {"force": True}, + }) + + +def test_operation_request_rejects_extra_top_level_fields(): + request = { + "version": "1.0", + "operation": "platform.health", + "prohibited_extra": "attack", + } + with pytest.raises(ValidationError) as exc_info: + OperationRequest.model_validate(request) + assert "extra_forbidden" in [e["type"] for e in exc_info.value.errors()] + + +def test_operation_request_backward_compatibility_aliases(): + # Accepts 'action' alias for 'operation', and 'params' alias for 'parameters' + request = { + "action": "workload.deploy", + "target": "jellyfin", + "params": {"recreate": True}, + } + validated = OperationRequest.model_validate(request) + assert validated.operation == OperationType.WORKLOAD_DEPLOY + assert validated.action == OperationType.WORKLOAD_DEPLOY + assert validated.parameters == {"recreate": True} + assert validated.params == {"recreate": True} + + +# --------------------------------------------------------------------------- +# Closed 6-Code Error Taxonomy +# --------------------------------------------------------------------------- + + +def test_error_code_taxonomy_contains_exactly_6_canonical_codes(): + assert len(ErrorCode) == 6 + expected_codes = { + "ERR_VALIDATION_FAILED", + "ERR_AUTH_REQUIRED", + "ERR_PERMISSION_DENIED", + "ERR_TARGET_NOT_FOUND", + "ERR_CONCURRENT_MUTATION", + "ERR_EXECUTION_FAILED", + } + assert {code.value for code in ErrorCode} == expected_codes + + +def test_error_code_http_status_mapping(): + assert ErrorCode.ERR_VALIDATION_FAILED.http_status == 400 + assert ErrorCode.ERR_AUTH_REQUIRED.http_status == 401 + assert ErrorCode.ERR_PERMISSION_DENIED.http_status == 403 + assert ErrorCode.ERR_TARGET_NOT_FOUND.http_status == 404 + assert ErrorCode.ERR_CONCURRENT_MUTATION.http_status == 409 + assert ErrorCode.ERR_EXECUTION_FAILED.http_status == 500 + + +def test_operation_error_accepts_valid_error_code(): + err = OperationError( + code=ErrorCode.ERR_AUTH_REQUIRED, + message="Bearer token required", + ) + assert err.code == ErrorCode.ERR_AUTH_REQUIRED + assert err.message == "Bearer token required" + assert err.details is None + + +def test_operation_error_accepts_string_error_code_coercion(): + err = OperationError.model_validate({ + "code": "ERR_CONCURRENT_MUTATION", + "message": "Operation locked by concurrent task", + }) + assert err.code == ErrorCode.ERR_CONCURRENT_MUTATION + + +def test_operation_error_rejects_invalid_error_code(): + with pytest.raises(ValidationError): + OperationError.model_validate({ + "code": "ERR_CUSTOM_CODE", + "message": "Invalid code", + }) + + +def test_operation_error_rejects_extra_fields(): + with pytest.raises(ValidationError): + OperationError.model_validate({ + "code": "ERR_VALIDATION_FAILED", + "message": "Failed", + "secret_leak": "value", + }) + + +# --------------------------------------------------------------------------- +# Error Sanitizer (Information Disclosure Prevention) +# --------------------------------------------------------------------------- + + +def test_sanitize_validation_error_strips_input_and_url(): + # Create a model with secret value that fails validation + class SecretPayload(BaseModel): + token: str = "default" + + try: + LogsParams.model_validate({ + "tail": "SUPER_SECRET_TOKEN_DO_NOT_LEAK", + }) + except ValidationError as exc: + op_err = sanitize_validation_error(exc) + + assert op_err.code == ErrorCode.ERR_VALIDATION_FAILED + assert op_err.message == "Request payload validation failed" + assert op_err.details is not None + assert len(op_err.details) > 0 + + # Ensure neither input nor url appears in any details dictionary + for detail in op_err.details: + assert "input" not in detail + assert "url" not in detail + assert "SUPER_SECRET_TOKEN_DO_NOT_LEAK" not in str(detail) + assert "loc" in detail + assert "msg" in detail + assert "type" in detail + + +# --------------------------------------------------------------------------- +# OperationResponse Consistency & Edge Cases +# --------------------------------------------------------------------------- + + +def test_operation_response_accepts_success_without_error(): + response_data = { + "version": "1.0", + "success": True, + "operation_id": "op_123", + "operation": "workload.deploy", + "target": "snappymail", + "output": "Snappymail deployment complete", + } + validated = OperationResponse.model_validate(response_data) + assert validated.success is True + assert validated.status == "success" + assert validated.error is None + assert validated.operation == OperationType.WORKLOAD_DEPLOY + assert validated.action == OperationType.WORKLOAD_DEPLOY + assert validated.operation_id == "op_123" + + +def test_operation_response_accepts_status_field_reconciliation(): + # Pass 'status': 'success' without 'success' + r1 = OperationResponse.model_validate({ + "version": "1.0", + "status": "success", + "operation_id": "op_123", + "operation": "platform.health", + }) + assert r1.success is True + assert r1.status == "success" + + # Pass 'status': 'error' without 'success' + r2 = OperationResponse.model_validate({ + "version": "1.0", + "status": "error", + "operation_id": "op_124", + "operation": "platform.health", + "error": { + "code": "ERR_EXECUTION_FAILED", + "message": "Health probe failed", + }, + }) + assert r2.success is False + assert r2.status == "error" + + +def test_operation_response_accepts_failure_with_nested_error(): + response_data = { + "version": "1.0", + "success": False, + "operation_id": "op_456", + "operation": "workload.deploy", + "target": "capybara", + "error": { + "code": "ERR_TARGET_NOT_FOUND", + "message": "Workload `capybara` does not exist", + }, + } + validated = OperationResponse.model_validate(response_data) + assert validated.success is False + assert validated.target == "capybara" + assert validated.operation_id == "op_456" + assert validated.operation == OperationType.WORKLOAD_DEPLOY + assert isinstance(validated.error, OperationError) + assert validated.error.code == ErrorCode.ERR_TARGET_NOT_FOUND + assert validated.error.message == "Workload `capybara` does not exist" + + +def test_operation_response_rejects_success_with_error(): + response_data = { + "version": "1.0", + "success": True, + "operation": "workload.deploy", + "target": "microservice1", + "operation_id": "op_124", + "error": { + "code": "ERR_VALIDATION_FAILED", + "message": "This error should not appear on success response", + }, + } + with pytest.raises(ValidationError) as exc_info: + OperationResponse.model_validate(response_data) + assert "cannot contain an error" in str(exc_info.value) + + +def test_operation_response_rejects_failure_without_error(): + response_data = { + "version": "1.0", + "success": False, + "operation": "workload.deploy", + "target": "microservice2", + "operation_id": "op_125", + } + with pytest.raises(ValidationError) as exc_info: + OperationResponse.model_validate(response_data) + assert "must contain an error" in str(exc_info.value) + + +def test_operation_response_rejects_inconsistent_status_and_success(): + response_data = { + "version": "1.0", + "success": True, + "status": "error", + "operation": "platform.health", + "operation_id": "op_126", + } + with pytest.raises(ValidationError) as exc_info: + OperationResponse.model_validate(response_data) + assert "'status' and 'success' must agree" in str(exc_info.value) + + +def test_operation_response_rejects_extra_fields(): + response_data = { + "version": "1.0", + "success": True, + "operation": "platform.health", + "operation_id": "op_127", + "unauthorized_field": "data", + } + with pytest.raises(ValidationError) as exc_info: + OperationResponse.model_validate(response_data) + assert "extra_forbidden" in [e["type"] for e in exc_info.value.errors()] + + +# --------------------------------------------------------------------------- +# Core Manifest compose_pull Action +# --------------------------------------------------------------------------- + + +def test_core_manifest_allows_compose_pull_action(): + assert "compose_pull" in ALLOWED_ACTIONS + + valid_manifest = { + "schema_version": "1.0", + "name": "snappymail", + "source": { + "type": "git", + "url": "https://github.com/example/snappymail.git", + "ref": "main", + }, + "deployment": { + "strategy": "compose", + "actions": ["git_pull", "compose_pull", "compose_up"], + }, + } + parsed = Manifest.model_validate(valid_manifest) + assert parsed.deployment.actions == ["git_pull", "compose_pull", "compose_up"] \ No newline at end of file diff --git a/todo.txt b/todo.txt index f354321..2963a01 100644 --- a/todo.txt +++ b/todo.txt @@ -22,7 +22,7 @@ x 2026-10-15 (B) Scrub hardcoded domain defaults across scripts and tests enforc x 2026-10-15 (A) De-tautologize appctl env injection test to execute scripts/appctl directly with mock docker in tests/security/test_security_invariants.py +test @security x 2026-10-15 (A) Clarify Pydantic v2 target architecture, strict typing rules, and domain precedence in docs/plans/p4-readiness-plan.md +docs @p4-gate x 2026-10-15 (A) Migrate core_manifest.py to Pydantic v2 models for strict type validation and serialization +manifest @schema -(A) Implement strict Pydantic v2 API contracts, error sanitizer, and compose_pull action in scripts/appctl_contracts.py and scripts/core_manifest.py +contracts @p4 +x 2026-10-19 (A) Implement strict Pydantic v2 API contracts, error sanitizer, and compose_pull action in scripts/appctl_contracts.py and scripts/core_manifest.py +contracts @p4 (A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4 (A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4 (B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4 From 8ce74ff52065d05c42e87a7862688559c3fd6af1 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 13:08:35 -0500 Subject: [PATCH 04/43] feat(appctl): implement append-only audit logger and per-target lock manager --- scripts/appctl_audit.py | 402 ++++++++++++++++++++++++++++++++ tests/unit/test_appctl_audit.py | 336 ++++++++++++++++++++++++++ todo.txt | 2 +- 3 files changed, 739 insertions(+), 1 deletion(-) create mode 100644 scripts/appctl_audit.py create mode 100644 tests/unit/test_appctl_audit.py diff --git a/scripts/appctl_audit.py b/scripts/appctl_audit.py new file mode 100644 index 0000000..635afe1 --- /dev/null +++ b/scripts/appctl_audit.py @@ -0,0 +1,402 @@ +""" +appctl_audit.py — Append-Only Audit Logger & Per-Target Lock Manager (P4 Slice 2) + +Governs the audit telemetry and concurrency control for homelab-appctl.service: +- Append-only JSONL audit writer adhering to RFC-compliant schema (mode 0600) +- Pre-execution DISPATCHED fail-closed disk guard +- Sensitive parameter and error redaction (*_KEY, *_SECRET, *_PASSWORD, etc.) +- Non-blocking per-target flock context manager raising ConcurrentMutationError (409) +""" + +from __future__ import annotations + +import fcntl +import os +import re +import secrets +import threading +from datetime import UTC, datetime +from enum import StrEnum +from pathlib import Path +from types import TracebackType +from typing import Annotated, Any, Literal, Self + +from appctl_contracts import StrictModel +from pydantic import BeforeValidator, ConfigDict, Field, StrictInt, StrictStr + +DEFAULT_AUDIT_LOG = Path("/var/log/homelab/appctl/audit.jsonl") +DEFAULT_LOCK_DIR = Path("/var/lib/homelab/appctl/locks") + +REDACT_KEY_PATTERNS = re.compile( + r".*(?:_KEY|_SECRET|_PASSWORD|_TOKEN|_PASS|_HASH)$", re.IGNORECASE +) + + +class AuditPhase(StrEnum): + """Lifecycle phases for control plane audit events.""" + + DISPATCHED = "DISPATCHED" + COMPLETED = "COMPLETED" + FAILED = "FAILED" + DENIED = "DENIED" + + +def _coerce_phase(v: Any) -> Any: + if isinstance(v, str): + try: + return AuditPhase(v) + except ValueError: + return v + return v + + +FlexibleAuditPhase = Annotated[ + AuditPhase, + BeforeValidator(_coerce_phase), +] + + +class PrincipalAudit(StrictModel): + """Authenticated principal details captured in audit records.""" + + identity: StrictStr + role: StrictStr + token_id: StrictStr | None = None + auth_method: StrictStr + + +class AuditResult(StrictModel): + """Execution outcome details captured in audit records.""" + + status: Literal["SUCCESS", "FAILED", "DENIED", "IN_PROGRESS"] + exit_code: StrictInt | None = None + duration_ms: StrictInt | None = None + commit_sha: StrictStr | None = None + error_code: StrictStr | None = None + message: StrictStr | None = None + + +class AuditEvent(StrictModel): + """RFC-compliant single-line JSONL audit event model (ADR-0002 / DEC-03).""" + + model_config = ConfigDict(extra="forbid", strict=True) + + audit_version: Literal["1.0"] = "1.0" + event_id: StrictStr + operation_id: StrictStr + timestamp: StrictStr + phase: FlexibleAuditPhase + principal: PrincipalAudit + action: StrictStr + target: StrictStr | None = None + transport: StrictStr + origin: StrictStr + client: StrictStr + parameters: dict[str, Any] = Field(default_factory=dict) + result: AuditResult | None = None + + +class AuditPersistenceError(Exception): + """Raised when an audit record cannot be persisted or flushed to disk.""" + + +class ConcurrentMutationError(Exception): + """Raised when a per-target operation lock cannot be acquired (409 Conflict).""" + + def __init__(self, target: str, message: str | None = None) -> None: + self.target = target + msg = message or f"Operation on target '{target}' is locked by a concurrent task." + super().__init__(msg) + + +def redact_sensitive_data(val: Any) -> Any: + """ + Recursively redact values whose dictionary keys match sensitive patterns + (*_KEY, *_SECRET, *_PASSWORD, *_TOKEN, *_PASS, *_HASH). + """ + if isinstance(val, dict): + return { + k: "[REDACTED]" if REDACT_KEY_PATTERNS.match(str(k)) else redact_sensitive_data(v) + for k, v in val.items() + } + if isinstance(val, list): + return [redact_sensitive_data(v) for v in val] + return val + + +def generate_event_id() -> str: + """Generate a unique event identifier.""" + return f"evt_{secrets.token_hex(6)}" + + +def generate_operation_id() -> str: + """Generate a unique operation identifier.""" + return f"op_{secrets.token_hex(6)}" + + +def current_iso_timestamp() -> str: + """Current UTC timestamp formatted as ISO 8601 with millisecond precision.""" + now = datetime.now(UTC) + return now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" + + +class AuditLogger: + """ + Append-only thread-safe audit logger writing single-line JSONL records. + Enforces mode 0600 on the log file and provides a fail-closed pre-execution + DISPATCHED disk guard. + """ + + def __init__(self, log_path: Path | str | None = None) -> None: + if log_path is not None: + self.log_path = Path(log_path) + elif "APPCTL_AUDIT_LOG" in os.environ: + self.log_path = Path(os.environ["APPCTL_AUDIT_LOG"]) + else: + self.log_path = DEFAULT_AUDIT_LOG + self._lock = threading.Lock() + + def _ensure_log_file(self) -> None: + """Ensure parent directories exist and file is initialized with mode 0600.""" + self.log_path.parent.mkdir(parents=True, exist_ok=True) + if not self.log_path.exists(): + fd = os.open( + self.log_path, + os.O_WRONLY | os.O_CREAT | os.O_APPEND, + 0o600, + ) + os.close(fd) + + def emit_event(self, event: AuditEvent) -> None: + """ + Append an audit event as a single JSON line to the audit log. + Flushes and fsyncs to ensure durability. Raises AuditPersistenceError on failure. + """ + with self._lock: + try: + self._ensure_log_file() + line = event.model_dump_json() + "\n" + fd = os.open( + self.log_path, + os.O_WRONLY | os.O_APPEND, + 0o600, + ) + try: + os.write(fd, line.encode("utf-8")) + os.fsync(fd) + finally: + os.close(fd) + except OSError as err: + raise AuditPersistenceError( + f"Failed to persist audit event '{event.event_id}': {err}" + ) from err + + def log_dispatched( + self, + operation_id: str, + principal: PrincipalAudit, + action: str, + target: str | None, + transport: str, + origin: str, + client: str, + parameters: dict[str, Any], + ) -> AuditEvent: + """ + Fail-closed pre-execution disk guard: logs DISPATCHED phase before any + subprocess or filesystem mutation begins. Raises AuditPersistenceError if disk write fails. + """ + clean_params = redact_sensitive_data(parameters) + event = AuditEvent( + event_id=generate_event_id(), + operation_id=operation_id, + timestamp=current_iso_timestamp(), + phase=AuditPhase.DISPATCHED, + principal=principal, + action=action, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=clean_params, + result=AuditResult(status="IN_PROGRESS"), + ) + self.emit_event(event) + return event + + def log_completed( + self, + operation_id: str, + principal: PrincipalAudit, + action: str, + target: str | None, + transport: str, + origin: str, + client: str, + parameters: dict[str, Any], + duration_ms: int, + commit_sha: str | None = None, + message: str | None = None, + ) -> AuditEvent: + """Log COMPLETED phase upon clean operation termination.""" + clean_params = redact_sensitive_data(parameters) + event = AuditEvent( + event_id=generate_event_id(), + operation_id=operation_id, + timestamp=current_iso_timestamp(), + phase=AuditPhase.COMPLETED, + principal=principal, + action=action, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=clean_params, + result=AuditResult( + status="SUCCESS", + exit_code=0, + duration_ms=duration_ms, + commit_sha=commit_sha, + error_code=None, + message=message or "Operation completed successfully", + ), + ) + self.emit_event(event) + return event + + def log_failed( + self, + operation_id: str, + principal: PrincipalAudit, + action: str, + target: str | None, + transport: str, + origin: str, + client: str, + parameters: dict[str, Any], + duration_ms: int | None = None, + exit_code: int | None = None, + error_code: str | None = None, + message: str | None = None, + ) -> AuditEvent: + """Log FAILED phase when validation or execution fails.""" + clean_params = redact_sensitive_data(parameters) + clean_msg = redact_sensitive_data(message) if message else None + event = AuditEvent( + event_id=generate_event_id(), + operation_id=operation_id, + timestamp=current_iso_timestamp(), + phase=AuditPhase.FAILED, + principal=principal, + action=action, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=clean_params, + result=AuditResult( + status="FAILED", + exit_code=exit_code, + duration_ms=duration_ms, + error_code=error_code, + message=clean_msg, + ), + ) + self.emit_event(event) + return event + + def log_denied( + self, + operation_id: str, + principal: PrincipalAudit, + action: str, + target: str | None, + transport: str, + origin: str, + client: str, + parameters: dict[str, Any], + error_code: str, + message: str, + ) -> AuditEvent: + """Log DENIED phase when authentication, RBAC, or concurrency lock rejects request.""" + clean_params = redact_sensitive_data(parameters) + event = AuditEvent( + event_id=generate_event_id(), + operation_id=operation_id, + timestamp=current_iso_timestamp(), + phase=AuditPhase.DENIED, + principal=principal, + action=action, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=clean_params, + result=AuditResult( + status="DENIED", + error_code=error_code, + message=message, + ), + ) + self.emit_event(event) + return event + + +class TargetLock: + """Context manager acquiring a non-blocking per-target flock.""" + + def __init__(self, lock_path: Path, target: str) -> None: + self.lock_path = lock_path + self.target = target + self._fd: int | None = None + + def __enter__(self) -> Self: + self.lock_path.parent.mkdir(parents=True, exist_ok=True) + fd = os.open( + self.lock_path, + os.O_RDWR | os.O_CREAT, + 0o600, + ) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except (BlockingIOError, OSError) as err: + os.close(fd) + raise ConcurrentMutationError(self.target) from err + self._fd = fd + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self._fd is not None: + try: + fcntl.flock(self._fd, fcntl.LOCK_UN) + finally: + os.close(self._fd) + self._fd = None + + +class TargetLockManager: + """Manages operational per-target locks under /var/lib/homelab/appctl/locks.""" + + def __init__(self, lock_dir: Path | str | None = None) -> None: + if lock_dir is not None: + self.lock_dir = Path(lock_dir) + elif "APPCTL_LOCK_DIR" in os.environ: + self.lock_dir = Path(os.environ["APPCTL_LOCK_DIR"]) + else: + self.lock_dir = DEFAULT_LOCK_DIR + + def lock_target(self, target: str) -> TargetLock: + """Return a non-blocking flock context manager for a workload target.""" + clean_target = re.sub(r"[^a-zA-Z0-9._-]", "_", target) + lock_path = self.lock_dir / f"{clean_target}.lock" + return TargetLock(lock_path, target) + + def homepage_sync_lock(self) -> TargetLock: + """Return a non-blocking flock context manager for homepage compilation.""" + lock_path = self.lock_dir / "_homepage_sync.lock" + return TargetLock(lock_path, "_homepage_sync") diff --git a/tests/unit/test_appctl_audit.py b/tests/unit/test_appctl_audit.py new file mode 100644 index 0000000..ce69250 --- /dev/null +++ b/tests/unit/test_appctl_audit.py @@ -0,0 +1,336 @@ +""" +tests/unit/test_appctl_audit.py — Unit Tests for Audit Logger & Concurrency Lock (P4 Slice 2) + +Behavior-driven test naming convention: +test___ +""" + +from __future__ import annotations + +import json +import os +import stat +from pathlib import Path + +import pytest +from appctl_audit import ( + AuditEvent, + AuditLogger, + AuditPersistenceError, + AuditPhase, + ConcurrentMutationError, + PrincipalAudit, + TargetLockManager, + redact_sensitive_data, +) + + +@pytest.fixture +def temp_audit_file(tmp_path: Path) -> Path: + return tmp_path / "audit" / "audit.jsonl" + + +@pytest.fixture +def temp_lock_dir(tmp_path: Path) -> Path: + lock_dir = tmp_path / "locks" + lock_dir.mkdir(parents=True, exist_ok=True) + return lock_dir + + +@pytest.fixture +def sample_principal() -> PrincipalAudit: + return PrincipalAudit( + identity="operator", + role="homelab-admin", + token_id="tok_admin_01", + auth_method="bearer_token", + ) + + +# --------------------------------------------------------------------------- +# File Permissions & Initialization +# --------------------------------------------------------------------------- + + +def test_audit_logger_enforces_0600_permissions_on_creation( + temp_audit_file: Path, sample_principal: PrincipalAudit +): + logger = AuditLogger(temp_audit_file) + logger.log_dispatched( + operation_id="op_100", + principal=sample_principal, + action="workload.deploy", + target="snappymail", + transport="unix_socket", + origin="peer_uid_1000", + client="appctl-cli/2.0", + parameters={"recreate": True}, + ) + + assert temp_audit_file.exists() + mode = stat.S_IMODE(temp_audit_file.stat().st_mode) + assert mode == 0o600 + + +# --------------------------------------------------------------------------- +# Audit Phases & RFC JSONL Schema +# --------------------------------------------------------------------------- + + +def test_audit_logger_writes_valid_jsonl_lifecycle( + temp_audit_file: Path, sample_principal: PrincipalAudit +): + logger = AuditLogger(temp_audit_file) + + # 1. DISPATCHED + evt_disp = logger.log_dispatched( + operation_id="op_101", + principal=sample_principal, + action="workload.update", + target="jellyfin", + transport="http", + origin="127.0.0.1:48291", + client="gitops-dispatcher/1.0", + parameters={"expected_branch": "main", "build": False}, + ) + assert evt_disp.phase == AuditPhase.DISPATCHED + assert evt_disp.result is not None + assert evt_disp.result.status == "IN_PROGRESS" + + # 2. COMPLETED + evt_comp = logger.log_completed( + operation_id="op_101", + principal=sample_principal, + action="workload.update", + target="jellyfin", + transport="http", + origin="127.0.0.1:48291", + client="gitops-dispatcher/1.0", + parameters={"expected_branch": "main", "build": False}, + duration_ms=1450, + commit_sha="a1b2c3d", + message="Workload updated and reconciled successfully", + ) + assert evt_comp.phase == AuditPhase.COMPLETED + assert evt_comp.result is not None + assert evt_comp.result.status == "SUCCESS" + assert evt_comp.result.exit_code == 0 + assert evt_comp.result.commit_sha == "a1b2c3d" + + # Read and validate JSONL file contents + lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines() + assert len(lines) == 2 + + parsed_disp = AuditEvent.model_validate(json.loads(lines[0])) + assert parsed_disp.phase == AuditPhase.DISPATCHED + assert parsed_disp.operation_id == "op_101" + + parsed_comp = AuditEvent.model_validate(json.loads(lines[1])) + assert parsed_comp.phase == AuditPhase.COMPLETED + assert parsed_comp.operation_id == "op_101" + + +def test_audit_logger_writes_failed_event( + temp_audit_file: Path, sample_principal: PrincipalAudit +): + logger = AuditLogger(temp_audit_file) + logger.log_failed( + operation_id="op_102", + principal=sample_principal, + action="workload.deploy", + target="jellyfin", + transport="unix_socket", + origin="peer_uid_1000", + client="appctl-cli/2.0", + parameters={"recreate": True}, + duration_ms=320, + exit_code=1, + error_code="ERR_EXECUTION_FAILED", + message="Docker compose failed with exit code 1", + ) + + lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines() + assert len(lines) == 1 + event = AuditEvent.model_validate(json.loads(lines[0])) + assert event.phase == AuditPhase.FAILED + assert event.result is not None + assert event.result.status == "FAILED" + assert event.result.exit_code == 1 + assert event.result.error_code == "ERR_EXECUTION_FAILED" + + +def test_audit_logger_writes_denied_event( + temp_audit_file: Path, sample_principal: PrincipalAudit +): + logger = AuditLogger(temp_audit_file) + logger.log_denied( + operation_id="op_103", + principal=sample_principal, + action="workload.config", + target="core", + transport="http", + origin="127.0.0.1:49000", + client="curl/8.1", + parameters={}, + error_code="ERR_PERMISSION_DENIED", + message="Role homelab-operator cannot target core stack", + ) + + lines = temp_audit_file.read_text(encoding="utf-8").strip().splitlines() + assert len(lines) == 1 + event = AuditEvent.model_validate(json.loads(lines[0])) + assert event.phase == AuditPhase.DENIED + assert event.result is not None + assert event.result.status == "DENIED" + assert event.result.error_code == "ERR_PERMISSION_DENIED" + + +# --------------------------------------------------------------------------- +# Secret Redaction +# --------------------------------------------------------------------------- + + +def test_redact_sensitive_data_masks_secret_keys(): + raw_params = { + "API_KEY": "supersecretkey123", + "WEBHOOK_SECRET": "whsec_9999", + "db_password": "mypassword", + "AUTH_TOKEN": "tok_12345", + "SSH_KEY": "ssh-ed25519 AAA...", + "PASSWORD_HASH": "$2b$12$...", + "recreate": True, + "nested": { + "SECRET_PASS": "pass123", + "normal_config": "enabled", + "list_items": [ + {"ITEM_SECRET": "leak", "id": 1}, + "safe_string", + ], + }, + } + + redacted = redact_sensitive_data(raw_params) + assert redacted["API_KEY"] == "[REDACTED]" + assert redacted["WEBHOOK_SECRET"] == "[REDACTED]" + assert redacted["db_password"] == "[REDACTED]" + assert redacted["AUTH_TOKEN"] == "[REDACTED]" + assert redacted["SSH_KEY"] == "[REDACTED]" + assert redacted["PASSWORD_HASH"] == "[REDACTED]" + assert redacted["recreate"] is True + assert redacted["nested"]["SECRET_PASS"] == "[REDACTED]" + assert redacted["nested"]["normal_config"] == "enabled" + assert redacted["nested"]["list_items"][0]["ITEM_SECRET"] == "[REDACTED]" + assert redacted["nested"]["list_items"][0]["id"] == 1 + assert redacted["nested"]["list_items"][1] == "safe_string" + + +def test_audit_logger_automatically_redacts_sensitive_parameters( + temp_audit_file: Path, sample_principal: PrincipalAudit +): + logger = AuditLogger(temp_audit_file) + logger.log_dispatched( + operation_id="op_104", + principal=sample_principal, + action="workload.deploy", + target="vaultwarden", + transport="unix_socket", + origin="peer_uid_1000", + client="appctl-cli/2.0", + parameters={"ADMIN_TOKEN": "super_token_leak", "recreate": True}, + ) + + content = temp_audit_file.read_text(encoding="utf-8") + assert "super_token_leak" not in content + assert "[REDACTED]" in content + + +# --------------------------------------------------------------------------- +# Pre-Execution Fail-Closed Disk Guard +# --------------------------------------------------------------------------- + + +def test_audit_logger_fails_closed_when_audit_log_unwritable( + tmp_path: Path, sample_principal: PrincipalAudit +): + read_only_dir = tmp_path / "readonly_audit" + read_only_dir.mkdir(parents=True, exist_ok=True) + unwritable_file = read_only_dir / "audit.jsonl" + unwritable_file.touch(mode=0o400) + os.chmod(unwritable_file, 0o400) + + # In addition, make directory read-only + os.chmod(read_only_dir, 0o500) + + try: + logger = AuditLogger(unwritable_file) + with pytest.raises(AuditPersistenceError) as exc_info: + logger.log_dispatched( + operation_id="op_105", + principal=sample_principal, + action="workload.deploy", + target="jellyfin", + transport="unix_socket", + origin="peer_uid_1000", + client="appctl-cli/2.0", + parameters={"recreate": True}, + ) + assert "Failed to persist audit event" in str(exc_info.value) + finally: + os.chmod(read_only_dir, 0o700) + os.chmod(unwritable_file, 0o600) + + +# --------------------------------------------------------------------------- +# Concurrency & Non-Blocking Flock Manager +# --------------------------------------------------------------------------- + + +def test_target_lock_manager_acquires_and_releases_lock(temp_lock_dir: Path): + manager = TargetLockManager(temp_lock_dir) + + with manager.lock_target("snappymail") as lock: + assert lock.target == "snappymail" + assert lock.lock_path.exists() + # Verify mode 0600 on lock file + assert stat.S_IMODE(lock.lock_path.stat().st_mode) == 0o600 + + # Lock can be re-acquired immediately after release + with manager.lock_target("snappymail"): + pass + + +def test_target_lock_manager_rejects_concurrent_mutation(temp_lock_dir: Path): + manager = TargetLockManager(temp_lock_dir) + + with ( + manager.lock_target("jellyfin"), + pytest.raises(ConcurrentMutationError) as exc_info, + manager.lock_target("jellyfin"), + ): + pass + + assert exc_info.value.target == "jellyfin" + assert "locked by a concurrent task" in str(exc_info.value) + + +def test_target_lock_manager_permits_independent_targets_concurrently( + temp_lock_dir: Path, +): + manager = TargetLockManager(temp_lock_dir) + + with manager.lock_target("app1"), manager.lock_target("app2"): + pass + + +def test_homepage_sync_lock_acquires_designated_file(temp_lock_dir: Path): + manager = TargetLockManager(temp_lock_dir) + + with ( + manager.homepage_sync_lock() as lock, + pytest.raises(ConcurrentMutationError) as exc_info, + manager.homepage_sync_lock(), + ): + pass + + assert lock.lock_path.name == "_homepage_sync.lock" + assert exc_info.value.target == "_homepage_sync" diff --git a/todo.txt b/todo.txt index 2963a01..e461507 100644 --- a/todo.txt +++ b/todo.txt @@ -23,7 +23,7 @@ x 2026-10-15 (A) De-tautologize appctl env injection test to execute scripts/app x 2026-10-15 (A) Clarify Pydantic v2 target architecture, strict typing rules, and domain precedence in docs/plans/p4-readiness-plan.md +docs @p4-gate x 2026-10-15 (A) Migrate core_manifest.py to Pydantic v2 models for strict type validation and serialization +manifest @schema x 2026-10-19 (A) Implement strict Pydantic v2 API contracts, error sanitizer, and compose_pull action in scripts/appctl_contracts.py and scripts/core_manifest.py +contracts @p4 -(A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4 +x 2026-10-19 (A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4 (A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4 (B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4 (B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) and wire gitops_dispatcher.py worker to daemon in scripts/appctl_daemon.py +daemon @p4 From d092ca17b8609fb55ad0a0184ac0f61ceefd5e11 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 13:12:35 -0500 Subject: [PATCH 05/43] feat(appctl): implement Bearer token authenticator, UDS peercred fallback, and 3-role RBAC gate --- scripts/appctl_auth.py | 360 +++++++++++++++++++++++++++++++++ tests/unit/test_appctl_auth.py | 326 +++++++++++++++++++++++++++++ todo.txt | 2 +- 3 files changed, 687 insertions(+), 1 deletion(-) create mode 100644 scripts/appctl_auth.py create mode 100644 tests/unit/test_appctl_auth.py diff --git a/scripts/appctl_auth.py b/scripts/appctl_auth.py new file mode 100644 index 0000000..0baa4f1 --- /dev/null +++ b/scripts/appctl_auth.py @@ -0,0 +1,360 @@ +""" +appctl_auth.py — Authentication & 3-Role RBAC Policy Enforcement (P4 Slice 3) + +Implements the zero-trust authorization pipeline for homelab-appctl.service: +- SOPS-managed SHA-256 Bearer token store loader (mode 0400 check, constant-time compare) +- Unix domain socket SO_PEERCRED fallback to homelab-viewer for zero-friction local reads +- Mandatory Bearer tokens for all network (HTTP) operations and all mutations / sensitive reads +- 3-role RBAC enforcement (homelab-admin, homelab-operator, homelab-viewer) +- Workload scope gating against config/deployments.yaml for homelab-operator +""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import os +import stat +from enum import StrEnum +from pathlib import Path +from typing import Annotated, Any, Literal + +from appctl_contracts import ( + ErrorCode, + OperationType, + StrictModel, +) +from pydantic import BeforeValidator, ConfigDict, Field, StrictStr + +try: + import yaml +except ImportError: + yaml = None # type: ignore[assignment] + +DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json") +DEFAULT_DEPLOYMENTS_FILE = Path(__file__).resolve().parent.parent / "config" / "deployments.yaml" + +CORE_TARGETS: frozenset[str] = frozenset({ + "core", + "traefik", + "authelia", + "lldap", + "stalwart", + "dozzle", + "socket-proxy", + "homepage", + "diun", + "watchtower", +}) + +SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset({ + OperationType.WORKLOAD_CONFIG, + OperationType.WORKLOAD_LOGS, +}) + +MUTATING_OPERATIONS: frozenset[OperationType] = frozenset({ + OperationType.WORKLOAD_DEPLOY, + OperationType.WORKLOAD_STOP, + OperationType.WORKLOAD_RESTART, + OperationType.WORKLOAD_UPDATE, + OperationType.WORKLOAD_PULL, + OperationType.PLATFORM_SYNC_HOMEPAGE, +}) + +READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset({ + OperationType.WORKLOAD_LIST, + OperationType.WORKLOAD_GET, + OperationType.WORKLOAD_RESOLVE, + OperationType.PLATFORM_SSL, + OperationType.PLATFORM_HEALTH, +}) + + +class Role(StrEnum): + """Hierarchical authorization roles for homelab-appctl.service.""" + + ADMIN = "homelab-admin" + OPERATOR = "homelab-operator" + VIEWER = "homelab-viewer" + + +def _coerce_role(v: Any) -> Any: + if isinstance(v, str): + try: + return Role(v) + except ValueError: + return v + return v + + +FlexibleRole = Annotated[ + Role, + BeforeValidator(_coerce_role), +] + + +class Principal(StrictModel): + """Authenticated caller identity and operational role.""" + + model_config = ConfigDict(extra="forbid", strict=True) + + identity: StrictStr + role: FlexibleRole + token_id: StrictStr | None = None + auth_method: Literal["bearer_token", "unix_peercred"] + + +class TokenDescriptor(StrictModel): + """Internal model for token entries in SOPS tokens.json store.""" + + model_config = ConfigDict(extra="forbid", strict=True) + + token_id: StrictStr + identity: StrictStr + role: FlexibleRole + sha256: Annotated[StrictStr, Field(pattern=r"^[0-9a-fA-F]{64}$")] + + +class AuthenticationError(Exception): + """Raised when authentication fails (401 Unauthorized).""" + + def __init__(self, message: str = "Authentication required", code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED) -> None: + super().__init__(message) + self.code = code + self.http_status = 401 + + +class AuthorizationError(Exception): + """Raised when an authenticated principal lacks required role or scope (403 Forbidden).""" + + def __init__(self, message: str = "Permission denied", code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED) -> None: + super().__init__(message) + self.code = code + self.http_status = 403 + + +class TokenStore: + """Loads and validates SHA-256 Bearer tokens from a mode 0400 store.""" + + def __init__(self, tokens_path: Path | str | None = None) -> None: + if tokens_path is not None: + self.tokens_path = Path(tokens_path) + elif "APPCTL_TOKENS_FILE" in os.environ: + self.tokens_path = Path(os.environ["APPCTL_TOKENS_FILE"]) + else: + self.tokens_path = DEFAULT_TOKENS_FILE + + def _verify_permissions(self) -> None: + """Enforce strict 0400 file mode: readable only by owner, no write/exec, no group/world.""" + if not self.tokens_path.is_file(): + raise AuthenticationError( + f"Token store '{self.tokens_path}' not found", + code=ErrorCode.ERR_AUTH_REQUIRED, + ) + # Check permissions: reject if group/world readable or writable (must be 0400) + mode = stat.S_IMODE(self.tokens_path.stat().st_mode) + if (mode & 0o077) != 0 or (mode & 0o200) != 0: + raise AuthenticationError( + f"Token store '{self.tokens_path}' has insecure mode {oct(mode)}; mode 0400 required", + code=ErrorCode.ERR_AUTH_REQUIRED, + ) + + def load_tokens(self) -> list[TokenDescriptor]: + """Load and parse token descriptors from the token store.""" + self._verify_permissions() + try: + content = self.tokens_path.read_text(encoding="utf-8") + data = json.loads(content) + if not isinstance(data, list): + raise TypeError("Tokens payload must be an array of token descriptors") + return [TokenDescriptor.model_validate(item) for item in data] + except (OSError, json.JSONDecodeError, ValueError, TypeError) as err: + raise AuthenticationError( + f"Failed to load token store '{self.tokens_path}': {err}", + code=ErrorCode.ERR_AUTH_REQUIRED, + ) from err + + def authenticate_bearer(self, secret: str) -> Principal: + """ + Hash secret with SHA-256 and look up against stored token descriptors using + constant-time hmac.compare_digest. + """ + if not secret: + raise AuthenticationError("Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED) + + secret_hash = hashlib.sha256(secret.encode("utf-8")).hexdigest() + tokens = self.load_tokens() + + for token in tokens: + if hmac.compare_digest(secret_hash, token.sha256): + return Principal( + identity=token.identity, + role=token.role, + token_id=token.token_id, + auth_method="bearer_token", + ) + + raise AuthenticationError("Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED) + + +def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[str]: + """ + Load admitted repository names and aliases from config/deployments.yaml. + Fails closed (empty set) if registry is missing or malformed. + """ + if deployments_path is not None: + reg_file = Path(deployments_path) + elif "HOMELAB_DEPLOYMENTS_FILE" in os.environ: + reg_file = Path(os.environ["HOMELAB_DEPLOYMENTS_FILE"]) + else: + reg_file = DEFAULT_DEPLOYMENTS_FILE + + if not reg_file.is_file(): + return set() + + yaml_errors = (yaml.YAMLError,) if yaml is not None else () + try: + content = reg_file.read_text(encoding="utf-8") + if yaml is not None: + data = yaml.safe_load(content) + else: + data = json.loads(content) + if not isinstance(data, dict): + return set() + + admitted: set[str] = set() + repos = data.get("repositories", {}) + if isinstance(repos, dict): + for name, entry in repos.items(): + admitted.add(name) + if isinstance(entry, dict): + aliases = entry.get("aliases", []) + if isinstance(aliases, list): + for alias in aliases: + if isinstance(alias, str) and alias.strip(): + admitted.add(alias.strip()) + return admitted + except (OSError, UnicodeDecodeError, ValueError, json.JSONDecodeError, *yaml_errors): + return set() + + +def authenticate_request( + transport: Literal["unix_socket", "http"], + auth_header: str | None, + peer_uid: int | None = None, + token_store: TokenStore | None = None, +) -> Principal: + """ + Authenticate an incoming request across transports: + - If Authorization header present: parses Bearer secret and verifies against TokenStore. + - If Authorization header missing over HTTP: fails closed with 401 ERR_AUTH_REQUIRED. + - If Authorization header missing over Unix socket: falls back to homelab-viewer with peer_uid. + """ + store = token_store or TokenStore() + + if auth_header is not None: + header_val = auth_header.strip() + if not header_val.startswith("Bearer "): + raise AuthenticationError( + "Malformed Authorization header: must start with 'Bearer '", + code=ErrorCode.ERR_AUTH_REQUIRED, + ) + secret = header_val[7:].strip() + if not secret: + raise AuthenticationError( + "Missing token secret in Authorization header", + code=ErrorCode.ERR_AUTH_REQUIRED, + ) + return store.authenticate_bearer(secret) + + # Missing Authorization header + if transport == "unix_socket": + if peer_uid is not None: + return Principal( + identity=f"unix_uid_{peer_uid}", + role=Role.VIEWER, + token_id=None, + auth_method="unix_peercred", + ) + raise AuthenticationError( + "Missing peer credentials over Unix socket", + code=ErrorCode.ERR_AUTH_REQUIRED, + ) + + # HTTP transport requires Bearer token strictly + raise AuthenticationError( + "Bearer token required over network transport", + code=ErrorCode.ERR_AUTH_REQUIRED, + ) + + +def enforce_rbac( + principal: Principal, + operation: OperationType, + target: str | None = None, + admitted_workloads: set[str] | None = None, +) -> None: + """ + Enforce 3-role RBAC policy (homelab-admin, homelab-operator, homelab-viewer). + Raises AuthorizationError (403) on violation. + """ + # 1. homelab-admin has unrestricted access across all operations and targets + if principal.role == Role.ADMIN: + return + + # 2. homelab-operator: + if principal.role == Role.OPERATOR: + # Platform homepage sync allowed + if operation == OperationType.PLATFORM_SYNC_HOMEPAGE: + return + + # Target checks for operations targeting infrastructure + if target is not None and (target in CORE_TARGETS or target == "core"): + raise AuthorizationError( + f"Role 'homelab-operator' is not permitted to target core service '{target}'", + code=ErrorCode.ERR_PERMISSION_DENIED, + ) + + # Non-sensitive reads are permitted + if operation in READ_ONLY_OPERATIONS: + return + + # Sensitive reads and mutations must target an admitted workload from deployments.yaml + if operation in SENSITIVE_OPERATIONS or operation in MUTATING_OPERATIONS: + if not target: + raise AuthorizationError( + f"Operation '{operation.value}' requires an explicit workload target", + code=ErrorCode.ERR_PERMISSION_DENIED, + ) + registry = ( + admitted_workloads + if admitted_workloads is not None + else load_admitted_workloads() + ) + if target not in registry: + raise AuthorizationError( + f"Target '{target}' is not registered in deployments.yaml for role 'homelab-operator'", + code=ErrorCode.ERR_PERMISSION_DENIED, + ) + return + + # 3. homelab-viewer: + if principal.role == Role.VIEWER: + if operation in MUTATING_OPERATIONS: + raise AuthorizationError( + f"Role 'homelab-viewer' is not permitted to execute mutating operation '{operation.value}'", + code=ErrorCode.ERR_PERMISSION_DENIED, + ) + if operation in SENSITIVE_OPERATIONS: + raise AuthorizationError( + f"Role 'homelab-viewer' is not permitted to access sensitive operation '{operation.value}'", + code=ErrorCode.ERR_PERMISSION_DENIED, + ) + if operation in READ_ONLY_OPERATIONS: + return + + raise AuthorizationError( + f"Operation '{operation.value}' denied for role '{principal.role.value}'", + code=ErrorCode.ERR_PERMISSION_DENIED, + ) diff --git a/tests/unit/test_appctl_auth.py b/tests/unit/test_appctl_auth.py new file mode 100644 index 0000000..da980db --- /dev/null +++ b/tests/unit/test_appctl_auth.py @@ -0,0 +1,326 @@ +""" +tests/unit/test_appctl_auth.py — Unit Tests for Authentication & 3-Role RBAC (P4 Slice 3) + +Behavior-driven test naming convention: +test___ +""" + +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path + +import pytest +from appctl_auth import ( + AuthenticationError, + AuthorizationError, + Principal, + Role, + TokenStore, + authenticate_request, + enforce_rbac, + load_admitted_workloads, +) +from appctl_contracts import ErrorCode, OperationType + + +@pytest.fixture +def secret_tokens() -> dict[str, str]: + return { + "admin_secret": "sec_admin_9876543210abcdef", + "operator_secret": "sec_operator_1234567890abcdef", + } + + +@pytest.fixture +def temp_tokens_file(tmp_path: Path, secret_tokens: dict[str, str]) -> Path: + tokens_path = tmp_path / "tokens.json" + admin_hash = hashlib.sha256(secret_tokens["admin_secret"].encode("utf-8")).hexdigest() + op_hash = hashlib.sha256(secret_tokens["operator_secret"].encode("utf-8")).hexdigest() + + data = [ + { + "token_id": "tok_admin_01", + "identity": "operator", + "role": "homelab-admin", + "sha256": admin_hash, + }, + { + "token_id": "tok_gitops_01", + "identity": "gitops-dispatcher", + "role": "homelab-operator", + "sha256": op_hash, + }, + ] + tokens_path.write_text(json.dumps(data), encoding="utf-8") + os.chmod(tokens_path, 0o400) + return tokens_path + + +@pytest.fixture +def admitted_workloads() -> set[str]: + return {"snappymail", "mail", "webmail", "jellyfin", "media", "docs"} + + +# --------------------------------------------------------------------------- +# TokenStore & Strict Permissions (0400) +# --------------------------------------------------------------------------- + + +def test_token_store_accepts_valid_0400_store(temp_tokens_file: Path): + store = TokenStore(temp_tokens_file) + tokens = store.load_tokens() + assert len(tokens) == 2 + assert tokens[0].role == Role.ADMIN + assert tokens[1].role == Role.OPERATOR + + +def test_token_store_rejects_insecure_file_permissions(tmp_path: Path): + bad_tokens_file = tmp_path / "insecure_tokens.json" + bad_tokens_file.write_text("[]", encoding="utf-8") + + # Insecure modes: 0644, 0600, 0777 + for insecure_mode in [0o644, 0o600, 0o777, 0o444]: + os.chmod(bad_tokens_file, insecure_mode) + store = TokenStore(bad_tokens_file) + with pytest.raises(AuthenticationError) as exc_info: + store.load_tokens() + assert "mode 0400 required" in str(exc_info.value) + assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED + + +def test_token_store_rejects_missing_file(tmp_path: Path): + missing_file = tmp_path / "nonexistent.json" + store = TokenStore(missing_file) + with pytest.raises(AuthenticationError) as exc_info: + store.load_tokens() + assert "not found" in str(exc_info.value) + + +# --------------------------------------------------------------------------- +# Bearer Token Authentication +# --------------------------------------------------------------------------- + + +def test_token_store_authenticates_valid_bearer_secrets( + temp_tokens_file: Path, secret_tokens: dict[str, str] +): + store = TokenStore(temp_tokens_file) + + p_admin = store.authenticate_bearer(secret_tokens["admin_secret"]) + assert p_admin.identity == "operator" + assert p_admin.role == Role.ADMIN + assert p_admin.token_id == "tok_admin_01" + assert p_admin.auth_method == "bearer_token" + + p_op = store.authenticate_bearer(secret_tokens["operator_secret"]) + assert p_op.identity == "gitops-dispatcher" + assert p_op.role == Role.OPERATOR + assert p_op.token_id == "tok_gitops_01" + + +def test_token_store_rejects_invalid_bearer_secret(temp_tokens_file: Path): + store = TokenStore(temp_tokens_file) + + with pytest.raises(AuthenticationError) as exc_info: + store.authenticate_bearer("wrong_secret_token_123") + assert "Invalid or unknown Bearer token" in str(exc_info.value) + assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED + + +def test_token_store_rejects_empty_bearer_secret(temp_tokens_file: Path): + store = TokenStore(temp_tokens_file) + + with pytest.raises(AuthenticationError) as exc_info: + store.authenticate_bearer("") + assert "Empty Bearer token provided" in str(exc_info.value) + + +# --------------------------------------------------------------------------- +# Transport Authentication Rules (HTTP vs. Unix Domain Socket) +# --------------------------------------------------------------------------- + + +def test_authenticate_request_over_http_requires_valid_bearer( + temp_tokens_file: Path, secret_tokens: dict[str, str] +): + store = TokenStore(temp_tokens_file) + + # Valid Bearer token + auth_header = f"Bearer {secret_tokens['admin_secret']}" + p = authenticate_request("http", auth_header, token_store=store) + assert p.role == Role.ADMIN + + # Missing Authorization header -> 401 + with pytest.raises(AuthenticationError) as exc_info: + authenticate_request("http", None, token_store=store) + assert "Bearer token required over network transport" in str(exc_info.value) + assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED + + # Malformed Authorization header -> 401 + with pytest.raises(AuthenticationError): + authenticate_request("http", "Basic dXNlcjpwYXNz", token_store=store) + + +def test_authenticate_request_over_uds_falls_back_to_viewer( + temp_tokens_file: Path, secret_tokens: dict[str, str] +): + store = TokenStore(temp_tokens_file) + + # Missing Authorization header over UDS with peer_uid=1000 + p = authenticate_request("unix_socket", None, peer_uid=1000, token_store=store) + assert p.identity == "unix_uid_1000" + assert p.role == Role.VIEWER + assert p.token_id is None + assert p.auth_method == "unix_peercred" + + # Explicit Bearer token over UDS confers full privileges + auth_header = f"Bearer {secret_tokens['admin_secret']}" + p_admin = authenticate_request("unix_socket", auth_header, peer_uid=1000, token_store=store) + assert p_admin.role == Role.ADMIN + assert p_admin.auth_method == "bearer_token" + + +def test_authenticate_request_over_uds_rejects_missing_peer_uid(): + with pytest.raises(AuthenticationError) as exc_info: + authenticate_request("unix_socket", None, peer_uid=None) + assert "Missing peer credentials" in str(exc_info.value) + + +# --------------------------------------------------------------------------- +# Deployments Registry Scope Loader +# --------------------------------------------------------------------------- + + +def test_load_admitted_workloads_parses_names_and_aliases(tmp_path: Path): + deploy_file = tmp_path / "deployments.yaml" + deploy_file.write_text(""" +schemaVersion: "1.0" +repositories: + snappymail: + path: "/home/operator/Sites/snappymail" + aliases: + - "mail" + - "webmail" + jellyfin: + path: "/home/operator/Sites/homelab-jellyfin" + aliases: + - "media" +""", encoding="utf-8") + + admitted = load_admitted_workloads(deploy_file) + assert "snappymail" in admitted + assert "mail" in admitted + assert "webmail" in admitted + assert "jellyfin" in admitted + assert "media" in admitted + assert "unknown_app" not in admitted + + +def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path): + admitted = load_admitted_workloads(tmp_path / "missing.yaml") + assert admitted == set() + + +# --------------------------------------------------------------------------- +# RBAC Policy Matrix Enforcement +# --------------------------------------------------------------------------- + + +def test_rbac_admin_permitted_across_all_operations_and_targets( + admitted_workloads: set[str], +): + admin = Principal(identity="admin_user", role=Role.ADMIN, auth_method="bearer_token") + + # Mutations across Core and Sites + enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads) + enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "traefik", admitted_workloads) + enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads) + enforce_rbac(admin, OperationType.WORKLOAD_CONFIG, "core", admitted_workloads) + enforce_rbac(admin, OperationType.WORKLOAD_LOGS, "traefik", admitted_workloads) + enforce_rbac(admin, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads) + enforce_rbac(admin, OperationType.WORKLOAD_LIST, None, admitted_workloads) + + +def test_rbac_operator_permitted_on_admitted_workloads( + admitted_workloads: set[str], +): + operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") + + # Permitted on admitted workload + enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads) + enforce_rbac(operator, OperationType.WORKLOAD_UPDATE, "mail", admitted_workloads) + enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads) + enforce_rbac(operator, OperationType.WORKLOAD_LOGS, "docs", admitted_workloads) + enforce_rbac(operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads) + enforce_rbac(operator, OperationType.WORKLOAD_LIST, None, admitted_workloads) + + +def test_rbac_operator_denied_on_core_targets( + admitted_workloads: set[str], +): + operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") + + # Targeting "core" stack + with pytest.raises(AuthorizationError) as exc_info: + enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads) + assert "not permitted to target core service 'core'" in str(exc_info.value) + assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED + + # Targeting core services (traefik, stalwart, etc.) + for core_svc in ["traefik", "authelia", "stalwart", "socket-proxy"]: + with pytest.raises(AuthorizationError) as exc_info: + enforce_rbac(operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads) + assert f"not permitted to target core service '{core_svc}'" in str(exc_info.value) + + +def test_rbac_operator_denied_on_unregistered_workload( + admitted_workloads: set[str], +): + operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") + + with pytest.raises(AuthorizationError) as exc_info: + enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unregistered_app", admitted_workloads) + assert "not registered in deployments.yaml" in str(exc_info.value) + assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED + + +def test_rbac_viewer_permitted_only_on_non_sensitive_reads(): + viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred") + + # Permitted reads + enforce_rbac(viewer, OperationType.WORKLOAD_LIST, None) + enforce_rbac(viewer, OperationType.WORKLOAD_GET, "snappymail") + enforce_rbac(viewer, OperationType.WORKLOAD_RESOLVE, "snappymail") + enforce_rbac(viewer, OperationType.PLATFORM_SSL, "snappymail") + enforce_rbac(viewer, OperationType.PLATFORM_HEALTH, None) + + +def test_rbac_viewer_denied_on_mutations(): + viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred") + + mutations = [ + OperationType.WORKLOAD_DEPLOY, + OperationType.WORKLOAD_STOP, + OperationType.WORKLOAD_RESTART, + OperationType.WORKLOAD_UPDATE, + OperationType.WORKLOAD_PULL, + OperationType.PLATFORM_SYNC_HOMEPAGE, + ] + for mut in mutations: + with pytest.raises(AuthorizationError) as exc_info: + enforce_rbac(viewer, mut, "snappymail") + assert "not permitted to execute mutating operation" in str(exc_info.value) + assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED + + +def test_rbac_viewer_denied_on_sensitive_reads(): + viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred") + + for sens_op in [OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]: + with pytest.raises(AuthorizationError) as exc_info: + enforce_rbac(viewer, sens_op, "snappymail") + assert "not permitted to access sensitive operation" in str(exc_info.value) + assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED diff --git a/todo.txt b/todo.txt index e461507..1188315 100644 --- a/todo.txt +++ b/todo.txt @@ -24,7 +24,7 @@ x 2026-10-15 (A) Clarify Pydantic v2 target architecture, strict typing rules, a x 2026-10-15 (A) Migrate core_manifest.py to Pydantic v2 models for strict type validation and serialization +manifest @schema x 2026-10-19 (A) Implement strict Pydantic v2 API contracts, error sanitizer, and compose_pull action in scripts/appctl_contracts.py and scripts/core_manifest.py +contracts @p4 x 2026-10-19 (A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4 -(A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4 +x 2026-10-19 (A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4 (B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4 (B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) and wire gitops_dispatcher.py worker to daemon in scripts/appctl_daemon.py +daemon @p4 (B) Add comprehensive unit and security test suite for P4 contracts, RBAC, audit guard, concurrency, and dual-transport parity in tests/unit/test_appctl_daemon.py +test @p4 From 9e30e113a09836592b96309eb76251a54efb0b5f Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 13:18:17 -0500 Subject: [PATCH 06/43] feat(appctl): implement operational router, pure-Python dotenv loader, and pre-flight gate --- scripts/appctl_contracts.py | 14 +- scripts/appctl_router.py | 840 +++++++++++++++++++++++++++++++ tests/unit/test_appctl_router.py | 511 +++++++++++++++++++ todo.txt | 2 +- 4 files changed, 1363 insertions(+), 4 deletions(-) create mode 100644 scripts/appctl_router.py create mode 100644 tests/unit/test_appctl_router.py diff --git a/scripts/appctl_contracts.py b/scripts/appctl_contracts.py index 1a0eaa7..9b10297 100644 --- a/scripts/appctl_contracts.py +++ b/scripts/appctl_contracts.py @@ -16,6 +16,7 @@ from enum import StrEnum from typing import Annotated, Any, Literal from pydantic import ( + AliasChoices, BaseModel, BeforeValidator, ConfigDict, @@ -243,9 +244,14 @@ class OperationRequest(StrictModel): model_config = ConfigDict(extra="forbid", strict=True, populate_by_name=True) version: Literal["1.0"] = "1.0" - operation: FlexibleOperationType = Field(alias="action") + operation: FlexibleOperationType = Field( + validation_alias=AliasChoices("operation", "action") + ) target: Annotated[StrictStr, Field(min_length=1)] | None = None - parameters: dict[str, Any] = Field(default_factory=dict, alias="params") + parameters: dict[str, Any] = Field( + default_factory=dict, + validation_alias=AliasChoices("parameters", "params"), + ) @property def action(self) -> OperationType: @@ -285,7 +291,9 @@ class OperationResponse(StrictModel): success: StrictBool | None = None status: Literal["success", "error"] | None = None operation_id: StrictStr = Field(min_length=1) - operation: FlexibleOperationType = Field(alias="action") + operation: FlexibleOperationType = Field( + validation_alias=AliasChoices("operation", "action") + ) target: StrictStr | None = None output: StrictStr = "" result: dict[str, Any] | None = None diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py new file mode 100644 index 0000000..67e25be --- /dev/null +++ b/scripts/appctl_router.py @@ -0,0 +1,840 @@ +""" +appctl_router.py — Operational Router & Unified Execution Engine (P4 Slice 4) + +Implements the single command execution pipeline for homelab-appctl.service: +- Pure-Python inert .env loader (enforcing ENV_KEY_RE, RESERVED_ENV_KEYS, zero shell evaluation) +- Canonical domain precedence resolution (HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN) +- Mandatory pre-flight validation (Path containment, parse_manifest, validate_compose_security) +- Bounded subprocess execution engine (fixed argv, shell=False, 256 KiB output cap, hard timeouts) +- Revision-consistent workload.update (clean tree check, git pull, post-pull validation, declared action execution) +- Synchronous atomic Homepage compilation under _homepage_sync.lock +""" + +from __future__ import annotations + +import os +import subprocess +import time +from pathlib import Path +from typing import Any + +from appctl_audit import ( + AuditLogger, + AuditPersistenceError, + ConcurrentMutationError, + PrincipalAudit, + TargetLockManager, + current_iso_timestamp, + generate_operation_id, + redact_sensitive_data, +) +from appctl_auth import ( + AuthorizationError, + Principal, + Role, + enforce_rbac, + load_admitted_workloads, +) +from appctl_contracts import ( + MUTATING_OPERATIONS, + SENSITIVE_READ_OPERATIONS, + TARGET_REQUIRED_OPERATIONS, + DeployParams, + ErrorCode, + GetParams, + ListParams, + LogsParams, + OperationError, + OperationRequest, + OperationResponse, + OperationType, + UpdateParams, +) +from appctl_engine import ( + CORE_DIR as ENGINE_CORE_DIR, +) +from appctl_engine import ( + HOMELAB_DOMAIN as ENGINE_HOMELAB_DOMAIN, +) +from appctl_engine import ( + SITES_DIR as ENGINE_SITES_DIR, +) +from appctl_engine import ( + check_ssl_cert, + cmd_sync_homepage, + get_sites_apps, + resolve_app, +) +from core_manifest import ( + ENV_KEY_RE, + RESERVED_ENV_KEYS, + Manifest, + ManifestValidationError, + parse_manifest, +) +from gitops_dispatcher import validate_compose_security + +MAX_OUTPUT_BYTES = 256 * 1024 # 256 KiB cap per invocation + + +class RouterValidationError(Exception): + """Raised when request payload or pre-flight validation fails (400 Bad Request).""" + + def __init__(self, message: str) -> None: + super().__init__(message) + self.code = ErrorCode.ERR_VALIDATION_FAILED + self.http_status = 400 + + +class RouterExecutionError(Exception): + """Raised when a subprocess or internal operation fails (500 Internal Error).""" + + def __init__(self, message: str, exit_code: int = 1) -> None: + super().__init__(message) + self.code = ErrorCode.ERR_EXECUTION_FAILED + self.exit_code = exit_code + self.http_status = 500 + + +def parse_dotenv(path: Path, validate_keys: bool = True) -> dict[str, str]: + """ + Pure-Python inert KEY=VALUE parser. + Never invokes a shell or evaluates variables. Enforces ENV_KEY_RE and RESERVED_ENV_KEYS. + """ + if not path.is_file(): + return {} + + env: dict[str, str] = {} + content = path.read_text(encoding="utf-8", errors="replace") + for line_num, raw_line in enumerate(content.splitlines(), start=1): + line = raw_line.strip() + if not line or line.startswith("#"): + continue + if "=" not in line: + continue + key, val = line.split("=", 1) + key = key.strip() + val = val.strip() + + # Strip optional surrounding single or double quotes + if len(val) >= 2 and ( + (val.startswith('"') and val.endswith('"')) + or (val.startswith("'") and val.endswith("'")) + ): + val = val[1:-1] + + if validate_keys: + if not ENV_KEY_RE.match(key): + raise RouterValidationError( + f"Prohibited environment key syntax in {path.name}:{line_num}: '{key}'" + ) + if key in RESERVED_ENV_KEYS: + raise RouterValidationError( + f"Prohibited reserved environment key in {path.name}:{line_num}: '{key}'" + ) + env[key] = val + return env + + +def resolve_canonical_domain() -> str: + """Resolve canonical platform domain: HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN (fails closed).""" + domain = ( + os.environ.get("HOMELAB_DOMAIN") + or os.environ.get("DOMAIN_SUFFIX") + or os.environ.get("DOMAIN") + or ENGINE_HOMELAB_DOMAIN + ) + if not domain or not domain.strip(): + raise RouterValidationError( + "Canonical domain is unset: HOMELAB_DOMAIN, DOMAIN_SUFFIX, or DOMAIN must be configured." + ) + return domain.strip() + + +def assemble_workload_env( + app_dir: Path, + manifest: Manifest | None, + app_name: str, +) -> dict[str, str]: + """ + Assemble the 6-layer in-memory execution environment for Docker Compose subprocesses: + 1. Base PATH and DOCKER_CONFIG + 2. Global rendered secrets (homeserver.env, traefik-deployments.env) + 3. Canonical domain lock + 4. Infrastructure defaults (PROXY_NETWORK, CERT_RESOLVER, SERVICE_NAME, DOMAIN) + 5. Validated manifest.env from app.yaml + 6. Workload .env and app.env files parsed inertly + """ + env: dict[str, str] = { + "PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"), + } + if "DOCKER_CONFIG" in os.environ: + env["DOCKER_CONFIG"] = os.environ["DOCKER_CONFIG"] + + # Layer 2: Global secrets from /run/secrets/rendered/ or /run/secrets/ + secrets_candidates = [ + Path("/run/secrets/rendered/homeserver.env"), + Path("/run/secrets/homeserver.env"), + Path("/run/secrets/rendered/traefik-deployments.env"), + Path("/run/secrets/traefik-deployments.env"), + ] + if "HOMESERVER_ENV_FILE" in os.environ: + secrets_candidates.insert(0, Path(os.environ["HOMESERVER_ENV_FILE"])) + + for sec_path in secrets_candidates: + if sec_path.is_file(): + env.update(parse_dotenv(sec_path, validate_keys=False)) + + # Layer 3 & 4: Domain & Infrastructure defaults + domain = resolve_canonical_domain() + env["HOMELAB_DOMAIN"] = domain + env["DOMAIN_SUFFIX"] = domain + env["DOMAIN"] = domain + env["PROXY_NETWORK"] = os.environ.get("PROXY_NETWORK", "proxy-net") + env["CERT_RESOLVER"] = os.environ.get("CERT_RESOLVER", "myresolver") + env["SERVICE_NAME"] = app_name + env["CONTAINER_NAME"] = app_name + env["SERVICE_DOMAIN"] = f"{app_name}.{domain}" + + # Layer 5: Validated manifest env + if manifest and manifest.env: + env.update(manifest.env) + + # Layer 6: Workload-scoped .env and app.env + for local_env in [app_dir / ".env", app_dir / "app.env"]: + if local_env.is_file(): + env.update(parse_dotenv(local_env, validate_keys=True)) + + return env + + +def run_bounded_subprocess( + cmd: list[str], + cwd: Path | str | None = None, + env: dict[str, str] | None = None, + timeout: float = 300.0, +) -> tuple[int, str, str]: + """ + Execute subprocess with fixed argv (shell=False), hard timeout, and 256 KiB output cap. + Returns (exit_code, stdout_str, stderr_str). + """ + proc = subprocess.Popen( + cmd, + cwd=str(cwd) if cwd else None, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, + ) + try: + raw_stdout, raw_stderr = proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired as exc: + proc.kill() + proc.communicate() + raise RouterExecutionError( + f"Command '{' '.join(cmd)}' timed out after {timeout} seconds", + exit_code=124, + ) from exc + + # Enforce 256 KiB cap on output + stdout_str = raw_stdout[:MAX_OUTPUT_BYTES].decode("utf-8", errors="replace") + if len(raw_stdout) > MAX_OUTPUT_BYTES: + stdout_str += "\n[TRUNCATED: Output exceeded 256 KiB limit]" + + stderr_str = raw_stderr[:MAX_OUTPUT_BYTES].decode("utf-8", errors="replace") + if len(raw_stderr) > MAX_OUTPUT_BYTES: + stderr_str += "\n[TRUNCATED: Stderr exceeded 256 KiB limit]" + + return proc.returncode, stdout_str, stderr_str + + +def validate_workload_preflight( + app_dir: Path, + allowed_root: Path, + app_name: str | None = None, +) -> tuple[Manifest, Path]: + """ + Enforce strict pre-flight gate: + 1. Target directory must be contained within allowed_root. + 2. app.yaml must parse cleanly via core_manifest.parse_manifest(). + 3. docker-compose.yml must pass validate_compose_security(). + """ + app_dir_resolved = app_dir.resolve() + allowed_root_resolved = allowed_root.resolve() + if not ( + app_dir_resolved == allowed_root_resolved + or app_dir_resolved.is_relative_to(allowed_root_resolved) + ): + raise RouterValidationError( + f"Path traversal rejected: '{app_dir}' is outside '{allowed_root}'" + ) + + manifest_file = app_dir / "app.yaml" + if not manifest_file.is_file(): + raise RouterValidationError(f"Workload manifest not found at '{manifest_file}'") + + try: + manifest = parse_manifest(manifest_file) + except ManifestValidationError as err: + raise RouterValidationError(f"Workload manifest validation failed: {err}") from err + + effective_name = app_name or manifest.name + compose_file = app_dir / "docker-compose.yml" + if compose_file.exists(): + ok, reason = validate_compose_security( + compose_file=compose_file, + allowed_root=app_dir, + app_name=effective_name, + ) + if not ok: + raise RouterValidationError( + f"Compose AST security validation failed for '{effective_name}': {reason}" + ) + + return manifest, compose_file + + +class OperationalRouter: + """Executes validated domain operations according to P4 boundaries and contracts.""" + + def __init__( + self, + audit_logger: AuditLogger | None = None, + lock_manager: TargetLockManager | None = None, + sites_dir: Path | str | None = None, + core_dir: Path | str | None = None, + ) -> None: + self.audit_logger = audit_logger or AuditLogger() + self.lock_manager = lock_manager or TargetLockManager() + self.sites_dir = Path(sites_dir or ENGINE_SITES_DIR) + self.core_dir = Path(core_dir or ENGINE_CORE_DIR) + + def dispatch( + self, + request: OperationRequest, + principal: Principal, + transport: str = "unix_socket", + origin: str = "peer_uid_1000", + client: str = "appctl-cli/2.0", + ) -> OperationResponse: + """Single entrypoint dispatching all 13 canonical domain operations.""" + op_id = generate_operation_id() + start_time = time.perf_counter() + target = request.target + operation = request.operation + admitted = load_admitted_workloads() + principal_audit = PrincipalAudit( + identity=principal.identity, + role=principal.role.value, + token_id=principal.token_id, + auth_method=principal.auth_method, + ) + + # 1. RBAC Gate + try: + enforce_rbac( + principal=principal, + operation=operation, + target=target, + admitted_workloads=admitted, + ) + except AuthorizationError as err: + self.audit_logger.log_denied( + operation_id=op_id, + principal=principal_audit, + action=operation.value, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=request.parameters, + error_code=err.code.value, + message=str(err), + ) + return OperationResponse( + version="1.0", + success=False, + operation_id=op_id, + operation=operation, + target=target, + error=OperationError(code=err.code, message=str(err)), + ) + + # 2. Target Resolution (for operations requiring target) + resolved_app = None + if operation in TARGET_REQUIRED_OPERATIONS: + if not target: + return OperationResponse( + version="1.0", + success=False, + operation_id=op_id, + operation=operation, + target=target, + error=OperationError( + code=ErrorCode.ERR_VALIDATION_FAILED, + message=f"Operation '{operation.value}' requires a non-empty target", + ), + ) + resolved_app = resolve_app(target) + if not resolved_app: + return OperationResponse( + version="1.0", + success=False, + operation_id=op_id, + operation=operation, + target=target, + error=OperationError( + code=ErrorCode.ERR_TARGET_NOT_FOUND, + message=f"Workload or core target '{target}' not found", + ), + ) + + # 3. Concurrency Lock & Pre-Execution Audit (Mutating Operations) + if operation in MUTATING_OPERATIONS: + lock_ctx = ( + self.lock_manager.homepage_sync_lock() + if operation == OperationType.PLATFORM_SYNC_HOMEPAGE + else self.lock_manager.lock_target(target or "_unknown") + ) + try: + with lock_ctx: + # Fail-closed pre-execution DISPATCHED audit guard + try: + self.audit_logger.log_dispatched( + operation_id=op_id, + principal=principal_audit, + action=operation.value, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=request.parameters, + ) + except AuditPersistenceError as audit_err: + return OperationResponse( + version="1.0", + success=False, + operation_id=op_id, + operation=operation, + target=target, + error=OperationError( + code=ErrorCode.ERR_EXECUTION_FAILED, + message=f"Pre-execution audit guard failed: {audit_err}", + ), + ) + + # Execute Mutation + return self._execute_operation( + request=request, + principal=principal, + principal_audit=principal_audit, + resolved_app=resolved_app, + op_id=op_id, + start_time=start_time, + transport=transport, + origin=origin, + client=client, + ) + except ConcurrentMutationError as lock_err: + self.audit_logger.log_denied( + operation_id=op_id, + principal=principal_audit, + action=operation.value, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=request.parameters, + error_code=ErrorCode.ERR_CONCURRENT_MUTATION.value, + message=str(lock_err), + ) + return OperationResponse( + version="1.0", + success=False, + operation_id=op_id, + operation=operation, + target=target, + error=OperationError( + code=ErrorCode.ERR_CONCURRENT_MUTATION, + message=str(lock_err), + ), + ) + + # 4. Read-Only Operations (no concurrency lock required) + return self._execute_operation( + request=request, + principal=principal, + principal_audit=principal_audit, + resolved_app=resolved_app, + op_id=op_id, + start_time=start_time, + transport=transport, + origin=origin, + client=client, + ) + + def _execute_operation( + self, + request: OperationRequest, + principal: Principal, + principal_audit: PrincipalAudit, + resolved_app: Any, + op_id: str, + start_time: float, + transport: str, + origin: str, + client: str, + ) -> OperationResponse: + """Route to specific operation handler with post-execution audit logging.""" + operation = request.operation + target = request.target + commit_sha: str | None = None + duration_ms = 0 + + try: + if operation == OperationType.WORKLOAD_LIST: + result_data = self._op_workload_list(request) + elif operation == OperationType.WORKLOAD_GET: + result_data = self._op_workload_get(request, resolved_app) + elif operation == OperationType.WORKLOAD_RESOLVE: + result_data = self._op_workload_resolve(resolved_app) + elif operation == OperationType.PLATFORM_SSL: + result_data = self._op_platform_ssl(target) + elif operation == OperationType.PLATFORM_HEALTH: + result_data = self._op_platform_health() + elif operation == OperationType.WORKLOAD_CONFIG: + result_data = self._op_workload_config(resolved_app, principal) + elif operation == OperationType.WORKLOAD_LOGS: + result_data = self._op_workload_logs(request, resolved_app) + elif operation == OperationType.WORKLOAD_DEPLOY: + result_data = self._op_workload_deploy(request, resolved_app) + elif operation == OperationType.WORKLOAD_STOP: + result_data = self._op_workload_stop(resolved_app) + elif operation == OperationType.WORKLOAD_RESTART: + result_data = self._op_workload_restart(resolved_app) + elif operation == OperationType.WORKLOAD_PULL: + result_data = self._op_workload_pull(resolved_app) + elif operation == OperationType.WORKLOAD_UPDATE: + result_data, commit_sha = self._op_workload_update(request, resolved_app) + elif operation == OperationType.PLATFORM_SYNC_HOMEPAGE: + result_data = self._op_platform_sync_homepage() + else: + raise RouterValidationError(f"Unsupported operation: {operation.value}") + + duration_ms = int((time.perf_counter() - start_time) * 1000) + + # Audit COMPLETED for mutating ops and sensitive reads + if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS: + self.audit_logger.log_completed( + operation_id=op_id, + principal=principal_audit, + action=operation.value, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=request.parameters, + duration_ms=duration_ms, + commit_sha=commit_sha, + message=result_data.get("message", "Operation completed successfully"), + ) + + return OperationResponse( + version="1.0", + success=True, + operation_id=op_id, + operation=operation, + target=target, + result=result_data, + output=result_data.get("output", ""), + duration_ms=duration_ms, + timestamp=current_iso_timestamp(), + ) + + except (RouterValidationError, RouterExecutionError) as err: + duration_ms = int((time.perf_counter() - start_time) * 1000) + if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS: + self.audit_logger.log_failed( + operation_id=op_id, + principal=principal_audit, + action=operation.value, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=request.parameters, + duration_ms=duration_ms, + exit_code=getattr(err, "exit_code", 1), + error_code=err.code.value, + message=str(err), + ) + return OperationResponse( + version="1.0", + success=False, + operation_id=op_id, + operation=operation, + target=target, + duration_ms=duration_ms, + error=OperationError(code=err.code, message=str(err)), + ) + + # ----------------------------------------------------------------------- + # Domain Operation Implementations + # ----------------------------------------------------------------------- + + def _op_workload_list(self, request: OperationRequest) -> dict[str, Any]: + params = request.parse_parameters() + assert isinstance(params, ListParams) + apps = get_sites_apps(sites_dir=str(self.sites_dir)) + apps_data = [a.to_dict() for a in apps] + return { + "total": len(apps_data), + "workloads": apps_data, + "message": f"Found {len(apps_data)} workloads", + } + + def _op_workload_get(self, request: OperationRequest, app: Any) -> dict[str, Any]: + params = request.parse_parameters() + assert isinstance(params, GetParams) + data = app.to_dict() + return {"workload": data, "message": f"Retrieved metadata for {app.name}"} + + def _op_workload_resolve(self, app: Any) -> dict[str, Any]: + return {"workload": app.to_dict(), "message": f"Resolved target to {app.name}"} + + def _op_platform_ssl(self, target: str | None) -> dict[str, Any]: + domain = target or resolve_canonical_domain() + try: + cert_info = check_ssl_cert(domain) + return {"ssl": cert_info, "message": f"SSL certificate inspected for {domain}"} + except Exception as err: + raise RouterExecutionError(f"SSL inspection failed for '{domain}': {err}") from err + + def _op_platform_health(self) -> dict[str, Any]: + return { + "status": "healthy", + "audit_log": str(self.audit_logger.log_path), + "lock_dir": str(self.lock_manager.lock_dir), + "message": "Control plane daemon healthy", + } + + def _op_workload_config(self, app: Any, principal: Principal) -> dict[str, Any]: + app_dir = Path(app.dir_path) + manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) + env = assemble_workload_env(app_dir, manifest, app.name) + + cmd = ["docker", "compose", "-f", str(compose_file), "config"] + code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0) + if code != 0: + raise RouterExecutionError(f"docker compose config failed: {stderr}", exit_code=code) + + config_output = stdout + if principal.role != Role.ADMIN: + # Redact secrets for non-admin callers + config_output = redact_sensitive_data(config_output) + + return {"output": config_output, "message": "Evaluated compose configuration"} + + def _op_workload_logs(self, request: OperationRequest, app: Any) -> dict[str, Any]: + params = request.parse_parameters() + assert isinstance(params, LogsParams) + app_dir = Path(app.dir_path) + manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) + env = assemble_workload_env(app_dir, manifest, app.name) + + cmd = [ + "docker", + "compose", + "-f", + str(compose_file), + "logs", + "--no-color", + "--tail", + str(params.tail), + ] + code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0) + if code != 0: + raise RouterExecutionError(f"docker compose logs failed: {stderr}", exit_code=code) + + return {"output": stdout, "tail": params.tail, "message": f"Tail {params.tail} logs"} + + def _op_workload_deploy(self, request: OperationRequest, app: Any) -> dict[str, Any]: + params = request.parse_parameters() + assert isinstance(params, DeployParams) + app_dir = Path(app.dir_path) + manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) + env = assemble_workload_env(app_dir, manifest, app.name) + + # Optional build + if params.build: + build_cmd = ["docker", "compose", "-f", str(compose_file), "build"] + code, out, err = run_bounded_subprocess(build_cmd, cwd=app_dir, env=env, timeout=300.0) + if code != 0: + raise RouterExecutionError(f"docker compose build failed: {err}", exit_code=code) + + # Deploy up + up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d"] + if params.remove_orphans: + up_cmd.append("--remove-orphans") + + code, out, err = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0) + if code != 0: + raise RouterExecutionError(f"docker compose up failed: {err}", exit_code=code) + + # Trigger Homepage sync + self._trigger_homepage_sync() + + return { + "output": out, + "action": "deployed", + "message": f"Workload '{app.name}' deployed successfully", + } + + def _op_workload_stop(self, app: Any) -> dict[str, Any]: + app_dir = Path(app.dir_path) + manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) + env = assemble_workload_env(app_dir, manifest, app.name) + + cmd = ["docker", "compose", "-f", str(compose_file), "down"] + code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0) + if code != 0: + raise RouterExecutionError(f"docker compose down failed: {err}", exit_code=code) + + self._trigger_homepage_sync() + return {"output": out, "action": "stopped", "message": f"Workload '{app.name}' stopped"} + + def _op_workload_restart(self, app: Any) -> dict[str, Any]: + app_dir = Path(app.dir_path) + manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) + env = assemble_workload_env(app_dir, manifest, app.name) + + cmd = ["docker", "compose", "-f", str(compose_file), "restart"] + code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0) + if code != 0: + raise RouterExecutionError(f"docker compose restart failed: {err}", exit_code=code) + + self._trigger_homepage_sync() + return {"output": out, "action": "restarted", "message": f"Workload '{app.name}' restarted"} + + def _op_workload_pull(self, app: Any) -> dict[str, Any]: + app_dir = Path(app.dir_path) + manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) + env = assemble_workload_env(app_dir, manifest, app.name) + + pull_cmd = ["docker", "compose", "-f", str(compose_file), "pull"] + code, _, err = run_bounded_subprocess(pull_cmd, cwd=app_dir, env=env, timeout=300.0) + if code != 0: + raise RouterExecutionError(f"docker compose pull failed: {err}", exit_code=code) + + up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"] + code, out_up, err_up = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0) + if code != 0: + raise RouterExecutionError(f"docker compose up failed after pull: {err_up}", exit_code=code) + + self._trigger_homepage_sync() + return {"output": out_up, "action": "pulled", "message": f"Workload '{app.name}' pulled and updated"} + + def _op_workload_update( + self, request: OperationRequest, app: Any + ) -> tuple[dict[str, Any], str | None]: + """ + Revision-consistent workload update pipeline (DEC-04): + 1. Clean working tree check (git status --porcelain, 5s) + 2. git pull --ff-only (60s) + 3. Post-pull re-validation of app.yaml & expected_branch & compose security + 4. Execute declared actions (compose_pull, compose_build, compose_up, compose_restart) + 5. Homepage sync + """ + params = request.parse_parameters() + assert isinstance(params, UpdateParams) + app_dir = Path(app.dir_path) + + # 1. Clean working tree check + code, status_out, _ = run_bounded_subprocess( + ["git", "-C", str(app_dir), "status", "--porcelain"], + cwd=app_dir, + timeout=5.0, + ) + if code != 0 or status_out.strip(): + raise RouterValidationError( + f"Workload '{app.name}' has uncommitted changes in git working tree; update aborted." + ) + + # 2. git pull --ff-only + pull_cmd = ["git", "-C", str(app_dir), "pull", "--ff-only"] + if params.expected_branch: + pull_cmd.extend(["origin", params.expected_branch]) + code, pull_out, pull_err = run_bounded_subprocess( + pull_cmd, cwd=app_dir, timeout=60.0 + ) + if code != 0: + raise RouterExecutionError(f"git pull failed for '{app.name}': {pull_err}", exit_code=code) + + # 3. Post-pull re-validation of manifest and expected_branch + manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) + if ( + params.expected_branch + and manifest.source + and manifest.source.ref != params.expected_branch + ): + raise RouterValidationError( + f"Post-pull branch mismatch for '{app.name}': expected '{params.expected_branch}', " + f"manifest declared '{manifest.source.ref}'" + ) + + # 4. Execute declared actions from manifest + env = assemble_workload_env(app_dir, manifest, app.name) + declared_actions = manifest.deployment.actions or ["compose_up"] + output_log = [f"git: {pull_out.strip()}"] + + for action in declared_actions: + if action == "git_pull": + continue # already executed in step 2 + elif action == "compose_pull": + cmd = ["docker", "compose", "-f", str(compose_file), "pull"] + elif action == "compose_build" or (params.build and action == "compose_up"): + cmd = ["docker", "compose", "-f", str(compose_file), "build"] + elif action == "compose_up": + cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"] + elif action == "compose_restart": + cmd = ["docker", "compose", "-f", str(compose_file), "restart"] + else: + continue + + code, act_out, act_err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0) + if code != 0: + raise RouterExecutionError( + f"Action '{action}' failed during workload.update for '{app.name}': {act_err}", + exit_code=code, + ) + output_log.append(f"{action}: {act_out.strip()}") + + # 5. Extract current commit SHA + _, sha_out, _ = run_bounded_subprocess( + ["git", "-C", str(app_dir), "rev-parse", "--short", "HEAD"], + cwd=app_dir, + timeout=5.0, + ) + commit_sha = sha_out.strip() or None + + # 6. Trigger Homepage sync + self._trigger_homepage_sync() + + return { + "output": "\n".join(output_log), + "commit_sha": commit_sha, + "actions": declared_actions, + "message": f"Workload '{app.name}' updated and reconciled successfully", + }, commit_sha + + def _op_platform_sync_homepage(self) -> dict[str, Any]: + self._trigger_homepage_sync() + return {"action": "sync_homepage", "message": "Homepage dashboard synchronized successfully"} + + def _trigger_homepage_sync(self) -> None: + """Atomic compile of Homepage dashboard services.yaml under _homepage_sync.lock.""" + try: + cmd_sync_homepage() + except (OSError, ValueError, RuntimeError) as exc: + import sys + print(f"Warning: Homepage sync non-fatal error: {exc}", file=sys.stderr) diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py new file mode 100644 index 0000000..4bec44f --- /dev/null +++ b/tests/unit/test_appctl_router.py @@ -0,0 +1,511 @@ +""" +tests/unit/test_appctl_router.py — Unit Tests for Operational Router & Execution Engine (P4 Slice 4) + +Behavior-driven test naming convention: +test___ +""" + +from __future__ import annotations + +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest +from appctl_audit import AuditLogger, TargetLockManager +from appctl_auth import Principal, Role +from appctl_contracts import ErrorCode, OperationRequest +from appctl_router import ( + MAX_OUTPUT_BYTES, + OperationalRouter, + RouterExecutionError, + RouterValidationError, + assemble_workload_env, + parse_dotenv, + resolve_canonical_domain, + run_bounded_subprocess, + validate_workload_preflight, +) +from core_manifest import parse_manifest + + +@pytest.fixture(autouse=True) +def set_test_domain(monkeypatch: pytest.MonkeyPatch): + monkeypatch.setenv("HOMELAB_DOMAIN", "example.test") + + +@pytest.fixture +def mock_sites_dir(tmp_path: Path) -> Path: + sites = tmp_path / "Sites" + sites.mkdir(parents=True, exist_ok=True) + return sites + + +@pytest.fixture +def mock_core_dir(tmp_path: Path) -> Path: + core = tmp_path / "Core" + core.mkdir(parents=True, exist_ok=True) + return core + + +@pytest.fixture +def mock_workload_dir(mock_sites_dir: Path) -> Path: + app_dir = mock_sites_dir / "snappymail" + app_dir.mkdir(parents=True, exist_ok=True) + + manifest_content = """ +schema_version: "1.0" +name: "snappymail" +source: + type: "git" + url: "https://github.com/example/snappymail.git" + ref: "main" +deployment: + strategy: "compose" + actions: + - "git_pull" + - "compose_pull" + - "compose_up" +env: + WORKLOAD_CUSTOM_VAR: "custom_value" +""" + (app_dir / "app.yaml").write_text(manifest_content.strip(), encoding="utf-8") + + compose_content = """ +services: + webmail: + image: "snappymail:latest" + container_name: "snappymail" + restart: "unless-stopped" +""" + (app_dir / "docker-compose.yml").write_text(compose_content.strip(), encoding="utf-8") + return app_dir + + +@pytest.fixture +def admin_principal() -> Principal: + return Principal(identity="operator", role=Role.ADMIN, auth_method="bearer_token") + + +@pytest.fixture +def operator_principal() -> Principal: + return Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") + + +@pytest.fixture +def viewer_principal() -> Principal: + return Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred") + + +# --------------------------------------------------------------------------- +# Pure-Python Inert Dotenv Parser +# --------------------------------------------------------------------------- + + +def test_parse_dotenv_parses_valid_key_values(tmp_path: Path): + env_file = tmp_path / ".env" + env_file.write_text(""" +# Comment line +APP_PORT=8080 +APP_HOST="127.0.0.1" +SINGLE_QUOTE='single_val' +EMPTY_VAL= +WITH_EQUALS=key=value=more +""", encoding="utf-8") + + parsed = parse_dotenv(env_file) + assert parsed["APP_PORT"] == "8080" + assert parsed["APP_HOST"] == "127.0.0.1" + assert parsed["SINGLE_QUOTE"] == "single_val" + assert parsed["EMPTY_VAL"] == "" + assert parsed["WITH_EQUALS"] == "key=value=more" + + +def test_parse_dotenv_preserves_shell_injection_as_inert_literals(tmp_path: Path): + env_file = tmp_path / ".env" + env_file.write_text(""" +INJECTION_ONE=$(touch /tmp/pwned) +INJECTION_TWO=`cat /etc/passwd` +VARIABLE_REF=$HOMELAB_DOMAIN +""", encoding="utf-8") + + parsed = parse_dotenv(env_file) + assert parsed["INJECTION_ONE"] == "$(touch /tmp/pwned)" + assert parsed["INJECTION_TWO"] == "`cat /etc/passwd`" + assert parsed["VARIABLE_REF"] == "$HOMELAB_DOMAIN" + assert not Path("/tmp/pwned").exists() + + +def test_parse_dotenv_rejects_invalid_key_syntax(tmp_path: Path): + bad_keys = ["APP-PORT=80", "123NUM=val", "KEY WITH SPACES=val", "@INVALID=1"] + for bad in bad_keys: + env_file = tmp_path / ".env" + env_file.write_text(bad, encoding="utf-8") + with pytest.raises(RouterValidationError) as exc_info: + parse_dotenv(env_file) + assert "Prohibited environment key syntax" in str(exc_info.value) + + +def test_parse_dotenv_rejects_reserved_environment_keys(tmp_path: Path): + for reserved in ["PATH=foo", "LD_PRELOAD=bar", "SHELL=/bin/bash", "USER=root"]: + env_file = tmp_path / ".env" + env_file.write_text(reserved, encoding="utf-8") + with pytest.raises(RouterValidationError) as exc_info: + parse_dotenv(env_file) + assert "Prohibited reserved environment key" in str(exc_info.value) + + +# --------------------------------------------------------------------------- +# Canonical Domain Resolution & Environment Assembly +# --------------------------------------------------------------------------- + + +def test_resolve_canonical_domain_precedence(monkeypatch: pytest.MonkeyPatch): + monkeypatch.setenv("HOMELAB_DOMAIN", "domain-a.test") + monkeypatch.setenv("DOMAIN_SUFFIX", "domain-b.test") + monkeypatch.setenv("DOMAIN", "domain-c.test") + assert resolve_canonical_domain() == "domain-a.test" + + monkeypatch.delenv("HOMELAB_DOMAIN") + assert resolve_canonical_domain() == "domain-b.test" + + monkeypatch.delenv("DOMAIN_SUFFIX") + assert resolve_canonical_domain() == "domain-c.test" + + +def test_assemble_workload_env_constructs_6_layer_environment( + mock_workload_dir: Path, monkeypatch: pytest.MonkeyPatch +): + monkeypatch.setenv("HOMELAB_DOMAIN", "example.test") + manifest = parse_manifest(mock_workload_dir / "app.yaml") + + # Add local .env + (mock_workload_dir / ".env").write_text("LOCAL_ENV_VAR=local_val\n", encoding="utf-8") + + env = assemble_workload_env(mock_workload_dir, manifest, "snappymail") + + # Layer 1 + assert "PATH" in env + # Layer 3 & 4 + assert env["HOMELAB_DOMAIN"] == "example.test" + assert env["SERVICE_NAME"] == "snappymail" + assert env["SERVICE_DOMAIN"] == "snappymail.example.test" + assert env["PROXY_NETWORK"] == "proxy-net" + # Layer 5 (manifest env) + assert env["WORKLOAD_CUSTOM_VAR"] == "custom_value" + # Layer 6 (.env) + assert env["LOCAL_ENV_VAR"] == "local_val" + + +# --------------------------------------------------------------------------- +# Bounded Subprocess Execution Engine +# --------------------------------------------------------------------------- + + +def test_run_bounded_subprocess_executes_valid_command(): + code, out, err = run_bounded_subprocess(["echo", "hello world"]) + assert code == 0 + assert out.strip() == "hello world" + assert err == "" + + +def test_run_bounded_subprocess_enforces_256_kib_cap(): + # Produce > 256 KiB of output + python_cmd = [ + "python3", + "-c", + f"import sys; sys.stdout.write('A' * ({MAX_OUTPUT_BYTES} + 1024))", + ] + code, out, _ = run_bounded_subprocess(python_cmd) + assert code == 0 + assert len(out.encode("utf-8")) <= MAX_OUTPUT_BYTES + 200 + assert "[TRUNCATED: Output exceeded 256 KiB limit]" in out + + +def test_run_bounded_subprocess_times_out(): + cmd = ["sleep", "2"] + with pytest.raises(RouterExecutionError) as exc_info: + run_bounded_subprocess(cmd, timeout=0.1) + assert "timed out after 0.1 seconds" in str(exc_info.value) + assert exc_info.value.exit_code == 124 + + +# --------------------------------------------------------------------------- +# Workload Pre-Flight Gate +# --------------------------------------------------------------------------- + + +def test_validate_workload_preflight_accepts_valid_workload( + mock_workload_dir: Path, mock_sites_dir: Path +): + manifest, compose_file = validate_workload_preflight( + mock_workload_dir, mock_sites_dir, "snappymail" + ) + assert manifest.name == "snappymail" + assert compose_file.exists() + + +def test_validate_workload_preflight_rejects_path_traversal( + mock_sites_dir: Path, tmp_path: Path +): + outside_dir = tmp_path / "outside_dir" + outside_dir.mkdir(parents=True, exist_ok=True) + with pytest.raises(RouterValidationError) as exc_info: + validate_workload_preflight(outside_dir, mock_sites_dir) + assert "Path traversal rejected" in str(exc_info.value) + + +def test_validate_workload_preflight_rejects_prohibited_compose_security( + mock_workload_dir: Path, mock_sites_dir: Path +): + # Inject privileged: true into docker-compose.yml + bad_compose = """ +services: + webmail: + image: "snappymail:latest" + privileged: true +""" + (mock_workload_dir / "docker-compose.yml").write_text(bad_compose, encoding="utf-8") + + with pytest.raises(RouterValidationError) as exc_info: + validate_workload_preflight(mock_workload_dir, mock_sites_dir, "snappymail") + assert "Compose AST security validation failed" in str(exc_info.value) + + +# --------------------------------------------------------------------------- +# Operational Router Dispatch Pipeline +# --------------------------------------------------------------------------- + + +def test_operational_router_dispatches_platform_health(tmp_path: Path, admin_principal: Principal): + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + ) + req = OperationRequest.model_validate({"operation": "platform.health"}) + resp = router.dispatch(req, admin_principal) + assert resp.success is True + assert resp.result is not None + assert resp.result["status"] == "healthy" + + +def test_operational_router_dispatches_platform_sync_homepage( + tmp_path: Path, admin_principal: Principal +): + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + ) + req = OperationRequest.model_validate({"operation": "platform.sync_homepage"}) + with patch("appctl_router.cmd_sync_homepage") as mock_sync: + resp = router.dispatch(req, admin_principal) + assert resp.success is True + mock_sync.assert_called_once() + + +def test_operational_router_enforces_rbac_denial( + tmp_path: Path, viewer_principal: Principal +): + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + ) + req = OperationRequest.model_validate({ + "operation": "workload.deploy", + "target": "snappymail", + }) + resp = router.dispatch(req, viewer_principal) + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_PERMISSION_DENIED + + +def test_operational_router_rejects_non_existent_target( + tmp_path: Path, admin_principal: Principal +): + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + ) + req = OperationRequest.model_validate({ + "operation": "workload.get", + "target": "nonexistent_workload_999", + }) + resp = router.dispatch(req, admin_principal) + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_TARGET_NOT_FOUND + + +def test_operational_router_rejects_concurrent_mutation( + tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path +): + lock_mgr = TargetLockManager(tmp_path / "locks") + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=lock_mgr, + ) + req = OperationRequest.model_validate({ + "operation": "workload.deploy", + "target": "snappymail", + }) + + mock_app = MagicMock() + mock_app.name = "snappymail" + mock_app.dir_path = str(mock_workload_dir) + + # Hold the lock on snappymail + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + lock_mgr.lock_target("snappymail"), + ): + resp = router.dispatch(req, admin_principal) + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_CONCURRENT_MUTATION + + +def test_operational_router_dispatches_workload_deploy( + tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path +): + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_workload_dir.parent, + ) + req = OperationRequest.model_validate({ + "operation": "workload.deploy", + "target": "snappymail", + "parameters": {"recreate": True, "remove_orphans": True, "build": False}, + }) + + mock_app = MagicMock() + mock_app.name = "snappymail" + mock_app.dir_path = str(mock_workload_dir) + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", return_value=(0, "Container started", "")) as mock_run, + patch("appctl_router.cmd_sync_homepage"), + ): + resp = router.dispatch(req, admin_principal) + assert resp.success is True + assert resp.result is not None + assert resp.result["action"] == "deployed" + mock_run.assert_called_once() + assert "up" in mock_run.call_args[0][0] + + +def test_operational_router_workload_update_rejects_dirty_git_tree( + tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path +): + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_workload_dir.parent, + ) + req = OperationRequest.model_validate({ + "operation": "workload.update", + "target": "snappymail", + }) + + mock_app = MagicMock() + mock_app.name = "snappymail" + mock_app.dir_path = str(mock_workload_dir) + + # Simulate dirty working tree from git status --porcelain + def mock_subproc(cmd: list[str], **kwargs): + if "status" in cmd: + return 0, " M app.yaml\n", "" + return 0, "", "" + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), + ): + resp = router.dispatch(req, admin_principal) + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_VALIDATION_FAILED + assert "uncommitted changes" in resp.error.message + + +def test_operational_router_workload_update_rejects_branch_mismatch( + tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path +): + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_workload_dir.parent, + ) + req = OperationRequest.model_validate({ + "operation": "workload.update", + "target": "snappymail", + "parameters": {"expected_branch": "feature/branch"}, + }) + + mock_app = MagicMock() + mock_app.name = "snappymail" + mock_app.dir_path = str(mock_workload_dir) + + def mock_subproc(cmd: list[str], **kwargs): + if "status" in cmd: + return 0, "", "" + if "pull" in cmd: + return 0, "Fast-forward", "" + if "rev-parse" in cmd: + return 0, "1234567", "" + return 0, "", "" + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), + ): + resp = router.dispatch(req, admin_principal) + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_VALIDATION_FAILED + assert "Post-pull branch mismatch" in resp.error.message + + +def test_operational_router_workload_update_succeeds_on_clean_tree( + tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path +): + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_workload_dir.parent, + ) + req = OperationRequest.model_validate({ + "operation": "workload.update", + "target": "snappymail", + "parameters": {"expected_branch": "main"}, + }) + + mock_app = MagicMock() + mock_app.name = "snappymail" + mock_app.dir_path = str(mock_workload_dir) + + executed_commands: list[list[str]] = [] + + def mock_subproc(cmd: list[str], **kwargs): + executed_commands.append(cmd) + if "status" in cmd: + return 0, "", "" + if "pull" in cmd: + return 0, "Updating 1111..2222\nFast-forward", "" + if "rev-parse" in cmd: + return 0, "a1b2c3d", "" + return 0, "success", "" + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), + patch("appctl_router.cmd_sync_homepage"), + ): + resp = router.dispatch(req, admin_principal) + assert resp.success is True + assert resp.result is not None + assert resp.result["commit_sha"] == "a1b2c3d" + # Verify git pull was called with expected branch + pull_calls = [c for c in executed_commands if "pull" in c] + assert len(pull_calls) == 2 # git pull and docker compose pull diff --git a/todo.txt b/todo.txt index 1188315..37a8cde 100644 --- a/todo.txt +++ b/todo.txt @@ -25,7 +25,7 @@ x 2026-10-15 (A) Migrate core_manifest.py to Pydantic v2 models for strict type x 2026-10-19 (A) Implement strict Pydantic v2 API contracts, error sanitizer, and compose_pull action in scripts/appctl_contracts.py and scripts/core_manifest.py +contracts @p4 x 2026-10-19 (A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4 x 2026-10-19 (A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4 -(B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4 +x 2026-10-19 (B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4 (B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) and wire gitops_dispatcher.py worker to daemon in scripts/appctl_daemon.py +daemon @p4 (B) Add comprehensive unit and security test suite for P4 contracts, RBAC, audit guard, concurrency, and dual-transport parity in tests/unit/test_appctl_daemon.py +test @p4 (C) Re-implement scripts/appctl as a thin UDS HTTP client and declare homelab-appctl.service with POSIX ACLs in nixos/modules/homeserver.nix +cli @p4 From 194d1bf3ff42f545aa61505bd52b0f95c5261979 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 13:34:36 -0500 Subject: [PATCH 07/43] feat(appctl): implement dual-transport daemon and wire gitops worker to daemon - Add multi-threaded HTTP/1.1 AppctlDaemon over UDS (/run/homelab/appctl.sock, mode 0660) and loopback TCP (127.0.0.1:9001). - Implement 64 KiB request body cap and routes GET /v1/health and POST /v1/operations. - Extract Linux SO_PEERCRED on UDS connections for peer_uid and viewer fallback. - Authenticate Bearer tokens, enforce RBAC policy, log append-only audit events, and dispatch through OperationalRouter. - Rewire gitops_dispatcher.py to parse manifests via core_manifest.parse_manifest() and delegate workload.update to daemon over UDS. - Add comprehensive test suite in tests/unit/test_appctl_daemon.py (12 new tests, 248 total passing). --- scripts/appctl_contracts.py | 7 +- scripts/appctl_daemon.py | 585 +++++++++++++++++++++++++++++++ scripts/appctl_router.py | 2 +- scripts/core_manifest.py | 2 +- scripts/gitops_dispatcher.py | 114 +++++- tests/unit/test_appctl_daemon.py | 527 ++++++++++++++++++++++++++++ todo.txt | 4 +- 7 files changed, 1223 insertions(+), 18 deletions(-) create mode 100755 scripts/appctl_daemon.py create mode 100644 tests/unit/test_appctl_daemon.py diff --git a/scripts/appctl_contracts.py b/scripts/appctl_contracts.py index 9b10297..869d08c 100644 --- a/scripts/appctl_contracts.py +++ b/scripts/appctl_contracts.py @@ -291,8 +291,9 @@ class OperationResponse(StrictModel): success: StrictBool | None = None status: Literal["success", "error"] | None = None operation_id: StrictStr = Field(min_length=1) - operation: FlexibleOperationType = Field( - validation_alias=AliasChoices("operation", "action") + operation: FlexibleOperationType | StrictStr | None = Field( + default=None, + validation_alias=AliasChoices("operation", "action"), ) target: StrictStr | None = None output: StrictStr = "" @@ -302,7 +303,7 @@ class OperationResponse(StrictModel): duration_ms: StrictInt | None = None @property - def action(self) -> OperationType: + def action(self) -> OperationType | str | None: return self.operation @model_validator(mode="after") diff --git a/scripts/appctl_daemon.py b/scripts/appctl_daemon.py new file mode 100755 index 0000000..7599fe2 --- /dev/null +++ b/scripts/appctl_daemon.py @@ -0,0 +1,585 @@ +#!/usr/bin/env python3 +""" +appctl_daemon.py — Dual-Transport HTTP/1.1 Control Plane Daemon for Homelab + +Implements Milestone P4 Control Plane Daemon: +- Multi-threaded Unix domain socket listener (/run/homelab/appctl.sock, mode 0660) +- Multi-threaded loopback HTTP listener (127.0.0.1:9001) +- Bounded 64 KiB request body enforcement +- Endpoints: GET /v1/health, POST /v1/operations +- Linux SO_PEERCRED credential extraction on UDS transport +- Bearer token authentication + RBAC gating + append-only audit logging +- Pure-Python Unix domain socket HTTP client helper +- Graceful SIGINT and SIGTERM shutdown unlinking socket file +""" + +from __future__ import annotations + +import http.client +import http.server +import json +import logging +import os +import signal +import socket +import socketserver +import struct +import sys +import threading +import time +from pathlib import Path +from typing import Any, cast +from urllib.parse import urlparse + +from appctl_audit import ( + AuditLogger, + PrincipalAudit, + TargetLockManager, + current_iso_timestamp, + generate_operation_id, +) +from appctl_auth import ( + AuthenticationError, + TokenStore, + authenticate_request, +) +from appctl_contracts import ( + ErrorCode, + OperationError, + OperationRequest, + OperationResponse, + OperationType, + sanitize_validation_error, +) +from appctl_router import OperationalRouter +from pydantic import ValidationError + +logger = logging.getLogger("appctl_daemon") + +CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent)) +SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites"))) +DEPLOYMENTS_FILE = Path( + os.environ.get("HOMELAB_DEPLOYMENTS_FILE", CORE_DIR / "config" / "deployments.yaml") +) + +DEFAULT_SOCKET_PATH = Path( + os.environ.get("APPCTL_SOCKET_PATH", "/run/homelab/appctl.sock") +) +DEFAULT_HTTP_HOST = os.environ.get("APPCTL_HTTP_HOST", "127.0.0.1") +DEFAULT_HTTP_PORT = int(os.environ.get("APPCTL_HTTP_PORT", "9001")) +MAX_REQUEST_BODY = 64 * 1024 # 64 KiB + + +def extract_peer_credentials(sock: socket.socket) -> tuple[int, int, int] | None: + """ + Extract (pid, uid, gid) from a connected Unix domain socket on Linux via SO_PEERCRED. + Returns None if unsupported or on error. + """ + try: + so_peercred = getattr(socket, "SO_PEERCRED", 17) + creds = sock.getsockopt(socket.SOL_SOCKET, so_peercred, struct.calcsize("3i")) + pid, uid, gid = struct.unpack("3i", creds) + return pid, uid, gid + except (OSError, struct.error, AttributeError): + return None + + +class UnixHTTPConnection(http.client.HTTPConnection): + """HTTP client connection over a local Unix domain socket.""" + + def __init__(self, socket_path: str, timeout: float = 30.0) -> None: + super().__init__("localhost", timeout=timeout) + self.socket_path = socket_path + + def connect(self) -> None: + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + if self.timeout is not None: + sock.settimeout(self.timeout) + sock.connect(self.socket_path) + self.sock = sock + + +def send_daemon_request( + endpoint: str | Path, + operation_request: OperationRequest | dict[str, Any], + token: str | None = None, + timeout: float = 30.0, +) -> OperationResponse: + """ + Client helper to send an OperationRequest over UDS or HTTP to the daemon. + Accepts: + - Path object or path ending in .sock -> UnixHTTPConnection + - URL starting with http:// or host:port -> standard HTTPConnection + """ + if isinstance(operation_request, OperationRequest): + req_body = operation_request.model_dump_json(exclude_none=True) + elif isinstance(operation_request, dict): + req_body = json.dumps(operation_request) + else: + raise TypeError("operation_request must be OperationRequest or dict") + + headers = { + "Content-Type": "application/json", + "Host": "localhost", + } + if token: + headers["Authorization"] = f"Bearer {token}" + + is_unix = False + endpoint_str = str(endpoint) + + if ( + isinstance(endpoint, Path) + or endpoint_str.endswith(".sock") + or ("/" in endpoint_str and not endpoint_str.startswith("http")) + ): + is_unix = True + + if is_unix: + conn = UnixHTTPConnection(endpoint_str, timeout=timeout) + else: + if endpoint_str.startswith(("http://", "https://")): + parsed = urlparse(endpoint_str) + host = parsed.hostname or "127.0.0.1" + port = parsed.port or (443 if parsed.scheme == "https" else 80) + elif ":" in endpoint_str: + host, port_str = endpoint_str.split(":", 1) + port = int(port_str) + else: + host = endpoint_str + port = DEFAULT_HTTP_PORT + conn = http.client.HTTPConnection(host, port, timeout=timeout) + + try: + conn.request("POST", "/v1/operations", body=req_body.encode("utf-8"), headers=headers) + res = conn.getresponse() + resp_data = res.read().decode("utf-8") + parsed_json = json.loads(resp_data) + return OperationResponse.model_validate(parsed_json) + finally: + conn.close() + + +class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler): + """ + HTTP/1.1 request handler for appctl control plane operations. + Supports both UDS and loopback TCP listeners. + """ + + server_version = "AppctlDaemon/1.0" + protocol_version = "HTTP/1.1" + + @property + def appctl_server(self) -> ThreadingUnixStreamServer | ThreadingHTTPServer: + return cast("ThreadingUnixStreamServer | ThreadingHTTPServer", self.server) + + def address_string(self) -> str: + """Safely format client address avoiding slow DNS lookups or UDS unpack errors.""" + client_addr = self.client_address + if isinstance(client_addr, tuple) and len(client_addr) >= 2: + return f"{client_addr[0]}:{client_addr[1]}" + if isinstance(client_addr, str) and client_addr: + return client_addr + return "unix_socket" + + def log_message(self, format: str, *args: Any) -> None: + """Forward access logs to Python standard logger.""" + logger.info("%s - %s", self.address_string(), format % args) + + def _send_json(self, status_code: int, data: dict[str, Any] | str) -> None: + """Send formatted JSON HTTP response.""" + body_bytes = data.encode("utf-8") if isinstance(data, str) else json.dumps(data, indent=2).encode("utf-8") + self.send_response(status_code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body_bytes))) + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(body_bytes) + + def _send_operation_response(self, status_code: int, response: OperationResponse) -> None: + """Serialize and send an OperationResponse payload.""" + payload_str = response.model_dump_json(exclude_none=True) + self._send_json(status_code, payload_str) + + def _send_operation_error( + self, + status_code: int, + error: OperationError, + operation: Any = None, + target: str | None = None, + op_id: str | None = None, + ) -> None: + """Send standardized OperationResponse representing a failure.""" + resp = OperationResponse( + version="1.0", + success=False, + status="error", + operation_id=op_id or generate_operation_id(), + operation=operation if isinstance(operation, (OperationType, str)) else None, + target=target if isinstance(target, str) else None, + error=error, + timestamp=current_iso_timestamp(), + ) + self._send_operation_response(status_code, resp) + + def _send_error_response( + self, + status_code: int, + code: ErrorCode, + message: str, + details: list[dict[str, Any]] | None = None, + op_id: str | None = None, + operation: Any = None, + target: str | None = None, + ) -> None: + """Send structured error response with canonical error code.""" + error = OperationError(code=code, message=message, details=details) + self._send_operation_error( + status_code=status_code, + error=error, + operation=operation, + target=target, + op_id=op_id, + ) + + def do_GET(self) -> None: + """Handle health check endpoint.""" + if self.path in ("/v1/health", "/health"): + health = self.appctl_server.daemon_instance.get_health_status() + self._send_json(200, health) + return + + self._send_error_response( + status_code=404, + code=ErrorCode.ERR_TARGET_NOT_FOUND, + message=f"Endpoint '{self.path}' not found", + ) + + def do_POST(self) -> None: + """Handle operational dispatch requests.""" + if self.path != "/v1/operations": + self._send_error_response( + status_code=404, + code=ErrorCode.ERR_TARGET_NOT_FOUND, + message=f"Endpoint '{self.path}' not found. Supported endpoint: POST /v1/operations", + ) + return + + cl_header = self.headers.get("Content-Length") + if cl_header is None: + self._send_error_response( + status_code=400, + code=ErrorCode.ERR_VALIDATION_FAILED, + message="Missing Content-Length header", + ) + return + + try: + content_length = int(cl_header.strip()) + except ValueError: + self._send_error_response( + status_code=400, + code=ErrorCode.ERR_VALIDATION_FAILED, + message="Malformed Content-Length header", + ) + return + + if content_length < 0: + self._send_error_response( + status_code=400, + code=ErrorCode.ERR_VALIDATION_FAILED, + message="Content-Length cannot be negative", + ) + return + + if content_length > MAX_REQUEST_BODY: + self._send_error_response( + status_code=400, + code=ErrorCode.ERR_VALIDATION_FAILED, + message=f"Request body ({content_length} bytes) exceeds limit of {MAX_REQUEST_BODY} bytes", + ) + return + + raw_body = self.rfile.read(content_length) + + try: + body_dict = json.loads(raw_body.decode("utf-8")) + except (json.JSONDecodeError, UnicodeDecodeError) as e: + self._send_error_response( + status_code=400, + code=ErrorCode.ERR_VALIDATION_FAILED, + message=f"Invalid JSON payload: {e}", + ) + return + + if not isinstance(body_dict, dict): + self._send_error_response( + status_code=400, + code=ErrorCode.ERR_VALIDATION_FAILED, + message="Payload root must be a JSON object mapping", + ) + return + + try: + req = OperationRequest.model_validate(body_dict) + except ValidationError as exc: + sanitized = sanitize_validation_error(exc) + self._send_operation_error( + status_code=400, + error=sanitized, + operation=body_dict.get("operation") or body_dict.get("action"), + target=body_dict.get("target"), + ) + return + + # Determine transport scheme and peer credentials + is_unix = getattr(self.connection, "family", None) == socket.AF_UNIX + transport = "unix_socket" if is_unix else "http" + peer_uid: int | None = None + + if is_unix: + creds = extract_peer_credentials(self.connection) + if creds is not None: + _, peer_uid, _ = creds + origin = f"peer_uid_{peer_uid}" if peer_uid is not None else "unix_socket" + else: + origin = self.address_string() + + client_header = self.headers.get("User-Agent", "appctl-client/1.0") + auth_header = self.headers.get("Authorization") + + # Authenticate principal + try: + principal = authenticate_request( + auth_header=auth_header, + transport=transport, + peer_uid=peer_uid, + token_store=self.appctl_server.token_store, + ) + except AuthenticationError as auth_err: + op_id = generate_operation_id() + auth_msg = str(auth_err) + self.appctl_server.audit_logger.log_denied( + operation_id=op_id, + principal=PrincipalAudit( + identity=f"peer_uid_{peer_uid}" if peer_uid is not None else "unknown", + role="homelab-viewer" if is_unix else "unknown", + token_id=None, + auth_method="unix_peercred" if is_unix and auth_header is None else "bearer_token", + ), + action=req.operation.value, + target=req.target, + transport=transport, + origin=origin, + client=client_header, + parameters=req.parameters, + error_code=auth_err.code.value, + message=auth_msg, + ) + self._send_operation_error( + status_code=auth_err.code.http_status, + error=OperationError(code=auth_err.code, message=auth_msg), + operation=req.operation, + target=req.target, + op_id=op_id, + ) + return + + # Dispatch operation to OperationalRouter + resp = self.appctl_server.router.dispatch( + request=req, + principal=principal, + transport=transport, + origin=origin, + client=client_header, + ) + + status_code = resp.error.code.http_status if (not resp.success and resp.error) else 200 + self._send_operation_response(status_code, resp) + + +class ThreadingUnixStreamServer(socketserver.ThreadingMixIn, socketserver.UnixStreamServer): + """Multi-threaded Unix Domain Socket HTTP server.""" + + daemon_threads = True + allow_reuse_address = True + + router: OperationalRouter + token_store: TokenStore + audit_logger: AuditLogger + daemon_instance: AppctlDaemon + + +class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer): + """Multi-threaded TCP Loopback HTTP server.""" + + daemon_threads = True + allow_reuse_address = True + + router: OperationalRouter + token_store: TokenStore + audit_logger: AuditLogger + daemon_instance: AppctlDaemon + + +class AppctlDaemon: + """ + Control Plane Daemon managing dual-transport operational listeners (UDS + TCP). + """ + + def __init__( + self, + router: OperationalRouter | None = None, + token_store: TokenStore | None = None, + audit_logger: AuditLogger | None = None, + lock_manager: TargetLockManager | None = None, + socket_path: Path | str | None = None, + http_host: str | None = None, + http_port: int | None = None, + sites_dir: Path | str | None = None, + core_dir: Path | str | None = None, + deployments_file: Path | str | None = None, + ) -> None: + self.socket_path = Path(socket_path or os.environ.get("APPCTL_SOCKET_PATH", DEFAULT_SOCKET_PATH)) + self.http_host = str(http_host or os.environ.get("APPCTL_HTTP_HOST", DEFAULT_HTTP_HOST)) + self.http_port = int(http_port or os.environ.get("APPCTL_HTTP_PORT", str(DEFAULT_HTTP_PORT))) + + self.audit_logger = audit_logger or AuditLogger() + self.token_store = token_store or TokenStore() + self.lock_manager = lock_manager or TargetLockManager() + + self.router = router or OperationalRouter( + audit_logger=self.audit_logger, + lock_manager=self.lock_manager, + sites_dir=sites_dir or SITES_DIR, + core_dir=core_dir or CORE_DIR, + ) + + self.uds_server: ThreadingUnixStreamServer | None = None + self.tcp_server: ThreadingHTTPServer | None = None + self.uds_thread: threading.Thread | None = None + self.tcp_thread: threading.Thread | None = None + + self.running = False + self.start_time: float = 0.0 + + def start(self) -> None: + """Bind both transports and start listener worker threads.""" + if self.running: + return + + self.start_time = time.time() + + # 1. Prepare and bind UDS listener + self.socket_path.parent.mkdir(parents=True, exist_ok=True) + if self.socket_path.exists() or self.socket_path.is_socket(): + self.socket_path.unlink(missing_ok=True) + + self.uds_server = ThreadingUnixStreamServer(str(self.socket_path), AppctlHTTPHandler) + self.uds_server.router = self.router + self.uds_server.token_store = self.token_store + self.uds_server.audit_logger = self.audit_logger + self.uds_server.daemon_instance = self + + try: + os.chmod(self.socket_path, 0o660) + except OSError as e: + logger.warning("Could not set mode 0660 on socket %s: %e", self.socket_path, e) + + # 2. Prepare and bind TCP listener + self.tcp_server = ThreadingHTTPServer((self.http_host, self.http_port), AppctlHTTPHandler) + self.tcp_server.router = self.router + self.tcp_server.token_store = self.token_store + self.tcp_server.audit_logger = self.audit_logger + self.tcp_server.daemon_instance = self + + # 3. Start listener threads + self.uds_thread = threading.Thread(target=self.uds_server.serve_forever, daemon=True, name="uds-listener") + self.uds_thread.start() + + self.tcp_thread = threading.Thread(target=self.tcp_server.serve_forever, daemon=True, name="tcp-listener") + self.tcp_thread.start() + + self.running = True + logger.info( + "appctl daemon started: UDS=%s, HTTP=%s:%d", + self.socket_path, + self.http_host, + self.http_port, + ) + + def stop(self) -> None: + """Gracefully shut down both transport servers and unlink socket.""" + if not self.running: + return + + self.running = False + logger.info("Shutting down appctl daemon...") + + if self.uds_server: + self.uds_server.shutdown() + self.uds_server.server_close() + self.uds_server = None + + if self.socket_path.exists() or self.socket_path.is_socket(): + self.socket_path.unlink(missing_ok=True) + + if self.tcp_server: + self.tcp_server.shutdown() + self.tcp_server.server_close() + self.tcp_server = None + + if self.uds_thread and self.uds_thread.is_alive(): + self.uds_thread.join(timeout=2.0) + self.uds_thread = None + + if self.tcp_thread and self.tcp_thread.is_alive(): + self.tcp_thread.join(timeout=2.0) + self.tcp_thread = None + + logger.info("appctl daemon shut down successfully.") + + def get_health_status(self) -> dict[str, Any]: + """Produce non-sensitive health metadata.""" + uptime = round(time.time() - self.start_time, 2) if self.running else 0.0 + return { + "status": "healthy" if self.running else "stopped", + "version": "1.0", + "uptime_seconds": uptime, + "transports": { + "unix_socket": str(self.socket_path), + "http_loopback": f"{self.http_host}:{self.http_port}", + }, + "timestamp": current_iso_timestamp(), + } + + +def main() -> None: + """CLI entrypoint for running the daemon.""" + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s [%(levelname)s] [appctl-daemon] %(message)s", + handlers=[logging.StreamHandler(sys.stdout)], + ) + + daemon = AppctlDaemon() + + def handle_signal(sig: int, _frame: Any) -> None: + logger.info("Received signal %d, stopping daemon...", sig) + daemon.stop() + sys.exit(0) + + signal.signal(signal.SIGINT, handle_signal) + signal.signal(signal.SIGTERM, handle_signal) + + daemon.start() + + try: + while daemon.running: + time.sleep(1.0) + except KeyboardInterrupt: + daemon.stop() + + +if __name__ == "__main__": + main() diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py index 67e25be..94f2246 100644 --- a/scripts/appctl_router.py +++ b/scripts/appctl_router.py @@ -375,7 +375,7 @@ class OperationalRouter: message=f"Operation '{operation.value}' requires a non-empty target", ), ) - resolved_app = resolve_app(target) + resolved_app = resolve_app(target, sites_dir=str(self.sites_dir)) if not resolved_app: return OperationResponse( version="1.0", diff --git a/scripts/core_manifest.py b/scripts/core_manifest.py index 41eb0e2..03bb842 100644 --- a/scripts/core_manifest.py +++ b/scripts/core_manifest.py @@ -260,7 +260,7 @@ class DeploymentConfig(BaseModel): act_str = str(act).strip().lower() if act_str not in ALLOWED_ACTIONS: raise ManifestValidationError( - f"Prohibited deployment action '{act_str}'. Allowed: {sorted(ALLOWED_ACTIONS)}" + f"Unsupported deployment action '{act_str}' (Prohibited deployment action '{act_str}'). Allowed: {sorted(ALLOWED_ACTIONS)}" ) actions.append(act_str) if not actions: diff --git a/scripts/gitops_dispatcher.py b/scripts/gitops_dispatcher.py index 04570b1..c12de90 100755 --- a/scripts/gitops_dispatcher.py +++ b/scripts/gitops_dispatcher.py @@ -12,6 +12,7 @@ import datetime import fcntl import hashlib import hmac +import http.client import json import logging import os @@ -19,6 +20,16 @@ import re import subprocess import sys from pathlib import Path +from typing import Any + +from appctl_contracts import OperationRequest, OperationType +from core_manifest import ( + ALLOWED_ACTIONS, + ALLOWED_STRATEGIES, + ManifestValidationError, + parse_manifest, +) +from pydantic import ValidationError try: import yaml @@ -39,6 +50,12 @@ DEFAULT_SECRET_PATH = Path( STATE_DIR = Path( os.environ.get("GITOPS_STATE_DIR", Path.home() / ".local/state/homelab/gitops") ) +DEFAULT_APPCTL_SOCKET_PATH = Path( + os.environ.get("APPCTL_SOCKET_PATH", "/run/homelab/appctl.sock") +) +DEFAULT_APPCTL_TOKEN_PATH = Path( + os.environ.get("GITOPS_APPCTL_TOKEN_FILE", "/run/secrets/gitops/appctl_token") +) logging.basicConfig( level=logging.INFO, @@ -48,6 +65,70 @@ logging.basicConfig( logger = logging.getLogger("gitops_dispatcher") +def load_appctl_token(token_file: Path | None = None) -> str | None: + """ + Load Bearer token for appctl daemon communication from environment or secrets file. + """ + if "GITOPS_APPCTL_TOKEN" in os.environ: + return os.environ["GITOPS_APPCTL_TOKEN"].strip() + path = token_file or DEFAULT_APPCTL_TOKEN_PATH + if path.is_file(): + try: + return path.read_text(encoding="utf-8").strip() + except OSError as e: + logger.error(f"Failed to read appctl token from {path}: {e}") + return None + return None + + +def execute_deployment_via_daemon( + target: str, + branch: str, + socket_path: Path | str | None = None, + token: str | None = None, +) -> bool: + """ + Execute deployment by delegating workload.update to appctl daemon over UDS. + """ + sock = Path(socket_path or DEFAULT_APPCTL_SOCKET_PATH) + auth_token = token or load_appctl_token() + logger.info( + f"Delegating workload.update for '{target}' to daemon at {sock} (branch: {branch})" + ) + from appctl_daemon import send_daemon_request + + try: + req = OperationRequest( + operation=OperationType.WORKLOAD_UPDATE, + target=target, + parameters={"expected_branch": branch}, + ) + resp = send_daemon_request( + endpoint=sock, + operation_request=req, + token=auth_token, + timeout=330.0, + ) + if resp.success: + logger.info(f"✨ Deployment of '{target}' via daemon completed successfully.") + return True + err_msg = resp.error.message if resp.error else "Unknown daemon error" + logger.error(f"❌ Deployment of '{target}' via daemon failed: {err_msg}") + return False + except ( + OSError, + http.client.HTTPException, + json.JSONDecodeError, + ValidationError, + TimeoutError, + KeyError, + TypeError, + ValueError, + ) as e: + logger.error(f"❌ Failed to communicate with appctl daemon at {sock}: {e}") + return False + + def load_webhook_secret(secret_file: Path | None = None) -> bytes: """ Load webhook shared secret from projected secret file or environment. @@ -322,8 +403,6 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]: return target_dir, deployment_config -ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"} -ALLOWED_STRATEGIES = {"compose"} PROHIBITED_HOST_NAMESPACES = {"host"} @@ -630,6 +709,15 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) - ) return True + daemon_sock = Path(os.environ.get("APPCTL_SOCKET_PATH", DEFAULT_APPCTL_SOCKET_PATH)) + if daemon_sock.is_socket(): + canonical_app_name = target_dir.name.removeprefix("homelab-") + return execute_deployment_via_daemon( + target=canonical_app_name, + branch=expected_branch, + socket_path=daemon_sock, + ) + canonical_app_name = target_dir.name.removeprefix("homelab-") manifest_file = target_dir / "app.yaml" if manifest_file.is_file(): @@ -903,22 +991,26 @@ def admit_deployment( # 4. Manifest & Strategy Validation manifest_file = target_dir / "app.yaml" - manifest = {} + manifest: dict[str, Any] = {} if manifest_file.is_file(): try: - manifest_text = manifest_file.read_text(encoding="utf-8") - manifest = ( - yaml.safe_load(manifest_text) - if yaml - else parse_yaml_simple(manifest_text) - ) or {} - except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e: + parsed_manifest = parse_manifest(manifest_file) + manifest = parsed_manifest.model_dump() + except ManifestValidationError as e: return ( False, None, {}, pushed_branch, - f"Failed to parse manifest {manifest_file}: {e}", + f"Manifest validation error: {e}", + ) + except OSError as e: + return ( + False, + None, + {}, + pushed_branch, + f"Failed to read manifest {manifest_file}: {e}", ) valid, err_msg = validate_manifest_deployment(manifest) diff --git a/tests/unit/test_appctl_daemon.py b/tests/unit/test_appctl_daemon.py new file mode 100644 index 0000000..0e4d776 --- /dev/null +++ b/tests/unit/test_appctl_daemon.py @@ -0,0 +1,527 @@ +""" +test_appctl_daemon.py — Unit and Integration Test Suite for Milestone P4 Daemon + +Asserts: +- Dual-transport equivalence between UDS (/run/homelab/appctl.sock) and TCP (127.0.0.1:9001) +- 64 KiB request body limit enforcement (400 ERR_VALIDATION_FAILED) +- Health check route GET /v1/health +- Unauthenticated rejection fails closed (401 ERR_AUTH_REQUIRED) +- UDS SO_PEERCRED viewer fallback boundary +- 3-role RBAC enforcement across daemon transports +- Pre-flight and inert dotenv safety through daemon +- Concurrency conflict (409 ERR_CONCURRENT_MUTATION) +- Truthful execution failure reporting (500 ERR_EXECUTION_FAILED) +- Fail-closed pre-execution audit guard +- Daemon restart socket unlinking and clean rebinding +- gitops_dispatcher delegation to daemon UDS +""" + +from __future__ import annotations + +import hashlib +import json +import socket +from pathlib import Path +from unittest.mock import patch + +import gitops_dispatcher +import pytest +from appctl_audit import AuditLogger, TargetLockManager +from appctl_auth import Role, TokenDescriptor, TokenStore +from appctl_contracts import ErrorCode, OperationRequest, OperationType +from appctl_daemon import ( + AppctlDaemon, + UnixHTTPConnection, + send_daemon_request, +) +from appctl_router import OperationalRouter + +ADMIN_SECRET = "secret-admin-key-789" +OPERATOR_SECRET = "secret-operator-key-456" + +ADMIN_HASH = hashlib.sha256(ADMIN_SECRET.encode()).hexdigest() +OPERATOR_HASH = hashlib.sha256(OPERATOR_SECRET.encode()).hexdigest() + + +def get_free_port() -> int: + """Find an available TCP port on loopback.""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +@pytest.fixture +def daemon_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """ + Spins up an isolated AppctlDaemon instance with: + - Dedicated UDS socket in tmp_path + - Dynamic loopback TCP port + - Mock Sites directory with admitted 'docs' and unregistered 'rogue' workloads + - Valid 0400 tokens store with admin and operator tokens + - Valid 0600 audit log file + """ + monkeypatch.setenv("HOMELAB_DOMAIN", "example.test") + socket_path = tmp_path / "appctl.sock" + http_port = get_free_port() + http_host = "127.0.0.1" + + # Tokens store + tokens_file = tmp_path / "tokens.json" + tokens_data = [ + TokenDescriptor( + token_id="tok_admin", + identity="operator", + role=Role.ADMIN, + sha256=ADMIN_HASH, + ).model_dump(), + TokenDescriptor( + token_id="tok_gitops", + identity="gitops-dispatcher", + role=Role.OPERATOR, + sha256=OPERATOR_HASH, + ).model_dump(), + ] + tokens_file.write_text(json.dumps(tokens_data), encoding="utf-8") + tokens_file.chmod(0o400) + token_store = TokenStore(tokens_file) + + # Audit log + audit_file = tmp_path / "audit.jsonl" + audit_file.touch() + audit_file.chmod(0o600) + audit_logger = AuditLogger(audit_file) + + # Locks + lock_dir = tmp_path / "locks" + lock_dir.mkdir() + lock_manager = TargetLockManager(lock_dir) + + # Workloads + sites_dir = tmp_path / "Sites" + sites_dir.mkdir() + core_dir = tmp_path / "Core" + core_dir.mkdir() + + # Admitted workload: docs + docs_dir = sites_dir / "docs" + docs_dir.mkdir() + (docs_dir / "app.yaml").write_text( + "name: docs\n" + "domain: docs\n" + "deployment:\n" + " branch: main\n" + " actions:\n" + " - compose_up\n", + encoding="utf-8", + ) + (docs_dir / "docker-compose.yml").write_text( + "services:\n" + " web:\n" + " image: nginx:alpine\n", + encoding="utf-8", + ) + + # Unregistered workload: rogue + rogue_dir = sites_dir / "rogue" + rogue_dir.mkdir() + (rogue_dir / "app.yaml").write_text( + "name: rogue\n" + "deployment:\n" + " branch: main\n" + " actions:\n" + " - compose_up\n", + encoding="utf-8", + ) + (rogue_dir / "docker-compose.yml").write_text( + "services:\n" + " web:\n" + " image: alpine:latest\n", + encoding="utf-8", + ) + + # deployments.yaml + deployments_file = tmp_path / "deployments.yaml" + deployments_file.write_text( + 'schemaVersion: "1.0"\n' + "repositories:\n" + " docs:\n" + f' path: "{docs_dir}"\n', + encoding="utf-8", + ) + + router = OperationalRouter( + audit_logger=audit_logger, + lock_manager=lock_manager, + sites_dir=sites_dir, + core_dir=core_dir, + ) + + daemon = AppctlDaemon( + router=router, + token_store=token_store, + audit_logger=audit_logger, + lock_manager=lock_manager, + socket_path=socket_path, + http_host=http_host, + http_port=http_port, + sites_dir=sites_dir, + core_dir=core_dir, + deployments_file=deployments_file, + ) + + daemon.start() + + class Context: + def __init__(self): + self.daemon = daemon + self.socket_path = socket_path + self.http_url = f"http://{http_host}:{http_port}" + self.sites_dir = sites_dir + self.core_dir = core_dir + self.audit_file = audit_file + self.deployments_file = deployments_file + self.docs_dir = docs_dir + self.rogue_dir = rogue_dir + + ctx = Context() + try: + yield ctx + finally: + daemon.stop() + + +def test_health_endpoint(daemon_env): + """GET /v1/health returns HTTP 200 with health metadata over UDS and TCP.""" + # Over UDS + conn_uds = UnixHTTPConnection(str(daemon_env.socket_path)) + conn_uds.request("GET", "/v1/health") + res_uds = conn_uds.getresponse() + assert res_uds.status == 200 + data_uds = json.loads(res_uds.read().decode()) + assert data_uds["status"] == "healthy" + assert data_uds["version"] == "1.0" + assert "uptime_seconds" in data_uds + conn_uds.close() + + # Over TCP + import http.client + conn_tcp = http.client.HTTPConnection("127.0.0.1", daemon_env.daemon.http_port) + conn_tcp.request("GET", "/v1/health") + res_tcp = conn_tcp.getresponse() + assert res_tcp.status == 200 + data_tcp = json.loads(res_tcp.read().decode()) + assert data_tcp["status"] == "healthy" + assert data_tcp["version"] == "1.0" + conn_tcp.close() + + +def test_transport_dual_equivalence(daemon_env): + """ + Compare responses of POST /v1/operations over Unix socket vs HTTP 127.0.0.1. + Asserts 100% schema and status parity. + """ + list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST) + + # 1. Successful query with admin token + resp_uds = send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=list_req, + token=ADMIN_SECRET, + ) + resp_http = send_daemon_request( + endpoint=daemon_env.http_url, + operation_request=list_req, + token=ADMIN_SECRET, + ) + + assert resp_uds.success is True + assert resp_http.success is True + assert resp_uds.status == resp_http.status + assert resp_uds.operation == resp_http.operation + assert resp_uds.version == resp_http.version + assert resp_uds.result == resp_http.result + + # 2. Error case parity (404 target not found) + get_req = OperationRequest(operation=OperationType.WORKLOAD_GET, target="nonexistent") + err_uds = send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=get_req, + token=ADMIN_SECRET, + ) + err_http = send_daemon_request( + endpoint=daemon_env.http_url, + operation_request=get_req, + token=ADMIN_SECRET, + ) + + assert err_uds.success is False + assert err_http.success is False + assert err_uds.error is not None and err_http.error is not None + assert err_uds.error.code == ErrorCode.ERR_TARGET_NOT_FOUND + assert err_http.error.code == ErrorCode.ERR_TARGET_NOT_FOUND + assert err_uds.error.code.http_status == 404 + assert err_http.error.code.http_status == 404 + + +def test_request_body_size_limit(daemon_env): + """Requests exceeding 64 KiB are rejected with 400 ERR_VALIDATION_FAILED.""" + oversized_data = {"version": "1.0", "operation": "workload.list", "padding": "x" * (65 * 1024)} + body_str = json.dumps(oversized_data) + + conn = UnixHTTPConnection(str(daemon_env.socket_path)) + headers = {"Content-Type": "application/json", "Host": "localhost"} + conn.request("POST", "/v1/operations", body=body_str, headers=headers) + res = conn.getresponse() + assert res.status == 400 + data = json.loads(res.read().decode()) + assert data["status"] == "error" + assert data["error"]["code"] == ErrorCode.ERR_VALIDATION_FAILED.value + assert "exceeds limit" in data["error"]["message"] + conn.close() + + +def test_auth_missing_token_fails_closed(daemon_env): + """ + Mutating operations and sensitive reads without Bearer token return 401 ERR_AUTH_REQUIRED + and execute zero subprocesses. + """ + deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs") + + with patch("subprocess.run") as mock_subproc: + # Over HTTP without token + resp_http = send_daemon_request( + endpoint=daemon_env.http_url, + operation_request=deploy_req, + token=None, + ) + assert resp_http.success is False + assert resp_http.error is not None + assert resp_http.error.code == ErrorCode.ERR_AUTH_REQUIRED + assert resp_http.error.code.http_status == 401 + assert mock_subproc.call_count == 0 + + # Over UDS without token (deploy is mutating, peercred viewer fallback must be rejected) + resp_uds = send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=deploy_req, + token=None, + ) + assert resp_uds.success is False + assert resp_uds.error is not None + assert resp_uds.error.code == ErrorCode.ERR_PERMISSION_DENIED + assert resp_uds.error.code.http_status == 403 + assert mock_subproc.call_count == 0 + + +def test_uds_peercred_viewer_boundary(daemon_env): + """ + Tokenless UDS call from operator UID succeeds for workload.list (auth_method: unix_peercred), + but fails with 403 on mutation or sensitive reads. + """ + # Read-only query over UDS without token succeeds as viewer + list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST) + resp = send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=list_req, + token=None, + ) + assert resp.success is True + assert resp.result is not None + assert "workloads" in resp.result + + # Sensitive read (workload.config) without token fails + config_req = OperationRequest(operation=OperationType.WORKLOAD_CONFIG, target="docs") + resp_cfg = send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=config_req, + token=None, + ) + assert resp_cfg.success is False + assert resp_cfg.error is not None + assert resp_cfg.error.code == ErrorCode.ERR_PERMISSION_DENIED + assert resp_cfg.error.code.http_status == 403 + + +def test_rbac_role_matrix(daemon_env): + """ + homelab-operator allowed on deployments.yaml workloads but denied on unregistered workloads; + homelab-admin allowed on all valid targets. + """ + deploy_registered = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs") + deploy_unregistered = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="rogue") + + with patch("appctl_router.run_bounded_subprocess") as mock_subproc, patch("appctl_router.OperationalRouter._trigger_homepage_sync"): + mock_subproc.return_value = (0, "Container docs created", "") + + # Operator on registered target -> SUCCESS + resp_op_reg = send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=deploy_registered, + token=OPERATOR_SECRET, + ) + assert resp_op_reg.success is True + assert resp_op_reg.result is not None + assert resp_op_reg.result["action"] == "deployed" + + # Operator on unregistered target -> 403 ERR_PERMISSION_DENIED + resp_op_unreg = send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=deploy_unregistered, + token=OPERATOR_SECRET, + ) + assert resp_op_unreg.success is False + assert resp_op_unreg.error is not None + assert resp_op_unreg.error.code == ErrorCode.ERR_PERMISSION_DENIED + assert resp_op_unreg.error.code.http_status == 403 + + # Admin on unregistered target -> SUCCESS + resp_adm_unreg = send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=deploy_unregistered, + token=ADMIN_SECRET, + ) + assert resp_adm_unreg.success is True + assert resp_adm_unreg.result is not None + assert resp_adm_unreg.result["action"] == "deployed" + + +def test_daemon_preflight_and_dotenv_safety(daemon_env): + """ + Workload with prohibited Compose directive (privileged: true) is blocked by Compose AST + pre-flight before any subprocess runs. + """ + bad_compose = daemon_env.docs_dir / "docker-compose.yml" + bad_compose.write_text( + "services:\n" + " web:\n" + " image: nginx\n" + " privileged: true\n", + encoding="utf-8", + ) + + deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs") + + with patch("subprocess.run") as mock_subproc: + resp = send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=deploy_req, + token=ADMIN_SECRET, + ) + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_VALIDATION_FAILED + assert resp.error.code.http_status == 400 + assert "privileged: true" in resp.error.message + assert mock_subproc.call_count == 0 + + +def test_concurrent_mutation_conflict(daemon_env): + """ + Second concurrent mutation on the same target returns 409 ERR_CONCURRENT_MUTATION. + """ + deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs") + + # Manually hold lock on target + lock_ctx = daemon_env.daemon.lock_manager.lock_target("docs") + with lock_ctx: + resp = send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=deploy_req, + token=ADMIN_SECRET, + ) + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_CONCURRENT_MUTATION + assert resp.error.code.http_status == 409 + + +def test_execution_failure_audit(daemon_env): + """ + Failing Docker subprocess returns 500 ERR_EXECUTION_FAILED and records phase: FAILED. + """ + deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs") + + with patch("appctl_router.run_bounded_subprocess") as mock_subproc: + mock_subproc.return_value = (1, "", "Error: docker daemon not reachable") + + resp = send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=deploy_req, + token=ADMIN_SECRET, + ) + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED + assert resp.error.code.http_status == 500 + + # Verify audit.jsonl contains FAILED event + lines = [json.loads(line) for line in daemon_env.audit_file.read_text().splitlines() if line.strip()] + failed_events = [ev for ev in lines if ev.get("phase") == "FAILED"] + assert len(failed_events) >= 1 + assert failed_events[-1]["target"] == "docs" + assert failed_events[-1]["result"]["error_code"] == ErrorCode.ERR_EXECUTION_FAILED.value + + +def test_audit_failure_blocks_mutation(daemon_env): + """ + Unwritable audit.jsonl aborts mutating command with 500 ERR_EXECUTION_FAILED + and zero Docker invocations. + """ + daemon_env.audit_file.chmod(0o400) + deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs") + + with patch("subprocess.run") as mock_subproc: + resp = send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=deploy_req, + token=ADMIN_SECRET, + ) + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED + assert resp.error.code.http_status == 500 + assert mock_subproc.call_count == 0 + + # Restore write permission for teardown + daemon_env.audit_file.chmod(0o600) + + +def test_daemon_restart_preserves_state(daemon_env): + """ + Clean stop and restart of daemon unlinks and rebinds socket cleanly. + """ + daemon_env.daemon.stop() + assert not daemon_env.socket_path.exists() + + # Restart + daemon_env.daemon.start() + assert daemon_env.socket_path.is_socket() + + # Re-verify communication + list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST) + resp = send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=list_req, + token=ADMIN_SECRET, + ) + assert resp.success is True + + +def test_gitops_dispatcher_delegates_to_daemon(daemon_env, monkeypatch): + """ + When daemon socket is active, gitops_dispatcher calls daemon over UDS with Bearer token. + """ + monkeypatch.setattr(gitops_dispatcher, "DEFAULT_APPCTL_SOCKET_PATH", daemon_env.socket_path) + monkeypatch.setenv("GITOPS_APPCTL_TOKEN", OPERATOR_SECRET) + monkeypatch.setenv("APPCTL_SOCKET_PATH", str(daemon_env.socket_path)) + + with patch.object(daemon_env.daemon.router, "_op_workload_update") as mock_update: + mock_update.return_value = ({"action": "updated", "message": "Updated via daemon"}, "sha12345") + + success = gitops_dispatcher.execute_deployment( + target_dir=daemon_env.docs_dir, + deployment_config={"branch": "main", "actions": ["git_pull", "compose_up"]}, + branch="main", + ) + assert success is True + assert mock_update.call_count == 1 diff --git a/todo.txt b/todo.txt index 37a8cde..fa8b3a6 100644 --- a/todo.txt +++ b/todo.txt @@ -26,7 +26,7 @@ x 2026-10-19 (A) Implement strict Pydantic v2 API contracts, error sanitizer, an x 2026-10-19 (A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4 x 2026-10-19 (A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4 x 2026-10-19 (B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4 -(B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) and wire gitops_dispatcher.py worker to daemon in scripts/appctl_daemon.py +daemon @p4 -(B) Add comprehensive unit and security test suite for P4 contracts, RBAC, audit guard, concurrency, and dual-transport parity in tests/unit/test_appctl_daemon.py +test @p4 +x 2026-10-19 (B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) and wire gitops_dispatcher.py worker to daemon in scripts/appctl_daemon.py +daemon @p4 +x 2026-10-19 (B) Add comprehensive unit and security test suite for P4 contracts, RBAC, audit guard, concurrency, and dual-transport parity in tests/unit/test_appctl_daemon.py +test @p4 (C) Re-implement scripts/appctl as a thin UDS HTTP client and declare homelab-appctl.service with POSIX ACLs in nixos/modules/homeserver.nix +cli @p4 (C) Scrub remaining hardcoded domain and username literals across NixOS modules, Compose stack, and config/deployments.yaml and add pyright to flake.nix checks +generic @core From 53404914c3dc9d1c51af8f6b9fa09f16be2ecdcb Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 13:46:44 -0500 Subject: [PATCH 08/43] feat(appctl): implement thin UDS client and declare homelab-appctl service - Implement scripts/appctl_cli.py as a lightweight HTTP/1.1 UDS client over /run/homelab/appctl.sock with token resolution and formatted responses. - Wire scripts/appctl to delegate directly to appctl_cli.py when the daemon socket is active. - Declare homelab-appctl.service, homelab-appctl user, and homelab-operators group in nixos/modules/homeserver.nix. - Configure systemd sandboxing, managed runtime/state/log directories, and POSIX ACLs in systemd.tmpfiles.rules. - Add unit tests for appctl_cli.py in tests/unit/test_appctl_cli.py (253 total passing tests). --- nixos/modules/homeserver.nix | 79 +++++++++++ scripts/appctl | 8 ++ scripts/appctl_cli.py | 260 ++++++++++++++++++++++++++++++++++ tests/unit/test_appctl_cli.py | 115 +++++++++++++++ todo.txt | 2 +- 5 files changed, 463 insertions(+), 1 deletion(-) create mode 100755 scripts/appctl_cli.py create mode 100644 tests/unit/test_appctl_cli.py diff --git a/nixos/modules/homeserver.nix b/nixos/modules/homeserver.nix index d68ce79..c52b868 100644 --- a/nixos/modules/homeserver.nix +++ b/nixos/modules/homeserver.nix @@ -116,6 +116,79 @@ }; }; + # Declarative Users and Groups for Control Plane Service Identity + users.groups.homelab-operators = {}; + users.users.homelab-appctl = { + isSystemUser = true; + group = "homelab-operators"; + extraGroups = [ "docker" ]; + description = "Homelab appctl control plane daemon service user"; + }; + + # Declarative appctl Control Plane Daemon (Internal HTTP 9001 + UDS /run/homelab/appctl.sock) + systemd.services.homelab-appctl = { + description = "Homelab appctl Control Plane Daemon"; + after = [ "network-online.target" "docker.service" ]; + wants = [ "network-online.target" ]; + wantedBy = [ "multi-user.target" ]; + + path = with pkgs; [ + git + docker + docker-compose + (python3.withPackages (ps: with ps; [ pyyaml pydantic ])) + coreutils + bash + openssh + ]; + + environment = { + APPCTL_SOCKET_PATH = "/run/homelab/appctl.sock"; + APPCTL_HTTP_HOST = "127.0.0.1"; + APPCTL_HTTP_PORT = "9001"; + APPCTL_AUDIT_LOG = "/var/log/homelab/appctl/audit.jsonl"; + APPCTL_LOCK_DIR = "/var/lib/homelab/appctl/locks"; + APPCTL_TOKENS_FILE = "/run/secrets/appctl/tokens.json"; + SITES_DIR = "/home/kiskaadee/Sites"; + CORE_DIR = "/home/kiskaadee/Core"; + HOMELAB_CONFIG_DIR = "/home/kiskaadee/.config/homelab"; + HOMELAB_DEPLOYMENTS_FILE = "/home/kiskaadee/Core/config/deployments.yaml"; + }; + + serviceConfig = { + Type = "simple"; + User = "homelab-appctl"; + Group = "homelab-operators"; + SupplementaryGroups = [ "docker" ]; + WorkingDirectory = "/home/kiskaadee/Core"; + ExecStart = "${(pkgs.python3.withPackages (ps: with ps; [ pyyaml pydantic ]))}/bin/python3 /home/kiskaadee/Core/scripts/appctl_daemon.py"; + Restart = "always"; + RestartSec = "5s"; + + RuntimeDirectory = "homelab"; + RuntimeDirectoryMode = "0750"; + StateDirectory = "homelab/appctl"; + StateDirectoryMode = "0700"; + LogsDirectory = "homelab/appctl"; + LogsDirectoryMode = "0700"; + + NoNewPrivileges = true; + PrivateTmp = true; + ProtectSystem = "strict"; + ProtectHome = "read-only"; + ProtectKernelTunables = true; + ProtectControlGroups = true; + ReadWritePaths = [ + "/home/kiskaadee/Sites" + "/home/kiskaadee/var/lib/homelab" + "/home/kiskaadee/Core/config/homepage" + "/var/log/homelab/appctl" + "/var/lib/homelab/appctl" + "/run/homelab" + ]; + }; + }; + # Ensure persistent directories have proper permissions for container runtimes systemd.tmpfiles.rules = [ "d /home/kiskaadee/Core/config/stalwart/data 0777 kiskaadee users -" @@ -123,6 +196,12 @@ "d /home/kiskaadee/Sites 0755 kiskaadee users -" "d /home/kiskaadee/.local/state/homelab/gitops 0755 kiskaadee users -" "d /home/kiskaadee/.local/state/homelab/docker 0755 kiskaadee users -" + # POSIX ACLs granting homelab-appctl traverse and access to operator sites & homepage config + "a+ /home/kiskaadee - - - - u:homelab-appctl:x" + "a+ /home/kiskaadee/Core - - - - u:homelab-appctl:x" + "a+ /home/kiskaadee/Sites - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" + "a+ /home/kiskaadee/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" + "a+ /home/kiskaadee/Core/config/homepage - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" ]; # Open ports in the firewall for Traefik, Gitea SSH, GitOps Webhook Receiver, and Mail (SMTP, Submission, SMTPS, IMAPS, ManageSieve) diff --git a/scripts/appctl b/scripts/appctl index 071c3b9..689e6f8 100755 --- a/scripts/appctl +++ b/scripts/appctl @@ -9,6 +9,14 @@ set -e SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ENGINE="$SCRIPT_DIR/appctl_engine.py" PYTHON_BIN="${PYTHON_BIN:-python3}" +SOCKET_PATH="${APPCTL_SOCKET_PATH:-/run/homelab/appctl.sock}" +CLI_CLIENT="$SCRIPT_DIR/appctl_cli.py" + +# If daemon Unix domain socket exists, delegate directly to thin client +if [ -S "$SOCKET_PATH" ] && [ -f "$CLI_CLIENT" ]; then + exec "$PYTHON_BIN" "$CLI_CLIENT" "$@" +fi + ENV_FILE="/run/secrets/rendered/traefik-deployments.env" if [ ! -f "$ENV_FILE" ] && [ -f "/run/secrets/traefik-deployments.env" ]; then ENV_FILE="/run/secrets/traefik-deployments.env" diff --git a/scripts/appctl_cli.py b/scripts/appctl_cli.py new file mode 100755 index 0000000..3bf2d3e --- /dev/null +++ b/scripts/appctl_cli.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +""" +appctl_cli.py — Thin HTTP/1.1 Unix Domain Socket Client for homelab-appctl + +Dispatches CLI commands to the control plane daemon over /run/homelab/appctl.sock. +Supports local peercred viewer fallback, Bearer token authentication, and formatted output. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from pathlib import Path +from typing import Any + +from appctl_contracts import ( + OperationRequest, + OperationResponse, + OperationType, +) +from appctl_daemon import ( + DEFAULT_SOCKET_PATH, + send_daemon_request, +) + + +def resolve_token(cli_token: str | None = None) -> str | None: + """Resolve Bearer token from CLI flag, environment, or user token files.""" + if cli_token: + return cli_token.strip() + + if "APPCTL_TOKEN" in os.environ: + return os.environ["APPCTL_TOKEN"].strip() + + token_candidates = [ + Path.home() / ".config/homelab/token", + Path("/run/secrets/appctl/token"), + ] + for path in token_candidates: + if path.is_file(): + try: + return path.read_text(encoding="utf-8").strip() + except OSError: + continue + + return None + + +def format_response(resp: OperationResponse, raw_json: bool = False) -> str: + """Format an OperationResponse for human-friendly terminal display or JSON output.""" + if raw_json: + return resp.model_dump_json(indent=2, exclude_none=True) + + if not resp.success: + err_msg = resp.error.message if resp.error else "Unknown error" + code = f" [{resp.error.code.value}]" if resp.error else "" + return f"❌ Error{code}: {err_msg}" + + # If the engine produced terminal output (e.g. logs, compose config, status table), show it + if resp.output: + return resp.output + + if resp.result: + if "message" in resp.result and len(resp.result) <= 3: + return f"✨ {resp.result['message']}" + return json.dumps(resp.result, indent=2) + + return f"✨ Operation '{resp.operation}' succeeded." + + +def run_cli(argv: list[str] | None = None) -> int: + """Main CLI command parser and dispatcher.""" + common_parser = argparse.ArgumentParser(add_help=False) + common_parser.add_argument( + "--socket", + type=Path, + default=None, + help="Path to appctl Unix domain socket", + ) + common_parser.add_argument( + "--token", + type=str, + default=None, + help="Bearer token secret (overrides APPCTL_TOKEN and token files)", + ) + common_parser.add_argument( + "--json", + action="store_true", + help="Output raw JSON response", + ) + + parser = argparse.ArgumentParser( + prog="appctl", + description="Homelab Unified Control Plane Client", + parents=[common_parser], + ) + + subparsers = parser.add_subparsers(dest="command", help="Operational commands") + + # list / status + list_p = subparsers.add_parser("list", aliases=["status"], parents=[common_parser], help="List workloads") + list_p.add_argument("--core", action="store_true", help="Include core platform services") + list_p.add_argument("--fetch", action="store_true", help="Fetch remote git revisions") + list_p.add_argument("--ssl", action="store_true", help="Check SSL certificate status") + + # info + info_p = subparsers.add_parser("info", parents=[common_parser], help="Get workload metadata") + info_p.add_argument("target", help="Workload name") + info_p.add_argument("--ssl", action="store_true", help="Check SSL certificate status") + + # ssl + ssl_p = subparsers.add_parser("ssl", parents=[common_parser], help="Inspect platform SSL certificates") + ssl_p.add_argument("target", nargs="?", default=None, help="Target workload or platform") + + # health + subparsers.add_parser("health", parents=[common_parser], help="Check control plane daemon health") + + # up / deploy + up_p = subparsers.add_parser("up", aliases=["deploy"], parents=[common_parser], help="Deploy workload") + up_p.add_argument("target", help="Workload or core target") + up_p.add_argument("--build", action="store_true", help="Rebuild container images") + + # down / stop + down_p = subparsers.add_parser("down", aliases=["stop"], parents=[common_parser], help="Stop workload") + down_p.add_argument("target", help="Workload or core target") + + # restart + restart_p = subparsers.add_parser("restart", parents=[common_parser], help="Restart workload") + restart_p.add_argument("target", help="Workload or core target") + + # update + update_p = subparsers.add_parser("update", parents=[common_parser], help="Update workload revision") + update_p.add_argument("target", help="Workload target") + update_p.add_argument("--branch", default=None, help="Expected git branch") + + # pull + pull_p = subparsers.add_parser("pull", parents=[common_parser], help="Pull workload images") + pull_p.add_argument("target", help="Workload target") + + # logs + logs_p = subparsers.add_parser("logs", parents=[common_parser], help="View workload logs") + logs_p.add_argument("target", help="Workload target") + logs_p.add_argument("--tail", type=int, default=100, help="Number of log lines") + + # config + config_p = subparsers.add_parser("config", parents=[common_parser], help="View workload compose config") + config_p.add_argument("target", help="Workload target") + + # sync + subparsers.add_parser("sync", parents=[common_parser], help="Synchronize Homepage services.yaml") + + parsed, _ = parser.parse_known_args(argv) + + if not parsed.command: + parser.print_help() + return 1 + + token = resolve_token(parsed.token) + socket_path = parsed.socket or Path(os.environ.get("APPCTL_SOCKET_PATH", DEFAULT_SOCKET_PATH)) + + # Map command to OperationRequest + op_req: OperationRequest + cmd = parsed.command + + if cmd in ("list", "status"): + params: dict[str, Any] = { + "core": getattr(parsed, "core", False), + "fetch": getattr(parsed, "fetch", False), + "ssl": getattr(parsed, "ssl", False), + } + op_req = OperationRequest(operation=OperationType.WORKLOAD_LIST, parameters=params) + elif cmd == "info": + op_req = OperationRequest( + operation=OperationType.WORKLOAD_GET, + target=parsed.target, + parameters={"ssl": getattr(parsed, "ssl", False)}, + ) + elif cmd == "ssl": + op_req = OperationRequest( + operation=OperationType.PLATFORM_SSL, + target=parsed.target, + ) + elif cmd == "health": + op_req = OperationRequest(operation=OperationType.PLATFORM_HEALTH) + elif cmd in ("up", "deploy"): + op_req = OperationRequest( + operation=OperationType.WORKLOAD_DEPLOY, + target=parsed.target, + parameters={"build": getattr(parsed, "build", False)}, + ) + elif cmd in ("down", "stop"): + op_req = OperationRequest( + operation=OperationType.WORKLOAD_STOP, + target=parsed.target, + ) + elif cmd == "restart": + op_req = OperationRequest( + operation=OperationType.WORKLOAD_RESTART, + target=parsed.target, + ) + elif cmd == "update": + params = {} + if getattr(parsed, "branch", None): + params["expected_branch"] = parsed.branch + op_req = OperationRequest( + operation=OperationType.WORKLOAD_UPDATE, + target=parsed.target, + parameters=params, + ) + elif cmd == "pull": + op_req = OperationRequest( + operation=OperationType.WORKLOAD_PULL, + target=parsed.target, + ) + elif cmd == "logs": + op_req = OperationRequest( + operation=OperationType.WORKLOAD_LOGS, + target=parsed.target, + parameters={"tail": getattr(parsed, "tail", 100)}, + ) + elif cmd == "config": + op_req = OperationRequest( + operation=OperationType.WORKLOAD_CONFIG, + target=parsed.target, + ) + elif cmd == "sync": + op_req = OperationRequest(operation=OperationType.PLATFORM_SYNC_HOMEPAGE) + else: + print(f"❌ Unknown command '{cmd}'", file=sys.stderr) + return 1 + + try: + resp = send_daemon_request( + endpoint=socket_path, + operation_request=op_req, + token=token, + timeout=330.0, + ) + print(format_response(resp, raw_json=parsed.json)) + return 0 if resp.success else 1 + except FileNotFoundError: + print(f"❌ Error: appctl daemon socket not found at {socket_path}", file=sys.stderr) + return 1 + except ConnectionRefusedError: + print(f"❌ Error: appctl daemon is not accepting connections at {socket_path}", file=sys.stderr) + return 1 + except ( + OSError, + json.JSONDecodeError, + TimeoutError, + ValueError, + ) as e: + print(f"❌ Error: Failed to communicate with appctl daemon: {e}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(run_cli()) diff --git a/tests/unit/test_appctl_cli.py b/tests/unit/test_appctl_cli.py new file mode 100644 index 0000000..8093190 --- /dev/null +++ b/tests/unit/test_appctl_cli.py @@ -0,0 +1,115 @@ +""" +test_appctl_cli.py — Unit Tests for Thin UDS Client (scripts/appctl_cli.py) +""" + +from __future__ import annotations + +import io +from pathlib import Path +from unittest.mock import patch + +from appctl_cli import format_response, resolve_token, run_cli +from appctl_contracts import ( + ErrorCode, + OperationError, + OperationRequest, + OperationResponse, + OperationType, +) + + +def test_cli_token_resolution(tmp_path: Path, monkeypatch): + """Ensure token resolution checks CLI flag, environment, and config file.""" + # 1. Direct CLI argument precedence + assert resolve_token("explicit-secret") == "explicit-secret" + + # 2. Environment variable precedence + monkeypatch.setenv("APPCTL_TOKEN", "env-secret") + assert resolve_token(None) == "env-secret" + + # 3. File fallback + monkeypatch.delenv("APPCTL_TOKEN", raising=False) + cfg_token = tmp_path / "token" + cfg_token.write_text("file-secret\n", encoding="utf-8") + with patch("pathlib.Path.home", return_value=tmp_path): + dot_config = tmp_path / ".config" / "homelab" + dot_config.mkdir(parents=True) + (dot_config / "token").write_text("user-file-secret\n", encoding="utf-8") + assert resolve_token(None) == "user-file-secret" + + +def test_cli_format_response_success_and_error(): + """Ensure response formatter produces human-friendly strings and JSON.""" + success_resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_123", + operation=OperationType.WORKLOAD_DEPLOY, + output="Container started successfully", + ) + formatted = format_response(success_resp, raw_json=False) + assert "Container started successfully" in formatted + + raw_json = format_response(success_resp, raw_json=True) + assert '"operation": "workload.deploy"' in raw_json + assert '"success": true' in raw_json + + error_resp = OperationResponse( + version="1.0", + success=False, + operation_id="op_456", + operation=OperationType.WORKLOAD_DEPLOY, + error=OperationError(code=ErrorCode.ERR_PERMISSION_DENIED, message="Forbidden"), + ) + formatted_err = format_response(error_resp, raw_json=False) + assert "❌ Error [ERR_PERMISSION_DENIED]: Forbidden" in formatted_err + + +def test_cli_dispatches_list_command(): + """Ensure appctl list dispatches OperationRequest(workload.list).""" + mock_resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_001", + operation=OperationType.WORKLOAD_LIST, + output="NAME STATUS\ndocs running\n", + ) + + with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO) as mock_stdout: + ret = run_cli(["list", "--core"]) + assert ret == 0 + assert mock_send.call_count == 1 + req: OperationRequest = mock_send.call_args[1]["operation_request"] + assert req.operation == OperationType.WORKLOAD_LIST + assert req.parameters["core"] is True + assert "NAME STATUS" in mock_stdout.getvalue() + + +def test_cli_dispatches_mutation_command(): + """Ensure appctl up dispatches OperationRequest(workload.deploy).""" + mock_resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_002", + operation=OperationType.WORKLOAD_DEPLOY, + target="jellyfin", + result={"action": "deployed", "message": "Workload deployed"}, + ) + + with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO) as mock_stdout: + ret = run_cli(["up", "jellyfin", "--token", "tok_secret"]) + assert ret == 0 + assert mock_send.call_count == 1 + assert mock_send.call_args[1]["token"] == "tok_secret" + req: OperationRequest = mock_send.call_args[1]["operation_request"] + assert req.operation == OperationType.WORKLOAD_DEPLOY + assert req.target == "jellyfin" + assert "Workload deployed" in mock_stdout.getvalue() + + +def test_cli_handles_missing_socket(): + """Ensure friendly stderr message when socket is absent.""" + with patch("appctl_cli.send_daemon_request", side_effect=FileNotFoundError), patch("sys.stderr", new_callable=io.StringIO) as mock_stderr: + ret = run_cli(["list", "--socket", "/nonexistent/appctl.sock"]) + assert ret == 1 + assert "socket not found" in mock_stderr.getvalue() diff --git a/todo.txt b/todo.txt index fa8b3a6..5f99cb6 100644 --- a/todo.txt +++ b/todo.txt @@ -28,5 +28,5 @@ x 2026-10-19 (A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERC x 2026-10-19 (B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4 x 2026-10-19 (B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) and wire gitops_dispatcher.py worker to daemon in scripts/appctl_daemon.py +daemon @p4 x 2026-10-19 (B) Add comprehensive unit and security test suite for P4 contracts, RBAC, audit guard, concurrency, and dual-transport parity in tests/unit/test_appctl_daemon.py +test @p4 -(C) Re-implement scripts/appctl as a thin UDS HTTP client and declare homelab-appctl.service with POSIX ACLs in nixos/modules/homeserver.nix +cli @p4 +x 2026-10-19 (C) Re-implement scripts/appctl as a thin UDS HTTP client and declare homelab-appctl.service with POSIX ACLs in nixos/modules/homeserver.nix +cli @p4 (C) Scrub remaining hardcoded domain and username literals across NixOS modules, Compose stack, and config/deployments.yaml and add pyright to flake.nix checks +generic @core From 8cc06e24707882ef6190e0789e49026b80034426 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 13:59:18 -0500 Subject: [PATCH 09/43] chore(core): scrub personal domain/username literals and enforce pyright in flake checks --- .githooks/pre-commit | 12 ++- config/authelia/configuration.yml | 4 +- config/deployments.yaml | 20 ++--- config/homepage/bookmarks.yaml | 2 +- config/homepage/services.yaml.example | 6 +- docker-compose.yml | 10 +-- flake.nix | 2 + nixos/configuration.nix | 5 +- nixos/modules/dynu.nix | 2 +- nixos/modules/homeserver.nix | 94 ++++++++++++++-------- nixos/modules/traefik-deployments.nix | 34 ++++---- scripts/gitops_dispatcher.py | 6 +- tests/security/test_security_invariants.py | 9 ++- tests/unit/test_appctl_engine.py | 4 +- todo.txt | 2 +- 15 files changed, 132 insertions(+), 80 deletions(-) diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 0b4ac43..c30abf3 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -21,7 +21,17 @@ else echo "⚠️ [pre-commit] Neither ruff nor nix found; skipping ruff" fi -# 2. Run Pytest Suite +# 2. Run Pyright Type Checker +echo " ↳ Checking static types with Pyright..." +if command -v pyright >/dev/null 2>&1; then + pyright +elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then + nix develop --command pyright +else + echo "⚠️ [pre-commit] Neither pyright nor nix found; skipping pyright" +fi + +# 3. Run Pytest Suite echo " ↳ Running structural and security test suite with Pytest..." if [ -x ".venv/bin/pytest" ]; then .venv/bin/pytest tests/ diff --git a/config/authelia/configuration.yml b/config/authelia/configuration.yml index 6a13087..d9348e4 100644 --- a/config/authelia/configuration.yml +++ b/config/authelia/configuration.yml @@ -13,7 +13,7 @@ authentication_backend: address: 'ldap://lldap:3890' timeout: 5s start_tls: false - base_dn: 'dc=roadtotech,dc=me' + base_dn: '{{ env "LLDAP_LDAP_BASE_DN" "dc=example,dc=test" }}' additional_users_dn: 'ou=people' users_filter: '(&({username_attribute}={input})(objectClass=person))' additional_groups_dn: 'ou=groups' @@ -24,7 +24,7 @@ authentication_backend: display_name: 'displayName' mail: 'mail' group_name: 'cn' - user: 'uid=admin,ou=people,dc=roadtotech,dc=me' + user: 'uid=admin,ou=people,{{ env "LLDAP_LDAP_BASE_DN" "dc=example,dc=test" }}' access_control: default_policy: deny diff --git a/config/deployments.yaml b/config/deployments.yaml index e473ef5..5337311 100644 --- a/config/deployments.yaml +++ b/config/deployments.yaml @@ -6,48 +6,48 @@ schemaVersion: "1.0" repositories: snappymail: - path: "/home/kiskaadee/Sites/snappymail" + path: "~/Sites/snappymail" aliases: - "homelab-snappymail" - "mail" - "webmail" gitea: - path: "/home/kiskaadee/Sites/homelab-gitea" + path: "~/Sites/homelab-gitea" aliases: - "homelab-gitea" - "git" jellyfin: - path: "/home/kiskaadee/Sites/homelab-jellyfin" + path: "~/Sites/homelab-jellyfin" aliases: - "homelab-jellyfin" - "media" docs: - path: "/home/kiskaadee/Sites/homelab-doc2site" + path: "~/Sites/homelab-doc2site" aliases: - "doc2site" - "homelab-doc2site" courses: - path: "/home/kiskaadee/Sites/courses" + path: "~/Sites/courses" aliases: - "homelab-courses" bdinvite: - path: "/home/kiskaadee/Sites/homelab-bdinvite" + path: "~/Sites/homelab-bdinvite" aliases: - "homelab-bdinvite" - "birthday" landing: - path: "/home/kiskaadee/Sites/homelab-landing" + path: "~/Sites/homelab-landing" aliases: - "homelab-landing" mermaid: - path: "/home/kiskaadee/Sites/homelab-mermaid" + path: "~/Sites/homelab-mermaid" aliases: - "homelab-mermaid" excalidraw: - path: "/home/kiskaadee/Sites/homelab-excalidraw" + path: "~/Sites/homelab-excalidraw" aliases: - "homelab-excalidraw" houston: - path: "/home/kiskaadee/Sites/homelab-houston" + path: "~/Sites/homelab-houston" aliases: - "homelab-houston" diff --git a/config/homepage/bookmarks.yaml b/config/homepage/bookmarks.yaml index 91f51fb..decb7d4 100644 --- a/config/homepage/bookmarks.yaml +++ b/config/homepage/bookmarks.yaml @@ -5,7 +5,7 @@ - My Projects: - Github: - abbr: GH - href: https://github.com/kiskaadee?tab=repositories + href: https://github.com - Social Media: - Instagram: diff --git a/config/homepage/services.yaml.example b/config/homepage/services.yaml.example index 705e565..809c8fc 100644 --- a/config/homepage/services.yaml.example +++ b/config/homepage/services.yaml.example @@ -4,13 +4,13 @@ - Knowledge & Notes: - Docs-Viewer: icon: files.png - href: https://docs.roadtotech.me + href: https://docs.example.test description: Reactive Obsidian & Markdown Documentation Viewer server: my-docker container: docs - Excalidraw: icon: excalidraw.png - href: https://excalidraw.roadtotech.me + href: https://excalidraw.example.test description: Collaborative Whiteboarding & Sketching Tool server: my-docker container: excalidraw @@ -18,7 +18,7 @@ - Media & Productivity: - Jellyfin: icon: jellyfin.png - href: https://jellyfin.roadtotech.me + href: https://jellyfin.example.test description: Media Server & Streaming Hub server: my-docker container: jellyfin diff --git a/docker-compose.yml b/docker-compose.yml index 3dfc7f5..28c134f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -106,11 +106,11 @@ services: environment: - TZ=America/Bogota - LLDAP_HTTP_URL=https://users.${DOMAIN} - - LLDAP_LDAP_BASE_DN=dc=roadtotech,dc=me + - LLDAP_LDAP_BASE_DN=${LLDAP_LDAP_BASE_DN:-dc=example,dc=test} - LLDAP_JWT_SECRET=${LLDAP_JWT_SECRET} - LLDAP_KEY_SEED=${LLDAP_KEY_SEED} - LLDAP_LDAP_USER_PASS=${LLDAP_LDAP_USER_PASS} - - LLDAP_LDAP_USER_EMAIL=admin@${DOMAIN:-roadtotech.me} + - LLDAP_LDAP_USER_EMAIL=${LLDAP_ADMIN_EMAIL:-admin@${DOMAIN:-example.test}} - LLDAP_DATABASE_URL=sqlite:///data/users.db?mode=rwc volumes: - ./config/lldap/data:/data @@ -222,12 +222,12 @@ services: - DIUN_PROVIDERS_DOCKER_APIVERSION=${DOCKER_API_VERSION:-1.40} - DIUN_NOTIF_MAIL_HOST=stalwart - DIUN_NOTIF_MAIL_PORT=465 - - DIUN_NOTIF_MAIL_USERNAME=notifier@${DOMAIN:-roadtotech.me} + - DIUN_NOTIF_MAIL_USERNAME=${DIUN_NOTIF_MAIL_USERNAME:-notifier@${DOMAIN:-example.test}} - DIUN_NOTIF_MAIL_PASSWORD=${DIUN_SMTP_PASSWORD} - DIUN_NOTIF_MAIL_SSL=true - DIUN_NOTIF_MAIL_INSECURESKIPVERIFY=true - - DIUN_NOTIF_MAIL_FROM=notifier@${DOMAIN:-roadtotech.me} - - DIUN_NOTIF_MAIL_TO=kiskaadee@${DOMAIN:-roadtotech.me} + - DIUN_NOTIF_MAIL_FROM=${DIUN_NOTIF_MAIL_FROM:-notifier@${DOMAIN:-example.test}} + - DIUN_NOTIF_MAIL_TO=${DIUN_NOTIF_MAIL_TO:-operator@${DOMAIN:-example.test}} volumes: - ./config/diun:/data networks: diff --git a/flake.nix b/flake.nix index 099373c..09e6bc9 100644 --- a/flake.nix +++ b/flake.nix @@ -52,6 +52,7 @@ git pythonEnv ruff + pyright ]; } '' mkdir -p $out @@ -59,6 +60,7 @@ chmod -R u+w source cd source HOME=/tmp ruff check --no-cache . + HOME=/tmp pyright HOME=/tmp pytest -o cache_dir=/tmp/.pytest_cache tests/ ''; }; diff --git a/nixos/configuration.nix b/nixos/configuration.nix index f85e529..afb0cdb 100644 --- a/nixos/configuration.nix +++ b/nixos/configuration.nix @@ -1,5 +1,5 @@ # 🌐 Server NixOS Configuration — Turnkey Headless Homelab Appliance -# Standalone declarative configuration for the roadtotech.me homelab server. +# Standalone declarative configuration for the homelab server. # No Home Manager. No shared desktop modules. # Goal: wipe & restore from any NixOS installation via `nixos-install --flake ~/Core#server` @@ -14,6 +14,9 @@ ./modules/shell.nix # Declarative bash environment for the server ]; + # ── Homelab platform settings ──────────────────────────────────────────────── + homelab.operatorUser = "kiskaadee"; + # ── SOPS secrets configuration ────────────────────────────────────────────── # Set once here to avoid duplicate-option conflicts across submodules sops.defaultSopsFile = ./secrets.yaml; diff --git a/nixos/modules/dynu.nix b/nixos/modules/dynu.nix index 9574e51..998884e 100644 --- a/nixos/modules/dynu.nix +++ b/nixos/modules/dynu.nix @@ -15,7 +15,7 @@ in sops.secrets."dynu/domain" = { }; sops.secrets."dynu/password" = { }; sops.secrets."system/pdf_decrypt_password" = { - owner = "kiskaadee"; + owner = config.homelab.operatorUser; }; # Assemble the ddclient config file securely at boot time in /run/secrets/ diff --git a/nixos/modules/homeserver.nix b/nixos/modules/homeserver.nix index c52b868..b7983b9 100644 --- a/nixos/modules/homeserver.nix +++ b/nixos/modules/homeserver.nix @@ -4,8 +4,33 @@ { config, lib, pkgs, ... }: { - # Define the keys to decrypt from secrets.yaml - sops.secrets = lib.genAttrs [ + # Declarative configuration options for Homelab Core + options.homelab = { + domain = lib.mkOption { + type = lib.types.str; + default = "example.test"; + description = "Canonical domain for homelab services"; + }; + operatorUser = lib.mkOption { + type = lib.types.str; + default = "operator"; + description = "Primary operator user identity"; + }; + coreDir = lib.mkOption { + type = lib.types.str; + default = "/home/${config.homelab.operatorUser}/Core"; + description = "Path to Homelab Core repository"; + }; + sitesDir = lib.mkOption { + type = lib.types.str; + default = "/home/${config.homelab.operatorUser}/Sites"; + description = "Path to Sites directory"; + }; + }; + + config = { + # Define the keys to decrypt from secrets.yaml + sops.secrets = lib.genAttrs [ "dynu/api_key" "traefik/acme_email" "authelia/session_secret" @@ -18,13 +43,13 @@ "brevo/smtp_login" "brevo/smtp_key" "diun/smtp_password" - ] (name: { owner = "kiskaadee"; }); + ] (name: { owner = config.homelab.operatorUser; }); # Generate the unified environment file at runtime in /run/secrets/homeserver.env sops.templates."homeserver.env" = { - owner = "kiskaadee"; + owner = config.homelab.operatorUser; content = lib.generators.toKeyValue {} { - DOMAIN = "roadtotech.me"; + DOMAIN = config.homelab.domain; DOCKER_API_VERSION = "1.40"; DYNU_API_KEY = config.sops.placeholder."dynu/api_key"; ACME_EMAIL = config.sops.placeholder."traefik/acme_email"; @@ -53,7 +78,7 @@ serviceConfig = { Type = "oneshot"; RemainAfterExit = true; - WorkingDirectory = "/home/kiskaadee/Core"; + WorkingDirectory = config.homelab.coreDir; ExecStart = "${pkgs.docker-compose}/bin/docker-compose --env-file ${config.sops.templates."homeserver.env".path} up -d --remove-orphans"; ExecStop = "${pkgs.docker-compose}/bin/docker-compose down"; }; @@ -78,24 +103,24 @@ environment = { GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path; - DOCKER_CONFIG = "/home/kiskaadee/.local/state/homelab/docker"; + DOCKER_CONFIG = "/home/${config.homelab.operatorUser}/.local/state/homelab/docker"; }; serviceConfig = { Type = "simple"; - User = "kiskaadee"; + User = config.homelab.operatorUser; SupplementaryGroups = [ "docker" ]; - WorkingDirectory = "/home/kiskaadee/Core"; + WorkingDirectory = config.homelab.coreDir; ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [ { id = "deploy"; - execute-command = "/home/kiskaadee/Core/scripts/gitops_dispatcher.py"; + execute-command = "${config.homelab.coreDir}/scripts/gitops_dispatcher.py"; pass-arguments-to-command = [ { source = "raw-request-body"; } { source = "header"; name = "X-Gitea-Signature"; } { source = "header"; name = "X-Gitea-Event"; } ]; - command-working-directory = "/home/kiskaadee/Core"; + command-working-directory = config.homelab.coreDir; response-message = "Deployment payload dispatched successfully."; } ])} -port 9000 -verbose"; @@ -110,8 +135,8 @@ ProtectKernelTunables = true; ProtectControlGroups = true; ReadWritePaths = [ - "/home/kiskaadee/Sites" - "/home/kiskaadee/.local/state/homelab" + config.homelab.sitesDir + "/home/${config.homelab.operatorUser}/.local/state/homelab" ]; }; }; @@ -149,10 +174,10 @@ APPCTL_AUDIT_LOG = "/var/log/homelab/appctl/audit.jsonl"; APPCTL_LOCK_DIR = "/var/lib/homelab/appctl/locks"; APPCTL_TOKENS_FILE = "/run/secrets/appctl/tokens.json"; - SITES_DIR = "/home/kiskaadee/Sites"; - CORE_DIR = "/home/kiskaadee/Core"; - HOMELAB_CONFIG_DIR = "/home/kiskaadee/.config/homelab"; - HOMELAB_DEPLOYMENTS_FILE = "/home/kiskaadee/Core/config/deployments.yaml"; + SITES_DIR = config.homelab.sitesDir; + CORE_DIR = config.homelab.coreDir; + HOMELAB_CONFIG_DIR = "/home/${config.homelab.operatorUser}/.config/homelab"; + HOMELAB_DEPLOYMENTS_FILE = "${config.homelab.coreDir}/config/deployments.yaml"; }; serviceConfig = { @@ -160,8 +185,8 @@ User = "homelab-appctl"; Group = "homelab-operators"; SupplementaryGroups = [ "docker" ]; - WorkingDirectory = "/home/kiskaadee/Core"; - ExecStart = "${(pkgs.python3.withPackages (ps: with ps; [ pyyaml pydantic ]))}/bin/python3 /home/kiskaadee/Core/scripts/appctl_daemon.py"; + WorkingDirectory = config.homelab.coreDir; + ExecStart = "${(pkgs.python3.withPackages (ps: with ps; [ pyyaml pydantic ]))}/bin/python3 ${config.homelab.coreDir}/scripts/appctl_daemon.py"; Restart = "always"; RestartSec = "5s"; @@ -179,9 +204,9 @@ ProtectKernelTunables = true; ProtectControlGroups = true; ReadWritePaths = [ - "/home/kiskaadee/Sites" - "/home/kiskaadee/var/lib/homelab" - "/home/kiskaadee/Core/config/homepage" + config.homelab.sitesDir + "/home/${config.homelab.operatorUser}/var/lib/homelab" + "${config.homelab.coreDir}/config/homepage" "/var/log/homelab/appctl" "/var/lib/homelab/appctl" "/run/homelab" @@ -191,19 +216,20 @@ # Ensure persistent directories have proper permissions for container runtimes systemd.tmpfiles.rules = [ - "d /home/kiskaadee/Core/config/stalwart/data 0777 kiskaadee users -" - "d /home/kiskaadee/Core/config/stalwart/etc 0777 kiskaadee users -" - "d /home/kiskaadee/Sites 0755 kiskaadee users -" - "d /home/kiskaadee/.local/state/homelab/gitops 0755 kiskaadee users -" - "d /home/kiskaadee/.local/state/homelab/docker 0755 kiskaadee users -" + "d ${config.homelab.coreDir}/config/stalwart/data 0777 ${config.homelab.operatorUser} users -" + "d ${config.homelab.coreDir}/config/stalwart/etc 0777 ${config.homelab.operatorUser} users -" + "d ${config.homelab.sitesDir} 0755 ${config.homelab.operatorUser} users -" + "d /home/${config.homelab.operatorUser}/.local/state/homelab/gitops 0755 ${config.homelab.operatorUser} users -" + "d /home/${config.homelab.operatorUser}/.local/state/homelab/docker 0755 ${config.homelab.operatorUser} users -" # POSIX ACLs granting homelab-appctl traverse and access to operator sites & homepage config - "a+ /home/kiskaadee - - - - u:homelab-appctl:x" - "a+ /home/kiskaadee/Core - - - - u:homelab-appctl:x" - "a+ /home/kiskaadee/Sites - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" - "a+ /home/kiskaadee/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" - "a+ /home/kiskaadee/Core/config/homepage - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" + "a+ /home/${config.homelab.operatorUser} - - - - u:homelab-appctl:x" + "a+ ${config.homelab.coreDir} - - - - u:homelab-appctl:x" + "a+ ${config.homelab.sitesDir} - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" + "a+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" + "a+ ${config.homelab.coreDir}/config/homepage - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" ]; - # Open ports in the firewall for Traefik, Gitea SSH, GitOps Webhook Receiver, and Mail (SMTP, Submission, SMTPS, IMAPS, ManageSieve) - networking.firewall.allowedTCPPorts = [ 80 443 2223 9000 25 465 587 993 4190 ]; + # Open ports in the firewall for Traefik, Gitea SSH, GitOps Webhook Receiver, and Mail (SMTP, Submission, SMTPS, IMAPS, ManageSieve) + networking.firewall.allowedTCPPorts = [ 80 443 2223 9000 25 465 587 993 4190 ]; + }; } diff --git a/nixos/modules/traefik-deployments.nix b/nixos/modules/traefik-deployments.nix index 795ef4b..66b0b6a 100644 --- a/nixos/modules/traefik-deployments.nix +++ b/nixos/modules/traefik-deployments.nix @@ -15,31 +15,31 @@ "postgres/password" "postgres/db" "gitea/runner_token" - ] (name: { owner = "kiskaadee"; }); + ] (name: { owner = config.homelab.operatorUser; }); # Generate the unified environment file at runtime in /run/secrets/traefik-deployments.env sops.templates."traefik-deployments.env" = { - owner = "kiskaadee"; + owner = config.homelab.operatorUser; content = lib.generators.toKeyValue {} { # --- Core / Infrastructure Settings --- PROXY_NETWORK = "proxy-net"; CERT_RESOLVER = "myresolver"; - DOMAIN_SUFFIX = "roadtotech.me"; + DOMAIN_SUFFIX = config.homelab.domain; # --- Dashboard & Landing --- - DASHBOARD_DOMAIN = "dashboard.roadtotech.me"; - LANDING_DOMAIN = "roadtotech.me"; + DASHBOARD_DOMAIN = "dashboard.${config.homelab.domain}"; + LANDING_DOMAIN = config.homelab.domain; # --- Docs --- - DOCS_DOMAIN = "docs.roadtotech.me"; - DOCS_PROJECT_PATH = "/home/kiskaadee/Brain"; + DOCS_DOMAIN = "docs.${config.homelab.domain}"; + DOCS_PROJECT_PATH = "/home/${config.homelab.operatorUser}/Brain"; # --- Excalidraw --- - EXCALIDRAW_DOMAIN = "excalidraw.roadtotech.me"; + EXCALIDRAW_DOMAIN = "excalidraw.${config.homelab.domain}"; # --- Gitea --- - GITEA_DOMAIN = "gitea.roadtotech.me"; - GITEA_SSH_DOMAIN = "gitea.roadtotech.me"; + GITEA_DOMAIN = "gitea.${config.homelab.domain}"; + GITEA_SSH_DOMAIN = "gitea.${config.homelab.domain}"; GITEA_SSH_PORT = "2223"; GITEA_AUTH_MIDDLEWARE = "https-redirect@docker"; GITEA_RUNNER_TOKEN = config.sops.placeholder."gitea/runner_token"; @@ -48,7 +48,7 @@ JELLYFIN_SERVICE_NAME = "jellyfin"; JELLYFIN_CONTAINER_NAME = "jellyfin"; JELLYFIN_IMAGE_TAG = "latest"; - JELLYFIN_DOMAIN = "jellyfin.roadtotech.me"; + JELLYFIN_DOMAIN = "jellyfin.${config.homelab.domain}"; JELLYFIN_TZ = "UTC"; JELLYFIN_PUID = "1000"; JELLYFIN_PGID = "1000"; @@ -60,7 +60,7 @@ # --- Learning Dashboard --- LEARNING_SERVICE_NAME = "learning-hub"; - LEARNING_DOMAIN = "learning.roadtotech.me"; + LEARNING_DOMAIN = "learning.${config.homelab.domain}"; LEARNING_APP_PORT = "8000"; LEARNING_SOCKET_PROXY_NETWORK = "socket-net"; LEARNING_DOCKER_HOST = "tcp://socket-proxy:2375"; @@ -68,25 +68,25 @@ TURSO_AUTH_TOKEN = config.sops.placeholder."learning/turso_auth_token"; # --- Mermaid --- - MERMAID_DOMAIN = "mermaid.roadtotech.me"; + MERMAID_DOMAIN = "mermaid.${config.homelab.domain}"; MERMAID_SERVICE_NAME = "mermaid"; # --- Minecraft --- - MINECRAFT_DOMAIN = "minecraft.roadtotech.me"; + MINECRAFT_DOMAIN = "minecraft.${config.homelab.domain}"; # --- MongoDB --- MONGO_ROOT_USERNAME = config.sops.placeholder."mongo/root_username"; MONGO_ROOT_PASSWORD = config.sops.placeholder."mongo/root_password"; - MONGO_DOMAIN = "mongodb.roadtotech.me"; + MONGO_DOMAIN = "mongodb.${config.homelab.domain}"; # --- PostgreSQL --- POSTGRES_USER = config.sops.placeholder."postgres/user"; POSTGRES_PASSWORD = config.sops.placeholder."postgres/password"; POSTGRES_DB = config.sops.placeholder."postgres/db"; - POSTGRES_DOMAIN = "pgsql.roadtotech.me"; + POSTGRES_DOMAIN = "pgsql.${config.homelab.domain}"; # --- Ollama --- - OLLAMA_DOMAIN = "ollama.roadtotech.me"; + OLLAMA_DOMAIN = "ollama.${config.homelab.domain}"; OLLAMA_API_KEY = config.sops.placeholder."ollama/api_key"; OLLAMA_REPLICAS = "1"; OLLAMA_DATA_VOLUME = "ollama_data"; diff --git a/scripts/gitops_dispatcher.py b/scripts/gitops_dispatcher.py index c12de90..18e992d 100755 --- a/scripts/gitops_dispatcher.py +++ b/scripts/gitops_dispatcher.py @@ -285,7 +285,11 @@ def get_trusted_repository_mapping() -> dict[str, Path]: raw_path = entry.get("path") if not raw_path: continue - p = Path(raw_path).expanduser().resolve() + if raw_path.startswith("~/Sites/") or raw_path == "~/Sites": + sub = raw_path[len("~/Sites"):].lstrip("/") + p = (SITES_DIR / sub).resolve() if sub else SITES_DIR.resolve() + else: + p = Path(raw_path).expanduser().resolve() # Enforce strict containment strictly inside SITES_DIR if SITES_DIR.is_dir() and p.is_relative_to(SITES_DIR.resolve()): mapping[reg_name] = p diff --git a/tests/security/test_security_invariants.py b/tests/security/test_security_invariants.py index 9cd6c28..f186b90 100644 --- a/tests/security/test_security_invariants.py +++ b/tests/security/test_security_invariants.py @@ -180,13 +180,20 @@ exit 0 def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests(): """Ensure personal domains and operator usernames are absent from scripts, tests, and documentation.""" forbidden = ["roadtotech.me", "kiskaadee"] - root_dirs = [CORE_ROOT / "scripts", CORE_ROOT / "tests", CORE_ROOT / "docs"] + root_dirs = [ + CORE_ROOT / "scripts", + CORE_ROOT / "tests", + CORE_ROOT / "docs", + CORE_ROOT / "nixos" / "modules", + CORE_ROOT / "config", + ] root_files = [ CORE_ROOT / "README.md", CORE_ROOT / "ROADMAP.md", CORE_ROOT / "AGENTS.md", CORE_ROOT / "SECURITY.md", CORE_ROOT / "flake.nix", + CORE_ROOT / "docker-compose.yml", ] violations = [] diff --git a/tests/unit/test_appctl_engine.py b/tests/unit/test_appctl_engine.py index 2666dea..1ec3378 100644 --- a/tests/unit/test_appctl_engine.py +++ b/tests/unit/test_appctl_engine.py @@ -83,7 +83,7 @@ def test_manifest_data_overrides_default_values(app_factory: AppFactory): dir_name="homelab-custom", manifest_yaml=""" name: custom-app - domain: custom.roadtotech.local + domain: custom.example.test auth: false visible: false networks: @@ -95,7 +95,7 @@ def test_manifest_data_overrides_default_values(app_factory: AppFactory): app = engine.resolve_app("custom-app", apps) assert app is not None - assert app.domain == "custom.roadtotech.local" + assert app.domain == "custom.example.test" assert app.auth is False assert app.networks == ["custom-net"] diff --git a/todo.txt b/todo.txt index 5f99cb6..e445404 100644 --- a/todo.txt +++ b/todo.txt @@ -29,4 +29,4 @@ x 2026-10-19 (B) Implement operational router, pure-Python dotenv loader, Compos x 2026-10-19 (B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) and wire gitops_dispatcher.py worker to daemon in scripts/appctl_daemon.py +daemon @p4 x 2026-10-19 (B) Add comprehensive unit and security test suite for P4 contracts, RBAC, audit guard, concurrency, and dual-transport parity in tests/unit/test_appctl_daemon.py +test @p4 x 2026-10-19 (C) Re-implement scripts/appctl as a thin UDS HTTP client and declare homelab-appctl.service with POSIX ACLs in nixos/modules/homeserver.nix +cli @p4 -(C) Scrub remaining hardcoded domain and username literals across NixOS modules, Compose stack, and config/deployments.yaml and add pyright to flake.nix checks +generic @core +x 2026-10-19 (C) Scrub remaining hardcoded domain and username literals across NixOS modules, Compose stack, and config/deployments.yaml and add pyright to flake.nix checks +generic @core From 154cde272bc734eae56f77aea3c06b947226ded8 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 15:25:37 -0500 Subject: [PATCH 10/43] fix(router): enable Core platform stack dispatch and manifest-free orchestration Closes #2 --- scripts/appctl_engine.py | 6 +- scripts/appctl_router.py | 179 ++++++++++++++++----- tests/unit/test_appctl_router.py | 259 +++++++++++++++++++++++++++++++ 3 files changed, 402 insertions(+), 42 deletions(-) diff --git a/scripts/appctl_engine.py b/scripts/appctl_engine.py index cc722f0..76ef831 100755 --- a/scripts/appctl_engine.py +++ b/scripts/appctl_engine.py @@ -347,6 +347,7 @@ def resolve_app( query: str, apps: list[SitesApp] | None = None, sites_dir: str | None = None, + core_dir: str | None = None, ) -> App | None: """ Resolve a query string to a SitesApp or CoreService. @@ -357,6 +358,7 @@ def resolve_app( sites_dir=sites_dir if sites_dir is not None else SITES_DIR ) + c_dir = core_dir if core_dir is not None else CORE_DIR query_clean = query.strip().lower() # 1. Exact match on canonical name @@ -380,7 +382,7 @@ def resolve_app( return app # 5. Match Core services - for svc in get_core_services(): + for svc in get_core_services(core_dir=c_dir): if svc.name.lower() == query_clean: return svc @@ -390,7 +392,7 @@ def resolve_app( domain=HOMELAB_DOMAIN, container="", description="Homelab Core Platform Stack", - dir_path=CORE_DIR, + dir_path=c_dir, app_type="core", ) diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py index 94f2246..4f8c2bf 100644 --- a/scripts/appctl_router.py +++ b/scripts/appctl_router.py @@ -248,6 +248,17 @@ def run_bounded_subprocess( return proc.returncode, stdout_str, stderr_str +def _resolve_compose_file(app_dir: Path) -> Path: + """Resolve docker-compose.yml or docker-compose.yaml inside app_dir.""" + yml = app_dir / "docker-compose.yml" + yaml_ext = app_dir / "docker-compose.yaml" + if yml.is_file(): + return yml + if yaml_ext.is_file(): + return yaml_ext + return yml + + def validate_workload_preflight( app_dir: Path, allowed_root: Path, @@ -279,7 +290,7 @@ def validate_workload_preflight( raise RouterValidationError(f"Workload manifest validation failed: {err}") from err effective_name = app_name or manifest.name - compose_file = app_dir / "docker-compose.yml" + compose_file = _resolve_compose_file(app_dir) if compose_file.exists(): ok, reason = validate_compose_security( compose_file=compose_file, @@ -294,6 +305,34 @@ def validate_workload_preflight( return manifest, compose_file +def validate_core_preflight( + app_dir: Path, + core_dir: Path, +) -> Path: + """ + Enforce pre-flight gate for Core platform targets (core / core_service): + 1. Target directory must resolve strictly to core_dir. + 2. Core docker-compose.yml must exist as a regular file inside core_dir. + """ + app_dir_resolved = app_dir.resolve() + core_dir_resolved = core_dir.resolve() + if app_dir_resolved != core_dir_resolved: + raise RouterValidationError( + f"Path traversal rejected: Core target directory '{app_dir}' does not match '{core_dir}'" + ) + + compose_file = _resolve_compose_file(app_dir) + if not compose_file.is_file(): + raise RouterValidationError(f"Core compose file not found at '{compose_file}'") + + if compose_file.is_symlink() and not compose_file.resolve().is_relative_to(core_dir_resolved): + raise RouterValidationError( + f"Core compose file symlink escapes Core root: '{compose_file}'" + ) + + return compose_file + + class OperationalRouter: """Executes validated domain operations according to P4 boundaries and contracts.""" @@ -309,6 +348,37 @@ class OperationalRouter: self.sites_dir = Path(sites_dir or ENGINE_SITES_DIR) self.core_dir = Path(core_dir or ENGINE_CORE_DIR) + @staticmethod + def _is_core_target(app: Any) -> bool: + return getattr(app, "app_type", "app") in ("core", "core_service") + + @staticmethod + def _target_container(app: Any) -> str: + if getattr(app, "app_type", "app") == "core_service": + container = getattr(app, "container", "") + return str(container).strip() if isinstance(container, str) else "" + return "" + + def _prepare_target_context( + self, app: Any + ) -> tuple[Path, Manifest | None, Path, dict[str, str], str]: + """ + Validate pre-flight boundaries and assemble environment for either a Core + target (core / core_service) or a Sites workload (app). + Returns (app_dir, manifest, compose_file, env, container_name). + """ + app_dir = Path(app.dir_path) + if self._is_core_target(app): + compose_file = validate_core_preflight(app_dir, self.core_dir) + manifest = None + else: + manifest, compose_file = validate_workload_preflight( + app_dir, self.sites_dir, app.name + ) + env = assemble_workload_env(app_dir, manifest, app.name) + container = self._target_container(app) + return app_dir, manifest, compose_file, env, container + def dispatch( self, request: OperationRequest, @@ -375,7 +445,11 @@ class OperationalRouter: message=f"Operation '{operation.value}' requires a non-empty target", ), ) - resolved_app = resolve_app(target, sites_dir=str(self.sites_dir)) + resolved_app = resolve_app( + target, + sites_dir=str(self.sites_dir), + core_dir=str(self.core_dir), + ) if not resolved_app: return OperationResponse( version="1.0", @@ -619,9 +693,7 @@ class OperationalRouter: } def _op_workload_config(self, app: Any, principal: Principal) -> dict[str, Any]: - app_dir = Path(app.dir_path) - manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) - env = assemble_workload_env(app_dir, manifest, app.name) + app_dir, _, compose_file, env, _ = self._prepare_target_context(app) cmd = ["docker", "compose", "-f", str(compose_file), "config"] code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0) @@ -638,9 +710,7 @@ class OperationalRouter: def _op_workload_logs(self, request: OperationRequest, app: Any) -> dict[str, Any]: params = request.parse_parameters() assert isinstance(params, LogsParams) - app_dir = Path(app.dir_path) - manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) - env = assemble_workload_env(app_dir, manifest, app.name) + app_dir, _, compose_file, env, container = self._prepare_target_context(app) cmd = [ "docker", @@ -652,6 +722,9 @@ class OperationalRouter: "--tail", str(params.tail), ] + if container: + cmd.append(container) + code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0) if code != 0: raise RouterExecutionError(f"docker compose logs failed: {stderr}", exit_code=code) @@ -661,13 +734,14 @@ class OperationalRouter: def _op_workload_deploy(self, request: OperationRequest, app: Any) -> dict[str, Any]: params = request.parse_parameters() assert isinstance(params, DeployParams) - app_dir = Path(app.dir_path) - manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) - env = assemble_workload_env(app_dir, manifest, app.name) + app_dir, _, compose_file, env, container = self._prepare_target_context(app) + is_core = self._is_core_target(app) # Optional build if params.build: build_cmd = ["docker", "compose", "-f", str(compose_file), "build"] + if container: + build_cmd.append(container) code, out, err = run_bounded_subprocess(build_cmd, cwd=app_dir, env=env, timeout=300.0) if code != 0: raise RouterExecutionError(f"docker compose build failed: {err}", exit_code=code) @@ -676,13 +750,16 @@ class OperationalRouter: up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d"] if params.remove_orphans: up_cmd.append("--remove-orphans") + if container: + up_cmd.append(container) code, out, err = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0) if code != 0: raise RouterExecutionError(f"docker compose up failed: {err}", exit_code=code) - # Trigger Homepage sync - self._trigger_homepage_sync() + # Trigger Homepage sync for Sites workloads + if not is_core: + self._trigger_homepage_sync() return { "output": out, @@ -691,47 +768,58 @@ class OperationalRouter: } def _op_workload_stop(self, app: Any) -> dict[str, Any]: - app_dir = Path(app.dir_path) - manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) - env = assemble_workload_env(app_dir, manifest, app.name) + app_dir, _, compose_file, env, container = self._prepare_target_context(app) + is_core = self._is_core_target(app) + + if container: + cmd = ["docker", "compose", "-f", str(compose_file), "stop", container] + else: + cmd = ["docker", "compose", "-f", str(compose_file), "down"] - cmd = ["docker", "compose", "-f", str(compose_file), "down"] code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0) if code != 0: - raise RouterExecutionError(f"docker compose down failed: {err}", exit_code=code) + raise RouterExecutionError(f"docker compose stop/down failed: {err}", exit_code=code) - self._trigger_homepage_sync() + if not is_core: + self._trigger_homepage_sync() return {"output": out, "action": "stopped", "message": f"Workload '{app.name}' stopped"} def _op_workload_restart(self, app: Any) -> dict[str, Any]: - app_dir = Path(app.dir_path) - manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) - env = assemble_workload_env(app_dir, manifest, app.name) + app_dir, _, compose_file, env, container = self._prepare_target_context(app) + is_core = self._is_core_target(app) cmd = ["docker", "compose", "-f", str(compose_file), "restart"] + if container: + cmd.append(container) + code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0) if code != 0: raise RouterExecutionError(f"docker compose restart failed: {err}", exit_code=code) - self._trigger_homepage_sync() + if not is_core: + self._trigger_homepage_sync() return {"output": out, "action": "restarted", "message": f"Workload '{app.name}' restarted"} def _op_workload_pull(self, app: Any) -> dict[str, Any]: - app_dir = Path(app.dir_path) - manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) - env = assemble_workload_env(app_dir, manifest, app.name) + app_dir, _, compose_file, env, container = self._prepare_target_context(app) + is_core = self._is_core_target(app) pull_cmd = ["docker", "compose", "-f", str(compose_file), "pull"] + if container: + pull_cmd.append(container) code, _, err = run_bounded_subprocess(pull_cmd, cwd=app_dir, env=env, timeout=300.0) if code != 0: raise RouterExecutionError(f"docker compose pull failed: {err}", exit_code=code) up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"] + if container: + up_cmd.append(container) code, out_up, err_up = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0) if code != 0: raise RouterExecutionError(f"docker compose up failed after pull: {err_up}", exit_code=code) - self._trigger_homepage_sync() + if not is_core: + self._trigger_homepage_sync() return {"output": out_up, "action": "pulled", "message": f"Workload '{app.name}' pulled and updated"} def _op_workload_update( @@ -748,6 +836,8 @@ class OperationalRouter: params = request.parse_parameters() assert isinstance(params, UpdateParams) app_dir = Path(app.dir_path) + is_core = self._is_core_target(app) + container = self._target_container(app) # 1. Clean working tree check code, status_out, _ = run_bounded_subprocess( @@ -771,20 +861,25 @@ class OperationalRouter: raise RouterExecutionError(f"git pull failed for '{app.name}': {pull_err}", exit_code=code) # 3. Post-pull re-validation of manifest and expected_branch - manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) - if ( - params.expected_branch - and manifest.source - and manifest.source.ref != params.expected_branch - ): - raise RouterValidationError( - f"Post-pull branch mismatch for '{app.name}': expected '{params.expected_branch}', " - f"manifest declared '{manifest.source.ref}'" - ) + if is_core: + compose_file = validate_core_preflight(app_dir, self.core_dir) + manifest = None + declared_actions = ["compose_pull", "compose_up"] + else: + manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) + if ( + params.expected_branch + and manifest.source + and manifest.source.ref != params.expected_branch + ): + raise RouterValidationError( + f"Post-pull branch mismatch for '{app.name}': expected '{params.expected_branch}', " + f"manifest declared '{manifest.source.ref}'" + ) + declared_actions = manifest.deployment.actions or ["compose_up"] - # 4. Execute declared actions from manifest + # 4. Execute declared actions env = assemble_workload_env(app_dir, manifest, app.name) - declared_actions = manifest.deployment.actions or ["compose_up"] output_log = [f"git: {pull_out.strip()}"] for action in declared_actions: @@ -801,6 +896,9 @@ class OperationalRouter: else: continue + if container: + cmd.append(container) + code, act_out, act_err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0) if code != 0: raise RouterExecutionError( @@ -818,7 +916,8 @@ class OperationalRouter: commit_sha = sha_out.strip() or None # 6. Trigger Homepage sync - self._trigger_homepage_sync() + if not is_core: + self._trigger_homepage_sync() return { "output": "\n".join(output_log), diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 4bec44f..0ad7536 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -509,3 +509,262 @@ def test_operational_router_workload_update_succeeds_on_clean_tree( # Verify git pull was called with expected branch pull_calls = [c for c in executed_commands if "pull" in c] assert len(pull_calls) == 2 # git pull and docker compose pull + + +# --------------------------------------------------------------------------- +# Core Platform Stack & Core Service Dispatch (Issue #2) +# --------------------------------------------------------------------------- + + +def test_operational_router_dispatches_core_stack_operations( + tmp_path: Path, + admin_principal: Principal, + mock_sites_dir: Path, + mock_core_dir: Path, +): + compose_content = """ +services: + traefik: + image: "traefik:v3.6" + container_name: "traefik" + authelia: + image: "authelia/authelia:latest" + container_name: "authelia" +""" + (mock_core_dir / "docker-compose.yml").write_text(compose_content.strip(), encoding="utf-8") + + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_sites_dir, + core_dir=mock_core_dir, + ) + + executed_cmds: list[list[str]] = [] + + def mock_subproc(cmd: list[str], **kwargs): + executed_cmds.append(cmd) + return 0, "ok", "" + + with ( + patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), + patch("appctl_router.cmd_sync_homepage") as mock_sync, + ): + # 1. Deploy core stack + resp_deploy = router.dispatch( + OperationRequest.model_validate({"operation": "workload.deploy", "target": "core"}), + admin_principal, + ) + assert resp_deploy.success is True + assert executed_cmds[-1] == [ + "docker", + "compose", + "-f", + str(mock_core_dir / "docker-compose.yml"), + "up", + "-d", + "--remove-orphans", + ] + + # 2. Stop core stack (uses `down` for full stack) + resp_stop = router.dispatch( + OperationRequest.model_validate({"operation": "workload.stop", "target": "core"}), + admin_principal, + ) + assert resp_stop.success is True + assert executed_cmds[-1] == [ + "docker", + "compose", + "-f", + str(mock_core_dir / "docker-compose.yml"), + "down", + ] + + # 3. Restart core stack + resp_restart = router.dispatch( + OperationRequest.model_validate({"operation": "workload.restart", "target": "core"}), + admin_principal, + ) + assert resp_restart.success is True + assert executed_cmds[-1] == [ + "docker", + "compose", + "-f", + str(mock_core_dir / "docker-compose.yml"), + "restart", + ] + + # 4. Config core stack + resp_config = router.dispatch( + OperationRequest.model_validate({"operation": "workload.config", "target": "core"}), + admin_principal, + ) + assert resp_config.success is True + assert executed_cmds[-1] == [ + "docker", + "compose", + "-f", + str(mock_core_dir / "docker-compose.yml"), + "config", + ] + + # Core operations do not trigger Homepage Sites sync + mock_sync.assert_not_called() + + +def test_operational_router_dispatches_core_service_container_scoped_operations( + tmp_path: Path, + admin_principal: Principal, + mock_sites_dir: Path, + mock_core_dir: Path, +): + (mock_core_dir / "docker-compose.yml").write_text( + "services:\n traefik:\n image: traefik:v3.6\n", encoding="utf-8" + ) + + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_sites_dir, + core_dir=mock_core_dir, + ) + + executed_cmds: list[list[str]] = [] + + def mock_subproc(cmd: list[str], **kwargs): + executed_cmds.append(cmd) + return 0, "ok", "" + + with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc): + # 1. Deploy single core service (traefik) + resp_deploy = router.dispatch( + OperationRequest.model_validate({"operation": "workload.deploy", "target": "traefik"}), + admin_principal, + ) + assert resp_deploy.success is True + assert executed_cmds[-1][-1] == "traefik" + assert "up" in executed_cmds[-1] + + # 2. Stop single core service (uses `stop traefik`, NOT `down`) + resp_stop = router.dispatch( + OperationRequest.model_validate({"operation": "workload.stop", "target": "traefik"}), + admin_principal, + ) + assert resp_stop.success is True + assert executed_cmds[-1] == [ + "docker", + "compose", + "-f", + str(mock_core_dir / "docker-compose.yml"), + "stop", + "traefik", + ] + + # 3. Restart single core service + resp_restart = router.dispatch( + OperationRequest.model_validate({"operation": "workload.restart", "target": "traefik"}), + admin_principal, + ) + assert resp_restart.success is True + assert executed_cmds[-1] == [ + "docker", + "compose", + "-f", + str(mock_core_dir / "docker-compose.yml"), + "restart", + "traefik", + ] + + # 4. Pull single core service + resp_pull = router.dispatch( + OperationRequest.model_validate({"operation": "workload.pull", "target": "traefik"}), + admin_principal, + ) + assert resp_pull.success is True + assert executed_cmds[-2] == [ + "docker", + "compose", + "-f", + str(mock_core_dir / "docker-compose.yml"), + "pull", + "traefik", + ] + assert executed_cmds[-1] == [ + "docker", + "compose", + "-f", + str(mock_core_dir / "docker-compose.yml"), + "up", + "-d", + "--remove-orphans", + "traefik", + ] + + # 5. Logs single core service + resp_logs = router.dispatch( + OperationRequest.model_validate({"operation": "workload.logs", "target": "traefik"}), + admin_principal, + ) + assert resp_logs.success is True + assert executed_cmds[-1][-1] == "traefik" + + +def test_operational_router_dispatches_core_update_without_manifest( + tmp_path: Path, + admin_principal: Principal, + mock_sites_dir: Path, + mock_core_dir: Path, +): + (mock_core_dir / "docker-compose.yml").write_text( + "services:\n traefik:\n image: traefik:v3.6\n", encoding="utf-8" + ) + + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_sites_dir, + core_dir=mock_core_dir, + ) + + executed_cmds: list[list[str]] = [] + + def mock_subproc(cmd: list[str], **kwargs): + executed_cmds.append(cmd) + if "status" in cmd: + return 0, "", "" + if "rev-parse" in cmd: + return 0, "c0ffee1", "" + return 0, "ok", "" + + with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc): + resp = router.dispatch( + OperationRequest.model_validate({"operation": "workload.update", "target": "core"}), + admin_principal, + ) + assert resp.success is True + assert resp.result is not None + assert resp.result["commit_sha"] == "c0ffee1" + assert resp.result["actions"] == ["compose_pull", "compose_up"] + + +def test_operational_router_rejects_operator_role_on_core_targets( + tmp_path: Path, + operator_principal: Principal, + mock_sites_dir: Path, + mock_core_dir: Path, +): + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_sites_dir, + core_dir=mock_core_dir, + ) + for target in ("core", "traefik", "authelia"): + resp = router.dispatch( + OperationRequest.model_validate({"operation": "workload.restart", "target": target}), + operator_principal, + ) + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_PERMISSION_DENIED + From 0b5ba58ecf8221fecdcd7e927da07dd40705380a Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 15:34:24 -0500 Subject: [PATCH 11/43] fix(cli): restore human-readable tabular output and bash autocompletion Closes #3 --- scripts/appctl | 15 +++- scripts/appctl_cli.py | 139 ++++++++++++++++++++++++++++++- scripts/appctl_router.py | 32 ++++++- tests/unit/test_appctl_cli.py | 115 +++++++++++++++++++++++++ tests/unit/test_appctl_router.py | 45 ++++++++++ 5 files changed, 337 insertions(+), 9 deletions(-) diff --git a/scripts/appctl b/scripts/appctl index 689e6f8..81ba6e7 100755 --- a/scripts/appctl +++ b/scripts/appctl @@ -12,10 +12,17 @@ PYTHON_BIN="${PYTHON_BIN:-python3}" SOCKET_PATH="${APPCTL_SOCKET_PATH:-/run/homelab/appctl.sock}" CLI_CLIENT="$SCRIPT_DIR/appctl_cli.py" -# If daemon Unix domain socket exists, delegate directly to thin client -if [ -S "$SOCKET_PATH" ] && [ -f "$CLI_CLIENT" ]; then - exec "$PYTHON_BIN" "$CLI_CLIENT" "$@" -fi +# If daemon Unix domain socket exists, delegate operational commands directly to thin client +# (fast-path local completion and resolution helpers through appctl_engine.py) +case "${1:-}" in + complete|completion|resolve) + ;; + *) + if [ -S "$SOCKET_PATH" ] && [ -f "$CLI_CLIENT" ]; then + exec "$PYTHON_BIN" "$CLI_CLIENT" "$@" + fi + ;; +esac ENV_FILE="/run/secrets/rendered/traefik-deployments.env" if [ ! -f "$ENV_FILE" ] && [ -f "/run/secrets/traefik-deployments.env" ]; then diff --git a/scripts/appctl_cli.py b/scripts/appctl_cli.py index 3bf2d3e..01df017 100755 --- a/scripts/appctl_cli.py +++ b/scripts/appctl_cli.py @@ -48,6 +48,120 @@ def resolve_token(cli_token: str | None = None) -> str | None: return None +def _format_workload_table(workloads: list[dict[str, Any]]) -> str: + """Format a list of workload dictionaries into a human-readable tabular display.""" + if not workloads: + return "ℹ️ No workloads found." + + has_ssl = any("ssl" in w and isinstance(w["ssl"], dict) for w in workloads) + lines: list[str] = [] + + if has_ssl: + lines.append( + f"{'SERVICE':<18} {'TYPE':<14} {'DOMAIN':<30} {'CERT':<24} {'DESCRIPTION'}" + ) + lines.append( + f"{'-------':<18} {'----':<14} {'------':<30} {'----':<24} {'-----------'}" + ) + else: + lines.append( + f"{'SERVICE':<18} {'TYPE':<14} {'DOMAIN':<30} {'DESCRIPTION'}" + ) + lines.append( + f"{'-------':<18} {'----':<14} {'------':<30} {'-----------'}" + ) + + for w in workloads: + name = str(w.get("name", "-")) + w_type = str(w.get("type", w.get("app_type", "app"))) + domain = str(w.get("domain", "-")) + desc = str(w.get("description", "")) + if w.get("manifest_error"): + desc = f"⚠️ {w['manifest_error']}" + elif w.get("deployment_status"): + desc = f"{w['deployment_status']} ({w.get('provenance_status', '-')})" + + if has_ssl: + ssl_info = w.get("ssl") + cert_status = ( + str(ssl_info.get("status", "-")) + if isinstance(ssl_info, dict) + else "-" + ) + lines.append( + f"{name:<18} {w_type:<14} {domain:<30} {cert_status:<24} {desc}" + ) + else: + lines.append(f"{name:<18} {w_type:<14} {domain:<30} {desc}") + + return "\n".join(lines) + + +def _format_workload_info(workload: dict[str, Any]) -> str: + """Format a single workload metadata dictionary for `appctl info`.""" + name = workload.get("name", "unknown") + w_type = workload.get("type", workload.get("app_type", "app")) + header = ( + f"ℹ️ Core Infrastructure Service: {name}" + if w_type in ("core", "core_service") + else f"ℹ️ Workload Overview: {name}" + ) + lines = [ + header, + "-" * 50, + f"Directory: {workload.get('dir_path', '-')}", + f"Domain: {workload.get('domain', '-')}", + f"Type: {w_type}", + f"Description: {workload.get('description', '-')}", + ] + if workload.get("container"): + lines.append(f"Container: {workload['container']}") + aliases = workload.get("aliases") + if isinstance(aliases, list) and aliases: + lines.append(f"Aliases: {', '.join(str(a) for a in aliases)}") + networks = workload.get("networks") + if isinstance(networks, list) and networks: + lines.append(f"Networks: {', '.join(str(n) for n in networks)}") + if "auth" in workload: + lines.append(f"Auth Protected: {workload['auth']}") + if "visible" in workload: + lines.append(f"Dashboard: {'Visible' if workload['visible'] else 'Hidden'}") + source = workload.get("source") + if isinstance(source, dict): + lines.append(f"Source URL: {source.get('url', '-')}") + lines.append(f"Target Ref: {source.get('ref', '-')}") + if workload.get("manifest_error"): + lines.append(f"\n⚠️ Manifest Validation Error:\n {workload['manifest_error']}") + ssl_info = workload.get("ssl") + if isinstance(ssl_info, dict): + lines.append("\n🔒 SSL/TLS Certificate:") + lines.append(f" Status: {ssl_info.get('status', '-')}") + lines.append(f" Issuer: {ssl_info.get('issuer', '-')}") + lines.append(f" Expiration: {ssl_info.get('formatted_expiry', '-')}") + return "\n".join(lines) + + +def _format_ssl_info(ssl_info: dict[str, Any]) -> str: + """Format SSL certificate details for `appctl ssl`.""" + domain = ssl_info.get("domain", "-") + lines = [ + f"🔒 SSL/TLS Certificate: {domain}", + "-" * 50, + f"Domain: {domain}", + f"Status: {ssl_info.get('status', '-')}", + f"Issuer: {ssl_info.get('issuer', '-')}", + f"Subject: {ssl_info.get('subject', '-')}", + f"Expiration: {ssl_info.get('not_after', '-')}", + ] + if ssl_info.get("days_remaining") is not None: + lines.append( + f"Days Remaining: {ssl_info['days_remaining']} days ({ssl_info.get('formatted_expiry', '-')})" + ) + if ssl_info.get("error"): + lines.append(f"Details/Error: {ssl_info['error']}") + return "\n".join(lines) + + def format_response(resp: OperationResponse, raw_json: bool = False) -> str: """Format an OperationResponse for human-friendly terminal display or JSON output.""" if raw_json: @@ -63,6 +177,14 @@ def format_response(resp: OperationResponse, raw_json: bool = False) -> str: return resp.output if resp.result: + if "workloads" in resp.result and isinstance(resp.result["workloads"], list): + return _format_workload_table(resp.result["workloads"]) + if resp.operation == OperationType.WORKLOAD_RESOLVE and "workload" in resp.result: + return json.dumps(resp.result["workload"]) + if "workload" in resp.result and isinstance(resp.result["workload"], dict): + return _format_workload_info(resp.result["workload"]) + if "ssl" in resp.result and isinstance(resp.result["ssl"], dict): + return _format_ssl_info(resp.result["ssl"]) if "message" in resp.result and len(resp.result) <= 3: return f"✨ {resp.result['message']}" return json.dumps(resp.result, indent=2) @@ -101,14 +223,18 @@ def run_cli(argv: list[str] | None = None) -> int: # list / status list_p = subparsers.add_parser("list", aliases=["status"], parents=[common_parser], help="List workloads") - list_p.add_argument("--core", action="store_true", help="Include core platform services") - list_p.add_argument("--fetch", action="store_true", help="Fetch remote git revisions") - list_p.add_argument("--ssl", action="store_true", help="Check SSL certificate status") + list_p.add_argument("--core", "-c", "--all", "-a", action="store_true", dest="core", help="Include core platform services") + list_p.add_argument("--fetch", "-f", action="store_true", help="Fetch remote git revisions") + list_p.add_argument("--ssl", "-s", action="store_true", help="Check SSL certificate status") # info info_p = subparsers.add_parser("info", parents=[common_parser], help="Get workload metadata") info_p.add_argument("target", help="Workload name") - info_p.add_argument("--ssl", action="store_true", help="Check SSL certificate status") + info_p.add_argument("--ssl", "-s", action="store_true", help="Check SSL certificate status") + + # resolve + resolve_p = subparsers.add_parser("resolve", parents=[common_parser], help="Resolve target metadata") + resolve_p.add_argument("target", help="Workload or core target") # ssl ssl_p = subparsers.add_parser("ssl", parents=[common_parser], help="Inspect platform SSL certificates") @@ -177,6 +303,11 @@ def run_cli(argv: list[str] | None = None) -> int: target=parsed.target, parameters={"ssl": getattr(parsed, "ssl", False)}, ) + elif cmd == "resolve": + op_req = OperationRequest( + operation=OperationType.WORKLOAD_RESOLVE, + target=parsed.target, + ) elif cmd == "ssl": op_req = OperationRequest( operation=OperationType.PLATFORM_SSL, diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py index 4f8c2bf..2b51e21 100644 --- a/scripts/appctl_router.py +++ b/scripts/appctl_router.py @@ -62,6 +62,7 @@ from appctl_engine import ( from appctl_engine import ( check_ssl_cert, cmd_sync_homepage, + get_core_services, get_sites_apps, resolve_app, ) @@ -73,6 +74,7 @@ from core_manifest import ( parse_manifest, ) from gitops_dispatcher import validate_compose_security +from provenance import inspect_workload_two_axis MAX_OUTPUT_BYTES = 256 * 1024 # 256 KiB cap per invocation @@ -660,7 +662,33 @@ class OperationalRouter: params = request.parse_parameters() assert isinstance(params, ListParams) apps = get_sites_apps(sites_dir=str(self.sites_dir)) - apps_data = [a.to_dict() for a in apps] + apps_data: list[dict[str, Any]] = [] + + for app in apps: + item = app.to_dict() + app_path = Path(app.dir_path) + if params.fetch: + manifest_obj = app.manifest_obj or Manifest( + name=app.name, domain=app.domain + ) + two_axis = inspect_workload_two_axis( + app_dir=app_path, + manifest=manifest_obj, + fetch_upstream=True, + ) + item["deployment_status"] = two_axis.checkout.status_label + item["provenance_status"] = two_axis.provenance.status.value + if params.ssl and not app.is_internal: + item["ssl"] = check_ssl_cert(app.domain) + apps_data.append(item) + + if params.core: + for svc in get_core_services(core_dir=str(self.core_dir)): + svc_dict = svc.to_dict() + if params.ssl and not svc.is_internal: + svc_dict["ssl"] = check_ssl_cert(svc.domain) + apps_data.append(svc_dict) + return { "total": len(apps_data), "workloads": apps_data, @@ -671,6 +699,8 @@ class OperationalRouter: params = request.parse_parameters() assert isinstance(params, GetParams) data = app.to_dict() + if params.ssl and not getattr(app, "is_internal", True): + data["ssl"] = check_ssl_cert(app.domain) return {"workload": data, "message": f"Retrieved metadata for {app.name}"} def _op_workload_resolve(self, app: Any) -> dict[str, Any]: diff --git a/tests/unit/test_appctl_cli.py b/tests/unit/test_appctl_cli.py index 8093190..48d022d 100644 --- a/tests/unit/test_appctl_cli.py +++ b/tests/unit/test_appctl_cli.py @@ -113,3 +113,118 @@ def test_cli_handles_missing_socket(): ret = run_cli(["list", "--socket", "/nonexistent/appctl.sock"]) assert ret == 1 assert "socket not found" in mock_stderr.getvalue() + + +def test_cli_format_response_renders_workload_list_table(): + """Ensure workload.list renders a human-readable table instead of suppressing it behind result['message'].""" + resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_list_01", + operation=OperationType.WORKLOAD_LIST, + result={ + "total": 2, + "workloads": [ + { + "name": "snappymail", + "type": "app", + "domain": "mail.example.test", + "description": "Webmail client", + }, + { + "name": "traefik", + "type": "core_service", + "domain": "traefik.example.test", + "description": "Edge Reverse Proxy", + }, + ], + "message": "Found 2 workloads", + }, + output="", + ) + rendered = format_response(resp, raw_json=False) + assert "SERVICE" in rendered + assert "DOMAIN" in rendered + assert "snappymail" in rendered + assert "mail.example.test" in rendered + assert "traefik" in rendered + assert "Edge Reverse Proxy" in rendered + assert "✨ Found 2 workloads" not in rendered + + +def test_cli_format_response_renders_workload_get_info(): + """Ensure workload.get (appctl info) renders structured workload metadata.""" + resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_get_01", + operation=OperationType.WORKLOAD_GET, + target="snappymail", + result={ + "workload": { + "name": "snappymail", + "type": "app", + "dir_path": "/home/operator/Sites/snappymail", + "domain": "mail.example.test", + "description": "Lightweight Webmail", + "aliases": ["webmail", "mail"], + "networks": ["proxy-net"], + "auth": True, + "visible": True, + }, + "message": "Retrieved metadata for snappymail", + }, + output="", + ) + rendered = format_response(resp, raw_json=False) + assert "Workload Overview: snappymail" in rendered + assert "/home/operator/Sites/snappymail" in rendered + assert "mail.example.test" in rendered + assert "webmail, mail" in rendered + assert "✨ Retrieved metadata" not in rendered + + +def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path, monkeypatch): + """Ensure scripts/appctl executes `complete` and `completion` via appctl_engine.py even when socket exists.""" + import os + import shutil + import socket as std_socket + import subprocess + import sys + + bash_bin = shutil.which("bash") or "bash" + sock_path = tmp_path / "appctl.sock" + srv = std_socket.socket(std_socket.AF_UNIX, std_socket.SOCK_STREAM) + srv.bind(str(sock_path)) + try: + appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl" + env = { + "PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"), + "PYTHON_BIN": sys.executable, + "HOMELAB_DOMAIN": "example.test", + "APPCTL_SOCKET_PATH": str(sock_path), + "SITES_DIR": str(tmp_path), + } + res_comp = subprocess.run( + [bash_bin, str(appctl_script), "completion", "bash"], + env=env, + capture_output=True, + text=True, + check=False, + ) + assert res_comp.returncode == 0 + assert "_appctl_completions()" in res_comp.stdout + + res_words = subprocess.run( + [bash_bin, str(appctl_script), "complete", "services"], + env=env, + capture_output=True, + text=True, + check=False, + ) + assert res_words.returncode == 0 + assert "traefik" in res_words.stdout + assert "core" in res_words.stdout + finally: + srv.close() + diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 0ad7536..2199243 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -768,3 +768,48 @@ def test_operational_router_rejects_operator_role_on_core_targets( assert resp.error is not None assert resp.error.code == ErrorCode.ERR_PERMISSION_DENIED + +def test_operational_router_workload_list_honors_filter_params( + tmp_path: Path, + viewer_principal: Principal, + mock_workload_dir: Path, + mock_core_dir: Path, +): + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_workload_dir.parent, + core_dir=mock_core_dir, + ) + + # Without --core: only Sites workloads (1) + resp_sites = router.dispatch( + OperationRequest.model_validate({ + "operation": "workload.list", + "parameters": {"core": False, "fetch": False, "ssl": False}, + }), + viewer_principal, + ) + assert resp_sites.success is True + assert resp_sites.result is not None + assert resp_sites.result["total"] == 1 + assert resp_sites.result["workloads"][0]["name"] == "snappymail" + + # With --core and --ssl: includes Core services and SSL inspection + with patch("appctl_router.check_ssl_cert", return_value={"status": "🟢 80d remaining", "domain": "example.test"}) as mock_ssl: + resp_core = router.dispatch( + OperationRequest.model_validate({ + "operation": "workload.list", + "parameters": {"core": True, "fetch": False, "ssl": True}, + }), + viewer_principal, + ) + assert resp_core.success is True + assert resp_core.result is not None + names = {w["name"] for w in resp_core.result["workloads"]} + assert "snappymail" in names + assert "traefik" in names + assert "authelia" in names + assert mock_ssl.call_count >= 1 + + From 2668dcc5a855b66303a4843352625219bb3516b3 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 15:38:59 -0500 Subject: [PATCH 12/43] fix(nixos): add operator to homelab-operators and configure daemon systemd sandbox Closes #4 --- nixos/configuration.nix | 7 ++++--- nixos/modules/homeserver.nix | 8 ++++++-- scripts/appctl_daemon.py | 2 +- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/nixos/configuration.nix b/nixos/configuration.nix index afb0cdb..a2ac096 100644 --- a/nixos/configuration.nix +++ b/nixos/configuration.nix @@ -63,9 +63,10 @@ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICAVPPMk+WApUd/fo78+lsRGnLKSlY4GDZiNGKwBAifD" ]; extraGroups = [ - "wheel" # sudo access - "docker" # run docker without sudo - "networkmanager" # modify network settings + "wheel" # sudo access + "docker" # run docker without sudo + "homelab-operators" # access /run/homelab/appctl.sock + "networkmanager" # modify network settings ]; }; diff --git a/nixos/modules/homeserver.nix b/nixos/modules/homeserver.nix index b7983b9..f74ace7 100644 --- a/nixos/modules/homeserver.nix +++ b/nixos/modules/homeserver.nix @@ -109,7 +109,7 @@ serviceConfig = { Type = "simple"; User = config.homelab.operatorUser; - SupplementaryGroups = [ "docker" ]; + SupplementaryGroups = [ "docker" "homelab-operators" ]; WorkingDirectory = config.homelab.coreDir; ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [ { @@ -137,12 +137,13 @@ ReadWritePaths = [ config.homelab.sitesDir "/home/${config.homelab.operatorUser}/.local/state/homelab" + "/run/homelab" ]; }; }; # Declarative Users and Groups for Control Plane Service Identity - users.groups.homelab-operators = {}; + users.groups.homelab-operators.members = [ config.homelab.operatorUser ]; users.users.homelab-appctl = { isSystemUser = true; group = "homelab-operators"; @@ -168,6 +169,9 @@ ]; environment = { + HOME = "/var/lib/homelab/appctl"; + DOCKER_CONFIG = "/var/lib/homelab/appctl/.docker"; + HOMELAB_DOMAIN = config.homelab.domain; APPCTL_SOCKET_PATH = "/run/homelab/appctl.sock"; APPCTL_HTTP_HOST = "127.0.0.1"; APPCTL_HTTP_PORT = "9001"; diff --git a/scripts/appctl_daemon.py b/scripts/appctl_daemon.py index 7599fe2..b720b41 100755 --- a/scripts/appctl_daemon.py +++ b/scripts/appctl_daemon.py @@ -484,7 +484,7 @@ class AppctlDaemon: try: os.chmod(self.socket_path, 0o660) except OSError as e: - logger.warning("Could not set mode 0660 on socket %s: %e", self.socket_path, e) + logger.warning("Could not set mode 0660 on socket %s: %s", self.socket_path, e) # 2. Prepare and bind TCP listener self.tcp_server = ThreadingHTTPServer((self.http_host, self.http_port), AppctlHTTPHandler) From 528bd0d4bcabca203eb39bf251e2996f0341a8c2 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 15:45:00 -0500 Subject: [PATCH 13/43] feat(secrets): bootstrap SOPS appctl tokens and wire GitOps worker token Closes #5 --- nixos/modules/homeserver.nix | 43 +++++++++++++++++++++++------------- nixos/secrets.yaml | 7 ++++-- 2 files changed, 33 insertions(+), 17 deletions(-) diff --git a/nixos/modules/homeserver.nix b/nixos/modules/homeserver.nix index f74ace7..95970e8 100644 --- a/nixos/modules/homeserver.nix +++ b/nixos/modules/homeserver.nix @@ -30,20 +30,32 @@ config = { # Define the keys to decrypt from secrets.yaml - sops.secrets = lib.genAttrs [ - "dynu/api_key" - "traefik/acme_email" - "authelia/session_secret" - "authelia/storage_encryption_key" - "authelia/jwt_secret" - "lldap/jwt_secret" - "lldap/key_seed" - "lldap/admin_password" - "gitops/webhook_secret" - "brevo/smtp_login" - "brevo/smtp_key" - "diun/smtp_password" - ] (name: { owner = config.homelab.operatorUser; }); + sops.secrets = (lib.genAttrs [ + "dynu/api_key" + "traefik/acme_email" + "authelia/session_secret" + "authelia/storage_encryption_key" + "authelia/jwt_secret" + "lldap/jwt_secret" + "lldap/key_seed" + "lldap/admin_password" + "gitops/webhook_secret" + "brevo/smtp_login" + "brevo/smtp_key" + "diun/smtp_password" + ] (name: { owner = config.homelab.operatorUser; })) // { + "appctl/tokens_json" = { + owner = "homelab-appctl"; + group = "homelab-operators"; + mode = "0400"; + path = "/run/secrets/appctl/tokens.json"; + }; + "gitops/appctl_token" = { + owner = config.homelab.operatorUser; + group = "homelab-operators"; + mode = "0400"; + }; + }; # Generate the unified environment file at runtime in /run/secrets/homeserver.env sops.templates."homeserver.env" = { @@ -103,6 +115,7 @@ environment = { GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path; + GITOPS_APPCTL_TOKEN_FILE = config.sops.secrets."gitops/appctl_token".path; DOCKER_CONFIG = "/home/${config.homelab.operatorUser}/.local/state/homelab/docker"; }; @@ -177,7 +190,7 @@ APPCTL_HTTP_PORT = "9001"; APPCTL_AUDIT_LOG = "/var/log/homelab/appctl/audit.jsonl"; APPCTL_LOCK_DIR = "/var/lib/homelab/appctl/locks"; - APPCTL_TOKENS_FILE = "/run/secrets/appctl/tokens.json"; + APPCTL_TOKENS_FILE = config.sops.secrets."appctl/tokens_json".path; SITES_DIR = config.homelab.sitesDir; CORE_DIR = config.homelab.coreDir; HOMELAB_CONFIG_DIR = "/home/${config.homelab.operatorUser}/.config/homelab"; diff --git a/nixos/secrets.yaml b/nixos/secrets.yaml index a74ee72..041430d 100644 --- a/nixos/secrets.yaml +++ b/nixos/secrets.yaml @@ -30,6 +30,7 @@ system: pdf_decrypt_password: ENC[AES256_GCM,data:n3XTANd+PbejUw==,iv:y2VIabyv/DfTgztbjS6M/xIfRNKOL+U+r3eXsal32OQ=,tag:oFpXg2E9dDM5dwkjSZkLgw==,type:str] gitops: webhook_secret: ENC[AES256_GCM,data:Kj3d0Repa3OOvjCkW6+kakQEfsCdpdVJQd71Am6zQHBt7QkLtxlnovUmmS+zJ+jChQBbCc9/7LunFvFT2pL36w==,iv:qh1pEIVtvB/fxbMv+a9pworhbXsIpfF5gKWS22Zn0GU=,tag:D4RNXkWhg9l3BJFp7MMloA==,type:str] + appctl_token: ENC[AES256_GCM,data:+2BK6LejtvIj68+88zrjzgod8tXXVSRH+WpmIIHCbGU7aKbdTK20JlIIKb2u+2w/fHVrTwxUkX+dp5/AHsU+ZvVWh7tUsEo=,iv:tX5+bTfFFil46o7ZXa3dLIQH5+ET2e+75qRvjSJrhwU=,tag:mVGkDADx8RqaSi3AnDyPEw==,type:str] lldap: jwt_secret: ENC[AES256_GCM,data:RHtVgZJzNK7PFFvYO4jSsv+3928PYG2RdajG3ETEfN5eh0FwAmqcC98X2scT8H2JAeDV+bRI6QMZ3FoNRNcOHw==,iv:YGYImZJQzf1ONkc9lq2bEV/eWKIPfTyH+2hKzObaY08=,tag:jcUYKHrYSPYvHjQ86hLl0g==,type:str] key_seed: ENC[AES256_GCM,data:8Jf/xyMMXQFYxSO9RezTQRcS+Amm9hYOf97K03H/8cI=,iv:D5BJ4I12cMp2HAdCJC8MD/LnrBskbX7X/a6TnyisuMk=,tag:fhxge0iBSPllyrGQfCkw7w==,type:str] @@ -37,6 +38,8 @@ lldap: brevo: smtp_login: ENC[AES256_GCM,data:zfqKsAtoAOWCrSqx38sknwcJZT2m8W2J,iv:tMwTNDf+2CE3/8rKqWTWLl5Zp4LUVNSFV90QN94VXxo=,tag:XYXz9w3oIa0qkcfjCcgcYg==,type:str] smtp_key: ENC[AES256_GCM,data:YulXyaVF/sLWE9x12yxdBAj9KMbfP/CK/7FS3XkYO8sCj3GWgPbNoSaUT/9quLWHPtCsBxxdLeLoDNa1jE2WRyHP1W+Ioyyx5sAzdzevzHIBmfP+fdw0rKhe,iv:QT0HfzNPsTqXlN3IC/+bBzJfUzN9YkXYiv/3uqkXHBw=,tag:vBetkZPDYoh0Yy3BpMT9BQ==,type:str] +appctl: + tokens_json: ENC[AES256_GCM,data:O2vsiMMcZjsduFSRen1MnnckdRYK45aPH40EhX42h1WUwf62Nm58PV5BQJOgJ97AH3hOH97mzg1tjL0C1oV/epXMaypRWY9AGLS00CfzD2sgdM5Wx7VKbfGggFnGqgd7veaCA+pxUC0uTk/Dq2Cz/uhXhLX1wVjafX0OAqS6fxO+L9Oza3+RBtKgx2xX0AKW+KSZQUM1nvNW8R/Eyvnqvw2OSb2FdKN1CKhlVWhCZiaxTe8617BqGhJDL9pu4lfn0m+tdIwvluI3h8cmKuT6dzd01Jxr0EHBY/+mZZ/WQoNhIy4QulFpKiMudiT+WGzUm+UT4mYBoGwzQCVV8MD7W1r84mkbCkLc/HpWG08TqK4tpAdtLgYK3Zslr1+lmboWyJ6WcinmxkhUexhj+gTyfXYmVSB3fF8PIeyQINGB3rLvmpZ7DDMzYa1ICgFbJ6zmYa54TXRDLGzLD09koeDp9FhXNKPvuwz2x4uwWDDUfU8wwTkGbw==,iv:FJpB+WZiE4PKUhIuwBWIB/TLtifwCzGRMtbMx7x6ly8=,tag:NZQXYFnVBqbOONl+Yh3tuA==,type:str] sops: age: - enc: | @@ -57,7 +60,7 @@ sops: yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A== -----END AGE ENCRYPTED FILE----- recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg - lastmodified: "2026-09-25T00:49:38Z" - mac: ENC[AES256_GCM,data:EyJ9V0aYo7isyqnW6HWBz4hD2X6xa+VRNg3TaK88gkX6YCG/H0htBfMf/VYl/hOA/eEZW+uMVys8Ocula9zpY1Pd1gUbWt5FrXQvooYNhtCFCFUAJdsrmif8Ru7AXazFbyhhaeBSBjSQURM0qi69XqllVvfmiSz32WlX/QIOZ/c=,iv:znmm8JuFKSFl2IGGhRG77SE9kqy3uFWUK8VjocJ18n4=,tag:tG000kt5a6W1fa0IEfvLLQ==,type:str] + lastmodified: "2026-10-19T20:40:13Z" + mac: ENC[AES256_GCM,data:rui8qF/l3ucq8vrZniHtGjlLGPq7ihteKK7rcaz2prRvmo7nHd97Axt7oElo050HFuoaJB1/coVPzYcAUozjZNsNx3TQYABGFWvxF5Y0SxjdLc1rqAjGR/j2Cf5wmvF9H457KBHfij2gQHY/ZZ2Nyd9aEpAKSFtKkn3aYkmTvW4=,iv:RdQWUpkahFEYEhd9kTpPG0GMJaHr7b+wbhf5MBhk6mo=,tag:1E3mcFk/EMnJNNxuZ6AXAw==,type:str] unencrypted_suffix: _unencrypted version: 3.13.3 From 25e79898afcc19c80f2ab5fdedd760abf536a033 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 17:05:20 -0500 Subject: [PATCH 14/43] docs(p4): reconcile operational documentation with control plane daemon architecture Closes #6 --- ROADMAP.md | 18 ++++---- docs/appctl.md | 89 ++++++++++++++++++++------------------- docs/architecture.md | 14 +++--- docs/gitops.md | 2 +- docs/secrets-and-state.md | 29 ++++++++++--- todo.txt | 5 +++ 6 files changed, 91 insertions(+), 66 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c9ec57a..03b290d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -24,15 +24,15 @@ It describes the implementation trajectory and phased engineering milestones for ## 🔍 Current Implementation Baseline vs. Target Architecture -| Architectural Area | Current Implementation Baseline (Milestone P3) | Target Architecture (Roadmap v6) | +| Architectural Area | Current Implementation Baseline (Milestone P4) | Target Architecture (Roadmap v6) | | :--- | :--- | :--- | -| **`appctl` Architecture** | Bash CLI wrapper (`scripts/appctl`) driving local subprocesses (`docker compose`, `git`) and Python engine. | Dedicated daemon service (`homelab-appctl.service`, user `homelab-appctl`) exposing `POST /v1/operations` over Unix socket and HTTP. | -| **Operational Auth** | Host Unix permissions; sourcing runtime secrets from `/run/secrets/`. | Mandatory SHA-256 Bearer token + 3-role RBAC + UDS `SO_PEERCRED` viewer fallback (P4); LLDAP directory RBAC & Authelia ForwardAuth (P5). | -| **Metadata & Schema Engine** | Unified engine (`scripts/appctl_engine.py`) with two-axis provenance and fail-closed Pydantic v2 schema v1.0 parser (`scripts/core_manifest.py`). | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | +| **`appctl` Architecture** | Dedicated daemon service (`homelab-appctl.service`, user `homelab-appctl`) exposing `POST /v1/operations` over Unix socket and loopback HTTP, with thin-client CLI (`scripts/appctl_cli.py`). | Expand with Operations UI and external ForwardAuth integration (P5–P7). | +| **Operational Auth** | Mandatory SHA-256 Bearer token + 3-role RBAC + UDS `SO_PEERCRED` viewer fallback (`/run/secrets/appctl/tokens.json`). | LLDAP directory RBAC & Authelia ForwardAuth (P5). | +| **Metadata & Schema Engine** | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | Unified across `DeploymentModel` materialization (P6). | | **Deployment Model** | Direct authoring of `app.yaml` and `docker-compose.yml` in `~/Sites//`. | 5-stage lifecycle (planned in P6): `DeploymentProposal` $\to$ operator-approved `DeploymentModel` in Git $\to$ `appctl` materialization. | -| **GitOps Engine** | Webhook dispatcher (`scripts/gitops_dispatcher.py`) with HMAC-SHA256 auth, Compose AST security validator, and `flock` serialization. | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | +| **GitOps Engine** | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | Integrated with `DeploymentModel` reconciliation (P6). | | **Secret Distribution** | Age-encrypted `nixos/secrets.yaml` decrypted by `sops-nix` to tmpfs `/run/secrets/`. | Host secrets remain in `sops-nix`; workload secrets referenced by key and projected via `SecretProvider` (planned in P5). | -| **Dashboard** | `appctl sync` compiles `config/homepage/services.yaml` from `app.yaml` manifests. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for management (planned in P7). | +| **Dashboard** | `appctl sync` compiles `config/homepage/services.yaml` from `app.yaml` manifests under `_homepage_sync.lock`. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for management (planned in P7). | --- @@ -44,8 +44,8 @@ It describes the implementation trajectory and phased engineering milestones for | **P1** | **Mail Topology Realignment** | Topology & State | ✅ **Completed** | Re-homed Stalwart to the dedicated `smtp.` subdomain; migrated SnappyMail to `~/Sites/snappymail` with zero data loss. | | **P2** | **GitOps Hardening** | Ingress Security | ✅ **Completed** | Authoritative Core repository registry (`deployments.yaml`), Compose AST security validator, systemd sandboxing. | | **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0 with Pydantic v2 fail-closed models (`core_manifest.py`), two-axis status inspection, unified `appctl_engine.py`. | -| **P4** | **Control Plane Daemon** | API & Dispatch | 🎯 **Current / Up Next** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. | -| **P5** | **Identity & Secrets** | Auth & Providers | ⏳ **Planned** | LLDAP RBAC group mapping, Authelia ForwardAuth header integration, user-scoped token lifecycle, `SecretProvider` reference resolution. | +| **P4** | **Control Plane Daemon** | API & Dispatch | ✅ **Completed** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. | +| **P5** | **Identity & Secrets** | Auth & Providers | 🎯 **Current / Up Next** | LLDAP RBAC group mapping, Authelia ForwardAuth header integration, user-scoped token lifecycle, `SecretProvider` reference resolution. | | **P6** | **Deployment Model & AI**| Intent Authoring | ⏳ **Planned** | Capability catalog, `DeploymentProposal` $\to$ `DeploymentModel` compiler, Git commit pipeline. | | **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. | @@ -99,7 +99,7 @@ It describes the implementation trajectory and phased engineering milestones for --- ### Milestone P4: Appctl Control Plane Daemon & Command-Oriented API -**Status**: 🎯 **Current / Up Next** +**Status**: ✅ **Completed** * **Objective**: Evolve `appctl` from a collection of local shell scripts into the authoritative platform daemon while enforcing authorization gates from day one. * **Key Deliverables**: 1. *Daemon Service (`homelab-appctl.service`)*: Systemd daemon running as dedicated user `homelab-appctl` (`Group = "homelab-operators"`), exposing one logical HTTP/1.1 API across dual transports: Unix domain socket (`/run/homelab/appctl.sock`) on host and loopback HTTP listener (`127.0.0.1:9001`). diff --git a/docs/appctl.md b/docs/appctl.md index 576cdef..02de3a9 100644 --- a/docs/appctl.md +++ b/docs/appctl.md @@ -3,47 +3,48 @@ The `appctl` tool is the command-line orchestrator and metadata engine for the **Homelab Core** platform. It coordinates interactions between independent workload repositories in `~/Sites` and platform services in `~/Core`. > [!NOTE] -> **Implementation Reference**: This document serves as the **current implementation manual (Milestone P3)** for the `appctl` Bash CLI wrapper (`scripts/appctl`), metadata/provenance engine (`scripts/appctl_engine.py`), and Pydantic v2 manifest parser (`scripts/core_manifest.py`). -> For the platform's planned Milestone P4 control-plane daemon transition and phased engineering roadmap, see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md). +> **Implementation Reference**: This document serves as the **current implementation manual (Milestone P4)** for the `appctl` Operational Control Plane Daemon (`scripts/appctl_daemon.py`), Operational Router (`scripts/appctl_router.py`), Thin-Client CLI (`scripts/appctl`, `scripts/appctl_cli.py`), metadata/provenance engine (`scripts/appctl_engine.py`), and Pydantic v2 manifest parser (`scripts/core_manifest.py`). +> For the platform's phased engineering roadmap, see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md). --- ## 1. How `appctl` Works -`appctl` consists of three cooperating modules in `scripts/`: -1. **[`scripts/appctl`](../scripts/appctl)** (Bash CLI wrapper): Parses CLI arguments, sources runtime secret templates, injects validated workload environment variables, dispatches `docker compose` commands, and provides shell autocompletions. -2. **[`scripts/appctl_engine.py`](../scripts/appctl_engine.py)** (Discovery, Provenance & TLS Engine): Scans `~/Sites/*`, evaluates **two-axis status** (local deployment checkout state vs. upstream software provenance), inspects live container health and TLS certificates, and compiles the Homepage dashboard configuration. -3. **[`scripts/core_manifest.py`](../scripts/core_manifest.py)** (Schema v1.0 Parser & Validator): Enforces fail-closed Pydantic v2 validation (`ConfigDict(extra="forbid")`) on `app.yaml` manifests, validates upstream Git transport schemes (`https://`, `ssh://`, `git@`), classifies reference mutability (branch, tag, commit SHA), and blocks reserved host environment keys (`PATH`, `LD_PRELOAD`, `IFS`, `CORE_DIR`, `SITES_DIR`, etc.). +Under Milestone P4, `appctl` operates as a centralized operational control plane daemon (`homelab-appctl.service`, running as isolated user `homelab-appctl:homelab-operators`) backed by cooperating modules in `scripts/`: + +1. **[`scripts/appctl`](../scripts/appctl) & [`scripts/appctl_cli.py`](../scripts/appctl_cli.py)** (Thin-Client CLI): Dispatches operational commands over the Unix domain socket (`/run/homelab/appctl.sock`) using HTTP/1.1 (`POST /v1/operations`), resolves operator Bearer tokens (`--token`, `APPCTL_TOKEN`, `~/.config/homelab/token`), renders human-readable tables, and fast-paths local shell autocompletions (`complete`, `completion`, `resolve`). +2. **[`scripts/appctl_daemon.py`](../scripts/appctl_daemon.py) & [`scripts/appctl_contracts.py`](../scripts/appctl_contracts.py)** (Dual-Transport Control Plane Server & Contracts): Serves a single logical HTTP/1.1 API (`POST /v1/operations` + `GET /v1/health`) identically across `/run/homelab/appctl.sock` (mode `0660`) and loopback TCP (`127.0.0.1:9001`), enforcing 64 KiB request caps and strict Pydantic v2 contracts (`ConfigDict(extra="forbid", strict=True)`). +3. **[`scripts/appctl_auth.py`](../scripts/appctl_auth.py) & [`scripts/appctl_audit.py`](../scripts/appctl_audit.py)** (Zero-Trust Auth, 3-Role RBAC & Fail-Closed Audit Guard): Verifies SHA-256 Bearer tokens against `/run/secrets/appctl/tokens.json` (mode `0400`) using `hmac.compare_digest`, maps tokenless local UDS `SO_PEERCRED` callers strictly to `homelab-viewer` (non-sensitive read-only inspection), enforces `homelab-admin` / `homelab-operator` / `homelab-viewer` RBAC, serializes mutations via per-target `fcntl.flock`, and writes append-only audit records to `/var/log/homelab/appctl/audit.jsonl` (mode `0600`) before any mutation executes. +4. **[`scripts/appctl_router.py`](../scripts/appctl_router.py)** (Operational Router & Unified Execution Engine): Enforces pre-flight path containment, `core_manifest.parse_manifest()`, and `validate_compose_security()` AST checks; assembles the 6-layer execution environment in pure Python (zero shell `source` or `eval`); and runs bounded `git` and `docker compose` subprocesses (`shell=False`, 256 KiB output cap, hard timeouts). +5. **[`scripts/appctl_engine.py`](../scripts/appctl_engine.py) & [`scripts/core_manifest.py`](../scripts/core_manifest.py)** (Discovery, Provenance & Schema v1.0 Validator): Scans `~/Sites/*`, evaluates **two-axis status** (local deployment checkout state vs. upstream software provenance), inspects live container health and TLS certificates, validates `app.yaml` manifests, and atomically compiles the Homepage dashboard configuration under `_homepage_sync.lock`. ```text - ┌───────────────────────────────┐ - │ appctl │ - └───────────────┬───────────────┘ - │ - ▼ - ┌───────────────────────────┐ - │ setup_app_env() │ - └─────────────┬─────────────┘ - │ - ┌──────────────────────────┴──────────────────────────┐ - ▼ ▼ -[ appctl_engine.py resolve ] [ Source Secrets ] -• Parses app.yaml via core_manifest.py /run/secrets/traefik-deployments.env -• Fails closed on manifest_error /run/secrets/homeserver.env - │ │ - └──────────────────────────┬──────────────────────────┘ - ▼ - ┌─────────────────────────────┐ - │ Injected Compose Context │ - │ • PROXY_NETWORK │ - │ • SERVICE_DOMAIN / DOMAIN │ - │ • CONTAINER_NAME │ - │ • Validated manifest env │ - └──────────────┬──────────────┘ - ▼ - ┌─────────────────────────────┐ - │ docker compose │ - └─────────────────────────────┘ + ┌──────────────────────────┐ ┌──────────────────────────┐ + │ appctl (CLI) │ │ homelab-gitops.service │ + └────────────┬─────────────┘ └────────────┬─────────────┘ + │ UDS (/run/homelab/appctl.sock) │ Bearer Token (homelab-operator) + └─────────────────┬─────────────────┘ + ▼ + ┌────────────────────────────────────────────────┐ + │ homelab-appctl.service (appctl_daemon.py) │ + │ • POST /v1/operations & GET /v1/health │ + │ • Auth: SHA-256 tokens.json + SO_PEERCRED │ + │ • RBAC: admin / operator / viewer │ + └────────────────────────┬───────────────────────┘ + ▼ + ┌────────────────────────────────────────────────┐ + │ OperationalRouter (appctl_router.py) │ + │ • Per-target flock + Fail-closed DISPATCHED │ + │ audit write (/var/log/homelab/appctl/...) │ + │ • Pre-flight: parse_manifest() + Compose AST │ + │ • Pure-Python 6-layer .env assembly │ + └────────────────────────┬───────────────────────┘ + ▼ + ┌────────────────────────────────────────────────┐ + │ Bounded Subprocess Engine (shell=False) │ + │ • git status / pull --ff-only │ + │ • docker compose -f │ + └────────────────────────────────────────────────┘ ``` --- @@ -197,21 +198,21 @@ homepage: ## 4. Environment Injection & Resolution Precedence -When `appctl` executes commands against a workload, environment variables are resolved in this sequence: +When `OperationalRouter` (`scripts/appctl_router.py`) executes commands against a workload or Core stack, the 6-layer execution environment is assembled in memory using a pure-Python inert `KEY=VALUE` parser (`parse_dotenv`) with zero shell `source` or variable expansion: -1. **Global Secrets & Templates**: Sourced from `/run/secrets/rendered/homeserver.env` and `/run/secrets/rendered/traefik-deployments.env` (with `/run/secrets/*` fallbacks). -2. **Canonical Root Domain Lock**: `HOMELAB_DOMAIN` is locked at startup using precedence `HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN` so per-workload `DOMAIN` exports cannot corrupt the platform apex domain. -3. **Infrastructure Defaults**: +1. **Base System Path & Docker Config**: `PATH` and `DOCKER_CONFIG`. +2. **Global Secrets & Templates**: Parsed inertly from `/run/secrets/rendered/homeserver.env` and `/run/secrets/rendered/traefik-deployments.env` (with `/run/secrets/*` fallbacks). +3. **Canonical Root Domain Lock**: `HOMELAB_DOMAIN` is locked using precedence `HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN` (failing closed if unset). +4. **Infrastructure Defaults & Application Identity**: - `PROXY_NETWORK` (defaults to `proxy-net`) - `CERT_RESOLVER` (defaults to `myresolver`) - - `DOMAIN_SUFFIX` (defaults to `$HOMELAB_DOMAIN`) -4. **Application Identity**: + - `DOMAIN_SUFFIX` (`$HOMELAB_DOMAIN`) - `SERVICE_NAME` = `` - `CONTAINER_NAME` = `` - - `SERVICE_DOMAIN` = `` - - `DOMAIN` = `` -5. **Manifest Variables**: Validated key-value pairs from the `env:` block in `app.yaml` (emitted via null-delimited stream without shell `eval`). -6. **Local Repository Files**: Sourced from `$APP_DIR/.env` and `$APP_DIR/app.env` if present. + - `SERVICE_DOMAIN` = `.` + - `DOMAIN` = `` +5. **Manifest Variables**: Validated key-value pairs from the `env:` block in `app.yaml`. +6. **Local Repository Files**: Parsed inertly from `$APP_DIR/.env` and `$APP_DIR/app.env` if present, rejecting any key violating `ENV_KEY_RE` or matching `RESERVED_ENV_KEYS`. --- diff --git a/docs/architecture.md b/docs/architecture.md index 4d70ab9..e60ea1c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3,8 +3,8 @@ This document details the architectural structure, component roles, networking models, and security controls of the **Homelab Core** platform. > [!NOTE] -> **Implementation Scope**: This document details the **current runtime architecture (Milestone P3)**, edge routing, container topologies, and network isolation models of Homelab Core. -> For the planned Milestone P4 control-plane daemon transition and phased engineering milestones, see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md). +> **Implementation Scope**: This document details the **current runtime architecture (Milestone P4)**, operational control plane daemon (`homelab-appctl.service`), edge routing, container topologies, and network isolation models of Homelab Core. +> For phased engineering milestones (P5–P7), see [`ROADMAP.md`](../ROADMAP.md) and the [Architecture Decision Index](decisions/README.md). --- @@ -42,16 +42,17 @@ The runtime environment consists of four functional layers: │ ▼ ┌────────────────────────────────────────────────────────────────────────┐ -│ 4. HOST FOUNDATION │ +│ 4. HOST FOUNDATION & CONTROL PLANE DAEMONS │ │ NixOS Linux · sops-nix Secrets · Docker Engine · Systemd Units │ +│ homelab-appctl.service (Control Plane Daemon) · homelab-gitops │ │ Smart Dynu DDNS Monitor · Host Firewall · /run Secret Projections │ └────────────────────────────────────────────────────────────────────────┘ ``` ### C. Cross-Cutting Orchestration Orchestration coordinates operations across the runtime layers: -* **`appctl` CLI, Provenance Engine & Schema Parser (`scripts/appctl`, `scripts/appctl_engine.py`, `scripts/core_manifest.py`)**: Current CLI implementation coordinating workload discovery, fail-closed Pydantic v2 `app.yaml` validation, two-axis provenance inspection, and Homepage compilation across workloads and Core. Under Milestone P4, this transitions into the centralized operational control plane daemon (`homelab-appctl.service`). -* **GitOps Webhook Dispatcher (`scripts/gitops_dispatcher.py`)**: Governed by the `homelab-gitops.service` systemd unit, it receives webhooks on port 9000, verifies HMAC-SHA256 signatures, enforces the `config/deployments.yaml` allowlist and Compose AST security checks, and dispatches serialized deployment actions for `~/Sites` workloads. +* **`appctl` Operational Control Plane Daemon (`homelab-appctl.service`, `scripts/appctl_daemon.py`, `scripts/appctl_router.py`)**: Centralized control plane running under isolated service identity `homelab-appctl:homelab-operators`. Exposes `POST /v1/operations` and `GET /v1/health` over `/run/homelab/appctl.sock` (mode `0660`) and `127.0.0.1:9001`, enforcing SHA-256 Bearer token authentication, 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`), per-target `flock` serialization, fail-closed append-only audit logging (`/var/log/homelab/appctl/audit.jsonl`), Pydantic v2 `app.yaml` validation, Compose AST security checks, and pure-Python `.env` assembly. +* **GitOps Webhook Dispatcher (`scripts/gitops_dispatcher.py`)**: Governed by the `homelab-gitops.service` systemd unit, it receives webhooks on port 9000, verifies HMAC-SHA256 signatures, enforces the `config/deployments.yaml` allowlist, and delegates serialized `workload.update` execution to `homelab-appctl.service` over `/run/homelab/appctl.sock` using its `homelab-operator` Bearer token. --- @@ -91,7 +92,8 @@ Orchestration coordinates operations across the runtime layers: ### F. Host Foundation & Daemons * **`homeserver-core.service`**: Systemd unit managing the Core Docker Compose stack (`~/Core/docker-compose.yml`) using secrets projected to `/run/secrets/homeserver.env`. -* **`homelab-gitops.service`**: Systemd unit listening on port 9000 executing `scripts/gitops_dispatcher.py` under strict systemd sandboxing (`ProtectSystem=strict`, `ProtectHome=read-only`). +* **`homelab-appctl.service`**: Operational control plane daemon running as dedicated user `homelab-appctl:homelab-operators` with dual listeners (`/run/homelab/appctl.sock` and `127.0.0.1:9001`), fail-closed audit logging (`/var/log/homelab/appctl/audit.jsonl`), and strict systemd sandboxing (`ProtectSystem=strict`, `ProtectHome=read-only`). +* **`homelab-gitops.service`**: Systemd unit listening on port 9000 executing `scripts/gitops_dispatcher.py` under strict systemd sandboxing (`ProtectSystem=strict`, `ProtectHome=read-only`), delegating worker deployments to `homelab-appctl.service`. * **`dynu-monitor.service` & `dynu-monitor.timer`**: IP change monitor executing `nixos/scripts/monitor.py` every 30 minutes to detect WAN IP changes and update DNS via `ddclient`. --- diff --git a/docs/gitops.md b/docs/gitops.md index 0e0c8a5..ed30e70 100644 --- a/docs/gitops.md +++ b/docs/gitops.md @@ -106,7 +106,7 @@ Before executing `docker compose up -d`, `validate_compose_security()` parses th To avoid blocking HTTP connections and handle overlapping pushes: 1. **Immediate HTTP 200 Return**: Upon passing admission, the dispatcher writes a pending file (`~/.local/state/homelab/gitops/.pending.json`), spawns a detached worker (`--worker `), and returns HTTP 200. -2. **Per-Target `flock` Serialization**: The worker acquires an exclusive non-blocking `fcntl.flock` on `~/.local/state/homelab/gitops/.lock`. If a worker is already running for this target, the second worker exits safely while the running worker continues to drain the pending file. +2. **Per-Target `flock` Serialization & Daemon Delegation**: The worker acquires an exclusive non-blocking `fcntl.flock` on `~/.local/state/homelab/gitops/.lock`. When `/run/homelab/appctl.sock` is available, the worker delegates `workload.update` to `homelab-appctl.service` over UDS authenticating with `/run/secrets/gitops/appctl_token` (`homelab-operator` role), which executes `git pull --ff-only`, re-validates `app.yaml` and Compose security, runs the declared actions, logs to `/var/log/homelab/appctl/audit.jsonl`, and syncs Homepage. 3. **Commit Superseding**: - Commit A begins deploying. - Commit B arrives and is written to the pending file. diff --git a/docs/secrets-and-state.md b/docs/secrets-and-state.md index f30b6e4..28448c0 100644 --- a/docs/secrets-and-state.md +++ b/docs/secrets-and-state.md @@ -29,17 +29,23 @@ This document explains the secrets distribution architecture, runtime projection │ 3. /run/secrets/gitops/webhook_secret │ │ -> Consumed by homelab-gitops.service for HMAC verification │ │ │ -│ 4. /run/credentials/ddclient.service/ddclient.conf │ +│ 4. /run/secrets/appctl/tokens.json (mode 0400, homelab-appctl) │ +│ -> Consumed by homelab-appctl.service for SHA-256 Bearer auth │ +│ │ +│ 5. /run/secrets/gitops/appctl_token (mode 0400, operatorUser) │ +│ -> Consumed by homelab-gitops.service worker for UDS daemon auth │ +│ │ +│ 6. /run/credentials/ddclient.service/ddclient.conf │ │ -> Consumed by systemd ddclient service │ │ │ -│ 5. /run/secrets/pdf_decrypt_password │ +│ 7. /run/secrets/pdf_decrypt_password │ │ -> Consumed by shell pdf_dc utility │ └────────────────────────────────────────────────────────────────────────┘ ``` --- -## 3. Projected Secret Templates +## 3. Projected Secret Templates & Token Store ### A. Core Platform Environment (`/run/secrets/homeserver.env`) Generated by `nixos/modules/homeserver.nix`. Supplies credentials to the Core Compose stack: @@ -54,7 +60,13 @@ Generated by `nixos/modules/homeserver.nix`. Supplies credentials to the Core Co * `SMTP_SERVER`, `SMTP_PORT`, `SMTP_LOGIN`, `SMTP_KEY`: Outbound relay credentials (Brevo) for Stalwart mail transport. ### B. Workload Deployments Environment (`/run/secrets/traefik-deployments.env`) -Generated by `nixos/modules/traefik-deployments.nix`. Projects shared infrastructure secrets and workload credentials that `appctl` sources when orchestrating stacks in `~/Sites` (such as database passwords, API keys, and runner tokens). +Generated by `nixos/modules/traefik-deployments.nix`. Projects shared infrastructure secrets and workload credentials that `appctl` parses inertly in pure Python when orchestrating stacks in `~/Sites` (such as database passwords, API keys, and runner tokens). + +### C. Control Plane Token Store (`/run/secrets/appctl/tokens.json` & `/run/secrets/gitops/appctl_token`) +Provisioned from `nixos/secrets.yaml` (`appctl/tokens_json` and `gitops/appctl_token`): +* `/run/secrets/appctl/tokens.json`: Owned by `homelab-appctl:homelab-operators` with strict mode `0400` (enforced fail-closed by `TokenStore._verify_permissions()`). Stores SHA-256 hex digests of Bearer secrets mapped to `token_id`, `identity`, and `role` (`homelab-admin`, `homelab-operator`, `homelab-viewer`). +* `/run/secrets/gitops/appctl_token`: Owned by `config.homelab.operatorUser` (mode `0400`). Supplies the `homelab-operator` Bearer secret to `homelab-gitops.service` when delegating `workload.update` to `homelab-appctl.service`. +* `~/.config/homelab/token`: Local operator Bearer token (mode `0600`) read by `appctl_cli.py` for interactive CLI mutations. --- @@ -80,6 +92,9 @@ lldap: admin_password: "..." gitops: webhook_secret: "..." + appctl_token: "..." +appctl: + tokens_json: "[...]" brevo: smtp_login: "..." smtp_key: "..." @@ -97,7 +112,7 @@ sudo nixos-rebuild switch --flake ~/Core#server Homelab Core separates **user identity** from **static platform secrets**: -* **Static Secrets**: Stored in `nixos/secrets.yaml` (system API keys, JWT secrets, database passwords). +* **Static Secrets**: Stored in `nixos/secrets.yaml` (system API keys, JWT secrets, database passwords, control-plane token hashes). * **Dynamic User Directory**: User accounts, credentials, and group memberships are managed live in **LLDAP** (`https://users.${HOMELAB_DOMAIN}`). User account updates do not require editing `secrets.yaml` or rebuilding NixOS. * **Authelia Integration**: Authelia queries LLDAP over LDAP (`ldap://lldap:3890`) at runtime using credentials projected from `/run/secrets/homeserver.env`. @@ -109,7 +124,9 @@ Homelab Core separates **user identity** from **static platform secrets**: | :--- | :--- | :--- | :--- | | **Declarative Config** | `~/Core/nixos/*.nix`, `docker-compose.yml` | ✅ Yes | System and container definitions | | **Encrypted Secrets** | `~/Core/nixos/secrets.yaml` | ✅ Yes (Encrypted) | SOPS Age-encrypted secret source | -| **Runtime Secrets** | `/run/secrets/*` | ❌ No (RAM tmpfs) | Ephemeral decrypted environment files | +| **Runtime Secrets** | `/run/secrets/*` | ❌ No (RAM tmpfs) | Ephemeral decrypted environment & token files | +| **Control Plane Audit** | `/var/log/homelab/appctl/audit.jsonl` | ❌ No | Append-only JSONL security & mutation log (`0600`) | +| **Control Plane Locks** | `/var/lib/homelab/appctl/locks/` | ❌ No | Per-target `flock` files & `_homepage_sync.lock` | | **SSL Certificates** | `~/Core/config/letsencrypt/acme.json` | ❌ No | Active Let's Encrypt certificates (mode 0600) | | **User Directory** | `~/Core/config/lldap/data/` | ❌ No | LLDAP SQLite database (`users.db`) | | **Auth Database** | `~/Core/config/authelia/db.sqlite3` | ❌ No | Authelia session database | diff --git a/todo.txt b/todo.txt index e445404..a7e4024 100644 --- a/todo.txt +++ b/todo.txt @@ -30,3 +30,8 @@ x 2026-10-19 (B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) a x 2026-10-19 (B) Add comprehensive unit and security test suite for P4 contracts, RBAC, audit guard, concurrency, and dual-transport parity in tests/unit/test_appctl_daemon.py +test @p4 x 2026-10-19 (C) Re-implement scripts/appctl as a thin UDS HTTP client and declare homelab-appctl.service with POSIX ACLs in nixos/modules/homeserver.nix +cli @p4 x 2026-10-19 (C) Scrub remaining hardcoded domain and username literals across NixOS modules, Compose stack, and config/deployments.yaml and add pyright to flake.nix checks +generic @core +x 2026-10-19 (A) Enable Core platform stack and core_service container-scoped dispatch in OperationalRouter in scripts/appctl_router.py +router @p4 +x 2026-10-19 (A) Restore human-readable tabular output, list filter parameters, and bash autocompletion fast-path in scripts/appctl_cli.py and scripts/appctl +cli @p4 +x 2026-10-19 (A) Add operatorUser to homelab-operators group and configure daemon systemd sandbox HOME and DOCKER_CONFIG in nixos/modules/homeserver.nix +nixos @p4 +x 2026-10-19 (A) Provision SOPS appctl/tokens_json and gitops/appctl_token secrets and wire GITOPS_APPCTL_TOKEN_FILE in nixos/secrets.yaml and nixos/modules/homeserver.nix +secrets @p4 +x 2026-10-19 (B) Reconcile operational documentation and ROADMAP.md with Milestone P4 control plane daemon architecture +docs @p4 From b6ec909bb68d59160a0b5c87d4eb7d874459f3dd Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 23 Oct 2026 15:47:33 -0500 Subject: [PATCH 15/43] fix(core): resolve AST parser and strict model incompatibilities for mutation testing Configure mutmut mutation testing framework, eliminate Parso AST syntax errors in appctl engine, permit dynamic mutant injection on strict Pydantic models, and prune redundant dead code. - Tooling & Configuration: - Add setup.cfg defining authoritative [mutmut] runner configuration and file copy targets. - Update .gitignore to exclude mutants/ and .mutmut-cache/ directories. - AST Parser Compatibility: - scripts/appctl_engine.py: rewrite parenthesized multi-context statements with 'as' targets to nested with blocks (# noqa: SIM117) to prevent Parso 0.8.7 grammar syntax errors during AST mutation. - Pydantic v2 Invariants & Dead Code Removal: - scripts/appctl_contracts.py: configure ignored_types=(dict,) on StrictModel and OperationRequest to permit unannotated class-level mutant injection; replace unreachable OPERATION_PARAMS_MAP fallback defaults with direct mapping access. - scripts/core_manifest.py: configure ignored_types=(dict,) on strict manifest models; prune redundant branch patterns in classify_ref() down to single fallback. - scripts/appctl_auth.py: remove redundant target == "core" check in enforce_rbac(). Rationale: Mutmut failed to parse scripts/appctl_engine.py and threw PydanticUserError when injecting unannotated mutant dictionaries into strict models with extra="forbid". Resolving these AST and contract barriers allows mutation test runners to analyze core control plane scripts hermetically. --- .gitignore | 2 ++ pyproject.toml | 2 ++ scripts/appctl_auth.py | 2 +- scripts/appctl_contracts.py | 16 ++++++++++++---- scripts/appctl_engine.py | 17 +++++++---------- scripts/core_manifest.py | 35 ++++++++++++++--------------------- setup.cfg | 6 ++++++ 7 files changed, 44 insertions(+), 36 deletions(-) create mode 100644 setup.cfg diff --git a/.gitignore b/.gitignore index e9fd555..fb97674 100644 --- a/.gitignore +++ b/.gitignore @@ -46,6 +46,8 @@ __pycache__/ *.pyc .pytest_cache/ .ruff_cache/ +mutants/ +.mutmut-cache/ # Local Bootstrap & Operational Scripts scripts/bootstrap_lldap_users.py diff --git a/pyproject.toml b/pyproject.toml index 6dfa6a2..f669741 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,3 +20,5 @@ pythonpath = [ ".", "scripts" ] + + diff --git a/scripts/appctl_auth.py b/scripts/appctl_auth.py index 0baa4f1..02672e0 100644 --- a/scripts/appctl_auth.py +++ b/scripts/appctl_auth.py @@ -310,7 +310,7 @@ def enforce_rbac( return # Target checks for operations targeting infrastructure - if target is not None and (target in CORE_TARGETS or target == "core"): + if target is not None and target in CORE_TARGETS: raise AuthorizationError( f"Role 'homelab-operator' is not permitted to target core service '{target}'", code=ErrorCode.ERR_PERMISSION_DENIED, diff --git a/scripts/appctl_contracts.py b/scripts/appctl_contracts.py index 869d08c..1508666 100644 --- a/scripts/appctl_contracts.py +++ b/scripts/appctl_contracts.py @@ -33,7 +33,8 @@ from pydantic import ( class StrictModel(BaseModel): """Base model propagating strict validation across all control plane models — ADR-0003.""" - model_config = ConfigDict(extra="forbid", strict=True) + model_config = ConfigDict(extra="forbid", strict=True, ignored_types=(dict,)) + class OperationType(StrEnum): @@ -241,7 +242,13 @@ def sanitize_validation_error(exc: ValidationError) -> OperationError: class OperationRequest(StrictModel): """Defines the body requirements of an HTTP/1.1 operation request.""" - model_config = ConfigDict(extra="forbid", strict=True, populate_by_name=True) + model_config = ConfigDict( + extra="forbid", + strict=True, + populate_by_name=True, + ignored_types=(dict,), + ) + version: Literal["1.0"] = "1.0" operation: FlexibleOperationType = Field( @@ -272,16 +279,17 @@ class OperationRequest(StrictModel): def validate_request(self) -> OperationRequest: if self.operation in TARGET_REQUIRED_OPERATIONS and not self.target: raise ValueError(f"Operation '{self.operation.value}' requires a non-empty target") - param_model = OPERATION_PARAMS_MAP.get(self.operation, EmptyParams) + param_model = OPERATION_PARAMS_MAP[self.operation] param_model.model_validate(self.parameters) return self def parse_parameters(self) -> StrictModel: """Parse and return the typed parameter model for this operation.""" - param_model = OPERATION_PARAMS_MAP.get(self.operation, EmptyParams) + param_model = OPERATION_PARAMS_MAP[self.operation] return param_model.model_validate(self.parameters) + class OperationResponse(StrictModel): """Defines the standard response payload for control plane operations.""" diff --git a/scripts/appctl_engine.py b/scripts/appctl_engine.py index 76ef831..1db4413 100755 --- a/scripts/appctl_engine.py +++ b/scripts/appctl_engine.py @@ -244,11 +244,10 @@ def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]: KeyError, ) as err: raw_data = None - with ( - contextlib.suppress(Exception), - open(manifest_path, "r", encoding="utf-8") as f, - ): + with contextlib.suppress(Exception), open(manifest_path, "r", encoding="utf-8") as f: raw_data = yaml.safe_load(f) + + app_dict = raw_data if isinstance(raw_data, dict) else {} apps.append( sites_app_from_manifest( @@ -516,12 +515,10 @@ def check_ssl_cert( try: ctx = ssl.create_default_context() - with ( - socket.create_connection((domain, port), timeout=timeout) as sock, - ctx.wrap_socket(sock, server_hostname=domain) as ssock, - ): - raw_cert = ssock.getpeercert() - cert = raw_cert if isinstance(raw_cert, dict) else {} + with socket.create_connection((domain, port), timeout=timeout) as sock: # noqa: SIM117 + with ctx.wrap_socket(sock, server_hostname=domain) as ssock: + raw_cert = ssock.getpeercert() + cert = raw_cert if isinstance(raw_cert, dict) else {} not_after_str = str(cert.get("notAfter", "")) days_remaining = None diff --git a/scripts/core_manifest.py b/scripts/core_manifest.py index 03bb842..590b582 100644 --- a/scripts/core_manifest.py +++ b/scripts/core_manifest.py @@ -164,30 +164,16 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]: if SEMVER_TAG_RE.match(ref): return RefType.TAG, ref - # Standard branch naming patterns - if ref in { - "main", - "master", - "develop", - "dev", - "trunk", - "staging", - "prod", - "production", - }: - return RefType.BRANCH, ref - - if ref.startswith(("feat/", "fix/", "release/", "chore/", "refactor/")): - return RefType.BRANCH, ref - - # Fallback default: non-versioned arbitrary string treated as branch + # Non-versioned arbitrary string treated as branch return RefType.BRANCH, ref + class SourceConfig(BaseModel): """Upstream source provenance descriptor.""" - model_config = ConfigDict(extra="forbid") + model_config = ConfigDict(extra="forbid", ignored_types=(dict,)) + url: str ref: str = "main" @@ -235,7 +221,8 @@ class SourceConfig(BaseModel): class DeploymentConfig(BaseModel): """Continuous deployment strategy and action policy.""" - model_config = ConfigDict(extra="forbid") + model_config = ConfigDict(extra="forbid", ignored_types=(dict,)) + strategy: str = "compose" branch: str = "main" @@ -275,7 +262,8 @@ class DeploymentConfig(BaseModel): class HomepageConfig(BaseModel): """Dashboard card metadata for Homepage.""" - model_config = ConfigDict(extra="forbid") + model_config = ConfigDict(extra="forbid", ignored_types=(dict,)) + title: str group: str = "Applications" @@ -301,7 +289,12 @@ class Manifest(BaseModel): 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, + ignored_types=(dict,), + ) + name: str schema_version: str = Field(default="1.0", alias="schemaVersion") diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..090393f --- /dev/null +++ b/setup.cfg @@ -0,0 +1,6 @@ +[mutmut] +also_copy= + pyproject.toml + docker-compose.yml + config + scripts From 3230e08bf9ec157bf533f2883ec01e4f5685ff69 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 23 Oct 2026 16:18:02 -0500 Subject: [PATCH 16/43] test(mutation): harden assertion boundaries and eliminate surviving mutants across unit suite Harden unit test assertions and coverage across core control plane modules based on mutation testing findings. - tests/unit/test_appctl_cli.py: preserve PYTHONPATH in subprocess environment; add coverage for empty workload lists, core service display, rich metadata, SSL status formatting (_format_ssl_info), and resolve JSON output. - tests/unit/test_appctl_auth.py: assert specific ErrorCode on permission denials; verify operator denial without explicit target on mutating operations. - tests/unit/test_appctl_audit.py: verify journal serialization and entry ordering. - tests/unit/test_appctl_contracts.py: verify sanitize_validation_error strips secret token values and exact error details. - tests/unit/test_appctl_router.py: assert RouterValidationError on whitespace domains and verify domain canonicalization. - tests/unit/test_core_manifest.py: anchor empty URL regex validation; verify rejection of root repository URLs (https://git.example.com/). - tests/unit/test_provenance.py: verify Class B workload image-only status and default timeout enforcement in resolve_upstream_provenance(). Rationale: Mutation analysis identified weak substring assertions and missing branch coverage across CLI output formatting and security boundaries. Hardening these assertions kills surviving mutants and prevents behavioral regressions. --- tests/unit/test_appctl_audit.py | 21 +++++ tests/unit/test_appctl_auth.py | 59 ++++++++++++- tests/unit/test_appctl_cli.py | 132 ++++++++++++++++++++++++++++ tests/unit/test_appctl_contracts.py | 23 +++-- tests/unit/test_appctl_router.py | 16 ++++ tests/unit/test_core_manifest.py | 59 ++++++++++++- tests/unit/test_provenance.py | 20 +++++ 7 files changed, 319 insertions(+), 11 deletions(-) diff --git a/tests/unit/test_appctl_audit.py b/tests/unit/test_appctl_audit.py index ce69250..92edd18 100644 --- a/tests/unit/test_appctl_audit.py +++ b/tests/unit/test_appctl_audit.py @@ -112,9 +112,13 @@ def test_audit_logger_writes_valid_jsonl_lifecycle( message="Workload updated and reconciled successfully", ) assert evt_comp.phase == AuditPhase.COMPLETED + assert evt_comp.target == "jellyfin" + assert evt_comp.parameters == {"expected_branch": "main", "build": False} assert evt_comp.result is not None assert evt_comp.result.status == "SUCCESS" assert evt_comp.result.exit_code == 0 + assert evt_comp.result.duration_ms == 1450 + assert evt_comp.result.message == "Workload updated and reconciled successfully" assert evt_comp.result.commit_sha == "a1b2c3d" # Read and validate JSONL file contents @@ -153,10 +157,14 @@ def test_audit_logger_writes_failed_event( assert len(lines) == 1 event = AuditEvent.model_validate(json.loads(lines[0])) assert event.phase == AuditPhase.FAILED + assert event.target == "jellyfin" + assert event.parameters == {"recreate": True} assert event.result is not None assert event.result.status == "FAILED" assert event.result.exit_code == 1 assert event.result.error_code == "ERR_EXECUTION_FAILED" + assert event.result.duration_ms == 320 + assert event.result.message == "Docker compose failed with exit code 1" def test_audit_logger_writes_denied_event( @@ -334,3 +342,16 @@ def test_homepage_sync_lock_acquires_designated_file(temp_lock_dir: Path): assert lock.lock_path.name == "_homepage_sync.lock" assert exc_info.value.target == "_homepage_sync" + + +def test_target_lock_manager_sanitizes_special_characters_and_supports_env( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + custom_lock_dir = tmp_path / "custom_locks" + monkeypatch.setenv("APPCTL_LOCK_DIR", str(custom_lock_dir)) + manager = TargetLockManager() + assert manager.lock_dir == custom_lock_dir + + with manager.lock_target("special/tenant:workload@v1!#$") as lock: + assert lock.lock_path.name == "special_tenant_workload_v1___.lock" + assert lock.lock_path.exists() diff --git a/tests/unit/test_appctl_auth.py b/tests/unit/test_appctl_auth.py index da980db..07f36f4 100644 --- a/tests/unit/test_appctl_auth.py +++ b/tests/unit/test_appctl_auth.py @@ -219,10 +219,36 @@ repositories: assert "unknown_app" not in admitted -def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path): +def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: Path): + deploy_file = tmp_path / "deployments.json" + deploy_file.write_text(json.dumps({ + "repositories": { + "app1": { + "path": "/home/operator/Sites/app1", + "aliases": [123, None, " ", "valid_alias"] + } + } + }), encoding="utf-8") + + admitted = load_admitted_workloads(deploy_file) + assert "app1" in admitted + assert "valid_alias" in admitted + assert 123 not in admitted + assert None not in admitted + assert "" not in admitted + + +def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): admitted = load_admitted_workloads(tmp_path / "missing.yaml") assert admitted == set() + # Test HOMELAB_DEPLOYMENTS_FILE fallback + deploy_file = tmp_path / "env_deploy.yaml" + deploy_file.write_text("repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8") + monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deploy_file)) + admitted_env = load_admitted_workloads(None) + assert "env_app" in admitted_env + # --------------------------------------------------------------------------- # RBAC Policy Matrix Enforcement @@ -274,6 +300,37 @@ def test_rbac_operator_denied_on_core_targets( with pytest.raises(AuthorizationError) as exc_info: enforce_rbac(operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads) assert f"not permitted to target core service '{core_svc}'" in str(exc_info.value) + assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED + + +def test_rbac_operator_denied_without_target_on_mutating_or_sensitive_ops( + admitted_workloads: set[str], +): + operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") + + for op in [OperationType.WORKLOAD_DEPLOY, OperationType.WORKLOAD_UPDATE, OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]: + with pytest.raises(AuthorizationError) as exc_info: + enforce_rbac(operator, op, None, admitted_workloads) + assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value) + assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED + + with pytest.raises(AuthorizationError) as exc_info: + enforce_rbac(operator, op, "", admitted_workloads) + assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value) + assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED + + +def test_rbac_operator_with_default_admitted_workloads(monkeypatch: pytest.MonkeyPatch, tmp_path: Path): + deployments_file = tmp_path / "deployments.yaml" + deployments_file.write_text("repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8") + monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file)) + + operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") + enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "customapp", admitted_workloads=None) + + with pytest.raises(AuthorizationError) as exc_info: + enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unknownapp", admitted_workloads=None) + assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED def test_rbac_operator_denied_on_unregistered_workload( diff --git a/tests/unit/test_appctl_cli.py b/tests/unit/test_appctl_cli.py index 48d022d..23e6e58 100644 --- a/tests/unit/test_appctl_cli.py +++ b/tests/unit/test_appctl_cli.py @@ -184,6 +184,135 @@ def test_cli_format_response_renders_workload_get_info(): assert "✨ Retrieved metadata" not in rendered +def test_cli_format_response_renders_empty_workload_list(): + resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_list_empty", + operation=OperationType.WORKLOAD_LIST, + result={"total": 0, "workloads": []}, + output="", + ) + rendered = format_response(resp, raw_json=False) + assert rendered == "ℹ️ No workloads found." + + +def test_cli_format_response_renders_core_service_and_rich_metadata(): + resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_get_core", + operation=OperationType.WORKLOAD_GET, + target="traefik", + result={ + "workload": { + "name": "traefik", + "type": "core_service", + "dir_path": "/home/operator/Core", + "domain": "traefik.example.test", + "container": "traefik-proxy", + "description": "Edge Ingress", + "aliases": ["edge"], + "networks": ["proxy-net", "internal"], + "auth": False, + "visible": False, + "source": { + "url": "https://git.example.com/repo.git", + "ref": "main", + }, + "manifest_error": "Syntax error in app.yaml", + "ssl": { + "status": "valid", + "issuer": "Let's Encrypt", + "formatted_expiry": "2027-01-01", + }, + }, + }, + output="", + ) + rendered = format_response(resp, raw_json=False) + assert "ℹ️ Core Infrastructure Service: traefik" in rendered + assert "Container: traefik-proxy" in rendered + assert "Aliases: edge" in rendered + assert "Networks: proxy-net, internal" in rendered + assert "Auth Protected: False" in rendered + assert "Dashboard: Hidden" in rendered + assert "Source URL: https://git.example.com/repo.git" in rendered + assert "Target Ref: main" in rendered + assert "⚠️ Manifest Validation Error:" in rendered + assert "Syntax error in app.yaml" in rendered + assert "🔒 SSL/TLS Certificate:" in rendered + assert "Status: valid" in rendered + + +def test_cli_format_response_renders_ssl_info(): + resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_ssl_01", + operation=OperationType.PLATFORM_SSL, + result={ + "ssl": { + "domain": "app.example.test", + "status": "valid", + "issuer": "Let's Encrypt Authority X3", + "subject": "CN=app.example.test", + "not_after": "2027-01-01 00:00:00 GMT", + "days_remaining": 75, + "formatted_expiry": "in 75 days", + "error": "Near expiration warning", + } + }, + output="", + ) + rendered = format_response(resp, raw_json=False) + assert "🔒 SSL/TLS Certificate: app.example.test" in rendered + assert "Domain: app.example.test" in rendered + assert "Status: valid" in rendered + assert "Issuer: Let's Encrypt Authority X3" in rendered + assert "Subject: CN=app.example.test" in rendered + assert "Expiration: 2027-01-01 00:00:00 GMT" in rendered + assert "Days Remaining: 75 days (in 75 days)" in rendered + assert "Details/Error: Near expiration warning" in rendered + + +def test_cli_format_response_renders_workload_resolve_json(): + import json + workload_data = {"name": "app1", "dir": "/sites/app1"} + resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_resolve_01", + operation=OperationType.WORKLOAD_RESOLVE, + result={"workload": workload_data}, + output="", + ) + rendered = format_response(resp, raw_json=False) + assert json.loads(rendered) == workload_data + + +def test_cli_format_response_error_without_error_payload(): + from unittest.mock import MagicMock + resp = MagicMock(spec=OperationResponse) + resp.success = False + resp.error = None + rendered = format_response(resp, raw_json=False) + assert rendered == "❌ Error: Unknown error" + + + +def test_cli_format_response_default_success_message(): + resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_succ", + operation=OperationType.PLATFORM_HEALTH, + ) + rendered = format_response(resp, raw_json=False) + assert rendered == "✨ Operation 'platform.health' succeeded." + + + def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path, monkeypatch): """Ensure scripts/appctl executes `complete` and `completion` via appctl_engine.py even when socket exists.""" import os @@ -205,6 +334,9 @@ def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path, "APPCTL_SOCKET_PATH": str(sock_path), "SITES_DIR": str(tmp_path), } + if "PYTHONPATH" in os.environ: + env["PYTHONPATH"] = os.environ["PYTHONPATH"] + res_comp = subprocess.run( [bash_bin, str(appctl_script), "completion", "bash"], env=env, diff --git a/tests/unit/test_appctl_contracts.py b/tests/unit/test_appctl_contracts.py index a76c79b..c04ff57 100644 --- a/tests/unit/test_appctl_contracts.py +++ b/tests/unit/test_appctl_contracts.py @@ -493,16 +493,23 @@ def test_sanitize_validation_error_strips_input_and_url(): assert op_err.code == ErrorCode.ERR_VALIDATION_FAILED assert op_err.message == "Request payload validation failed" assert op_err.details is not None - assert len(op_err.details) > 0 + assert len(op_err.details) == 1 + detail = op_err.details[0] # Ensure neither input nor url appears in any details dictionary - for detail in op_err.details: - assert "input" not in detail - assert "url" not in detail - assert "SUPER_SECRET_TOKEN_DO_NOT_LEAK" not in str(detail) - assert "loc" in detail - assert "msg" in detail - assert "type" in detail + assert "input" not in detail + assert "url" not in detail + assert "SUPER_SECRET_TOKEN_DO_NOT_LEAK" not in str(detail) + assert detail["loc"] == ["tail"] + assert detail["type"] == "int_type" + assert "Input should be a valid integer" in detail["msg"] + + # Verify defense-in-depth: exc.errors called with include_input=False and include_url=False + from unittest.mock import MagicMock + mock_exc = MagicMock(spec=ValidationError) + mock_exc.errors.return_value = [{"loc": ("field",), "type": "value_error", "msg": "Invalid"}] + sanitize_validation_error(mock_exc) + mock_exc.errors.assert_called_once_with(include_input=False, include_url=False) # --------------------------------------------------------------------------- diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 2199243..50d0cd1 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -171,6 +171,22 @@ def test_resolve_canonical_domain_precedence(monkeypatch: pytest.MonkeyPatch): monkeypatch.delenv("DOMAIN_SUFFIX") assert resolve_canonical_domain() == "domain-c.test" + # Fails closed when domain is unset + monkeypatch.delenv("DOMAIN") + monkeypatch.setattr("appctl_router.ENGINE_HOMELAB_DOMAIN", "") + with pytest.raises(RouterValidationError, match="Canonical domain is unset"): + resolve_canonical_domain() + + # Fails closed when domain is whitespace only + monkeypatch.setenv("HOMELAB_DOMAIN", " ") + with pytest.raises(RouterValidationError, match="Canonical domain is unset"): + resolve_canonical_domain() + + # Strips leading and trailing whitespace + monkeypatch.setenv("HOMELAB_DOMAIN", " stripped.example.test ") + assert resolve_canonical_domain() == "stripped.example.test" + + def test_assemble_workload_env_constructs_6_layer_environment( mock_workload_dir: Path, monkeypatch: pytest.MonkeyPatch diff --git a/tests/unit/test_core_manifest.py b/tests/unit/test_core_manifest.py index d16eb78..edf2f5e 100644 --- a/tests/unit/test_core_manifest.py +++ b/tests/unit/test_core_manifest.py @@ -57,20 +57,73 @@ def test_validate_transport_rejects_http(insecure_url: str): validate_transport(insecure_url) +@pytest.mark.parametrize( + "empty_or_invalid_url", + [ + "", + " ", + None, + ], +) +def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url): + with pytest.raises(ManifestValidationError, match=r"^Source URL cannot be empty\.$"): + validate_transport(empty_or_invalid_url) # type: ignore[arg-type] + + +@pytest.mark.parametrize( + ("root_path_url", "scheme"), + [ + ("https://git.example.com/", "HTTPS"), + ("ssh://git.example.com/", "SSH"), + ], +) +def test_validate_transport_rejects_root_repository_path(root_path_url: str, scheme: str): + with pytest.raises( + ManifestValidationError, + match=rf"^Malformed {scheme} source URL \(missing repository path\)", + ): + validate_transport(root_path_url) + + @pytest.mark.parametrize( "traversal_url", [ "../../etc/shadow", "/home/operator/secret", "~/vault", - "file:///etc/passwd", + r"repo\windows\payload", + r"..\traversal", ], ) def test_validate_transport_rejects_paths_and_traversal(traversal_url: str): - with pytest.raises(ManifestValidationError): + with pytest.raises( + ManifestValidationError, + match="Prohibited filesystem path or traversal in source URL", + ): validate_transport(traversal_url) +def test_validate_transport_rejects_file_scheme(): + with pytest.raises( + ManifestValidationError, + match="Invalid source.url scheme: 'file:///etc/passwd'", + ): + validate_transport("file:///etc/passwd") + + +@pytest.mark.parametrize( + "empty_ref", + [ + "", + " ", + None, + 12345, + ], +) +def test_classify_ref_empty_or_invalid_defaults_to_main(empty_ref): + assert classify_ref(empty_ref) == (RefType.BRANCH, "main") # type: ignore[arg-type] + + def test_classify_ref_branches(): assert classify_ref("main") == (RefType.BRANCH, "main") assert classify_ref("refs/heads/develop") == (RefType.BRANCH, "develop") @@ -79,6 +132,8 @@ def test_classify_ref_branches(): "feat/manifest-engine", ) assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0") + assert classify_ref("custom-adhoc-branch") == (RefType.BRANCH, "custom-adhoc-branch") + def test_classify_ref_tags(): diff --git a/tests/unit/test_provenance.py b/tests/unit/test_provenance.py index a068658..01c5834 100644 --- a/tests/unit/test_provenance.py +++ b/tests/unit/test_provenance.py @@ -230,3 +230,23 @@ def test_inspect_workload_two_axis(tmp_path: Path): ) assert status_fetch.provenance.status == ProvenanceStatus.SYNCED mock_resolve.assert_called_once() + + +def test_resolve_upstream_provenance_class_b_and_default_timeout(): + # 1. Class B workload (source is None) + prov_class_b = resolve_upstream_provenance(None) + assert prov_class_b.status == ProvenanceStatus.IMAGE_ONLY + assert prov_class_b.message == "Class B workload deploys prebuilt container images directly" + + # 2. Default timeout (10.0s) verification + source = SourceConfig( + url="https://git.example.com/operator/app.git", + ref="main", + ref_type=RefType.BRANCH, + transport=TransportScheme.HTTPS, + ) + with patch("subprocess.run") as mock_run: + mock_run.return_value = MagicMock(returncode=0, stdout="abc1234567890abcdef1234567890abcdef12345\trefs/heads/main\n") + prov = resolve_upstream_provenance(source, local_commit="abc1234") + assert prov.status == ProvenanceStatus.SYNCED + assert mock_run.call_args[1]["timeout"] == 10.0 From ce7ffa8c46afe8c50aec6a92f617a46bf28cde01 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 23 Oct 2026 16:54:11 -0500 Subject: [PATCH 17/43] docs(plan): align roadmap, ADR-0002, and tasks with MCP gateway and decoupling plan - Add master implementation plan in docs/plans/p4-refactor-and-decoupling-plan.md outlining operator identity migration, dynamic LDAP base DN derivation, recursive POSIX ACLs, and host Git safe directory requirements. - Re-scope Milestone P6 in ROADMAP.md, ADR-0002, and decision index to Homelab MCP Gateway, formally deprecating on-server AI deployment compilers in favor of external JSON-RPC protocol tools with human-in-the-loop gating. - Reconcile docs/appctl.md regarding bounded container log snapshots (--tail) and Core platform update mechanics via NixOS rebuilds. - Populate todo.txt with prioritized implementation tasks for the upcoming decoupling and control plane hardening work. --- ROADMAP.md | 18 ++-- docs/appctl.md | 12 ++- .../0002-appctl-control-plane-architecture.md | 7 +- docs/decisions/README.md | 2 +- docs/plans/p4-refactor-and-decoupling-plan.md | 87 +++++++++++++++++++ todo.txt | 8 ++ 6 files changed, 116 insertions(+), 18 deletions(-) create mode 100644 docs/plans/p4-refactor-and-decoupling-plan.md diff --git a/ROADMAP.md b/ROADMAP.md index 03b290d..1145ab5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -46,7 +46,7 @@ It describes the implementation trajectory and phased engineering milestones for | **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0 with Pydantic v2 fail-closed models (`core_manifest.py`), two-axis status inspection, unified `appctl_engine.py`. | | **P4** | **Control Plane Daemon** | API & Dispatch | ✅ **Completed** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. | | **P5** | **Identity & Secrets** | Auth & Providers | 🎯 **Current / Up Next** | LLDAP RBAC group mapping, Authelia ForwardAuth header integration, user-scoped token lifecycle, `SecretProvider` reference resolution. | -| **P6** | **Deployment Model & AI**| Intent Authoring | ⏳ **Planned** | Capability catalog, `DeploymentProposal` $\to$ `DeploymentModel` compiler, Git commit pipeline. | +| **P6** | **Homelab MCP Gateway** | Protocol Integration | ⏳ **Planned** | Standardized JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`), client-side human-in-the-loop approvals, deprecation of on-server AI proposal compilers. | | **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. | --- @@ -122,15 +122,15 @@ It describes the implementation trajectory and phased engineering milestones for --- -### Milestone P6: Homelab Deployment Model & AI Authoring Workflow -**Status**: ⏳ **Planned** -* **Objective**: Enable safe, human-reviewed workload authoring from upstream repositories. +### Milestone P6: Homelab MCP Gateway (Protocol Tool Integration) +**Status**: ⏳ **Planned** *(Amended: Deprecated on-server `DeploymentProposal` compiler in favor of decoupled Model Context Protocol gateway)* +* **Objective**: Expose `appctl` control plane capabilities over standardized JSON-RPC Model Context Protocol (MCP) tools for external AI assistants (Antigravity, Claude Code, Cursor) without running unverified autonomous agents on the appliance host. * **Key Deliverables**: - 1. *Platform Capability Catalog*: Machine-readable specification of Core capabilities and security invariants. - 2. *DeploymentProposal Schema*: Candidate model format produced by AI discovery workflows. - 3. *DeploymentModel Git Pipeline*: Operator approves proposal into a `DeploymentModel`; the model is committed to the version-controlled deployment repository (Git). - 4. *Materialization & Reconciliation*: `appctl` validates the committed model, provisions state roots, compiles platform descriptors (`app.yaml` + Compose), and reconciles running containers. -* **Exit Criteria**: Human approval gate strictly enforced; AI possesses zero execution authority; generated workloads conform to all Core invariants. + 1. *Protocol Tool Gateway*: Standardized MCP server wrapping deterministic `appctl` operations (`appctl_status`, `appctl_logs`, `appctl_deploy`, `appctl_audit`) over JSON-RPC. + 2. *Client-Side Human-in-the-Loop Confirmation*: Native IDE/client confirmation gating for all mutating tools before execution. + 3. *Deprecate On-Server AI Proposal Compiler*: Remove requirements for server-side `DeploymentProposal` $\to$ `DeploymentModel` pipelines; desired state remains standard Git-tracked declarative YAML (`app.yaml` + Compose). + 4. *Schema & Tool Security Guards*: Strict Pydantic parameter validation on incoming MCP tool calls matching `appctl_contracts.py`. +* **Exit Criteria**: External AI clients successfully query status, inspect logs, and request deployments through MCP with strict confirmation gates; Core boundaries remain 100% deterministic with zero autonomous agent code on the host. --- diff --git a/docs/appctl.md b/docs/appctl.md index 02de3a9..cbf6472 100644 --- a/docs/appctl.md +++ b/docs/appctl.md @@ -116,19 +116,23 @@ Restarts the target stack or individual container: * `appctl restart core`: Restarts all Core Compose services. * `appctl restart traefik`: Restarts only the Traefik container. -#### `appctl update ` -Performs a sequential update workflow: +#### `appctl update ` +Performs a sequential update workflow for a Sites workload stack: 1. Verifies that the local Git working tree is clean (aborts if uncommitted changes exist). 2. Runs `git pull --ff-only` to fast-forward the current branch. 3. Runs `docker compose pull` to fetch updated container images. 4. Runs `docker compose up -d --remove-orphans` to recreate containers. 5. Runs `appctl sync` to update the Homepage dashboard. +> [!NOTE] +> Core platform updates are managed via version-controlled NixOS generations (`git pull` followed by `nixos-rebuild switch`), not through `appctl update core` (as Core is mounted read-only for `homelab-appctl.service`). + #### `appctl pull ` Pulls latest container images and recreates the target service. -#### `appctl logs ` -Streams container logs (`docker compose logs -f`). Supports passing specific container names (`appctl logs core traefik` or `appctl logs stalwart`). +#### `appctl logs [--tail N]` +Fetches a bounded snapshot of container logs (default: `--tail 100`). Supports passing a workload or targeted Core service container (e.g., `appctl logs traefik`). +*(Note: As an HTTP/1.1 request-response API, log streaming `-f` is replaced by bounded snapshots).* #### `appctl config ` Validates the manifest and renders the resolved Docker Compose configuration with all injected variables. Fails closed if `app.yaml` is missing or invalid. diff --git a/docs/decisions/0002-appctl-control-plane-architecture.md b/docs/decisions/0002-appctl-control-plane-architecture.md index 7a7f462..13b2979 100644 --- a/docs/decisions/0002-appctl-control-plane-architecture.md +++ b/docs/decisions/0002-appctl-control-plane-architecture.md @@ -95,11 +95,10 @@ Chosen option: **Option 3: Authoritative `homelab-appctl.service` Daemon with Si * Shell `eval` and `source` are completely eliminated. Subprocess environments are assembled in memory via an inert pure-Python `KEY=VALUE` reader enforcing `ENV_KEY_RE`, `RESERVED_ENV_KEYS`, and canonical domain precedence (`HOMELAB_DOMAIN` $\to$ `DOMAIN_SUFFIX` $\to$ `DOMAIN`). * Every workload mutation and `workload.config` call enforces path containment, `core_manifest.parse_manifest()`, and `validate_compose_security()` pre-flight inspection before invoking Docker Compose. -#### 6. Declarative Git Truth, Five-Stage Deployment Model & AI Boundary (P5–P7 Trajectory) +#### 6. Declarative Git Truth, Model Context Protocol (MCP) Gateway & AI Boundary (P5–P7 Trajectory) * **Git is Authoritative**: Approved deployment definitions are versioned in Git; `appctl` reconciles desired Git state into running containers. -* **Five-Stage Model Lifecycle (P6)**: - $$\text{Repository} \xrightarrow{\text{Investigation}} \text{Application Profile} \xrightarrow{\text{Proposal}} \text{DeploymentProposal} \xrightarrow{\text{Human Selection}} \text{DeploymentModel (Git)} \xrightarrow{\text{appctl Materialize}} \text{Deployment Definition} \xrightarrow{\text{Reconcile}} \text{Containers}$$ -* **AI Authoring Boundary (P6)**: AI agents act strictly as upstream `DeploymentProposal` generators with zero execution or mutation authority. +* **Architecture Amendment (2026-10-23 — MCP Tool Gateway Supersedes On-Server Authoring)**: + The 5-stage on-server AI deployment authoring compiler (`ApplicationProfile` $\to$ `DeploymentProposal` $\to$ `DeploymentModel`) originally planned for Milestone P6 is **deprecated and superseded by a decoupled Model Context Protocol (MCP) Tool Gateway**. Rather than building bespoke AI authoring engines or autonomous agents into the appliance host, platform management operations (`appctl_status`, `appctl_deploy`, `appctl_logs`, `appctl_audit`) will be exposed via standardized JSON-RPC MCP tools consumed by external developer clients (Antigravity, Claude Code, Cursor) with native human-in-the-loop confirmation. The deterministic boundary of `appctl` is preserved, with zero autonomous AI agent code executing inside the appliance host. * **Secret Reference Invariant (P5)**: Manifests reference secrets by key (`secretKeyRef`) resolved at runtime via `SecretProvider`, never storing plaintext credentials in Git. * **Client Decoupling (P7)**: Homepage remains a read-only status portal; interactive web management belongs to a dedicated Operations UI client consuming `POST /v1/operations`. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index e60cdde..a18664e 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -38,7 +38,7 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using 2. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**: Every mutating operation and sensitive read (`workload.config`, `workload.logs`) requires an authenticated SHA-256 Bearer token (`/run/secrets/appctl/tokens.json`); tokenless UDS calls fall back via `SO_PEERCRED` strictly to `homelab-viewer` read-only inspection. 3. **Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)**: Daemon executes as `homelab-appctl:homelab-operators` with mode `0600` append-only `/var/log/homelab/appctl/audit.jsonl` and a pre-execution `DISPATCHED` disk guard. 4. **GitOps Worker Unification & Pure-Python Pre-Flight (`DEC-04`, `DEC-05`)**: `gitops_dispatcher.py` worker delegates `workload.update` to the daemon; shell `source`/`eval` are replaced with pure-Python `.env` parsing and mandatory `validate_compose_security()` pre-flight checks. - 5. **Git Truth, Five-Stage Deployment Model & AI Boundary (P5–P7)**: Git remains authoritative deployment state; separates `ApplicationProfile` $\to$ `DeploymentProposal` (AI) $\to$ `DeploymentModel` (human-approved in Git) $\to$ materialized descriptors; resolves workload secrets via `SecretProvider` (`secretKeyRef`). + 5. **Git Truth, Model Context Protocol (MCP) Gateway & AI Boundary (P5–P7)**: Git remains authoritative deployment state; on-server AI proposal compilers deprecated in favor of a decoupled Model Context Protocol (MCP) tool gateway with human confirmation gating; resolves workload secrets via `SecretProvider` (`secretKeyRef`). ### [ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model](0001-3tier-architecture-and-provenance.md) * **Canonical Document**: [`0001-3tier-architecture-and-provenance.md`](0001-3tier-architecture-and-provenance.md) diff --git a/docs/plans/p4-refactor-and-decoupling-plan.md b/docs/plans/p4-refactor-and-decoupling-plan.md new file mode 100644 index 0000000..e3b9159 --- /dev/null +++ b/docs/plans/p4-refactor-and-decoupling-plan.md @@ -0,0 +1,87 @@ +# 📋 Implementation Plan: Control Plane Hardening, Instance Decoupling & MCP Alignment + +**Document Version**: 1.0 +**Status**: 🚀 Approved for Implementation +**Date**: 2026-10-23 +**Target Milestone**: P4 Hardening & P6 Deprecation +**Branch**: `refactor/appctl-rework` + +--- + +## 1. Executive Summary & Context + +During the pre-merge readiness investigation of the `refactor/appctl-rework` branch, four deployment blockers and several architectural divergences were identified: +1. **Unconfigured Root Domain**: `options.homelab.domain` defaulted to `"example.test"`, which would overwrite live routing templates (`homeserver.env`, `traefik-deployments.env`) upon `nixos-rebuild switch`. +2. **Authelia/LLDAP Base DN Desynchronization**: Compose defaulted `LLDAP_LDAP_BASE_DN` to `dc=example,dc=test`, conflicting with the existing on-host LLDAP database (`dc=,dc=`). +3. **Operator Identity Coupling**: Core configurations referenced legacy operator username literals rather than a generic system operator (`operator`). +4. **POSIX ACL & Git Dubious Ownership**: `tmpfiles.rules` used lowercase `a+` (non-recursive), leaving existing checkouts in `~/Sites` unwriteable to `homelab-appctl`. Furthermore, Git 2.35.2+ lacked `safe.directory` declarations for `homelab-appctl`. +5. **AI Authoring Boundary Evolution**: Earlier architectural planning explored an on-server 5-stage deployment authoring pipeline (`ApplicationProfile` $\to$ `DeploymentProposal` $\to$ `DeploymentModel` compiler). This requirement is formally deprecated in favor of a decoupled Model Context Protocol (MCP) tool gateway. + +This plan establishes the concrete implementation work packages to resolve these findings and ensure 100% deployment safety. + +--- + +## 2. Architectural Decisions & Scope + +### A. Operator Identity Decoupling (Legacy Operator $\to$ `operator`) +- Standardize the primary platform operator as `operator` with home directory `/home/operator`. +- `config.homelab.operatorUser` defaults to `"operator"`. +- NixOS declares user `operator` (`uid = 1000` or standard user, `extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]`). +- Eliminates hardcoded personal usernames from the Core platform foundation. + +### B. Platform Genericism & Instance Profile +- Core modules in `nixos/modules/` remain strictly generic, defaulting to RFC 2606 placeholders (`example.test`). +- `nixos/configuration.nix` serves as the appliance instance profile where `homelab.domain` and `homelab.operatorUser` are explicitly set (e.g., using the host's configured production domain). +- `LLDAP_LDAP_BASE_DN` is computed dynamically in Nix from `config.homelab.domain` (`domain: example.test` $\implies$ `dc=example,dc=test`), eliminating hardcoded domain strings across templates and Compose files. + +### C. Control Plane Security & POSIX Permissions +- **Recursive ACLs**: Change `a+` to uppercase `A+` for `${config.homelab.sitesDir}` and `${config.homelab.coreDir}/config/homepage` in `systemd.tmpfiles.rules`. +- **Git Safe Directory**: Configure `programs.git.config.safe.directory = [ "/home/operator/Sites/*" ]` for the host. +- **Fail-Closed CLI**: If `/run/homelab/appctl.sock` is unavailable, `scripts/appctl` fails closed with an informative error rather than silently falling back to unauthenticated Bash execution. +- **CLI Status Restoration**: Restore live container inspection (`get_docker_status()`) in `workload.list` and format the `STATUS` column in `scripts/appctl_cli.py`. + +### D. Deprecation of On-Server AI Authoring Pipeline (MCP Gateway Adoption) +- As documented in `~/Brain/02-discussions/homelab/mcp-gateway-and-platform-evolution.md`, on-server AI deployment agents (`DeploymentProposal` compilers) are deprecated. +- Milestone P6 is redefined as the **Homelab MCP Gateway**: + - Exposes deterministic `appctl` operations over JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`, `appctl_audit`). + - Gated by native client-side human confirmation (Antigravity, Claude Code, Cursor). + - Keeps Core 100% deterministic with zero autonomous agent loops executing on the appliance host. + +--- + +## 3. Work Breakdown Structure (WBS) + +### Phase 1: Host Configuration & Identity Migration +- [ ] **Task 1.1**: Update `nixos/configuration.nix` to declare user `operator` and configure `homelab.operatorUser = "operator"` and `homelab.domain` with the configured production domain. +- [ ] **Task 1.2**: Declare `programs.git.config.safe.directory = [ "/home/operator/Sites/*" ]` in `nixos/configuration.nix`. +- [ ] **Task 1.3**: Derive `LLDAP_LDAP_BASE_DN` dynamically from `config.homelab.domain` in `nixos/modules/homeserver.nix` and pass it to `sops.templates."homeserver.env"`. +- [ ] **Task 1.4**: Update `docker-compose.yml` to consume `LLDAP_LDAP_BASE_DN` from `homeserver.env`. +- [ ] **Task 1.5**: Update `systemd.tmpfiles.rules` in `nixos/modules/homeserver.nix` from `a+` to recursive `A+` on `sitesDir`. + +### Phase 2: CLI Hardening & Status Parity +- [ ] **Task 2.1**: Update `scripts/appctl` to fail closed when `[ ! -S "$SOCKET_PATH" ]`, removing the silent fallback to legacy Bash. +- [ ] **Task 2.2**: Update `_op_workload_list` in `scripts/appctl_router.py` to query live container health (`get_docker_status()`). +- [ ] **Task 2.3**: Update `_format_workload_table` in `scripts/appctl_cli.py` to render the `STATUS` column (`🟢 Running (1)` / `🔴 Stopped`). +- [ ] **Task 2.4**: Bootstrap operator admin token documentation and setup instructions in `docs/appctl.md` and `docs/secrets-and-state.md`. + +### Phase 3: Architectural Records & Roadmap Synchronization +- [x] **Task 3.1**: Update `ROADMAP.md` (P6 redefined as Homelab MCP Gateway; on-server AI compiler deprecated). +- [x] **Task 3.2**: Add architectural amendment note to `docs/decisions/0002-appctl-control-plane-architecture.md`. +- [x] **Task 3.3**: Update `docs/decisions/README.md`. +- [x] **Task 3.4**: Update `docs/appctl.md` (clarifying bounded log snapshots and Core update workflow). +- [x] **Task 3.5**: Synchronize `todo.txt` with active implementation tasks. + +--- + +## 4. Verification & Quality Gates + +The implementation must pass: +1. **Static Analysis & Linting**: `ruff check .` and `pyright` (0 errors, 0 warnings). +2. **Full Regression Suite**: All 283 existing unit, security, and invariant tests passing. +3. **New Test Coverage**: + - Assert dynamic LDAP base DN computation from domain. + - Assert `scripts/appctl` fails closed when socket is absent. + - Assert `appctl list` output formatting includes container status. + - Assert platform genericism invariants across updated Nix modules. +4. **Hermetic Flake Check**: `nix flake check` builds cleanly. +5. **NixOS Evaluation**: `nix eval .#nixosConfigurations.server.config.system.build.toplevel.drvPath` evaluates without warnings. diff --git a/todo.txt b/todo.txt index a7e4024..529524e 100644 --- a/todo.txt +++ b/todo.txt @@ -35,3 +35,11 @@ x 2026-10-19 (A) Restore human-readable tabular output, list filter parameters, x 2026-10-19 (A) Add operatorUser to homelab-operators group and configure daemon systemd sandbox HOME and DOCKER_CONFIG in nixos/modules/homeserver.nix +nixos @p4 x 2026-10-19 (A) Provision SOPS appctl/tokens_json and gitops/appctl_token secrets and wire GITOPS_APPCTL_TOKEN_FILE in nixos/secrets.yaml and nixos/modules/homeserver.nix +secrets @p4 x 2026-10-19 (B) Reconcile operational documentation and ROADMAP.md with Milestone P4 control plane daemon architecture +docs @p4 +(A) Migrate operator user from kiskaadee to operator in nixos/configuration.nix and homeserver.nix +nixos @core +(A) Derive LLDAP_LDAP_BASE_DN dynamically from homelab.domain in nixos/modules/homeserver.nix and docker-compose.yml +nixos @auth +(A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms +(A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git +(B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security +(B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux +(B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth +(C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap From 8da559381fece567bf9e519eb486e86de2c574e2 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 27 Oct 2026 00:16:28 -0500 Subject: [PATCH 18/43] feat(nixos): decouple operator identity, derive LDAP base DN, and enforce recursive ACLs - Migrate default administrative user from 'kiskaadee' to generic 'operator' in nixos/configuration.nix. - Configure programs.git.config.safe.directory to allow the homelab-appctl daemon to execute Git commands against operator Sites repositories. - Derive LLDAP_LDAP_BASE_DN dynamically from config.homelab.domain in nixos/modules/homeserver.nix and project it to both lldap and authelia in docker-compose.yml. - Upgrade systemd.tmpfiles.rules for Sites, var/lib, and homepage config to recursive POSIX ACLs ('A+') to ensure automatic permission inheritance for newly created directories and files. - Add security invariant tests asserting LLDAP/Authelia env wiring, dynamic base DN derivation, and recursive ACL rule syntax. --- docker-compose.yml | 1 + nixos/configuration.nix | 13 ++++- nixos/modules/homeserver.nix | 12 +++-- tests/security/test_security_invariants.py | 58 ++++++++++++++++++++++ 4 files changed, 78 insertions(+), 6 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 28c134f..1557b8e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -142,6 +142,7 @@ services: - ./config/authelia:/config environment: - DOMAIN=${DOMAIN} + - LLDAP_LDAP_BASE_DN=${LLDAP_LDAP_BASE_DN} - AUTHELIA_SESSION_SECRET=${AUTHELIA_SESSION_SECRET} - AUTHELIA_STORAGE_ENCRYPTION_KEY=${AUTHELIA_STORAGE_ENCRYPTION_KEY} - AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET=${AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET} diff --git a/nixos/configuration.nix b/nixos/configuration.nix index a2ac096..19f184c 100644 --- a/nixos/configuration.nix +++ b/nixos/configuration.nix @@ -15,7 +15,15 @@ ]; # ── Homelab platform settings ──────────────────────────────────────────────── - homelab.operatorUser = "kiskaadee"; + homelab.operatorUser = "operator"; + + # ── Host Git Safe Directory ────────────────────────────────────────────────── + programs.git = { + enable = true; + config.safe.directory = [ + "/home/${config.homelab.operatorUser}/Sites/*" + ]; + }; # ── SOPS secrets configuration ────────────────────────────────────────────── # Set once here to avoid duplicate-option conflicts across submodules @@ -57,8 +65,9 @@ networking.networkmanager.enable = true; # ── User account ───────────────────────────────────────────────────────────── - users.users.kiskaadee = { + users.users.${config.homelab.operatorUser} = { isNormalUser = true; + description = "Primary server administrator"; openssh.authorizedKeys.keys = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICAVPPMk+WApUd/fo78+lsRGnLKSlY4GDZiNGKwBAifD" ]; diff --git a/nixos/modules/homeserver.nix b/nixos/modules/homeserver.nix index 95970e8..09cc54d 100644 --- a/nixos/modules/homeserver.nix +++ b/nixos/modules/homeserver.nix @@ -28,7 +28,10 @@ }; }; - config = { + config = let + domainParts = lib.splitString "." config.homelab.domain; + ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts); + in { # Define the keys to decrypt from secrets.yaml sops.secrets = (lib.genAttrs [ "dynu/api_key" @@ -62,6 +65,7 @@ owner = config.homelab.operatorUser; content = lib.generators.toKeyValue {} { DOMAIN = config.homelab.domain; + LLDAP_LDAP_BASE_DN = ldapBaseDn; DOCKER_API_VERSION = "1.40"; DYNU_API_KEY = config.sops.placeholder."dynu/api_key"; ACME_EMAIL = config.sops.placeholder."traefik/acme_email"; @@ -241,9 +245,9 @@ # POSIX ACLs granting homelab-appctl traverse and access to operator sites & homepage config "a+ /home/${config.homelab.operatorUser} - - - - u:homelab-appctl:x" "a+ ${config.homelab.coreDir} - - - - u:homelab-appctl:x" - "a+ ${config.homelab.sitesDir} - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" - "a+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" - "a+ ${config.homelab.coreDir}/config/homepage - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" + "A+ ${config.homelab.sitesDir} - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" + "A+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" + "A+ ${config.homelab.coreDir}/config/homepage - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx" ]; # Open ports in the firewall for Traefik, Gitea SSH, GitOps Webhook Receiver, and Mail (SMTP, Submission, SMTPS, IMAPS, ManageSieve) diff --git a/tests/security/test_security_invariants.py b/tests/security/test_security_invariants.py index f186b90..477759a 100644 --- a/tests/security/test_security_invariants.py +++ b/tests/security/test_security_invariants.py @@ -194,6 +194,7 @@ def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests( CORE_ROOT / "SECURITY.md", CORE_ROOT / "flake.nix", CORE_ROOT / "docker-compose.yml", + CORE_ROOT / "nixos" / "configuration.nix", ] violations = [] @@ -218,3 +219,60 @@ def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests( assert not violations, "Platform genericism violations detected:\n" + "\n".join( violations ) + + +def test_docker_compose_authelia_and_lldap_base_dn(): + """Ensure both lldap and authelia services receive LLDAP_LDAP_BASE_DN in docker-compose.yml.""" + compose_path = CORE_ROOT / "docker-compose.yml" + with open(compose_path, encoding="utf-8") as f: + compose = yaml.safe_load(f) + + services = compose.get("services", {}) + assert "lldap" in services, "lldap service must exist in docker-compose.yml" + assert "authelia" in services, "authelia service must exist in docker-compose.yml" + + def get_env_map(svc_def: dict) -> dict[str, str]: + env_items = svc_def.get("environment", []) + res = {} + for item in env_items: + if isinstance(item, str) and "=" in item: + k, v = item.split("=", 1) + res[k.strip()] = v.strip() + return res + + lldap_env = get_env_map(services["lldap"]) + authelia_env = get_env_map(services["authelia"]) + + assert "LLDAP_LDAP_BASE_DN" in lldap_env, ( + "LLDAP_LDAP_BASE_DN must be declared in lldap environment" + ) + assert "LLDAP_LDAP_BASE_DN" in authelia_env, ( + "LLDAP_LDAP_BASE_DN must be passed to authelia environment for LDAP template expansion" + ) + + +def test_nixos_homeserver_env_template_defines_dynamic_base_dn(): + """Ensure homeserver.nix derives LLDAP_LDAP_BASE_DN dynamically from homelab.domain.""" + homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix" + content = homeserver_nix.read_text(encoding="utf-8") + + assert "LLDAP_LDAP_BASE_DN" in content, ( + "homeserver.nix must define LLDAP_LDAP_BASE_DN in homeserver.env template" + ) + assert 'lib.splitString "."' in content or "splitString" in content, ( + "homeserver.nix must compute LDAP base DN dynamically from domain components" + ) + + +def test_nixos_tmpfiles_rules_use_recursive_acls(): + """Ensure tmpfiles.rules uses uppercase A+ for recursive ACL inheritance on sites and homepage.""" + homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix" + content = homeserver_nix.read_text(encoding="utf-8") + + assert '"A+ ${config.homelab.sitesDir}' in content, ( + "tmpfiles.rules must use uppercase 'A+' for recursive ACL inheritance on sitesDir" + ) + assert '"A+ ${config.homelab.coreDir}/config/homepage' in content, ( + "tmpfiles.rules must use uppercase 'A+' for recursive ACL inheritance on homepage config" + ) + From dae99af189f660ba32f635eed7fd421d0d6f1e58 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 27 Oct 2026 00:17:04 -0500 Subject: [PATCH 19/43] docs(p4): record completion of Phase 1 host decoupling and track build flag task - Mark Tasks 1.1-1.5 complete in docs/plans/p4-refactor-and-decoupling-plan.md and todo.txt. - Register Task 2.5 to wire --build/--no-cache and compose_build --pull in the P4 refactor plan and todo.txt. --- docs/plans/p4-refactor-and-decoupling-plan.md | 11 ++++++----- todo.txt | 9 +++++---- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/docs/plans/p4-refactor-and-decoupling-plan.md b/docs/plans/p4-refactor-and-decoupling-plan.md index e3b9159..b360ed6 100644 --- a/docs/plans/p4-refactor-and-decoupling-plan.md +++ b/docs/plans/p4-refactor-and-decoupling-plan.md @@ -52,17 +52,18 @@ This plan establishes the concrete implementation work packages to resolve these ## 3. Work Breakdown Structure (WBS) ### Phase 1: Host Configuration & Identity Migration -- [ ] **Task 1.1**: Update `nixos/configuration.nix` to declare user `operator` and configure `homelab.operatorUser = "operator"` and `homelab.domain` with the configured production domain. -- [ ] **Task 1.2**: Declare `programs.git.config.safe.directory = [ "/home/operator/Sites/*" ]` in `nixos/configuration.nix`. -- [ ] **Task 1.3**: Derive `LLDAP_LDAP_BASE_DN` dynamically from `config.homelab.domain` in `nixos/modules/homeserver.nix` and pass it to `sops.templates."homeserver.env"`. -- [ ] **Task 1.4**: Update `docker-compose.yml` to consume `LLDAP_LDAP_BASE_DN` from `homeserver.env`. -- [ ] **Task 1.5**: Update `systemd.tmpfiles.rules` in `nixos/modules/homeserver.nix` from `a+` to recursive `A+` on `sitesDir`. +- [x] **Task 1.1**: Update `nixos/configuration.nix` to declare user `operator` and configure `homelab.operatorUser = "operator"` and `homelab.domain` with the configured production domain. +- [x] **Task 1.2**: Declare `programs.git.config.safe.directory = [ "/home/operator/Sites/*" ]` in `nixos/configuration.nix`. +- [x] **Task 1.3**: Derive `LLDAP_LDAP_BASE_DN` dynamically from `config.homelab.domain` in `nixos/modules/homeserver.nix` and pass it to `sops.templates."homeserver.env"`. +- [x] **Task 1.4**: Update `docker-compose.yml` to consume `LLDAP_LDAP_BASE_DN` from `homeserver.env`. +- [x] **Task 1.5**: Update `systemd.tmpfiles.rules` in `nixos/modules/homeserver.nix` from `a+` to recursive `A+` on `sitesDir`. ### Phase 2: CLI Hardening & Status Parity - [ ] **Task 2.1**: Update `scripts/appctl` to fail closed when `[ ! -S "$SOCKET_PATH" ]`, removing the silent fallback to legacy Bash. - [ ] **Task 2.2**: Update `_op_workload_list` in `scripts/appctl_router.py` to query live container health (`get_docker_status()`). - [ ] **Task 2.3**: Update `_format_workload_table` in `scripts/appctl_cli.py` to render the `STATUS` column (`🟢 Running (1)` / `🔴 Stopped`). - [ ] **Task 2.4**: Bootstrap operator admin token documentation and setup instructions in `docs/appctl.md` and `docs/secrets-and-state.md`. +- [ ] **Task 2.5**: Wire `--build` and `--no-cache` in `scripts/appctl_cli.py`, pass `--pull` during `compose_build` in `scripts/appctl_router.py`, and document source-built action policy in `docs/appctl.md`. ### Phase 3: Architectural Records & Roadmap Synchronization - [x] **Task 3.1**: Update `ROADMAP.md` (P6 redefined as Homelab MCP Gateway; on-server AI compiler deprecated). diff --git a/todo.txt b/todo.txt index 529524e..4f8f3ce 100644 --- a/todo.txt +++ b/todo.txt @@ -35,11 +35,12 @@ x 2026-10-19 (A) Restore human-readable tabular output, list filter parameters, x 2026-10-19 (A) Add operatorUser to homelab-operators group and configure daemon systemd sandbox HOME and DOCKER_CONFIG in nixos/modules/homeserver.nix +nixos @p4 x 2026-10-19 (A) Provision SOPS appctl/tokens_json and gitops/appctl_token secrets and wire GITOPS_APPCTL_TOKEN_FILE in nixos/secrets.yaml and nixos/modules/homeserver.nix +secrets @p4 x 2026-10-19 (B) Reconcile operational documentation and ROADMAP.md with Milestone P4 control plane daemon architecture +docs @p4 -(A) Migrate operator user from kiskaadee to operator in nixos/configuration.nix and homeserver.nix +nixos @core -(A) Derive LLDAP_LDAP_BASE_DN dynamically from homelab.domain in nixos/modules/homeserver.nix and docker-compose.yml +nixos @auth -(A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms -(A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git +x 2026-10-23 (A) Migrate operator user from kiskaadee to operator in nixos/configuration.nix and homeserver.nix +nixos @core +x 2026-10-23 (A) Derive LLDAP_LDAP_BASE_DN dynamically from homelab.domain in nixos/modules/homeserver.nix and docker-compose.yml +nixos @auth +x 2026-10-23 (A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms +x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git (B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security (B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux (B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth +(B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4 (C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap From 7c1b9b75c57c9f54ee5d0d3701dbc7c73727dab7 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 30 Oct 2026 07:59:28 -0500 Subject: [PATCH 20/43] fix(cli): enforce fail-closed daemon socket check and remove legacy Bash fallback - Remove 312 lines of legacy Bash orchestration fallback in scripts/appctl - Fail closed with exit code 1 and actionable diagnostic error on stderr when socket is absent - Retain fast-path local shell completion handlers (complete, completion) - Auto-detect .venv Python interpreter when PYTHON_BIN is unset - Migrate test_appctl_env_injection_resilience to test production P4 environment assembly - Add unit tests for missing socket and offline completion in test_appctl_cli.py - Mark item completed in todo.txt Closes #9 Refs #9 --- scripts/appctl | 322 ++------------------- tests/security/test_security_invariants.py | 75 +++-- tests/unit/test_appctl_cli.py | 76 +++++ todo.txt | 2 +- 4 files changed, 138 insertions(+), 337 deletions(-) diff --git a/scripts/appctl b/scripts/appctl index 81ba6e7..5f6bc10 100755 --- a/scripts/appctl +++ b/scripts/appctl @@ -1,189 +1,26 @@ #!/usr/bin/env bash # appctl - Unified, Manifest-Driven Container Orchestrator -# Discovers individual application repositories located in ~/Sites/*/ -# Injects global homelab secrets, per-app metadata from app.yaml, and monitors Git sync +# Thin CLI wrapper delegating operational commands to homelab-appctl.service over UDS set -e SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ENGINE="$SCRIPT_DIR/appctl_engine.py" -PYTHON_BIN="${PYTHON_BIN:-python3}" +if [ -z "$PYTHON_BIN" ]; then + if [ -x "$SCRIPT_DIR/../.venv/bin/python3" ]; then + PYTHON_BIN="$SCRIPT_DIR/../.venv/bin/python3" + else + PYTHON_BIN="python3" + fi +fi SOCKET_PATH="${APPCTL_SOCKET_PATH:-/run/homelab/appctl.sock}" CLI_CLIENT="$SCRIPT_DIR/appctl_cli.py" -# If daemon Unix domain socket exists, delegate operational commands directly to thin client -# (fast-path local completion and resolution helpers through appctl_engine.py) +# Fast-path local shell completion helpers case "${1:-}" in - complete|completion|resolve) - ;; - *) - if [ -S "$SOCKET_PATH" ] && [ -f "$CLI_CLIENT" ]; then - exec "$PYTHON_BIN" "$CLI_CLIENT" "$@" - fi - ;; -esac - -ENV_FILE="/run/secrets/rendered/traefik-deployments.env" -if [ ! -f "$ENV_FILE" ] && [ -f "/run/secrets/traefik-deployments.env" ]; then - ENV_FILE="/run/secrets/traefik-deployments.env" -fi -export SITES_DIR="${SITES_DIR:-$HOME/Sites}" -export CORE_DIR="${CORE_DIR:-$HOME/Core}" -export ENV_FILE - -# Source global secrets/environment if available -HOMESERVER_ENV="/run/secrets/rendered/homeserver.env" -if [ ! -f "$HOMESERVER_ENV" ] && [ -f "/run/secrets/homeserver.env" ]; then - HOMESERVER_ENV="/run/secrets/homeserver.env" -fi -if [ -f "$HOMESERVER_ENV" ]; then - set -a - # shellcheck disable=SC1090 - source "$HOMESERVER_ENV" - set +a -fi - -if [ -f "$ENV_FILE" ]; then - set -a - # shellcheck disable=SC1090 - source "$ENV_FILE" - set +a -fi - -# Lock the homelab root domain before setup_app_env can mutate $DOMAIN -# Canonical precedence: HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN -export HOMELAB_DOMAIN="${HOMELAB_DOMAIN:-${DOMAIN_SUFFIX:-${DOMAIN:-}}}" - -# Show help usage -show_help() { - echo "🚀 appctl - Homelab Container Orchestrator" - echo "" - echo "Usage: appctl [service] [options...]" - echo "" - echo "Commands:" - echo " list, status [--fetch] [--core] [--ssl] List all applications with Git sync & container status" - echo " ssl [service] Inspect SSL/TLS certificates across homelab domains" - echo " info [--ssl] Display comprehensive application & Git diagnostics" - echo " up Start/build a service stack or Core component" - echo " down Stop and remove a service stack or Core component" - echo " restart Restart a service stack, Core component, or entire Core" - echo " update Full stack update (git pull -> compose pull -> recreate)" - echo " pull Pull latest images and recreate service or Core component" - echo " logs Stream service or Core component logs" - echo " config Validate and view resolved compose configuration" - echo " sync Synchronize Homepage dashboard services.yaml from app.yaml" - echo " completion [bash] Output shell autocompletion script" -} - -# Setup application environment based on resolved metadata -setup_app_env() { - local query="$1" - local resolved_json - resolved_json=$("$PYTHON_BIN" "$ENGINE" resolve "$query" || true) - - if [ -z "$resolved_json" ]; then - echo "❌ Error: Service '$query' not found under $SITES_DIR or Core" - exit 1 - fi - - # Extract fields via python json - TARGET_TYPE=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('type', 'app'))" "$resolved_json") - APP_DIR=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['dir_path'])" "$resolved_json") - CANONICAL_NAME=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['name'])" "$resolved_json") - TARGET_CONTAINER=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('container', ''))" "$resolved_json") - - if [ "$TARGET_TYPE" = "core" ] || [ "$TARGET_TYPE" = "core_service" ]; then - if [ ! -d "$CORE_DIR" ]; then - echo "❌ Error: Core directory not found at $CORE_DIR" - exit 1 - fi - CORE_ENV_FILE="/run/secrets/rendered/homeserver.env" - if [ ! -f "$CORE_ENV_FILE" ] && [ -f "/run/secrets/homeserver.env" ]; then - CORE_ENV_FILE="/run/secrets/homeserver.env" - fi - COMPOSE_ENV_ARG=() - if [ -f "$CORE_ENV_FILE" ]; then - COMPOSE_ENV_ARG=(--env-file "$CORE_ENV_FILE") - fi - return - fi - - RESOLVED_DOMAIN=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['domain'])" "$resolved_json") - - # 1. Base infrastructure defaults - export PROXY_NETWORK="${PROXY_NETWORK:-proxy-net}" - export NETWORK_NAME="${NETWORK_NAME:-$PROXY_NETWORK}" - export CERT_RESOLVER="${CERT_RESOLVER:-myresolver}" - export DOMAIN_SUFFIX="${DOMAIN_SUFFIX:-$HOMELAB_DOMAIN}" - - # 2. Canonical application identity - export SERVICE_NAME="$CANONICAL_NAME" - export CONTAINER_NAME="$CANONICAL_NAME" - export SERVICE_DOMAIN="$RESOLVED_DOMAIN" - export DOMAIN="$RESOLVED_DOMAIN" - - # 3. Dynamic environment variables from app.yaml (e.g. PROJECT_PATH, MEDIA_PATH, etc.) - while IFS= read -r -d '' k && IFS= read -r -d '' v; do - export "$k=$v" - done < <("$PYTHON_BIN" -c " -import json, re, sys -RESERVED = {'PATH', 'LD_PRELOAD', 'IFS', 'SHELL', 'USER', 'CORE_DIR', 'SITES_DIR', 'ENV_FILE', 'HOMESERVER_ENV'} -d = json.loads(sys.argv[1]) -env_dict = d.get('env', {}) -if isinstance(env_dict, dict): - for k, v in env_dict.items(): - k_str = str(k).strip() - if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', k_str) or k_str in RESERVED: - continue - if v is not None and v != '': - sys.stdout.buffer.write(k_str.encode('utf-8') + b'\0' + str(v).encode('utf-8') + b'\0') -" "$resolved_json") - - # 4. Source local .env if present - if [ -f "$APP_DIR/.env" ]; then - set -a - # shellcheck disable=SC1090 - source "$APP_DIR/.env" - set +a - fi - - # 5. Source local app.env if present - if [ -f "$APP_DIR/app.env" ]; then - set -a - # shellcheck disable=SC1090 - source "$APP_DIR/app.env" - set +a - fi -} - -if [ $# -lt 1 ]; then - show_help - exit 1 -fi - -COMMAND=$1 -APP=$2 - -case "$COMMAND" in - list|status) - "$PYTHON_BIN" "$ENGINE" list "${@:2}" - ;; - ssl) - "$PYTHON_BIN" "$ENGINE" ssl "${@:2}" - ;; - info) - if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi - "$PYTHON_BIN" "$ENGINE" info "${@:2}" - ;; - sync) - "$PYTHON_BIN" "$ENGINE" sync "${@:2}" - ;; complete) - "$PYTHON_BIN" "$ENGINE" complete "${@:2}" - ;; - resolve) - "$PYTHON_BIN" "$ENGINE" resolve "${@:2}" + exec "$PYTHON_BIN" "$ENGINE" complete "${@:2}" ;; completion) cat <<'EOF' @@ -199,7 +36,7 @@ _appctl_completions() { cword=$COMP_CWORD fi - local commands="list status ssl info up down restart update pull logs config sync completion" + local commands="list status ssl info up down restart update pull logs config sync health resolve completion" if [ "$cword" -eq 1 ]; then COMPREPLY=( $(compgen -W "$commands" -- "$cur") ) @@ -245,138 +82,13 @@ _appctl_completions() { } complete -F _appctl_completions appctl EOF - ;; - up) - if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi - setup_app_env "$APP" - if [ "$TARGET_TYPE" = "core" ]; then - echo "🚀 Starting Core stack ($CORE_DIR)..." - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "${@:3}" - elif [ "$TARGET_TYPE" = "core_service" ]; then - echo "🚀 Starting Core service: $TARGET_CONTAINER ($CORE_DIR)..." - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "$TARGET_CONTAINER" "${@:3}" - else - echo "🚀 Starting $CANONICAL_NAME ($APP_DIR)..." - cd "$APP_DIR" && docker compose up -d --remove-orphans "${@:3}" - "$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true - fi - ;; - down) - if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi - setup_app_env "$APP" - if [ "$TARGET_TYPE" = "core" ]; then - echo "🛑 Stopping Core stack ($CORE_DIR)..." - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" down "${@:3}" - elif [ "$TARGET_TYPE" = "core_service" ]; then - echo "🛑 Stopping Core service: $TARGET_CONTAINER ($CORE_DIR)..." - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" stop "$TARGET_CONTAINER" "${@:3}" - else - echo "🛑 Stopping $CANONICAL_NAME ($APP_DIR)..." - cd "$APP_DIR" && docker compose down "${@:3}" - "$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true - fi - ;; - restart) - if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi - setup_app_env "$APP" - if [ "$TARGET_TYPE" = "core" ]; then - if [ -n "$3" ] && [[ "$3" != -* ]]; then - echo "🔄 Restarting Core service: $3 ($CORE_DIR)..." - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "$3" "${@:4}" - else - echo "🔄 Restarting Core stack ($CORE_DIR)..." - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "${@:3}" - fi - elif [ "$TARGET_TYPE" = "core_service" ]; then - echo "🔄 Restarting Core service: $TARGET_CONTAINER ($CORE_DIR)..." - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "$TARGET_CONTAINER" "${@:3}" - else - echo "🔄 Restarting $CANONICAL_NAME ($APP_DIR)..." - cd "$APP_DIR" && docker compose down && docker compose up -d "${@:3}" - "$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true - fi - ;; - update) - if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi - setup_app_env "$APP" - if [ "$TARGET_TYPE" = "core" ]; then - echo "🔄 Updating Core stack ($CORE_DIR)..." - if [ -d "$CORE_DIR/.git" ]; then - if [ -n "$(git -C "$CORE_DIR" status --porcelain)" ]; then - echo "❌ Error: Cannot update. Working tree in $CORE_DIR has uncommitted changes." - exit 1 - fi - echo "📥 Pulling latest git changes for Core..." - git -C "$CORE_DIR" pull --ff-only - fi - echo "🐳 Pulling latest Core container images..." - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull - echo "🚀 Recreating Core container stack..." - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "${@:3}" - echo "✨ Core successfully updated!" - exit 0 - fi - - echo "🔄 Updating $CANONICAL_NAME ($APP_DIR)..." - if [ -d "$APP_DIR/.git" ]; then - if [ -n "$(git -C "$APP_DIR" status --porcelain)" ]; then - echo "❌ Error: Cannot update. Working tree in $APP_DIR has uncommitted changes." - echo "Commit or stash your changes before updating." - exit 1 - fi - echo "📥 Pulling latest git changes..." - git -C "$APP_DIR" pull --ff-only - fi - - echo "🐳 Pulling latest container images..." - cd "$APP_DIR" && docker compose pull - - echo "🚀 Recreating container stack..." - cd "$APP_DIR" && docker compose up -d --remove-orphans "${@:3}" - - "$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true - echo "✨ $CANONICAL_NAME successfully updated!" - ;; - pull) - if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi - setup_app_env "$APP" - if [ "$TARGET_TYPE" = "core" ]; then - echo "📥 Pulling latest images for Core stack..." - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull "${@:3}" - elif [ "$TARGET_TYPE" = "core_service" ]; then - echo "📥 Pulling latest image for Core service: $TARGET_CONTAINER..." - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull "$TARGET_CONTAINER" "${@:3}" - else - echo "📥 Pulling latest images for $CANONICAL_NAME..." - cd "$APP_DIR" && docker compose pull && docker compose up -d --remove-orphans "${@:3}" - fi - ;; - logs) - if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi - setup_app_env "$APP" - if [ "$TARGET_TYPE" = "core" ]; then - if [ -n "$3" ] && [[ "$3" != -* ]]; then - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "$3" "${@:4}" - else - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "${@:3}" - fi - elif [ "$TARGET_TYPE" = "core_service" ]; then - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "$TARGET_CONTAINER" "${@:3}" - else - cd "$APP_DIR" && docker compose logs -f "${@:3}" - fi - ;; - config) - if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi - setup_app_env "$APP" - if [ "$TARGET_TYPE" = "core" ] || [ "$TARGET_TYPE" = "core_service" ]; then - cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" config "${@:3}" - else - cd "$APP_DIR" && docker compose config "${@:3}" - fi + exit 0 ;; *) - show_help - exit 1 + if [ ! -S "$SOCKET_PATH" ]; then + echo "❌ Error: appctl daemon socket not found at $SOCKET_PATH. Ensure homelab-appctl.service is running." >&2 + exit 1 + fi + exec "$PYTHON_BIN" "$CLI_CLIENT" "$@" ;; esac diff --git a/tests/security/test_security_invariants.py b/tests/security/test_security_invariants.py index 477759a..440dbdf 100644 --- a/tests/security/test_security_invariants.py +++ b/tests/security/test_security_invariants.py @@ -4,11 +4,14 @@ Security invariant tests for Docker Compose and container isolation. import os import shutil -import subprocess -import sys from pathlib import Path import yaml +from appctl_audit import AuditLogger, TargetLockManager +from appctl_auth import Principal, Role +from appctl_contracts import OperationRequest +from appctl_router import OperationalRouter, assemble_workload_env +from core_manifest import parse_manifest # Comment-out reason: testing pyproject-level pythonpath definition CORE_ROOT = Path(__file__).resolve().parent.parent.parent @@ -101,10 +104,9 @@ def test_no_eval_in_appctl_script(): assert "eval " not in content, "Dangerous 'eval' detected in scripts/appctl!" -def test_appctl_env_injection_resilience(tmp_path: Path): +def test_appctl_env_injection_resilience(tmp_path: Path, monkeypatch): """Ensure environment values from app.yaml cannot execute shell commands via command substitution - - in scripts/appctl during environment setup. Executes scripts/appctl directly with a mock docker binary. + during P4 production environment assembly and router dispatch. Executes OperationalRouter with a mock docker binary. """ canary = tmp_path / "pwned.txt" payload = f"$(touch {canary})" @@ -127,14 +129,22 @@ env: "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. Verify unit-level pure Python environment assembly + monkeypatch.setenv("HOMELAB_DOMAIN", "example.test") + manifest = parse_manifest(app_dir / "app.yaml") + assembled_env = assemble_workload_env(app_dir, manifest, "vuln-app") + assert not canary.exists(), "Command substitution executed during assemble_workload_env!" + assert assembled_env["INJECTION_TEST"] == payload + assert assembled_env["NORMAL_VAR"] == "safe_value" + + # 3. Setup mock docker binary to capture environment without requiring a running Docker daemon mock_bin = tmp_path / "bin" mock_bin.mkdir() mock_docker = mock_bin / "docker" bash_bin = shutil.which("bash") or "bash" mock_docker_script = f"""#!{bash_bin} -if [ "$1" = "compose" ] && [ "$2" = "config" ]; then +if [ "$1" = "compose" ] && [ "$4" = "config" ]; then echo "MOCK_DOCKER_COMPOSE_CONFIG" echo "CAPTURED_INJECTION=$INJECTION_TEST" echo "CAPTURED_NORMAL=$NORMAL_VAR" @@ -145,36 +155,39 @@ exit 0 mock_docker.write_text(mock_docker_script, encoding="utf-8") mock_docker.chmod(0o755) - # 3. Execute scripts/appctl config vuln-app directly - appctl_path = CORE_ROOT / "scripts" / "appctl" - env = os.environ.copy() - if "NIX_PYTHONPATH" in env and "PYTHONPATH" not in env: - env["PYTHONPATH"] = env["NIX_PYTHONPATH"] - env["PATH"] = f"{mock_bin}:{Path(sys.executable).parent}:{env['PATH']}" - env["PYTHON_BIN"] = sys.executable - env["SITES_DIR"] = str(sites_dir) - env["HOMELAB_DOMAIN"] = "example.test" - env["CORE_DIR"] = str(CORE_ROOT) - - res = subprocess.run( - [bash_bin, str(appctl_path), "config", "vuln-app"], - env=env, - capture_output=True, - text=True, - check=False, + # 4. Dispatch workload.config through OperationalRouter + monkeypatch.setenv("PATH", f"{mock_bin}:{os.environ.get('PATH', '')}") + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=sites_dir, + core_dir=CORE_ROOT, + ) + req = OperationRequest.model_validate({ + "operation": "workload.config", + "target": "vuln-app", + }) + admin_principal = Principal( + identity="operator", + role=Role.ADMIN, + token_id="tok_admin", + auth_method="bearer_token", ) - # 4. Assertions: command substitution was not executed, script ran, and mock docker received literal value + resp = router.dispatch(req, admin_principal) + + # 5. Assertions: command substitution was not executed, router succeeded, mock docker received literal value assert not canary.exists(), ( "Command substitution was executed on the host during environment setup!" ) - assert res.returncode == 0, ( - f"appctl config failed: {res.stderr}\nStdout: {res.stdout}" + assert resp.success is True, ( + f"OperationalRouter dispatch failed: {resp.error}" ) - assert "MOCK_DOCKER_COMPOSE_CONFIG" in res.stdout - assert f"CAPTURED_INJECTION={payload}" in res.stdout - assert "CAPTURED_NORMAL=safe_value" in res.stdout - assert "/dangerous/override" not in res.stdout + assert resp.result is not None + output = resp.result.get("output", "") + assert "MOCK_DOCKER_COMPOSE_CONFIG" in output + assert f"CAPTURED_INJECTION={payload}" in output + assert "CAPTURED_NORMAL=safe_value" in output def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests(): diff --git a/tests/unit/test_appctl_cli.py b/tests/unit/test_appctl_cli.py index 23e6e58..cd085e9 100644 --- a/tests/unit/test_appctl_cli.py +++ b/tests/unit/test_appctl_cli.py @@ -360,3 +360,79 @@ def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path, finally: srv.close() + +def test_appctl_wrapper_fails_closed_when_socket_is_missing(tmp_path: Path): + """Ensure scripts/appctl fails closed with exit code 1 and diagnostic stderr when socket is missing.""" + import os + import shutil + import subprocess + import sys + + bash_bin = shutil.which("bash") or "bash" + non_existent_sock = tmp_path / "missing_appctl.sock" + appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl" + + env = { + "PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"), + "PYTHON_BIN": sys.executable, + "HOMELAB_DOMAIN": "example.test", + "APPCTL_SOCKET_PATH": str(non_existent_sock), + "SITES_DIR": str(tmp_path), + } + if "PYTHONPATH" in os.environ: + env["PYTHONPATH"] = os.environ["PYTHONPATH"] + + res = subprocess.run( + [bash_bin, str(appctl_script), "status"], + env=env, + capture_output=True, + text=True, + check=False, + ) + assert res.returncode == 1 + assert "daemon socket not found" in res.stderr + + +def test_appctl_wrapper_fast_paths_completion_without_socket(tmp_path: Path): + """Ensure scripts/appctl completes offline via appctl_engine.py even when socket is missing.""" + import os + import shutil + import subprocess + import sys + + bash_bin = shutil.which("bash") or "bash" + non_existent_sock = tmp_path / "missing_appctl.sock" + appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl" + + env = { + "PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"), + "PYTHON_BIN": sys.executable, + "HOMELAB_DOMAIN": "example.test", + "APPCTL_SOCKET_PATH": str(non_existent_sock), + "SITES_DIR": str(tmp_path), + } + if "PYTHONPATH" in os.environ: + env["PYTHONPATH"] = os.environ["PYTHONPATH"] + + res_comp = subprocess.run( + [bash_bin, str(appctl_script), "completion", "bash"], + env=env, + capture_output=True, + text=True, + check=False, + ) + assert res_comp.returncode == 0 + assert "_appctl_completions()" in res_comp.stdout + + res_words = subprocess.run( + [bash_bin, str(appctl_script), "complete", "services"], + env=env, + capture_output=True, + text=True, + check=False, + ) + assert res_words.returncode == 0 + assert "traefik" in res_words.stdout + assert "core" in res_words.stdout + + diff --git a/todo.txt b/todo.txt index 4f8f3ce..0f22d4b 100644 --- a/todo.txt +++ b/todo.txt @@ -39,7 +39,7 @@ x 2026-10-23 (A) Migrate operator user from kiskaadee to operator in nixos/confi x 2026-10-23 (A) Derive LLDAP_LDAP_BASE_DN dynamically from homelab.domain in nixos/modules/homeserver.nix and docker-compose.yml +nixos @auth x 2026-10-23 (A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git -(B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security +x 2026-10-30 (B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security (B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux (B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth (B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4 From 021c01171bab0116975d6b83a4f20da475877205 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 30 Oct 2026 08:54:16 -0500 Subject: [PATCH 21/43] feat(cli): restore live container status and default two-axis columns in workload.list - Query live container status via get_docker_status() for Sites apps and Core services - Inspect local Git checkout offline by default and query remotes only when --fetch is passed - Fix get_docker_status failure semantics to return Unknown instead of Stopped when Docker is unreachable - Format appctl list table with 5 canonical columns (SERVICE | DEPLOYMENT | PROVENANCE | STATUS | DOMAIN) - Append CERT column when --ssl is passed (6 columns) - Add comprehensive router and CLI unit tests covering live status and manifest error branches - Mark item completed in todo.txt Closes #10 Refs #10 --- scripts/appctl_cli.py | 33 ++++---- scripts/appctl_engine.py | 15 ++++ scripts/appctl_router.py | 24 +++++- tests/unit/test_appctl_cli.py | 96 ++++++++++++++++++++--- tests/unit/test_appctl_engine.py | 70 +++++++++++++++++ tests/unit/test_appctl_router.py | 129 +++++++++++++++++++++++++++++++ todo.txt | 2 +- 7 files changed, 342 insertions(+), 27 deletions(-) diff --git a/scripts/appctl_cli.py b/scripts/appctl_cli.py index 01df017..1fa520e 100755 --- a/scripts/appctl_cli.py +++ b/scripts/appctl_cli.py @@ -58,28 +58,33 @@ def _format_workload_table(workloads: list[dict[str, Any]]) -> str: if has_ssl: lines.append( - f"{'SERVICE':<18} {'TYPE':<14} {'DOMAIN':<30} {'CERT':<24} {'DESCRIPTION'}" + f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}" ) lines.append( - f"{'-------':<18} {'----':<14} {'------':<30} {'----':<24} {'-----------'}" + f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}" ) else: lines.append( - f"{'SERVICE':<18} {'TYPE':<14} {'DOMAIN':<30} {'DESCRIPTION'}" + f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN'}" ) lines.append( - f"{'-------':<18} {'----':<14} {'------':<30} {'-----------'}" + f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------'}" ) for w in workloads: - name = str(w.get("name", "-")) - w_type = str(w.get("type", w.get("app_type", "app"))) - domain = str(w.get("domain", "-")) - desc = str(w.get("description", "")) + name = str(w.get("name") or "-") + domain = str(w.get("domain") or "-") + status = str(w.get("status") or "-") + if w.get("manifest_error"): - desc = f"⚠️ {w['manifest_error']}" - elif w.get("deployment_status"): - desc = f"{w['deployment_status']} ({w.get('provenance_status', '-')})" + dep = "⚠️ Manifest Error" + prov = "⚠️ Invalid Manifest" + elif "deployment_status" in w: + dep = str(w["deployment_status"]) + prov = str(w.get("provenance_status") or "-") + else: + dep = "-" + prov = str(w.get("provenance_status") or "-") if has_ssl: ssl_info = w.get("ssl") @@ -89,10 +94,12 @@ def _format_workload_table(workloads: list[dict[str, Any]]) -> str: else "-" ) lines.append( - f"{name:<18} {w_type:<14} {domain:<30} {cert_status:<24} {desc}" + f"{name:<16} {dep:<22} {prov:<22} {status:<15} {domain:<28} {cert_status}" ) else: - lines.append(f"{name:<18} {w_type:<14} {domain:<30} {desc}") + lines.append( + f"{name:<16} {dep:<22} {prov:<24} {status:<15} {domain}" + ) return "\n".join(lines) diff --git a/scripts/appctl_engine.py b/scripts/appctl_engine.py index 1db4413..c03bb7a 100755 --- a/scripts/appctl_engine.py +++ b/scripts/appctl_engine.py @@ -108,6 +108,10 @@ class CoreService(App): app_type: str = "core_service" dir_path: str = CORE_DIR + @property + def container_name(self) -> str: + return self.container + @dataclass class SitesApp(App): @@ -411,6 +415,11 @@ def get_docker_status( text=True, check=False, ) + if inspect_res.returncode != 0: + err = (inspect_res.stderr or "").lower() + if "no such object" in err or "no such container" in err: + return "🔴 Stopped" + return "❓ Unknown" state = inspect_res.stdout.strip() if state.lower() == "true": return "🟢 Running (1)" @@ -431,6 +440,9 @@ def get_docker_status( text=True, check=False, ) + if res.returncode != 0: + return "❓ Unknown" + container_ids = [c for c in res.stdout.strip().splitlines() if c] if not container_ids: return "🔴 Stopped" @@ -441,6 +453,9 @@ def get_docker_status( text=True, check=False, ) + if inspect_res.returncode != 0: + return "❓ Unknown" + running_states = inspect_res.stdout.strip().splitlines() running_count = sum(1 for s in running_states if s.lower() == "true") total_count = len(container_ids) diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py index 2b51e21..e106af1 100644 --- a/scripts/appctl_router.py +++ b/scripts/appctl_router.py @@ -63,6 +63,7 @@ from appctl_engine import ( check_ssl_cert, cmd_sync_homepage, get_core_services, + get_docker_status, get_sites_apps, resolve_app, ) @@ -74,7 +75,7 @@ from core_manifest import ( parse_manifest, ) from gitops_dispatcher import validate_compose_security -from provenance import inspect_workload_two_axis +from provenance import get_local_checkout_status, inspect_workload_two_axis MAX_OUTPUT_BYTES = 256 * 1024 # 256 KiB cap per invocation @@ -667,24 +668,39 @@ class OperationalRouter: for app in apps: item = app.to_dict() app_path = Path(app.dir_path) - if params.fetch: + docker_status = get_docker_status(dir_path=app_path) + item["status"] = docker_status + + if app.manifest_error: + item["deployment_status"] = "⚠️ Manifest Error" + item["provenance_status"] = "⚠️ Invalid Manifest" + else: manifest_obj = app.manifest_obj or Manifest( name=app.name, domain=app.domain ) two_axis = inspect_workload_two_axis( app_dir=app_path, manifest=manifest_obj, - fetch_upstream=True, + fetch_upstream=params.fetch, + docker_status=docker_status, ) item["deployment_status"] = two_axis.checkout.status_label item["provenance_status"] = two_axis.provenance.status.value + if params.ssl and not app.is_internal: item["ssl"] = check_ssl_cert(app.domain) apps_data.append(item) if params.core: - for svc in get_core_services(core_dir=str(self.core_dir)): + core_checkout = get_local_checkout_status(self.core_dir) + for i, svc in enumerate(get_core_services(core_dir=str(self.core_dir))): svc_dict = svc.to_dict() + svc_dict["status"] = get_docker_status( + dir_path=self.core_dir, + container_name=svc.container_name, + ) + svc_dict["deployment_status"] = core_checkout.status_label if i == 0 else "" + svc_dict["provenance_status"] = "— Core Platform" if params.ssl and not svc.is_internal: svc_dict["ssl"] = check_ssl_cert(svc.domain) apps_data.append(svc_dict) diff --git a/tests/unit/test_appctl_cli.py b/tests/unit/test_appctl_cli.py index cd085e9..5c2ec94 100644 --- a/tests/unit/test_appctl_cli.py +++ b/tests/unit/test_appctl_cli.py @@ -116,7 +116,7 @@ def test_cli_handles_missing_socket(): def test_cli_format_response_renders_workload_list_table(): - """Ensure workload.list renders a human-readable table instead of suppressing it behind result['message'].""" + """Ensure workload.list renders the canonical 5-column layout matching docs/appctl.md.""" resp = OperationResponse( version="1.0", success=True, @@ -129,13 +129,17 @@ def test_cli_format_response_renders_workload_list_table(): "name": "snappymail", "type": "app", "domain": "mail.example.test", - "description": "Webmail client", + "deployment_status": "✓ Synced (main)", + "provenance_status": "✓ Synced", + "status": "🟢 Running (1)", }, { "name": "traefik", "type": "core_service", "domain": "traefik.example.test", - "description": "Edge Reverse Proxy", + "deployment_status": "", + "provenance_status": "— Core Platform", + "status": "🟢 Running (1)", }, ], "message": "Found 2 workloads", @@ -143,15 +147,89 @@ def test_cli_format_response_renders_workload_list_table(): output="", ) rendered = format_response(resp, raw_json=False) - assert "SERVICE" in rendered - assert "DOMAIN" in rendered - assert "snappymail" in rendered - assert "mail.example.test" in rendered - assert "traefik" in rendered - assert "Edge Reverse Proxy" in rendered + lines = rendered.splitlines() + assert len(lines) >= 4 + assert lines[0] == "SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN" + assert lines[1] == "------- ---------- ---------- ------ ------" + assert "snappymail" in lines[2] + assert "✓ Synced (main)" in lines[2] + assert "✓ Synced" in lines[2] + assert "🟢 Running (1)" in lines[2] + assert "mail.example.test" in lines[2] + + assert "traefik" in lines[3] + assert "— Core Platform" in lines[3] + assert "🟢 Running (1)" in lines[3] + assert "traefik.example.test" in lines[3] assert "✨ Found 2 workloads" not in rendered +def test_cli_format_response_renders_workload_list_table_with_ssl(): + """Ensure workload.list with SSL renders the canonical 6-column layout with CERT.""" + resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_list_ssl_01", + operation=OperationType.WORKLOAD_LIST, + result={ + "total": 1, + "workloads": [ + { + "name": "snappymail", + "type": "app", + "domain": "mail.example.test", + "deployment_status": "✓ Synced (main)", + "provenance_status": "✓ Synced", + "status": "🟢 Running (1)", + "ssl": {"status": "🟢 80d remaining"}, + }, + ], + "message": "Found 1 workloads", + }, + output="", + ) + rendered = format_response(resp, raw_json=False) + lines = rendered.splitlines() + assert len(lines) >= 3 + assert lines[0] == "SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN CERT" + assert lines[1] == "------- ---------- ---------- ------ ------ ----" + assert "snappymail" in lines[2] + assert "🟢 80d remaining" in lines[2] + + +def test_cli_format_response_renders_workload_list_table_with_manifest_error(): + """Ensure workload.list renders ⚠️ Manifest Error and ⚠️ Invalid Manifest, and status=None renders as '-'.""" + resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_list_err", + operation=OperationType.WORKLOAD_LIST, + result={ + "total": 1, + "workloads": [ + { + "name": "broken-app", + "type": "app", + "domain": "broken.example.test", + "manifest_error": "Syntax error in app.yaml", + "status": None, + }, + ], + "message": "Found 1 workloads", + }, + output="", + ) + rendered = format_response(resp, raw_json=False) + lines = rendered.splitlines() + assert len(lines) >= 3 + assert "broken-app" in lines[2] + assert "⚠️ Manifest Error" in lines[2] + assert "⚠️ Invalid Manifest" in lines[2] + # Ensure status is '-' and NOT 'None' + assert " None " not in lines[2] + assert " - " in lines[2] + + def test_cli_format_response_renders_workload_get_info(): """Ensure workload.get (appctl info) renders structured workload metadata.""" resp = OperationResponse( diff --git a/tests/unit/test_appctl_engine.py b/tests/unit/test_appctl_engine.py index 1ec3378..2721061 100644 --- a/tests/unit/test_appctl_engine.py +++ b/tests/unit/test_appctl_engine.py @@ -200,6 +200,7 @@ def test_docker_status_parser_running(monkeypatch): def mock_run(args, **kwargs): mock = MagicMock() + mock.returncode = 0 if "ps" in args: mock.stdout = "container123\n" if "inspect" in args: @@ -217,6 +218,7 @@ def test_docker_status_parser_stopped(monkeypatch): def mock_run(args, **kwargs): mock = MagicMock() + mock.returncode = 0 if "ps" in args: mock.stdout = "" return mock @@ -232,6 +234,7 @@ def test_docker_status_parser_degraded(monkeypatch): def mock_run(args, **kwargs): mock = MagicMock() + mock.returncode = 0 if "ps" in args: mock.stdout = "c1\nc2\n" if "inspect" in args: @@ -256,6 +259,7 @@ def test_docker_status_single_container(monkeypatch): def mock_run(args, **kwargs): mock = MagicMock() + mock.returncode = 0 if "authelia" in args: mock.stdout = "true\n" else: @@ -268,6 +272,72 @@ def test_docker_status_single_container(monkeypatch): assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped" +def test_docker_status_compose_ps_daemon_error(monkeypatch): + """Ensure get_docker_status returns '❓ Unknown' when docker compose ps fails (e.g. daemon unreachable).""" + import subprocess + + def mock_run(args, **kwargs): + return subprocess.CompletedProcess( + args=args, + returncode=1, + stdout="", + stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock", + ) + + monkeypatch.setattr("subprocess.run", mock_run) + assert engine.get_docker_status("/fake/dir") == "❓ Unknown" + + +def test_docker_status_compose_inspect_error(monkeypatch): + """Ensure get_docker_status returns '❓ Unknown' when docker inspect fails for compose containers.""" + import subprocess + + def mock_run(args, **kwargs): + if "ps" in args: + return subprocess.CompletedProcess(args=args, returncode=0, stdout="c1\n", stderr="") + return subprocess.CompletedProcess( + args=args, + returncode=1, + stdout="", + stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock", + ) + + monkeypatch.setattr("subprocess.run", mock_run) + assert engine.get_docker_status("/fake/dir") == "❓ Unknown" + + +def test_docker_status_single_container_daemon_error(monkeypatch): + """Ensure get_docker_status returns '❓ Unknown' when inspecting single container fails due to daemon error.""" + import subprocess + + def mock_run(args, **kwargs): + return subprocess.CompletedProcess( + args=args, + returncode=1, + stdout="", + stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock", + ) + + monkeypatch.setattr("subprocess.run", mock_run) + assert engine.get_docker_status("", container_name="traefik") == "❓ Unknown" + + +def test_docker_status_single_container_no_such_object(monkeypatch): + """Ensure get_docker_status returns '🔴 Stopped' when container does not exist.""" + import subprocess + + def mock_run(args, **kwargs): + return subprocess.CompletedProcess( + args=args, + returncode=1, + stdout="", + stderr="Error: No such object: traefik", + ) + + monkeypatch.setattr("subprocess.run", mock_run) + assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped" + + def test_docker_status_error_handling(monkeypatch): """Ensure get_docker_status handles subprocess failures gracefully.""" diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 50d0cd1..26b802a 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -829,3 +829,132 @@ def test_operational_router_workload_list_honors_filter_params( assert mock_ssl.call_count >= 1 +def test_operational_router_workload_list_includes_live_docker_and_two_axis_status( + tmp_path: Path, + viewer_principal: Principal, + mock_workload_dir: Path, + mock_core_dir: Path, +): + """Ensure workload.list always inspects docker status and computes two-axis status for apps and core.""" + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_workload_dir.parent, + core_dir=mock_core_dir, + ) + + with patch("appctl_router.get_docker_status", return_value="🟢 Running (1)") as mock_docker: + # 1. Sites workload offline (fetch=False) + resp = router.dispatch( + OperationRequest.model_validate({ + "operation": "workload.list", + "parameters": {"core": False, "fetch": False, "ssl": False}, + }), + viewer_principal, + ) + assert resp.success is True + assert resp.result is not None + workload = resp.result["workloads"][0] + assert workload["name"] == "snappymail" + assert workload["status"] == "🟢 Running (1)" + assert "deployment_status" in workload + assert "provenance_status" in workload + assert workload["provenance_status"] == "— Not Checked" + mock_docker.assert_called_with(dir_path=mock_workload_dir) + + # 2. Core services included (core=True) + resp_core = router.dispatch( + OperationRequest.model_validate({ + "operation": "workload.list", + "parameters": {"core": True, "fetch": False, "ssl": False}, + }), + viewer_principal, + ) + assert resp_core.success is True + assert resp_core.result is not None + core_workloads = {w["name"]: w for w in resp_core.result["workloads"]} + assert "traefik" in core_workloads + traefik = core_workloads["traefik"] + assert traefik["status"] == "🟢 Running (1)" + assert traefik["provenance_status"] == "— Core Platform" + assert "deployment_status" in traefik + + +def test_operational_router_workload_list_fetch_passes_fetch_upstream( + tmp_path: Path, + viewer_principal: Principal, + mock_workload_dir: Path, + mock_core_dir: Path, +): + """Ensure workload.list with fetch=True calls inspect_workload_two_axis with fetch_upstream=True.""" + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_workload_dir.parent, + core_dir=mock_core_dir, + ) + + with ( + patch("appctl_router.get_docker_status", return_value="🟢 Running (1)"), + patch("appctl_router.inspect_workload_two_axis") as mock_inspect, + ): + mock_two_axis = MagicMock() + mock_two_axis.checkout.status_label = "✓ Synced (main)" + mock_two_axis.provenance.status.value = "✓ Synced" + mock_inspect.return_value = mock_two_axis + + resp_fetch = router.dispatch( + OperationRequest.model_validate({ + "operation": "workload.list", + "parameters": {"core": False, "fetch": True, "ssl": False}, + }), + viewer_principal, + ) + assert resp_fetch.success is True + assert resp_fetch.result is not None + mock_inspect.assert_called_once() + _, kwargs = mock_inspect.call_args + assert kwargs.get("fetch_upstream") is True + w = resp_fetch.result["workloads"][0] + assert w["deployment_status"] == "✓ Synced (main)" + assert w["provenance_status"] == "✓ Synced" + + +def test_operational_router_workload_list_handles_manifest_error( + tmp_path: Path, + viewer_principal: Principal, + mock_sites_dir: Path, + mock_core_dir: Path, +): + """Ensure workload.list sets deployment_status and provenance_status correctly for apps with manifest errors.""" + broken_app_dir = mock_sites_dir / "broken-app" + broken_app_dir.mkdir(parents=True, exist_ok=True) + (broken_app_dir / "app.yaml").write_text("invalid_yaml: [unclosed list", encoding="utf-8") + + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_sites_dir, + core_dir=mock_core_dir, + ) + + with patch("appctl_router.get_docker_status", return_value="🔴 Stopped"): + resp = router.dispatch( + OperationRequest.model_validate({ + "operation": "workload.list", + "parameters": {"core": False, "fetch": False, "ssl": False}, + }), + viewer_principal, + ) + assert resp.success is True + assert resp.result is not None + apps = {w["name"]: w for w in resp.result["workloads"]} + assert "broken-app" in apps + broken = apps["broken-app"] + assert broken["manifest_error"] is not None + assert broken["deployment_status"] == "⚠️ Manifest Error" + assert broken["provenance_status"] == "⚠️ Invalid Manifest" + + + + diff --git a/todo.txt b/todo.txt index 0f22d4b..a24cc22 100644 --- a/todo.txt +++ b/todo.txt @@ -40,7 +40,7 @@ x 2026-10-23 (A) Derive LLDAP_LDAP_BASE_DN dynamically from homelab.domain in ni x 2026-10-23 (A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git x 2026-10-30 (B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security -(B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux +x 2026-10-30 (B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux (B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth (B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4 (C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap From f631d5627c704c874bf83605efb3681f479ee4f3 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 30 Oct 2026 09:32:55 -0500 Subject: [PATCH 22/43] feat(build): wire --build/--no-cache flags and pass --pull during compose_build - Extend DeployParams and UpdateParams with strict no_cache boolean implying build=True - Wire --build and --no-cache on appctl up, deploy, and update CLI commands - Update bash completion to suggest --build and --no-cache for up and update - Pass --pull (and --no-cache when requested) on docker compose build in OperationalRouter - Add comprehensive unit tests covering contract validation, CLI arguments, and router subprocess calls Refs #11 --- scripts/appctl | 20 ++- scripts/appctl_cli.py | 16 ++- scripts/appctl_contracts.py | 14 ++ scripts/appctl_router.py | 20 ++- tests/unit/test_appctl_cli.py | 77 +++++++++++ tests/unit/test_appctl_contracts.py | 39 +++++- tests/unit/test_appctl_router.py | 191 ++++++++++++++++++++++++++++ 7 files changed, 366 insertions(+), 11 deletions(-) diff --git a/scripts/appctl b/scripts/appctl index 5f6bc10..bd0b42c 100755 --- a/scripts/appctl +++ b/scripts/appctl @@ -70,7 +70,25 @@ _appctl_completions() { COMPREPLY=( $(compgen -W "$services" -- "$cur") ) fi ;; - up|down|restart|update|pull|logs|config) + up|deploy) + if [[ "$cur" == -* ]]; then + COMPREPLY=( $(compgen -W "--build --no-cache" -- "$cur") ) + else + local services + services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true) + COMPREPLY=( $(compgen -W "$services" -- "$cur") ) + fi + ;; + update) + if [[ "$cur" == -* ]]; then + COMPREPLY=( $(compgen -W "--branch --build --no-cache" -- "$cur") ) + else + local services + services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true) + COMPREPLY=( $(compgen -W "$services" -- "$cur") ) + fi + ;; + down|restart|pull|logs|config) local services services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true) COMPREPLY=( $(compgen -W "$services" -- "$cur") ) diff --git a/scripts/appctl_cli.py b/scripts/appctl_cli.py index 1fa520e..053c8bd 100755 --- a/scripts/appctl_cli.py +++ b/scripts/appctl_cli.py @@ -254,6 +254,7 @@ def run_cli(argv: list[str] | None = None) -> int: up_p = subparsers.add_parser("up", aliases=["deploy"], parents=[common_parser], help="Deploy workload") up_p.add_argument("target", help="Workload or core target") up_p.add_argument("--build", action="store_true", help="Rebuild container images") + up_p.add_argument("--no-cache", action="store_true", help="Rebuild container images without cache") # down / stop down_p = subparsers.add_parser("down", aliases=["stop"], parents=[common_parser], help="Stop workload") @@ -267,6 +268,8 @@ def run_cli(argv: list[str] | None = None) -> int: update_p = subparsers.add_parser("update", parents=[common_parser], help="Update workload revision") update_p.add_argument("target", help="Workload target") update_p.add_argument("--branch", default=None, help="Expected git branch") + update_p.add_argument("--build", action="store_true", help="Rebuild container images") + update_p.add_argument("--no-cache", action="store_true", help="Rebuild container images without cache") # pull pull_p = subparsers.add_parser("pull", parents=[common_parser], help="Pull workload images") @@ -323,10 +326,15 @@ def run_cli(argv: list[str] | None = None) -> int: elif cmd == "health": op_req = OperationRequest(operation=OperationType.PLATFORM_HEALTH) elif cmd in ("up", "deploy"): + build_flag = getattr(parsed, "build", False) + no_cache_flag = getattr(parsed, "no_cache", False) op_req = OperationRequest( operation=OperationType.WORKLOAD_DEPLOY, target=parsed.target, - parameters={"build": getattr(parsed, "build", False)}, + parameters={ + "build": build_flag or no_cache_flag, + "no_cache": no_cache_flag, + }, ) elif cmd in ("down", "stop"): op_req = OperationRequest( @@ -342,6 +350,12 @@ def run_cli(argv: list[str] | None = None) -> int: params = {} if getattr(parsed, "branch", None): params["expected_branch"] = parsed.branch + build_flag = getattr(parsed, "build", False) + no_cache_flag = getattr(parsed, "no_cache", False) + if build_flag or no_cache_flag: + params["build"] = True + if no_cache_flag: + params["no_cache"] = True op_req = OperationRequest( operation=OperationType.WORKLOAD_UPDATE, target=parsed.target, diff --git a/scripts/appctl_contracts.py b/scripts/appctl_contracts.py index 1508666..d85dbe3 100644 --- a/scripts/appctl_contracts.py +++ b/scripts/appctl_contracts.py @@ -161,6 +161,13 @@ class DeployParams(StrictModel): recreate: StrictBool = True remove_orphans: StrictBool = True build: StrictBool = False + no_cache: StrictBool = False + + @model_validator(mode="after") + def imply_build_from_no_cache(self) -> DeployParams: + if self.no_cache: + self.build = True + return self class UpdateParams(StrictModel): @@ -168,6 +175,13 @@ class UpdateParams(StrictModel): expected_branch: Annotated[StrictStr, Field(min_length=1)] | None = None build: StrictBool = False + no_cache: StrictBool = False + + @model_validator(mode="after") + def imply_build_from_no_cache(self) -> UpdateParams: + if self.no_cache: + self.build = True + return self class LogsParams(StrictModel): diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py index e106af1..230665b 100644 --- a/scripts/appctl_router.py +++ b/scripts/appctl_router.py @@ -785,7 +785,9 @@ class OperationalRouter: # Optional build if params.build: - build_cmd = ["docker", "compose", "-f", str(compose_file), "build"] + build_cmd = ["docker", "compose", "-f", str(compose_file), "build", "--pull"] + if params.no_cache: + build_cmd.append("--no-cache") if container: build_cmd.append(container) code, out, err = run_bounded_subprocess(build_cmd, cwd=app_dir, env=env, timeout=300.0) @@ -928,13 +930,23 @@ class OperationalRouter: env = assemble_workload_env(app_dir, manifest, app.name) output_log = [f"git: {pull_out.strip()}"] - for action in declared_actions: + actions = list(declared_actions) + if params.build and "compose_build" not in actions: + if "compose_up" in actions: + idx = actions.index("compose_up") + actions.insert(idx, "compose_build") + else: + actions.append("compose_build") + + for action in actions: if action == "git_pull": continue # already executed in step 2 elif action == "compose_pull": cmd = ["docker", "compose", "-f", str(compose_file), "pull"] - elif action == "compose_build" or (params.build and action == "compose_up"): - cmd = ["docker", "compose", "-f", str(compose_file), "build"] + elif action == "compose_build": + cmd = ["docker", "compose", "-f", str(compose_file), "build", "--pull"] + if params.no_cache: + cmd.append("--no-cache") elif action == "compose_up": cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"] elif action == "compose_restart": diff --git a/tests/unit/test_appctl_cli.py b/tests/unit/test_appctl_cli.py index 5c2ec94..43558af 100644 --- a/tests/unit/test_appctl_cli.py +++ b/tests/unit/test_appctl_cli.py @@ -107,6 +107,81 @@ def test_cli_dispatches_mutation_command(): assert "Workload deployed" in mock_stdout.getvalue() +def test_cli_up_and_deploy_build_and_no_cache_flags(): + """Ensure appctl up/deploy with --build and --no-cache flags dispatches correct parameters.""" + mock_resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_build_01", + operation=OperationType.WORKLOAD_DEPLOY, + target="jellyfin", + result={"action": "deployed", "message": "Workload deployed"}, + ) + + # 1. up with --build + with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO): + ret = run_cli(["up", "jellyfin", "--build", "--token", "tok_secret"]) + assert ret == 0 + req: OperationRequest = mock_send.call_args[1]["operation_request"] + assert req.operation == OperationType.WORKLOAD_DEPLOY + assert req.parameters.get("build") is True + assert req.parameters.get("no_cache") is False + + # 2. up with --no-cache implies build=True + with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO): + ret = run_cli(["up", "jellyfin", "--no-cache", "--token", "tok_secret"]) + assert ret == 0 + req = mock_send.call_args[1]["operation_request"] + assert req.parameters.get("no_cache") is True + assert req.parameters.get("build") is True + + # 3. deploy alias with --no-cache + with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO): + ret = run_cli(["deploy", "jellyfin", "--no-cache", "--token", "tok_secret"]) + assert ret == 0 + req = mock_send.call_args[1]["operation_request"] + assert req.parameters.get("no_cache") is True + assert req.parameters.get("build") is True + + +def test_cli_update_build_and_no_cache_flags(): + """Ensure appctl update with --build and --no-cache flags dispatches correct parameters.""" + mock_resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_upd_01", + operation=OperationType.WORKLOAD_UPDATE, + target="jellyfin", + result={"action": "updated", "message": "Workload updated"}, + ) + + # 1. update with --build + with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO): + ret = run_cli(["update", "jellyfin", "--build", "--token", "tok_secret"]) + assert ret == 0 + req: OperationRequest = mock_send.call_args[1]["operation_request"] + assert req.operation == OperationType.WORKLOAD_UPDATE + assert req.parameters.get("build") is True + assert req.parameters.get("no_cache", False) is False + + # 2. update with --no-cache implies build=True + with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO): + ret = run_cli(["update", "jellyfin", "--no-cache", "--token", "tok_secret"]) + assert ret == 0 + req = mock_send.call_args[1]["operation_request"] + assert req.parameters.get("no_cache") is True + assert req.parameters.get("build") is True + + # 3. update with --branch and --no-cache + with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO): + ret = run_cli(["update", "jellyfin", "--branch", "main", "--no-cache", "--token", "tok_secret"]) + assert ret == 0 + req = mock_send.call_args[1]["operation_request"] + assert req.parameters.get("expected_branch") == "main" + assert req.parameters.get("no_cache") is True + assert req.parameters.get("build") is True + + def test_cli_handles_missing_socket(): """Ensure friendly stderr message when socket is absent.""" with patch("appctl_cli.send_daemon_request", side_effect=FileNotFoundError), patch("sys.stderr", new_callable=io.StringIO) as mock_stderr: @@ -501,6 +576,8 @@ def test_appctl_wrapper_fast_paths_completion_without_socket(tmp_path: Path): ) assert res_comp.returncode == 0 assert "_appctl_completions()" in res_comp.stdout + assert "up|deploy)" in res_comp.stdout + assert "--build --no-cache" in res_comp.stdout res_words = subprocess.run( [bash_bin, str(appctl_script), "complete", "services"], diff --git a/tests/unit/test_appctl_contracts.py b/tests/unit/test_appctl_contracts.py index c04ff57..678cca9 100644 --- a/tests/unit/test_appctl_contracts.py +++ b/tests/unit/test_appctl_contracts.py @@ -210,12 +210,24 @@ def test_deploy_params_defaults_and_explicit_bounds(): assert p_default.recreate is True assert p_default.remove_orphans is True assert p_default.build is False + assert p_default.no_cache is False # Explicit - p_custom = DeployParams(recreate=False, remove_orphans=False, build=True) + p_custom = DeployParams(recreate=False, remove_orphans=False, build=True, no_cache=False) assert p_custom.recreate is False assert p_custom.remove_orphans is False assert p_custom.build is True + assert p_custom.no_cache is False + + # no_cache implies build=True + p_no_cache = DeployParams(no_cache=True) + assert p_no_cache.no_cache is True + assert p_no_cache.build is True + + # no_cache overrides explicit build=False + p_override = DeployParams(build=False, no_cache=True) + assert p_override.no_cache is True + assert p_override.build is True def test_deploy_params_rejects_non_strict_types(): @@ -226,6 +238,8 @@ def test_deploy_params_rejects_non_strict_types(): DeployParams(remove_orphans=bad_bool) # type: ignore[arg-type] with pytest.raises(ValidationError): DeployParams(build=bad_bool) # type: ignore[arg-type] + with pytest.raises(ValidationError): + DeployParams(no_cache=bad_bool) # type: ignore[arg-type] def test_deploy_params_rejects_extra_fields(): @@ -238,23 +252,38 @@ def test_update_params_defaults_and_explicit(): p_default = UpdateParams() assert p_default.expected_branch is None assert p_default.build is False + assert p_default.no_cache is False # Explicit - p_custom = UpdateParams(expected_branch="main", build=True) + p_custom = UpdateParams(expected_branch="main", build=True, no_cache=False) assert p_custom.expected_branch == "main" assert p_custom.build is True + assert p_custom.no_cache is False + + # no_cache implies build=True + p_no_cache = UpdateParams(no_cache=True) + assert p_no_cache.no_cache is True + assert p_no_cache.build is True + + # no_cache overrides explicit build=False + p_override = UpdateParams(build=False, no_cache=True) + assert p_override.no_cache is True + assert p_override.build is True def test_update_params_rejects_empty_branch_and_non_strict_types(): + for bad_bool in ["true", "false", 1, 0, None, [True]]: + with pytest.raises(ValidationError): + UpdateParams(build=bad_bool) # type: ignore[arg-type] + with pytest.raises(ValidationError): + UpdateParams(no_cache=bad_bool) # type: ignore[arg-type] + with pytest.raises(ValidationError): UpdateParams(expected_branch="") # min_length=1 with pytest.raises(ValidationError): UpdateParams(expected_branch=123) # type: ignore[arg-type] - with pytest.raises(ValidationError): - UpdateParams(build="true") # type: ignore[arg-type] - with pytest.raises(ValidationError): UpdateParams.model_validate({"build": False, "extra": "prohibited"}) diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 26b802a..471b9d5 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -411,6 +411,65 @@ def test_operational_router_dispatches_workload_deploy( assert "up" in mock_run.call_args[0][0] +def test_operational_router_workload_deploy_build_flags( + tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path +): + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_workload_dir.parent, + ) + mock_app = MagicMock() + mock_app.name = "snappymail" + mock_app.dir_path = str(mock_workload_dir) + + # 1. Deploy with build=True passes --pull + req_build = OperationRequest.model_validate({ + "operation": "workload.deploy", + "target": "snappymail", + "parameters": {"build": True}, + }) + executed_commands: list[list[str]] = [] + + def mock_subproc(cmd: list[str], **kwargs): + executed_commands.append(cmd) + return 0, "ok", "" + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), + patch("appctl_router.cmd_sync_homepage"), + ): + resp = router.dispatch(req_build, admin_principal) + assert resp.success is True + build_calls = [c for c in executed_commands if "build" in c] + assert len(build_calls) == 1 + assert build_calls[0] == [ + "docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull" + ] + + # 2. Deploy with no_cache=True passes --pull and --no-cache + req_no_cache = OperationRequest.model_validate({ + "operation": "workload.deploy", + "target": "snappymail", + "parameters": {"no_cache": True}, + }) + executed_commands.clear() + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), + patch("appctl_router.cmd_sync_homepage"), + ): + resp = router.dispatch(req_no_cache, admin_principal) + assert resp.success is True + build_calls = [c for c in executed_commands if "build" in c] + assert len(build_calls) == 1 + assert build_calls[0] == [ + "docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull", "--no-cache" + ] + + def test_operational_router_workload_update_rejects_dirty_git_tree( tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path ): @@ -527,6 +586,138 @@ def test_operational_router_workload_update_succeeds_on_clean_tree( assert len(pull_calls) == 2 # git pull and docker compose pull +def test_operational_router_workload_update_build_and_no_cache_flags( + tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path +): + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_workload_dir.parent, + ) + mock_app = MagicMock() + mock_app.name = "snappymail" + mock_app.dir_path = str(mock_workload_dir) + + executed_commands: list[list[str]] = [] + + def mock_subproc(cmd: list[str], **kwargs): + executed_commands.append(cmd) + if "status" in cmd: + return 0, "", "" + if "pull" in cmd and "git" in cmd: + return 0, "Updating 1111..2222\nFast-forward", "" + if "rev-parse" in cmd: + return 0, "a1b2c3d", "" + return 0, "success", "" + + # 1. Update with build=True + req_build = OperationRequest.model_validate({ + "operation": "workload.update", + "target": "snappymail", + "parameters": {"build": True}, + }) + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), + patch("appctl_router.cmd_sync_homepage"), + ): + resp = router.dispatch(req_build, admin_principal) + assert resp.success is True + build_calls = [c for c in executed_commands if "build" in c] + assert len(build_calls) == 1 + assert build_calls[0] == [ + "docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull" + ] + # Also ensure compose_up was executed + up_calls = [c for c in executed_commands if "up" in c] + assert len(up_calls) == 1 + + # 2. Update with no_cache=True implies build=True and appends --no-cache + req_no_cache = OperationRequest.model_validate({ + "operation": "workload.update", + "target": "snappymail", + "parameters": {"no_cache": True}, + }) + executed_commands.clear() + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), + patch("appctl_router.cmd_sync_homepage"), + ): + resp = router.dispatch(req_no_cache, admin_principal) + assert resp.success is True + build_calls = [c for c in executed_commands if "build" in c] + assert len(build_calls) == 1 + assert build_calls[0] == [ + "docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull", "--no-cache" + ] + up_calls = [c for c in executed_commands if "up" in c] + assert len(up_calls) == 1 + + +def test_operational_router_workload_update_declared_compose_build( + tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path +): + # Rewrite app.yaml with declared compose_build action + manifest_content = """ +schema_version: "1.0" +name: "snappymail" +source: + type: "git" + url: "https://github.com/example/snappymail.git" + ref: "main" +deployment: + strategy: "compose" + actions: + - "git_pull" + - "compose_build" + - "compose_up" +""" + (mock_workload_dir / "app.yaml").write_text(manifest_content.strip(), encoding="utf-8") + + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_workload_dir.parent, + ) + mock_app = MagicMock() + mock_app.name = "snappymail" + mock_app.dir_path = str(mock_workload_dir) + + executed_commands: list[list[str]] = [] + + def mock_subproc(cmd: list[str], **kwargs): + executed_commands.append(cmd) + if "status" in cmd: + return 0, "", "" + if "pull" in cmd and "git" in cmd: + return 0, "Updating 1111..2222\nFast-forward", "" + if "rev-parse" in cmd: + return 0, "a1b2c3d", "" + return 0, "success", "" + + # Update with declared compose_build invokes build --pull + req = OperationRequest.model_validate({ + "operation": "workload.update", + "target": "snappymail", + }) + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), + patch("appctl_router.cmd_sync_homepage"), + ): + resp = router.dispatch(req, admin_principal) + assert resp.success is True + build_calls = [c for c in executed_commands if "build" in c] + assert len(build_calls) == 1 + assert build_calls[0] == [ + "docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull" + ] + + # --------------------------------------------------------------------------- # Core Platform Stack & Core Service Dispatch (Issue #2) # --------------------------------------------------------------------------- From 8ad48a49db827aa067b183af82342bd3faec9851 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 30 Oct 2026 09:33:34 -0500 Subject: [PATCH 23/43] docs(appctl): document source-built workload policy and build flag semantics - Document --build, --no-cache, and automatic --pull behavior for appctl up and update - Add Source-Built Workload Policy note detailing compose_build action sequences - Mark item completed in todo.txt Closes #11 Refs #11 --- docs/appctl.md | 22 ++++++++++++++++------ todo.txt | 2 +- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/docs/appctl.md b/docs/appctl.md index cbf6472..73fce4e 100644 --- a/docs/appctl.md +++ b/docs/appctl.md @@ -101,11 +101,13 @@ appctl info docs --ssl ### Lifecycle Management -#### `appctl up ` +#### `appctl up [--build] [--no-cache]` Starts the specified service stack in detached mode (`--remove-orphans`). * For a workload in `~/Sites`: starts containers and triggers `appctl sync`. * For `core`: starts the entire Core Compose stack using `/run/secrets/homeserver.env`. * For an individual Core service (e.g., `appctl up traefik`): starts that specific container. +* When `--build` is passed: invokes `docker compose build --pull` prior to deployment. The `--pull` flag guarantees base images in Dockerfile `FROM` lines are refreshed from remote registries. +* When `--no-cache` is passed: `--build` is implied (`build: True`) and `docker compose build --pull --no-cache` is executed, forcing a clean rebuild without cached layers. #### `appctl down ` Stops and removes containers defined in the target's Compose file (or stops the targeted Core container). @@ -116,14 +118,22 @@ Restarts the target stack or individual container: * `appctl restart core`: Restarts all Core Compose services. * `appctl restart traefik`: Restarts only the Traefik container. -#### `appctl update ` -Performs a sequential update workflow for a Sites workload stack: +#### `appctl update [--branch ] [--build] [--no-cache]` +Performs a sequential, revision-consistent update workflow for a Sites workload stack: 1. Verifies that the local Git working tree is clean (aborts if uncommitted changes exist). -2. Runs `git pull --ff-only` to fast-forward the current branch. -3. Runs `docker compose pull` to fetch updated container images. -4. Runs `docker compose up -d --remove-orphans` to recreate containers. +2. Runs `git pull --ff-only [origin ]` to fast-forward the current branch. +3. Re-validates `app.yaml`, expected branch declaration, and Compose security rules against the newly pulled working tree. +4. Executes declared actions in `app.yaml` (`actions: [git_pull, compose_pull, compose_build, compose_up, compose_restart]`): + * `compose_pull`: Runs `docker compose pull` to fetch updated container images. + * `compose_build`: Runs `docker compose build --pull` (and `--no-cache` if requested). + * `compose_up`: Runs `docker compose up -d --remove-orphans` to recreate containers. + * When `--build` is passed via CLI, `compose_build` is automatically executed prior to `compose_up`, even if omitted from manifest actions. + * When `--no-cache` is passed, build is implied and executes with `--no-cache`. 5. Runs `appctl sync` to update the Homepage dashboard. +> [!NOTE] +> **Source-Built Workload Policy**: For workloads built directly from local source Dockerfiles rather than pre-built registry images, declare `compose_build` in `app.yaml` `deployment.actions` (`actions: [git_pull, compose_build, compose_up]`). Both manual `appctl update` and automated GitOps dispatcher runs will execute `docker compose build --pull` before recreating containers, ensuring reproducible builds with current upstream base layers. + > [!NOTE] > Core platform updates are managed via version-controlled NixOS generations (`git pull` followed by `nixos-rebuild switch`), not through `appctl update core` (as Core is mounted read-only for `homelab-appctl.service`). diff --git a/todo.txt b/todo.txt index a24cc22..cc6659f 100644 --- a/todo.txt +++ b/todo.txt @@ -42,5 +42,5 @@ x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in x 2026-10-30 (B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security x 2026-10-30 (B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux (B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth -(B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4 +x 2026-10-30 (B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4 (C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap From 24508f8d9238ad92060223419eb9081fa6b4cecb Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 30 Oct 2026 09:54:57 -0500 Subject: [PATCH 24/43] docs(auth): add operator admin token bootstrap helper and provisioning guide - Implement scripts/bootstrap_token.py generating 256-bit token with 0600 mode - Enforce parent directory 0700 mode and refuse overwrite without --force - Output SHA-256 JSON descriptor matching TokenDescriptor for SOPS tokens_json - Ensure zero plaintext secret leakage to stdout/stderr - Document token bootstrapping, SOPS configuration, and rotation in docs/appctl.md - Update control plane token store section in docs/secrets-and-state.md - Add 10 unit tests covering API, permissions, and CLI paths - Mark item completed in todo.txt and p4-refactor-and-decoupling-plan.md Closes #12 Refs #12 --- .gitignore | 1 + docs/appctl.md | 92 +++++++++ docs/plans/p4-refactor-and-decoupling-plan.md | 10 +- docs/secrets-and-state.md | 4 +- scripts/bootstrap_token.py | 173 +++++++++++++++++ tests/unit/test_bootstrap_token.py | 175 ++++++++++++++++++ todo.txt | 2 +- 7 files changed, 449 insertions(+), 8 deletions(-) create mode 100755 scripts/bootstrap_token.py create mode 100644 tests/unit/test_bootstrap_token.py diff --git a/.gitignore b/.gitignore index fb97674..faa86f9 100644 --- a/.gitignore +++ b/.gitignore @@ -52,3 +52,4 @@ mutants/ # Local Bootstrap & Operational Scripts scripts/bootstrap_lldap_users.py scripts/bootstrap_*.py +!scripts/bootstrap_token.py diff --git a/docs/appctl.md b/docs/appctl.md index 73fce4e..8264beb 100644 --- a/docs/appctl.md +++ b/docs/appctl.md @@ -47,6 +47,98 @@ Under Milestone P4, `appctl` operates as a centralized operational control plane └────────────────────────────────────────────────┘ ``` +### Operator Admin Token Bootstrapping & Rotation + +`appctl` implements zero-trust authorization across three roles: `homelab-admin`, `homelab-operator`, and `homelab-viewer`. Local Unix domain socket (`/run/homelab/appctl.sock`) callers without a token are granted `homelab-viewer` privileges via `SO_PEERCRED` for non-sensitive read-only commands (e.g., `appctl list`, `appctl status`, `appctl ssl`). + +Sensitive inspection (e.g., `appctl config ` which renders secrets in Compose definitions) and all mutating operations (e.g., `appctl up`, `appctl restart`, `appctl update`) require an authenticated Bearer token. + +#### Role of `~/.config/homelab/token` +The thin CLI client resolves Bearer tokens in the following order of precedence: +1. Direct CLI flag: `--token ` +2. Environment variable: `APPCTL_TOKEN` +3. Local operator token file: `~/.config/homelab/token` (mode `0600`) +4. System service token file: `/run/secrets/appctl/token` + +The standard operator setup stores a 256-bit hex Bearer token with mode `0600` in `~/.config/homelab/token`. + +#### Generating a Token (`scripts/bootstrap_token.py`) +To generate an operator token and its matching SHA-256 descriptor: + +```bash +python3 scripts/bootstrap_token.py +``` + +This utility: +1. Generates a cryptographically secure 256-bit token (`secrets.token_hex(32)`). +2. Computes the SHA-256 digest: `hashlib.sha256(raw_token.encode("utf-8")).hexdigest()`. +3. Ensures `~/.config/homelab` exists with mode `0700`. +4. Writes the raw Bearer token to `~/.config/homelab/token` with mode `0600`. +5. Outputs the JSON descriptor matching `TokenDescriptor` in `scripts/appctl_auth.py`: + +```json +{ + "token_id": "operator-admin", + "identity": "operator", + "role": "homelab-admin", + "sha256": "4a12...<64-hex-sha256>" +} +``` + +> [!NOTE] +> The raw secret is **never** printed to stdout or stderr. Only the descriptor snippet (containing the SHA-256 digest) is output. To print only the JSON snippet for automation or piping, pass `--print-json`. + +#### Registering the Descriptor in SOPS +Insert the generated JSON descriptor into your encrypted SOPS secrets store (`nixos/secrets.yaml`): + +```bash +sops nixos/secrets.yaml +``` + +Under `appctl.tokens_json`, add the entry to the JSON list: +```yaml +appctl: + tokens_json: | + [ + { + "token_id": "operator-admin", + "identity": "operator", + "role": "homelab-admin", + "sha256": "<64-hex-sha256>" + } + ] +``` + +Save and exit your editor (SOPS will re-encrypt the file), then project the updated secrets: +```bash +sudo nixos-rebuild switch --flake ~/Core#server +``` +This updates `/run/secrets/appctl/tokens.json` (owned by `homelab-appctl:homelab-operators`, mode `0400`), which `homelab-appctl.service` consumes. + +#### Verifying Token Authentication +Verify permissions using both unauthenticated and authenticated queries: + +1. **Viewer Inspection** (succeeds without token via `SO_PEERCRED`): + ```bash + appctl health + # Output: OK (homelab-appctl.service operational) + ``` + +2. **Admin-Gated Operation** (requires `homelab-admin` Bearer token): + ```bash + appctl config docs + # Renders the resolved Compose YAML with injected secrets + ``` + If the token is missing or mismatched, `appctl` returns `401 Unauthorized` or `403 Forbidden` with `ERR_PERMISSION_DENIED`. + +#### Token Rotation Workflow +To rotate an operator token: +1. Run `python3 scripts/bootstrap_token.py --force --token-id "operator-admin-$(date +%Y%m%d)"`. +2. Open `sops nixos/secrets.yaml` and add the new descriptor to `appctl.tokens_json`. Keep the old entry temporarily if multiple sessions share it, or replace it immediately. +3. Run `sudo nixos-rebuild switch --flake ~/Core#server` to apply the updated token store. +4. Verify CLI operations (`appctl config docs`). +5. Remove the deprecated token descriptor from `nixos/secrets.yaml` and re-run `nixos-rebuild switch`. + --- ## 2. CLI Command Reference diff --git a/docs/plans/p4-refactor-and-decoupling-plan.md b/docs/plans/p4-refactor-and-decoupling-plan.md index b360ed6..a204fc5 100644 --- a/docs/plans/p4-refactor-and-decoupling-plan.md +++ b/docs/plans/p4-refactor-and-decoupling-plan.md @@ -59,11 +59,11 @@ This plan establishes the concrete implementation work packages to resolve these - [x] **Task 1.5**: Update `systemd.tmpfiles.rules` in `nixos/modules/homeserver.nix` from `a+` to recursive `A+` on `sitesDir`. ### Phase 2: CLI Hardening & Status Parity -- [ ] **Task 2.1**: Update `scripts/appctl` to fail closed when `[ ! -S "$SOCKET_PATH" ]`, removing the silent fallback to legacy Bash. -- [ ] **Task 2.2**: Update `_op_workload_list` in `scripts/appctl_router.py` to query live container health (`get_docker_status()`). -- [ ] **Task 2.3**: Update `_format_workload_table` in `scripts/appctl_cli.py` to render the `STATUS` column (`🟢 Running (1)` / `🔴 Stopped`). -- [ ] **Task 2.4**: Bootstrap operator admin token documentation and setup instructions in `docs/appctl.md` and `docs/secrets-and-state.md`. -- [ ] **Task 2.5**: Wire `--build` and `--no-cache` in `scripts/appctl_cli.py`, pass `--pull` during `compose_build` in `scripts/appctl_router.py`, and document source-built action policy in `docs/appctl.md`. +- [x] **Task 2.1**: Update `scripts/appctl` to fail closed when `[ ! -S "$SOCKET_PATH" ]`, removing the silent fallback to legacy Bash. +- [x] **Task 2.2**: Update `_op_workload_list` in `scripts/appctl_router.py` to query live container health (`get_docker_status()`). +- [x] **Task 2.3**: Update `_format_workload_table` in `scripts/appctl_cli.py` to render the `STATUS` column (`🟢 Running (1)` / `🔴 Stopped`). +- [x] **Task 2.4**: Bootstrap operator admin token documentation and setup instructions in `docs/appctl.md` and `docs/secrets-and-state.md`. +- [x] **Task 2.5**: Wire `--build` and `--no-cache` in `scripts/appctl_cli.py`, pass `--pull` during `compose_build` in `scripts/appctl_router.py`, and document source-built action policy in `docs/appctl.md`. ### Phase 3: Architectural Records & Roadmap Synchronization - [x] **Task 3.1**: Update `ROADMAP.md` (P6 redefined as Homelab MCP Gateway; on-server AI compiler deprecated). diff --git a/docs/secrets-and-state.md b/docs/secrets-and-state.md index 28448c0..a17eb49 100644 --- a/docs/secrets-and-state.md +++ b/docs/secrets-and-state.md @@ -64,9 +64,9 @@ Generated by `nixos/modules/traefik-deployments.nix`. Projects shared infrastruc ### C. Control Plane Token Store (`/run/secrets/appctl/tokens.json` & `/run/secrets/gitops/appctl_token`) Provisioned from `nixos/secrets.yaml` (`appctl/tokens_json` and `gitops/appctl_token`): -* `/run/secrets/appctl/tokens.json`: Owned by `homelab-appctl:homelab-operators` with strict mode `0400` (enforced fail-closed by `TokenStore._verify_permissions()`). Stores SHA-256 hex digests of Bearer secrets mapped to `token_id`, `identity`, and `role` (`homelab-admin`, `homelab-operator`, `homelab-viewer`). +* `/run/secrets/appctl/tokens.json`: Owned by `homelab-appctl:homelab-operators` with strict mode `0400` (enforced fail-closed by `TokenStore._verify_permissions()`, rejecting any write bit or group/world readability). Stores a JSON array of SHA-256 token descriptors (`token_id`, `identity`, `role`, and 64-hex `sha256`) defined under `appctl/tokens_json` in `nixos/secrets.yaml`. * `/run/secrets/gitops/appctl_token`: Owned by `config.homelab.operatorUser` (mode `0400`). Supplies the `homelab-operator` Bearer secret to `homelab-gitops.service` when delegating `workload.update` to `homelab-appctl.service`. -* `~/.config/homelab/token`: Local operator Bearer token (mode `0600`) read by `appctl_cli.py` for interactive CLI mutations. +* `~/.config/homelab/token`: Local operator Bearer token written with strict mode `0600` (in a mode `0700` directory) by `scripts/bootstrap_token.py`. Automatically discovered and resolved by `appctl_cli.py` for authenticated operator interactions without needing `--token` flags or environment variables. --- diff --git a/scripts/bootstrap_token.py b/scripts/bootstrap_token.py new file mode 100755 index 0000000..abc3b01 --- /dev/null +++ b/scripts/bootstrap_token.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +""" +bootstrap_token.py — Operator Admin Token Bootstrap & Rotation Helper (WP4) + +Generates a 256-bit cryptographically secure Bearer token, saves it locally +with strict mode 0600 permissions (~/.config/homelab/token), and prints the +corresponding JSON descriptor for insertion into the SOPS tokens store +(nixos/secrets.yaml -> appctl/tokens_json). +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import secrets +import stat +import sys +from pathlib import Path +from typing import Any + +# Ensure scripts directory is in sys.path when executed directly +_scripts_dir = Path(__file__).resolve().parent +if str(_scripts_dir) not in sys.path: + sys.path.insert(0, str(_scripts_dir)) + +from appctl_auth import Role, TokenDescriptor + +DEFAULT_TOKEN_PATH = Path.home() / ".config/homelab/token" +DEFAULT_TOKEN_ID = "operator-admin" +DEFAULT_IDENTITY = "operator" +DEFAULT_ROLE = Role.ADMIN.value + + +def generate_token() -> tuple[str, str]: + """Generate a 256-bit cryptographically secure Bearer token and its SHA-256 digest.""" + raw_token = secrets.token_hex(32) + digest = hashlib.sha256(raw_token.encode()).hexdigest() + return raw_token, digest + + +def write_token_file(path: Path, raw_token: str, force: bool = False) -> None: + """ + Write raw Bearer token to path with mode 0600. + Ensures parent directory exists with mode 0700. + Fails closed if the destination exists and force is False. + """ + path = path.expanduser().resolve() + if path.exists() and not force: + raise FileExistsError( + f"Token file '{path}' already exists. Use --force / -f to overwrite." + ) + + parent = path.parent + if not parent.exists(): + parent.mkdir(mode=0o700, parents=True, exist_ok=True) + try: + parent.chmod(0o700) + except OSError: + pass + elif stat.S_IMODE(parent.stat().st_mode) != 0o700: + try: + parent.chmod(0o700) + except OSError: + pass + + fd = os.open(str(path), os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o600) + try: + content = f"{raw_token}\n".encode() + os.write(fd, content) + finally: + os.close(fd) + + path.chmod(0o600) + + +def bootstrap_token( + output_path: Path | str = DEFAULT_TOKEN_PATH, + token_id: str = DEFAULT_TOKEN_ID, + identity: str = DEFAULT_IDENTITY, + role: str = DEFAULT_ROLE, + force: bool = False, +) -> dict[str, Any]: + """ + Generate Bearer token, persist to file with strict permissions, + and return the validated TokenDescriptor dictionary. + """ + path = Path(output_path).expanduser().resolve() + raw_token, digest = generate_token() + + write_token_file(path, raw_token, force=force) + + # Validate against TokenDescriptor model + validated = TokenDescriptor( + token_id=token_id, + identity=identity, + role=Role(role), + sha256=digest, + ) + return validated.model_dump(mode="json") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Bootstrap or rotate an operator Bearer token for appctl." + ) + parser.add_argument( + "-o", + "--output", + default=str(DEFAULT_TOKEN_PATH), + help=f"Destination token file path (default: {DEFAULT_TOKEN_PATH})", + ) + parser.add_argument( + "--token-id", + default=DEFAULT_TOKEN_ID, + help=f"Token descriptor ID (default: {DEFAULT_TOKEN_ID})", + ) + parser.add_argument( + "--identity", + default=DEFAULT_IDENTITY, + help=f"Caller identity (default: {DEFAULT_IDENTITY})", + ) + parser.add_argument( + "--role", + default=DEFAULT_ROLE, + choices=[r.value for r in Role], + help=f"Role assignment (default: {DEFAULT_ROLE})", + ) + parser.add_argument( + "-f", + "--force", + action="store_true", + help="Overwrite existing token file if present", + ) + parser.add_argument( + "--print-json", + action="store_true", + help="Output only the JSON descriptor snippet for piping/automation", + ) + + args = parser.parse_args(argv) + + try: + descriptor = bootstrap_token( + output_path=args.output, + token_id=args.token_id, + identity=args.identity, + role=args.role, + force=args.force, + ) + except FileExistsError as err: + sys.stderr.write(f"Error: {err}\n") + return 1 + + json_snippet = json.dumps(descriptor, indent=2) + + if args.print_json: + sys.stdout.write(f"{json_snippet}\n") + else: + sys.stdout.write( + f"Generated Bearer token and saved to {args.output} (mode 0600).\n\n" + f"Add the following descriptor to your SOPS tokens store (nixos/secrets.yaml -> appctl/tokens_json):\n\n" + f"{json_snippet}\n\n" + f"After updating nixos/secrets.yaml with `sops nixos/secrets.yaml`, apply changes with:\n" + f" sudo nixos-rebuild switch --flake ~/Core#server\n" + ) + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/unit/test_bootstrap_token.py b/tests/unit/test_bootstrap_token.py new file mode 100644 index 0000000..7993c59 --- /dev/null +++ b/tests/unit/test_bootstrap_token.py @@ -0,0 +1,175 @@ +""" +tests/unit/test_bootstrap_token.py — Unit Tests for Operator Admin Token Bootstrap Helper (WP4) + +Verifies: +- 256-bit secure token generation (64 hex characters) and matching SHA-256 digest +- Strict 0600 file mode and 0700 parent directory creation +- TokenDescriptor Pydantic validation (scripts/appctl_auth.py) +- Refusal to overwrite existing token file without --force +- Overwriting existing token file when --force is supplied +- Secrets leakage prevention: raw Bearer token never appears in stdout/stderr +- Machine-readable JSON output via --print-json +""" + +from __future__ import annotations + +import hashlib +import json +import stat +import string +from pathlib import Path +from typing import Any + +import pytest +from appctl_auth import Role, TokenDescriptor +from bootstrap_token import ( + bootstrap_token, + generate_token, + main, + write_token_file, +) + + +def test_generate_token_produces_64_hex_token_and_valid_sha256() -> None: + raw_token, digest = generate_token() + assert len(raw_token) == 64 + assert all(c in string.hexdigits for c in raw_token) + assert len(digest) == 64 + assert all(c in string.hexdigits for c in digest) + expected_digest = hashlib.sha256(raw_token.encode("utf-8")).hexdigest() + assert digest == expected_digest + + +def test_write_token_file_creates_file_and_enforces_0600(tmp_path: Path) -> None: + token_file = tmp_path / "subdir" / "token" + write_token_file(token_file, "secret-token-12345") + assert token_file.is_file() + assert stat.S_IMODE(token_file.stat().st_mode) == 0o600 + assert stat.S_IMODE(token_file.parent.stat().st_mode) == 0o700 + assert token_file.read_text(encoding="utf-8") == "secret-token-12345\n" + + +def test_bootstrap_token_generates_file_with_strict_mode_0600(tmp_path: Path) -> None: + nested_dir = tmp_path / "nested" / "homelab" + token_file = nested_dir / "token" + + descriptor = bootstrap_token(output_path=token_file) + + assert token_file.is_file() + # Check parent directory mode is 0700 + parent_mode = stat.S_IMODE(nested_dir.stat().st_mode) + assert parent_mode == 0o700, f"Expected parent mode 0700, got {oct(parent_mode)}" + + # Check token file mode is 0600 + file_mode = stat.S_IMODE(token_file.stat().st_mode) + assert file_mode == 0o600, f"Expected file mode 0600, got {oct(file_mode)}" + + raw_token = token_file.read_text(encoding="utf-8").strip() + assert len(raw_token) == 64 + assert hashlib.sha256(raw_token.encode("utf-8")).hexdigest() == descriptor["sha256"] + + +def test_bootstrap_token_descriptor_validates_against_token_descriptor(tmp_path: Path) -> None: + token_file = tmp_path / "custom_token" + descriptor = bootstrap_token( + output_path=token_file, + token_id="custom-admin", + identity="operator", + role="homelab-admin", + ) + + validated = TokenDescriptor.model_validate(descriptor) + assert validated.token_id == "custom-admin" + assert validated.identity == "operator" + assert validated.role == Role.ADMIN + assert len(validated.sha256) == 64 + + +def test_bootstrap_token_refuses_overwrite_without_force(tmp_path: Path) -> None: + token_file = tmp_path / "token" + bootstrap_token(output_path=token_file) + original_token = token_file.read_text(encoding="utf-8") + + with pytest.raises(FileExistsError, match="already exists"): + bootstrap_token(output_path=token_file, force=False) + + assert token_file.read_text(encoding="utf-8") == original_token + + +def test_bootstrap_token_overwrites_with_force(tmp_path: Path) -> None: + token_file = tmp_path / "token" + descriptor1 = bootstrap_token(output_path=token_file) + first_token = token_file.read_text(encoding="utf-8").strip() + + descriptor2 = bootstrap_token(output_path=token_file, force=True) + second_token = token_file.read_text(encoding="utf-8").strip() + + assert first_token != second_token + assert descriptor1["sha256"] != descriptor2["sha256"] + assert descriptor2["sha256"] == hashlib.sha256(second_token.encode("utf-8")).hexdigest() + + +def test_bootstrap_cli_never_prints_raw_secret_to_stdout_or_stderr( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + token_file = tmp_path / "token" + ret = main(["--output", str(token_file)]) + assert ret == 0 + + raw_token = token_file.read_text(encoding="utf-8").strip() + captured = capsys.readouterr() + + # RAW SECRET MUST NEVER APPEAR IN STDOUT OR STDERR + assert raw_token not in captured.out, "Leak: raw token found in stdout!" + assert raw_token not in captured.err, "Leak: raw token found in stderr!" + + # Ensure stdout provides helpful human guidance + assert "operator-admin" in captured.out + assert "sops nixos/secrets.yaml" in captured.out + + +def test_bootstrap_cli_print_json_outputs_valid_json_descriptor( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + token_file = tmp_path / "token" + ret = main(["--output", str(token_file), "--print-json"]) + assert ret == 0 + + raw_token = token_file.read_text(encoding="utf-8").strip() + captured = capsys.readouterr() + + assert raw_token not in captured.out + assert captured.err == "" + + # Must be cleanly parseable as pure JSON + data: dict[str, Any] = json.loads(captured.out.strip()) + validated = TokenDescriptor.model_validate(data) + assert validated.token_id == "operator-admin" + assert validated.identity == "operator" + assert validated.role == Role.ADMIN + assert validated.sha256 == hashlib.sha256(raw_token.encode("utf-8")).hexdigest() + + +def test_bootstrap_cli_refuses_overwrite_and_exits_nonzero( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + token_file = tmp_path / "token" + assert main(["--output", str(token_file)]) == 0 + + ret = main(["--output", str(token_file)]) + assert ret != 0 + captured = capsys.readouterr() + assert "already exists" in captured.err + + +def test_bootstrap_cli_force_overwrites( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + token_file = tmp_path / "token" + assert main(["--output", str(token_file)]) == 0 + tok1 = token_file.read_text(encoding="utf-8").strip() + + assert main(["--output", str(token_file), "--force"]) == 0 + tok2 = token_file.read_text(encoding="utf-8").strip() + + assert tok1 != tok2 diff --git a/todo.txt b/todo.txt index cc6659f..9f2df63 100644 --- a/todo.txt +++ b/todo.txt @@ -41,6 +41,6 @@ x 2026-10-23 (A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites an x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git x 2026-10-30 (B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security x 2026-10-30 (B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux -(B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth +x 2026-10-30 (B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth x 2026-10-30 (B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4 (C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap From eb02543fa6403b1f2085e2ba39c781b727e423ab Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 30 Oct 2026 10:53:41 -0500 Subject: [PATCH 25/43] docs(roadmap): scrub residual DeploymentModel and DeploymentProposal references - Reconcile ROADMAP.md Invariants 6 & 7 with external MCP Gateway architecture - Update ROADMAP.md Baseline vs. Target table across metadata, deployment, and GitOps rows - Update Milestone P7 Operations UI deliverables in ROADMAP.md - Update ADR-0002 one-line summary in docs/decisions/README.md - Mark item completed in todo.txt Closes #13 Refs #13 --- ROADMAP.md | 12 ++++++------ docs/decisions/README.md | 2 +- todo.txt | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 1145ab5..80d0f5b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -15,8 +15,8 @@ It describes the implementation trajectory and phased engineering milestones for 3. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**: Entering via SSH does not bypass authentication. Every mutating operation and sensitive read (`workload.config`, `workload.logs`) requires an explicit Bearer token; tokenless local UDS calls fall back via `SO_PEERCRED` strictly to `homelab-viewer` read-only inspection. 4. **Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)**: `homelab-appctl.service` executes as isolated user `homelab-appctl:homelab-operators` with mode `0600` append-only `/var/log/homelab/appctl/audit.jsonl`. Mutating operations abort immediately (`500 ERR_EXECUTION_FAILED`) if the pre-execution `DISPATCHED` audit write fails. 5. **Unified Execution, Pre-Flight & Pure-Python Environment (`DEC-04`, `DEC-05`)**: Both CLI and GitOps worker paths execute through the daemon, enforcing Pydantic v2 manifest validation, `validate_compose_security()` AST checks, and inert pure-Python `.env` assembly (no shell `source` or `eval`). -6. **Separation of Intent from Implementation**: `DeploymentModel` captures implementation-agnostic intent; concrete platform descriptors (`app.yaml` + Compose) are materialized and enforced by `appctl`. -7. **AI Authoring Boundary**: AI agents act strictly as proposal generators (`DeploymentProposal`). Humans approve the intent (`DeploymentModel`). The AI possesses zero execution authority. +6. **Separation of Intent from Implementation**: Declarative manifests (`app.yaml` + Compose) versioned in Git capture workload intent and platform descriptors, materialized and enforced deterministically by `appctl`. +7. **AI Authoring Boundary & External MCP Gateway**: AI agents operate externally as proposal generators via client-side Model Context Protocol (MCP) tool integrations. Humans approve intent before any mutation is applied in Git. The server appliance hosts zero autonomous agent loops or on-server compilers. 8. **Secret Reference Invariant**: Deployment definitions store secret references (`secretKeyRef`), never plaintext material, resolved at runtime via `SecretProvider`. 9. **Clean State Root**: Mutable application runtime data resides strictly under `~/var/lib/homelab//`, isolated from Git repositories. @@ -28,9 +28,9 @@ It describes the implementation trajectory and phased engineering milestones for | :--- | :--- | :--- | | **`appctl` Architecture** | Dedicated daemon service (`homelab-appctl.service`, user `homelab-appctl`) exposing `POST /v1/operations` over Unix socket and loopback HTTP, with thin-client CLI (`scripts/appctl_cli.py`). | Expand with Operations UI and external ForwardAuth integration (P5–P7). | | **Operational Auth** | Mandatory SHA-256 Bearer token + 3-role RBAC + UDS `SO_PEERCRED` viewer fallback (`/run/secrets/appctl/tokens.json`). | LLDAP directory RBAC & Authelia ForwardAuth (P5). | -| **Metadata & Schema Engine** | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | Unified across `DeploymentModel` materialization (P6). | -| **Deployment Model** | Direct authoring of `app.yaml` and `docker-compose.yml` in `~/Sites//`. | 5-stage lifecycle (planned in P6): `DeploymentProposal` $\to$ operator-approved `DeploymentModel` in Git $\to$ `appctl` materialization. | -| **GitOps Engine** | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | Integrated with `DeploymentModel` reconciliation (P6). | +| **Metadata & Schema Engine** | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | Standardized JSON-RPC Model Context Protocol tools over Pydantic v2 schemas (P6). | +| **Deployment Model** | Direct authoring of `app.yaml` and `docker-compose.yml` in `~/Sites//`. | Authoritative declarative Git state (`app.yaml` + Compose) managed via CLI, GitOps, or client-gated MCP tools (P6). | +| **GitOps Engine** | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | Unified continuous deployment worker driven by Git webhooks delegating to control plane daemon (P4 baseline consolidated). | | **Secret Distribution** | Age-encrypted `nixos/secrets.yaml` decrypted by `sops-nix` to tmpfs `/run/secrets/`. | Host secrets remain in `sops-nix`; workload secrets referenced by key and projected via `SecretProvider` (planned in P5). | | **Dashboard** | `appctl sync` compiles `config/homepage/services.yaml` from `app.yaml` manifests under `_homepage_sync.lock`. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for management (planned in P7). | @@ -138,7 +138,7 @@ It describes the implementation trajectory and phased engineering milestones for **Status**: ⏳ **Planned** * **Objective**: Deliver a unified web-based management experience without coupling the control plane to specific frontend engines. * **Key Deliverables**: - 1. *Operations UI Client*: Dedicated lightweight web client consuming the `appctl` API for proposal review, approval, real-time log streaming, and API token management. + 1. *Operations UI Client*: Dedicated lightweight web client consuming the `appctl` API for workload inspection, deployment management, real-time log streaming, and API token management. 2. *Homepage Status Integration*: Homepage consumes live status widgets from `appctl` live endpoints or compiled service maps. * **Exit Criteria**: End-to-end browser and CLI deployment verification; Homepage accurately reflecting live container health. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index a18664e..1bb0446 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -11,7 +11,7 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using | Decision Record | Status | Date | Scope & One-Line Purpose | | :--- | :--- | :--- | :--- | | [**ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. | -| [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and the 5-stage `DeploymentModel` lifecycle. | +| [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and deterministic Git-backed declarative deployment state. | | [**ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model**](0001-3tier-architecture-and-provenance.md) | `accepted` | 2026-09-28 | Establishes 3-tier separation (Software, OCI Artifact, Sites Deployment, Core Platform), two workload classes (Source-Backed vs. Image-Only), isolated state root (`~/var/lib/homelab//`), and two operational inspection axes. | --- diff --git a/todo.txt b/todo.txt index 9f2df63..f5e339c 100644 --- a/todo.txt +++ b/todo.txt @@ -43,4 +43,4 @@ x 2026-10-30 (B) Enforce fail-closed check on daemon socket availability and rem x 2026-10-30 (B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux x 2026-10-30 (B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth x 2026-10-30 (B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4 -(C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap +x 2026-10-30 (C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap From caa8140cd3add946ad7fda27f652d43a9d2e8708 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 30 Oct 2026 12:13:11 -0500 Subject: [PATCH 26/43] feat(nixos): add dual-path instance domain injection and operator cutover runbook - Implement dual-path optional imports in nixos/configuration.nix for instance domain - Add nixos/instance.nix to .gitignore preserving platform genericism - Add invariant tests for default domain evaluation and dynamic LDAP base DN derivation - Document appliance domain injection and path: flake scheme in docs/setup_guide.md - Document 4-stage staged coexistence cutover runbook and rollback plan in docs/operations.md - Mark live host execution as BLOCKED pending authorized maintenance window - Update todo.txt and p4-refactor-and-decoupling-plan.md Closes #7 Refs #8 --- .gitignore | 1 + docs/operations.md | 192 +++++++++++++++++- docs/plans/p4-refactor-and-decoupling-plan.md | 24 ++- docs/setup_guide.md | 54 ++++- nixos/configuration.nix | 3 +- tests/security/test_security_invariants.py | 130 ++++++++++++ todo.txt | 1 + 7 files changed, 393 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index faa86f9..052cba8 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ backup.zip .envrc .direnv .venv +nixos/instance.nix # SSL / ACME Certificates & Keys config/letsencrypt/* diff --git a/docs/operations.md b/docs/operations.md index 1949b1a..3f60937 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -16,9 +16,15 @@ After modifying any file in `nixos/` (including `configuration.nix`, `hardware-c nix-switch # Or using the explicit command: -sudo nixos-rebuild switch --flake ~/Core#server +sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure ``` +> [!NOTE] +> **Flake Fetcher Scheme for Untracked Files**: +> When importing the gitignored `nixos/instance.nix`, Nix's default Git fetcher filters it out unless the `path:` scheme is used (`path:/home/operator/Core#server` or `path:~/Core#server`). The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index. +> If using `/etc/nixos/homelab-instance.nix`, a standard `--flake ~/Core#server --impure` works directly since `/etc/nixos` is outside the repository. + + ### Dry Build Validation & Rollback ```bash # Validate build without activating (catches evaluation and syntax errors) @@ -279,3 +285,187 @@ To bring up a replacement host from version control: ```bash sudo systemctl start homeserver-core ``` + +--- + +## 7. Operator Account Migration Runbook (Decision D2: Staged Coexistence Cutover) + +> [!CAUTION] +> **MAINTENANCE WINDOW REQUIRED — EXECUTION ON LIVE HOST CURRENTLY BLOCKED** +> Live execution of this runbook against production hosts is strictly blocked until an authorized platform maintenance window is scheduled. This runbook is codified for procedural readiness and dry-run verification only. + +This runbook defines the 4-stage staged coexistence cutover procedure to migrate host operation from a legacy personal operator account (``) to the platform standard `operator` user (`uid = 1000`, `extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]`), fulfilling Decision D2 and eliminating personal identity coupling. + +### Stage 1: Pre-Flight Checks +Before initiating data synchronization or service cutover, verify the target `operator` account environment: + +1. **Verify `operator` account existence and home directory**: + ```bash + id operator + # Expected output must include membership in: wheel, docker, homelab-operators + ls -ld /home/operator + ``` + +2. **Verify SSH key provisioning**: + Ensure the operator's authorized keys are installed with strict permissions: + ```bash + sudo ls -la /home/operator/.ssh/authorized_keys + sudo chmod 700 /home/operator/.ssh + sudo chmod 600 /home/operator/.ssh/authorized_keys + sudo chown -R operator:users /home/operator/.ssh + ``` + +3. **Verify administrative (`sudo`) access**: + Test that `operator` can authenticate and execute privileged commands without failure: + ```bash + sudo -u operator sudo -n true || echo "Passwordless or password sudo required for operator" + ``` + +4. **Verify persistent directories**: + Ensure `/home/operator/Sites` and `/home/operator/Core` target parent paths are ready: + ```bash + sudo mkdir -p /home/operator/{Core,Sites,.config/homelab} + sudo chown -R operator:homelab-operators /home/operator/{Core,Sites,.config} + ``` + +--- + +### Stage 2: State and Repository Synchronization +Synchronize repository checkouts, environment definitions, and runtime state from the legacy user account to `/home/operator/` using non-destructive archive flags (`-aHAX` preserves hard links, attributes, and extended ACLs): + +1. **Initial background synchronization**: + Seed the file trees for Core and Sites while services continue running: + ```bash + sudo rsync -aHAX --info=progress2 \ + --exclude=".venv" \ + --exclude=".pytest_cache" \ + /home//Core/ /home/operator/Core/ + + sudo rsync -aHAX --info=progress2 \ + /home//Sites/ /home/operator/Sites/ + + if [ -d "/home//.config/homelab" ]; then + sudo rsync -aHAX --info=progress2 \ + /home//.config/homelab/ /home/operator/.config/homelab/ + fi + ``` + +2. **Quiesce active database writers**: + Stop the platform stack to guarantee point-in-time consistency across SQLite databases (e.g. LLDAP `users.db`, Authelia `db.sqlite3`, Stalwart storage) before the cutover sync: + ```bash + sudo systemctl stop homeserver-core + ``` + +3. **Final delta synchronization (`--delete`)**: + Perform a rapid final delta synchronization with `--delete` to capture the quiesced database state and prune removed files: + ```bash + sudo rsync -aHAX --delete --info=progress2 \ + --exclude=".venv" \ + --exclude=".pytest_cache" \ + /home//Core/ /home/operator/Core/ + + sudo rsync -aHAX --delete --info=progress2 \ + /home//Sites/ /home/operator/Sites/ + ``` + +4. **Fix ownership and permissions**: + Set primary ownership to `operator` and group to `homelab-operators`: + ```bash + sudo chown -R operator:homelab-operators /home/operator/Core /home/operator/Sites /home/operator/.config + sudo chmod -R u+rwX,g+rX /home/operator/Core /home/operator/Sites + + # ACME certificate security invariant: Traefik strictly requires 0600 on acme.json; + # recursive group read permissions will cause Traefik to refuse to start. + if [ -f /home/operator/Core/config/letsencrypt/acme.json ]; then + sudo chmod 600 /home/operator/Core/config/letsencrypt/acme.json + fi + ``` + +--- + +### Stage 3: Service Rebuild & Environment Cutover +Activate the declarative configuration under the `operator` profile: + +1. **Configure instance domain injection (Decision D1)**: + Ensure `nixos/instance.nix` (or `/etc/nixos/homelab-instance.nix`) is in place with the host's production domain: + ```bash + cat << 'EOF' | sudo -u operator tee /home/operator/Core/nixos/instance.nix > /dev/null + { + homelab.domain = "example.com"; + } + EOF + chmod 600 /home/operator/Core/nixos/instance.nix + ``` + +2. **Rebuild NixOS host configuration**: + Execute the rebuild from the new canonical Core path using `--impure` and the `path:` scheme to import the untracked instance profile: + ```bash + cd /home/operator/Core + sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure + ``` + + > [!NOTE] + > The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index, ensuring untracked/gitignored `nixos/instance.nix` is evaluated. (If using `/etc/nixos/homelab-instance.nix`, bare `--flake .#server --impure` works directly). + +3. **Restart platform services**: + Restart the Core Compose stack and control plane services to consume updated paths: + ```bash + sudo systemctl restart homeserver-core + sudo systemctl restart homelab-appctl + sudo systemctl restart homelab-gitops + ``` + +--- + +### Stage 4: Post-Flight Verification +Validate system health and operational readiness under the `operator` identity: + +1. **Verify Git safe directory**: + Ensure Git does not complain about dubious ownership when invoked by `operator` or `homelab-appctl`: + ```bash + sudo -u operator git -C /home/operator/Core status + sudo -u operator git -C /home/operator/Sites/ status + ``` + +2. **Verify appctl control plane status**: + Execute CLI inspection using both UDS peercred authentication and token authentication: + ```bash + # Peercred UDS inspection + sudo -u operator appctl list --core + + # Workload health check + sudo -u operator appctl status + ``` + +3. **Verify SOPS secrets and tokens**: + Ensure `/run/secrets/appctl/tokens.json` is readable by `homelab-appctl` and valid tokens exist for operator administration: + ```bash + sudo ls -l /run/secrets/appctl/tokens.json + ``` + +4. **Verify container reachability & proxy routing**: + Check that external endpoints and internal reverse proxies resolve: + ```bash + docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" + curl -s -k https://127.0.0.1 -H "Host: dashboard.example.com" | head -n 5 + ``` + +--- + +### Rollback Procedure +If unexpected service degradation occurs during the cutover: + +1. **Revert NixOS system generation**: + ```bash + sudo nixos-rebuild switch --rollback + ``` + +2. **Restart legacy Core services**: + ```bash + sudo systemctl restart homeserver-core + sudo systemctl restart homelab-appctl + sudo systemctl restart homelab-gitops + ``` + +3. **Log rollback reason**: + Record the diagnostic failure logs in `journalctl -xe` and investigate before attempting another cutover window. diff --git a/docs/plans/p4-refactor-and-decoupling-plan.md b/docs/plans/p4-refactor-and-decoupling-plan.md index a204fc5..2fc2b34 100644 --- a/docs/plans/p4-refactor-and-decoupling-plan.md +++ b/docs/plans/p4-refactor-and-decoupling-plan.md @@ -29,9 +29,20 @@ This plan establishes the concrete implementation work packages to resolve these - NixOS declares user `operator` (`uid = 1000` or standard user, `extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]`). - Eliminates hardcoded personal usernames from the Core platform foundation. -### B. Platform Genericism & Instance Profile -- Core modules in `nixos/modules/` remain strictly generic, defaulting to RFC 2606 placeholders (`example.test`). -- `nixos/configuration.nix` serves as the appliance instance profile where `homelab.domain` and `homelab.operatorUser` are explicitly set (e.g., using the host's configured production domain). +### B. Platform Genericism & Instance Profile (Decision D1) +- Core modules in `nixos/modules/` remain strictly generic, defaulting to RFC 2606 placeholders (`example.test` and `operator`). +- **Decision D1: Dual-Path Instance Domain Injection**: Rather than committing host-specific production domains to tracked Git files, `nixos/configuration.nix` implements an optional dual-path import mechanism: + ```nix + imports = [ + ./hardware-configuration.nix + ./modules/homeserver.nix + ./modules/traefik-deployments.nix + ./modules/dynu.nix + ./modules/shell.nix + ] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix + ++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix; + ``` +- `nixos/instance.nix` is git-ignored, allowing host-specific overrides (like `homelab.domain = "example.com";`) without dirtying version control. Alternatively, `/etc/nixos/homelab-instance.nix` provides a persistent host-level configuration path outside the repository checkout. - `LLDAP_LDAP_BASE_DN` is computed dynamically in Nix from `config.homelab.domain` (`domain: example.test` $\implies$ `dc=example,dc=test`), eliminating hardcoded domain strings across templates and Compose files. ### C. Control Plane Security & POSIX Permissions @@ -72,6 +83,13 @@ This plan establishes the concrete implementation work packages to resolve these - [x] **Task 3.4**: Update `docs/appctl.md` (clarifying bounded log snapshots and Core update workflow). - [x] **Task 3.5**: Synchronize `todo.txt` with active implementation tasks. +### Phase 4: Work Package 6 (WP6: Instance Decoupling & Operator Cutover Runbook) +- [x] **Task 4.1**: Update `nixos/configuration.nix` with optional dual-path imports for `./instance.nix` and `/etc/nixos/homelab-instance.nix` (Decision D1). +- [x] **Task 4.2**: Add `nixos/instance.nix` to `.gitignore` to preserve 100% repository genericism. +- [x] **Task 4.3**: Implement automated invariant tests in `tests/security/test_security_invariants.py` (default domain evaluation, dynamic LDAP base DN, instance override, platform genericism). +- [x] **Task 4.4**: Document instance domain injection procedure in `docs/setup_guide.md`. +- [x] **Task 4.5**: Codify the 4-stage Staged Coexistence Cutover Runbook (Decision D2) in `docs/operations.md` with explicit notice blocking live host execution pending maintenance window. + --- ## 4. Verification & Quality Gates diff --git a/docs/setup_guide.md b/docs/setup_guide.md index e684339..447b271 100644 --- a/docs/setup_guide.md +++ b/docs/setup_guide.md @@ -32,24 +32,64 @@ sudo ls -l /etc/ssh/ssh_host_ed25519_key sudo chmod 600 /etc/ssh/ssh_host_ed25519_key ``` -### Step 2: Apply Declarative NixOS Configuration +### Step 2: Configure Appliance Instance Domain (Decision D1) +To preserve strict platform genericism, the repository files tracked in Git never contain production domains or personal operator identities, defaulting to RFC 2606 placeholders (`example.test` and `operator`). + +An appliance host supplies its production domain and local configuration overrides via one of two untracked dual-path files: +1. **Repository-local instance profile (`nixos/instance.nix`)**: + Create an untracked, git-ignored file in `nixos/instance.nix`: + ```nix + { + homelab.domain = "example.com"; + } + ``` + When rebuilding via `sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure` (or `path:~/Core#server --impure`), Nix automatically imports `nixos/instance.nix` if present. + + > [!NOTE] + > **Flake Fetcher Scheme for Untracked Files**: + > Because `nixos/instance.nix` is gitignored, Nix's default Git fetcher filters it out when evaluating standard Git flake references (e.g. `--flake ~/Core#server`). Prefixing the path with the `path:` scheme (e.g. `path:/home/operator/Core#server` or `path:~/Core#server`) instructs Nix to evaluate directly from the filesystem without filtering by the Git index. + > If using the host-level `/etc/nixos/homelab-instance.nix` instead, a bare `--flake .#server --impure` works directly because `/etc/nixos` resides outside the Git repository tree. + +2. **Host-level instance profile (`/etc/nixos/homelab-instance.nix`)**: + Alternatively, create a host-level file outside the Git checkout: + ```nix + { + homelab.domain = "example.com"; + } + ``` + This persists configuration across fresh repository clones or ephemeral branches. + +Both paths are declared optionally in `nixos/configuration.nix`: +```nix +imports = [ + ./hardware-configuration.nix + ./modules/homeserver.nix + ./modules/traefik-deployments.nix + ./modules/dynu.nix + ./modules/shell.nix +] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix + ++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix; +``` +When present, `homelab.domain` overrides the default (`example.test`), and all generated templates (`homeserver.env`, Traefik routing rules, and the dynamic `LLDAP_LDAP_BASE_DN`) automatically reflect the production domain without altering any tracked Git files. + +### Step 3: Apply Declarative NixOS Configuration ```bash cd ~/Core -sudo nixos-rebuild switch --flake ~/Core#server +sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure ``` This configures: * Docker daemon, host firewall rules, and system packages. * Decrypted secret files in `/run/secrets/homeserver.env` and `/run/secrets/traefik-deployments.env`. -* Systemd service units (`homeserver-core`, `homelab-gitops`, `dynu-monitor`). +* Systemd service units (`homeserver-core`, `homelab-appctl`, `homelab-gitops`, `dynu-monitor`). -### Step 3: Create External Docker Networks +### Step 4: Create External Docker Networks The Core Compose stack and workloads require the `proxy-net` and `socket-net` bridge networks: ```bash docker network create proxy-net 2>/dev/null || true docker network create socket-net 2>/dev/null || true ``` -### Step 4: Start Platform Services +### Step 5: Start Platform Services ```bash sudo systemctl start homeserver-core ``` @@ -58,7 +98,7 @@ Check running containers: docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" ``` -### Step 5: Verify DNS & Certificates +### Step 6: Verify DNS & Certificates 1. Trigger an immediate DDNS update: ```bash sudo systemctl start dynu-monitor @@ -68,7 +108,7 @@ docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" appctl ssl traefik ``` -### Step 6: Initialize LLDAP Directory +### Step 7: Initialize LLDAP Directory 1. Navigate to `https://users.${HOMELAB_DOMAIN}` (e.g., `https://users.example.com`). 2. Authenticate using `admin` and the password configured in `nixos/secrets.yaml` (`lldap/admin_password`). 3. Create standard user accounts and assign them to required groups. diff --git a/nixos/configuration.nix b/nixos/configuration.nix index 19f184c..af7a285 100644 --- a/nixos/configuration.nix +++ b/nixos/configuration.nix @@ -12,7 +12,8 @@ ./modules/traefik-deployments.nix # Traefik deployment secrets and env templates ./modules/dynu.nix # Dynu DDNS smart IP monitor service ./modules/shell.nix # Declarative bash environment for the server - ]; + ] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix + ++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix; # ── Homelab platform settings ──────────────────────────────────────────────── homelab.operatorUser = "operator"; diff --git a/tests/security/test_security_invariants.py b/tests/security/test_security_invariants.py index 440dbdf..91a0f0e 100644 --- a/tests/security/test_security_invariants.py +++ b/tests/security/test_security_invariants.py @@ -4,6 +4,7 @@ Security invariant tests for Docker Compose and container isolation. import os import shutil +import subprocess from pathlib import Path import yaml @@ -289,3 +290,132 @@ def test_nixos_tmpfiles_rules_use_recursive_acls(): "tmpfiles.rules must use uppercase 'A+' for recursive ACL inheritance on homepage config" ) + +def test_default_homelab_domain_evaluates_to_example_test(): + """Assert default homelab.domain in NixOS config evaluates to 'example.test'.""" + homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix" + content = homeserver_nix.read_text(encoding="utf-8") + assert 'default = "example.test";' in content, ( + "homeserver.nix must set default homelab.domain to 'example.test'" + ) + + nix_bin = shutil.which("nix") + if nix_bin and not os.environ.get("NIX_BUILD_TOP"): + cmd = [ + nix_bin, + "eval", + ".#nixosConfigurations.server.config.homelab.domain", + "--raw", + ] + res = subprocess.run( + cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True + ) + assert res.stdout.strip() == "example.test", ( + f"Default homelab.domain must be 'example.test', got '{res.stdout.strip()}'" + ) + + +def test_dynamic_lldap_base_dn_splits_domain_components(): + """Assert dynamic LLDAP_LDAP_BASE_DN splits domain into dc=... components for any domain.""" + homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix" + content = homeserver_nix.read_text(encoding="utf-8") + assert "LLDAP_LDAP_BASE_DN = ldapBaseDn;" in content, ( + "homeserver.nix must bind LLDAP_LDAP_BASE_DN to ldapBaseDn in homeserver.env template" + ) + assert 'domainParts = lib.splitString "." config.homelab.domain;' in content, ( + "homeserver.nix must split homelab.domain by '.'" + ) + assert 'ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts);' in content, ( + "homeserver.nix must map domain components into dc=${part}" + ) + + nix_bin = shutil.which("nix") + if nix_bin and not os.environ.get("NIX_BUILD_TOP"): + cases = [ + ("example.test", "dc=example,dc=test"), + ("my.homelab.internal", "dc=my,dc=homelab,dc=internal"), + ("local", "dc=local"), + ] + for domain, expected_dn in cases: + expr = ( + f'let flake = builtins.getFlake (toString ./.); lib = flake.inputs.nixpkgs.lib; ' + f'domainParts = lib.splitString "." "{domain}"; ' + f'in lib.concatStringsSep "," (map (part: "dc=${{part}}") domainParts)' + ) + cmd = [ + nix_bin, + "eval", + "--impure", + "--expr", + expr, + "--raw", + ] + res = subprocess.run( + cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True + ) + assert res.stdout.strip() == expected_dn, ( + f"Expected {expected_dn} for domain {domain}, got {res.stdout.strip()}" + ) + + # Also assert rendered sops template in default configuration contains correct LLDAP_LDAP_BASE_DN + cmd_tpl = [ + nix_bin, + "eval", + '.#nixosConfigurations.server.config.sops.templates."homeserver.env".content', + "--raw", + ] + res_tpl = subprocess.run( + cmd_tpl, cwd=CORE_ROOT, capture_output=True, text=True, check=True + ) + assert "LLDAP_LDAP_BASE_DN=dc=example,dc=test" in res_tpl.stdout + + +def test_dual_path_import_overrides_homelab_domain(): + """Assert dual-path import overrides homelab.domain when ./nixos/instance.nix is present.""" + nix_bin = shutil.which("nix") + if nix_bin and not os.environ.get("NIX_BUILD_TOP"): + instance_nix = CORE_ROOT / "nixos" / "instance.nix" + try: + instance_nix.write_text( + '{ homelab.domain = "custom.internal"; }\n', encoding="utf-8" + ) + cmd = [ + nix_bin, + "eval", + "--impure", + "path:.#nixosConfigurations.server.config.homelab.domain", + "--raw", + ] + res = subprocess.run( + cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True + ) + assert res.stdout.strip() == "custom.internal", ( + f"Expected homelab.domain to be overridden to 'custom.internal', got '{res.stdout.strip()}'" + ) + finally: + if instance_nix.exists(): + instance_nix.unlink() + + +def test_nixos_configuration_declares_dual_path_instance_imports(): + """Ensure nixos/configuration.nix includes optional dual-path instance imports.""" + config_nix = CORE_ROOT / "nixos" / "configuration.nix" + content = config_nix.read_text(encoding="utf-8") + assert "builtins.pathExists ./instance.nix" in content, ( + "nixos/configuration.nix must check for ./instance.nix via builtins.pathExists" + ) + assert "builtins.pathExists /etc/nixos/homelab-instance.nix" in content, ( + "nixos/configuration.nix must check for /etc/nixos/homelab-instance.nix via builtins.pathExists" + ) + + +def test_gitignore_includes_instance_nix(): + """Ensure nixos/instance.nix is ignored in .gitignore to preserve platform genericism.""" + gitignore = CORE_ROOT / ".gitignore" + content = gitignore.read_text(encoding="utf-8") + lines = [line.strip() for line in content.splitlines()] + assert "nixos/instance.nix" in lines, ( + "nixos/instance.nix must be explicitly ignored in .gitignore" + ) + + diff --git a/todo.txt b/todo.txt index f5e339c..47baa92 100644 --- a/todo.txt +++ b/todo.txt @@ -44,3 +44,4 @@ x 2026-10-30 (B) Restore live container status inspection in workload.list and f x 2026-10-30 (B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth x 2026-10-30 (B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4 x 2026-10-30 (C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap +x 2026-10-30 (A) Implement instance domain injection dual-path import and operator cutover runbook in nixos/configuration.nix and docs/ +generic @nixos From e2dbc97b0e5b1c12c809e4d988496ec29ae9c8c7 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 30 Oct 2026 13:37:10 -0500 Subject: [PATCH 27/43] fix(nixos): add Core to git safe.directory and update nix-switch to path flake scheme - Update nixos/configuration.nix to include /home/${operatorUser}/Core in programs.git.config.safe.directory, preventing dubious ownership errors when homelab-appctl runs read-only status checks - Update nix-switch alias in nixos/modules/shell.nix to use path:$HOME/Core#server --impure, ensuring gitignored instance.nix domain injection evaluates reliably - Add security invariant tests asserting safe.directory configuration and nix-switch alias format --- nixos/configuration.nix | 1 + nixos/modules/shell.nix | 4 +- tests/security/test_security_invariants.py | 52 ++++++++++++++++++++++ 3 files changed, 55 insertions(+), 2 deletions(-) diff --git a/nixos/configuration.nix b/nixos/configuration.nix index af7a285..76b1a5f 100644 --- a/nixos/configuration.nix +++ b/nixos/configuration.nix @@ -22,6 +22,7 @@ programs.git = { enable = true; config.safe.directory = [ + "/home/${config.homelab.operatorUser}/Core" "/home/${config.homelab.operatorUser}/Sites/*" ]; }; diff --git a/nixos/modules/shell.nix b/nixos/modules/shell.nix index 46e938f..cda1d58 100644 --- a/nixos/modules/shell.nix +++ b/nixos/modules/shell.nix @@ -62,8 +62,8 @@ reload = "exec bash"; pgoog = "ping google.com -c 3"; wifi = "nmtui"; - # NixOS rebuild targeting this flake - nix-switch = "sudo nixos-rebuild switch --flake ~/Core#server"; + # NixOS rebuild targeting this flake (path scheme + impure required for instance.nix) + nix-switch = "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure"; }; interactiveShellInit = '' diff --git a/tests/security/test_security_invariants.py b/tests/security/test_security_invariants.py index 91a0f0e..b03178c 100644 --- a/tests/security/test_security_invariants.py +++ b/tests/security/test_security_invariants.py @@ -419,3 +419,55 @@ def test_gitignore_includes_instance_nix(): ) +def test_nixos_switch_alias_uses_path_and_impure(): + """Ensure nix-switch alias in nixos/modules/shell.nix uses path: and --impure to prevent silent fail-open.""" + shell_nix = CORE_ROOT / "nixos" / "modules" / "shell.nix" + content = shell_nix.read_text(encoding="utf-8") + assert 'nix-switch = "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure";' in content, ( + "nixos/modules/shell.nix must configure nix-switch alias with path:$HOME/Core#server --impure" + ) + + +def test_nixos_safe_directory_includes_core_and_sites(): + """Ensure programs.git.config.safe.directory includes Core and Sites to prevent dubious ownership errors.""" + config_nix = CORE_ROOT / "nixos" / "configuration.nix" + content = config_nix.read_text(encoding="utf-8") + assert '"/home/${config.homelab.operatorUser}/Core"' in content, ( + "nixos/configuration.nix must include Core in git safe.directory" + ) + assert '"/home/${config.homelab.operatorUser}/Sites/*"' in content, ( + "nixos/configuration.nix must include Sites/* in git safe.directory" + ) + + nix_bin = shutil.which("nix") + if nix_bin and not os.environ.get("NIX_BUILD_TOP"): + cmd = [ + nix_bin, + "eval", + ".#nixosConfigurations.server.config.programs.git.config", + "--json", + ] + res = subprocess.run( + cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True + ) + import json + + configs = json.loads(res.stdout) + safe_dirs = [] + for cfg in configs: + if isinstance(cfg, dict) and "safe" in cfg and "directory" in cfg["safe"]: + dirs = cfg["safe"]["directory"] + if isinstance(dirs, list): + safe_dirs.extend(dirs) + else: + safe_dirs.append(dirs) + + assert "/home/operator/Core" in safe_dirs, ( + f"Expected '/home/operator/Core' in git safe.directory, got {safe_dirs}" + ) + assert "/home/operator/Sites/*" in safe_dirs, ( + f"Expected '/home/operator/Sites/*' in git safe.directory, got {safe_dirs}" + ) + + + From 4f1a63160b37960f0580b6c4a7ce488f1c792a33 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 30 Oct 2026 13:40:22 -0500 Subject: [PATCH 28/43] fix(provenance): report non-zero git status exits and update bootstrap rebuild hint MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Update get_local_checkout_status in scripts/provenance.py to surface non-zero git status exit codes as '⚠️ Git Error (exit )' rather than masking them as '✓ Clean' - Update scripts/bootstrap_token.py rebuild instruction to use path:$HOME/Core#server --impure, ensuring instance.nix evaluation is respected - Add unit test coverage for non-zero git exit handling and bootstrap rebuild guidance --- scripts/bootstrap_token.py | 2 +- scripts/provenance.py | 20 ++++++++++++++------ tests/unit/test_bootstrap_token.py | 1 + tests/unit/test_provenance.py | 16 ++++++++++++++++ 4 files changed, 32 insertions(+), 7 deletions(-) diff --git a/scripts/bootstrap_token.py b/scripts/bootstrap_token.py index abc3b01..8c3782c 100755 --- a/scripts/bootstrap_token.py +++ b/scripts/bootstrap_token.py @@ -163,7 +163,7 @@ def main(argv: list[str] | None = None) -> int: f"Add the following descriptor to your SOPS tokens store (nixos/secrets.yaml -> appctl/tokens_json):\n\n" f"{json_snippet}\n\n" f"After updating nixos/secrets.yaml with `sops nixos/secrets.yaml`, apply changes with:\n" - f" sudo nixos-rebuild switch --flake ~/Core#server\n" + f" sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure\n" ) return 0 diff --git a/scripts/provenance.py b/scripts/provenance.py index 4673f74..f9a700e 100644 --- a/scripts/provenance.py +++ b/scripts/provenance.py @@ -109,6 +109,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus: # 1. Check cleanliness is_dirty = False + git_error: str | None = None try: status_res = subprocess.run( ["git", "-C", str(path), "status", "--porcelain"], @@ -118,10 +119,14 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus: timeout=5.0, env=git_env, ) - if status_res.returncode == 0 and status_res.stdout.strip(): - is_dirty = True - except (subprocess.SubprocessError, OSError): + if status_res.returncode == 0: + if status_res.stdout.strip(): + is_dirty = True + else: + git_error = f"⚠️ Git Error (exit {status_res.returncode})" + except (subprocess.SubprocessError, OSError) as exc: is_dirty = False + git_error = f"⚠️ Git Error ({exc.__class__.__name__})" # 2. Get active branch branch = "" @@ -168,9 +173,12 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus: commit_sha = "" # 4. Format status label - state_symbol = "* Dirty" if is_dirty else "✓ Clean" - ref_desc = f"{branch}@{commit_sha}" if commit_sha else branch - status_label = f"{state_symbol} ({ref_desc})" if ref_desc else state_symbol + if git_error: + status_label = git_error + else: + state_symbol = "* Dirty" if is_dirty else "✓ Clean" + ref_desc = f"{branch}@{commit_sha}" if commit_sha else branch + status_label = f"{state_symbol} ({ref_desc})" if ref_desc else state_symbol return CheckoutStatus( is_git=True, diff --git a/tests/unit/test_bootstrap_token.py b/tests/unit/test_bootstrap_token.py index 7993c59..a30a986 100644 --- a/tests/unit/test_bootstrap_token.py +++ b/tests/unit/test_bootstrap_token.py @@ -126,6 +126,7 @@ def test_bootstrap_cli_never_prints_raw_secret_to_stdout_or_stderr( # Ensure stdout provides helpful human guidance assert "operator-admin" in captured.out assert "sops nixos/secrets.yaml" in captured.out + assert "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure" in captured.out def test_bootstrap_cli_print_json_outputs_valid_json_descriptor( diff --git a/tests/unit/test_provenance.py b/tests/unit/test_provenance.py index 01c5834..458afad 100644 --- a/tests/unit/test_provenance.py +++ b/tests/unit/test_provenance.py @@ -250,3 +250,19 @@ def test_resolve_upstream_provenance_class_b_and_default_timeout(): prov = resolve_upstream_provenance(source, local_commit="abc1234") assert prov.status == ProvenanceStatus.SYNCED assert mock_run.call_args[1]["timeout"] == 10.0 + + +def test_get_local_checkout_status_git_error(tmp_path: Path): + app_dir = tmp_path / "git_error_app" + app_dir.mkdir() + (app_dir / ".git").mkdir() + + with patch("subprocess.run") as mock_run: + mock_run.return_value = MagicMock( + returncode=128, stdout="", stderr="fatal: dubious ownership" + ) + status = get_local_checkout_status(app_dir) + assert status.is_git is True + assert status.is_dirty is False + assert status.status_label == "⚠️ Git Error (exit 128)" + From 3ba8e2b51d24c5b7ebcab7af944d6dd3a18eb702 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 30 Oct 2026 13:42:34 -0500 Subject: [PATCH 29/43] docs(operations): include var/lib/homelab state and workload quiescence in operator cutover runbook - Add explicit guidance to maintain active legacy SSH/terminal session throughout migration to prevent lockout - Document fallback operator user provisioning if coexistence account is not yet active - Add /home//var/lib/homelab and ~/.local/state/homelab to initial and final rsync stages to prevent workload state stranding - Quiesce active workload containers alongside core platform services before final rsync delta to guarantee database consistency - Extend ownership fixup to /home/operator/var and /home/operator/.local --- docs/operations.md | 76 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 58 insertions(+), 18 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 3f60937..4badb88 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -296,20 +296,29 @@ To bring up a replacement host from version control: This runbook defines the 4-stage staged coexistence cutover procedure to migrate host operation from a legacy personal operator account (``) to the platform standard `operator` user (`uid = 1000`, `extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]`), fulfilling Decision D2 and eliminating personal identity coupling. -### Stage 1: Pre-Flight Checks -Before initiating data synchronization or service cutover, verify the target `operator` account environment: +### Stage 1: Pre-Flight Checks & Session Preservation -1. **Verify `operator` account existence and home directory**: +> [!IMPORTANT] +> **Maintain Active Legacy Shell Session**: +> Do not terminate your active SSH or terminal session as ``. Keep at least one authenticated shell open throughout the entire cutover process to prevent lockout in case of SSH key, user profile, or PAM misconfiguration. + +1. **Verify or provision `operator` account**: + Check if the `operator` user exists in the running environment: ```bash id operator - # Expected output must include membership in: wheel, docker, homelab-operators - ls -ld /home/operator + ``` + If `operator` does not exist yet (as `homelab.operatorUser` has not been switched in the active NixOS generation), provision the initial coexistence user before proceeding: + ```bash + sudo useradd -m -s /run/current-system/sw/bin/bash -G wheel,docker,homelab-operators operator ``` -2. **Verify SSH key provisioning**: - Ensure the operator's authorized keys are installed with strict permissions: +2. **Verify SSH key provisioning & permissions**: + Ensure the operator's authorized keys are installed with strict permissions (copying from `` if needed): ```bash - sudo ls -la /home/operator/.ssh/authorized_keys + sudo mkdir -p /home/operator/.ssh + if [ ! -f /home/operator/.ssh/authorized_keys ] && [ -f /home//.ssh/authorized_keys ]; then + sudo cp /home//.ssh/authorized_keys /home/operator/.ssh/authorized_keys + fi sudo chmod 700 /home/operator/.ssh sudo chmod 600 /home/operator/.ssh/authorized_keys sudo chown -R operator:users /home/operator/.ssh @@ -321,20 +330,20 @@ Before initiating data synchronization or service cutover, verify the target `op sudo -u operator sudo -n true || echo "Passwordless or password sudo required for operator" ``` -4. **Verify persistent directories**: - Ensure `/home/operator/Sites` and `/home/operator/Core` target parent paths are ready: +4. **Prepare persistent directories**: + Ensure `/home/operator/Sites`, `/home/operator/Core`, `/home/operator/var/lib/homelab`, and state parent paths are ready: ```bash - sudo mkdir -p /home/operator/{Core,Sites,.config/homelab} - sudo chown -R operator:homelab-operators /home/operator/{Core,Sites,.config} + sudo mkdir -p /home/operator/{Core,Sites,.config/homelab,var/lib/homelab,.local/state/homelab} + sudo chown -R operator:homelab-operators /home/operator/{Core,Sites,.config,var,.local} ``` --- ### Stage 2: State and Repository Synchronization -Synchronize repository checkouts, environment definitions, and runtime state from the legacy user account to `/home/operator/` using non-destructive archive flags (`-aHAX` preserves hard links, attributes, and extended ACLs): +Synchronize repository checkouts, workload persistent data, and runtime state from the legacy user account to `/home/operator/` using non-destructive archive flags (`-aHAX` preserves hard links, attributes, and extended ACLs): 1. **Initial background synchronization**: - Seed the file trees for Core and Sites while services continue running: + Seed the file trees for Core, Sites, workload databases, and configurations while services continue running: ```bash sudo rsync -aHAX --info=progress2 \ --exclude=".venv" \ @@ -344,6 +353,16 @@ Synchronize repository checkouts, environment definitions, and runtime state fro sudo rsync -aHAX --info=progress2 \ /home//Sites/ /home/operator/Sites/ + if [ -d "/home//var/lib/homelab" ]; then + sudo rsync -aHAX --info=progress2 \ + /home//var/lib/homelab/ /home/operator/var/lib/homelab/ + fi + + if [ -d "/home//.local/state/homelab" ]; then + sudo rsync -aHAX --info=progress2 \ + /home//.local/state/homelab/ /home/operator/.local/state/homelab/ + fi + if [ -d "/home//.config/homelab" ]; then sudo rsync -aHAX --info=progress2 \ /home//.config/homelab/ /home/operator/.config/homelab/ @@ -351,9 +370,15 @@ Synchronize repository checkouts, environment definitions, and runtime state fro ``` 2. **Quiesce active database writers**: - Stop the platform stack to guarantee point-in-time consistency across SQLite databases (e.g. LLDAP `users.db`, Authelia `db.sqlite3`, Stalwart storage) before the cutover sync: + Stop running workload containers and the Core platform stack to guarantee point-in-time consistency across SQLite databases (e.g. LLDAP `users.db`, Authelia `db.sqlite3`, Stalwart storage, and workload app volumes in `~/var/lib/homelab/`) before the final sync: ```bash + # Stop running workload containers + appctl down --all 2>/dev/null || docker stop $(docker ps -q) 2>/dev/null || true + + # Stop platform core services sudo systemctl stop homeserver-core + sudo systemctl stop homelab-appctl + sudo systemctl stop homelab-gitops ``` 3. **Final delta synchronization (`--delete`)**: @@ -366,13 +391,28 @@ Synchronize repository checkouts, environment definitions, and runtime state fro sudo rsync -aHAX --delete --info=progress2 \ /home//Sites/ /home/operator/Sites/ + + if [ -d "/home//var/lib/homelab" ]; then + sudo rsync -aHAX --delete --info=progress2 \ + /home//var/lib/homelab/ /home/operator/var/lib/homelab/ + fi + + if [ -d "/home//.local/state/homelab" ]; then + sudo rsync -aHAX --delete --info=progress2 \ + /home//.local/state/homelab/ /home/operator/.local/state/homelab/ + fi ``` 4. **Fix ownership and permissions**: - Set primary ownership to `operator` and group to `homelab-operators`: + Set primary ownership to `operator` and group to `homelab-operators` across all migrated trees: ```bash - sudo chown -R operator:homelab-operators /home/operator/Core /home/operator/Sites /home/operator/.config - sudo chmod -R u+rwX,g+rX /home/operator/Core /home/operator/Sites + sudo chown -R operator:homelab-operators \ + /home/operator/Core \ + /home/operator/Sites \ + /home/operator/.config \ + /home/operator/.local \ + /home/operator/var + sudo chmod -R u+rwX,g+rX /home/operator/Core /home/operator/Sites /home/operator/var # ACME certificate security invariant: Traefik strictly requires 0600 on acme.json; # recursive group read permissions will cause Traefik to refuse to start. From 03c8fdcf8e5551b7a86c631b8d2b6390ea424751 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 30 Oct 2026 13:46:22 -0500 Subject: [PATCH 30/43] docs(core): reconcile README and SECURITY with Milestone P4 control plane daemon architecture - Update README.md to describe homelab-appctl.service operational control plane daemon architecture over UDS and loopback HTTP - Update Repository Structure table to include bootstrap_token.py and appctl_*.py daemon modules - Update Host System Management rebuild commands across docs to use path:$HOME/Core#server --impure - Document control plane transport isolation, SO_PEERCRED viewer auth, SHA-256 tokens, 3-tier RBAC, per-target flocking, and fail-closed audit logging in SECURITY.md --- README.md | 37 ++++++++++++++++++++++++++----------- SECURITY.md | 12 ++++++++++++ docs/appctl.md | 4 ++-- docs/secrets-and-state.md | 2 +- 4 files changed, 41 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index c100d4d..27afed9 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ It is designed around a strict two-tier boundary: All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime. > [!NOTE] -> **Current Implementation Baseline vs. Target Architecture**: This README documents the **currently implemented CLI and runtime baseline (Milestone P3)**. Under [Milestone P4 in `ROADMAP.md`](ROADMAP.md), `appctl` is transitioning from a host CLI orchestrator into a dedicated daemon service (`homelab-appctl.service`) exposing a unified logical API across local Unix socket and HTTP transports. See [`ROADMAP.md`](ROADMAP.md) for the full baseline-to-target matrix. +> **Milestone P4 Control Plane Architecture**: Under [Milestone P4 in `ROADMAP.md`](ROADMAP.md), `appctl` operates as an operational control plane daemon service (`homelab-appctl.service`) exposing a unified logical API across a local Unix Domain Socket (`/run/homelab/appctl.sock`) and loopback HTTP (`127.0.0.1:9876`). The thin `appctl` CLI delegates commands to this daemon with automatic `SO_PEERCRED` identity inspection and token-based RBAC. See [`docs/appctl.md`](docs/appctl.md) and [`ROADMAP.md`](ROADMAP.md) for details. --- @@ -49,8 +49,10 @@ All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_ ▲ │ (Host Orchestration & CD) ┌───────────────┴───────────────┐ - │ Host Control Plane Baseline │ - │ • appctl CLI + Engine │ + │ Host Control Plane (P4) │ + │ • thin appctl CLI │ + │ • homelab-appctl.service │ + │ (UDS / HTTP daemon) │ │ • homelab-gitops.service │ └───────────────────────────────┘ ``` @@ -82,10 +84,17 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran ├── nixos/ # Declarative NixOS modules, systemd units, and SOPS secret wiring ├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml) ├── scripts/ -│ ├── appctl # Operational CLI entrypoint and Compose environment orchestrator -│ ├── appctl_engine.py # Discovery, two-axis provenance, TLS inspection, and Homepage sync engine -│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for workload app.yaml -│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST security validation +│ ├── appctl # Thin operational CLI delegating to control plane daemon +│ ├── appctl_daemon.py # Async HTTP/UDS daemon server (homelab-appctl.service) +│ ├── appctl_router.py # Operational router, locking, RBAC & dispatch +│ ├── appctl_auth.py # SO_PEERCRED & Bearer token RBAC authentication +│ ├── appctl_audit.py # Append-only fail-closed structured audit logger +│ ├── appctl_contracts.py # Pydantic v2 schemas for daemon RPC requests & responses +│ ├── appctl_cli.py # Unified CLI client with dual transport fallbacks +│ ├── appctl_engine.py # Discovery, two-axis provenance, TLS inspection, and Homepage sync +│ ├── bootstrap_token.py # Operator Bearer token provisioning helper +│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for app.yaml +│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST validation │ └── test # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks) ├── tests/ # Unit, structural, and security invariant test suites └── docs/ # Architecture references, operational runbooks, and MADR decisions @@ -93,7 +102,7 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran --- -## Quickstart & Operations (Current CLI Baseline) +## Quickstart & Operations (Control Plane Daemon & CLI) ### Development & Verification @@ -111,7 +120,12 @@ pyright ### Workload Management (`appctl` CLI) +The thin `appctl` CLI connects directly to `homelab-appctl.service` via Unix Domain Socket (`/run/homelab/appctl.sock`) or loopback HTTP (`127.0.0.1:9876`). Local operators in `homelab-operators` or `wheel` receive read-only viewer access via kernel `SO_PEERCRED` without tokens, while mutating actions consume Bearer tokens from `~/.config/homelab/token`: + ```bash +# Check daemon health status +appctl health + # List all workloads with container health and local Git checkout status appctl list @@ -121,7 +135,7 @@ appctl list --fetch --ssl --core # Inspect detailed manifest, provenance, and container diagnostics for a workload appctl info -# Manage workload or Core service lifecycle (executes docker compose locally in the current baseline) +# Manage workload or Core service lifecycle (dispatched via homelab-appctl daemon) appctl up appctl down appctl restart @@ -136,11 +150,12 @@ appctl sync ### Host System Management ```bash -# Rebuild and activate the NixOS host configuration -sudo nixos-rebuild switch --flake .#server +# Rebuild and activate the NixOS host configuration (or use the 'nix-switch' alias) +sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure # Inspect platform systemd units systemctl status homeserver-core.service +systemctl status homelab-appctl.service systemctl status homelab-gitops.service systemctl status dynu-monitor.service ``` diff --git a/SECURITY.md b/SECURITY.md index e9f555a..159d7ae 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -31,6 +31,15 @@ This document outlines the security controls, container isolation rules, and ope * Secrets are stored encrypted in `nixos/secrets.yaml` using Age keys derived from the host SSH key (`/etc/ssh/ssh_host_ed25519_key`). * Decrypted secrets reside in RAM-backed ephemeral filesystems (`/run/secrets/`, `/run/credentials/`) and are not committed to unencrypted persistent files. +### F. Operational Control Plane Security (`homelab-appctl.service`) +* **Transport Isolation**: Daemon listens on a restricted Unix Domain Socket (`/run/homelab/appctl.sock`, mode `0660`, group `homelab-operators`) and loopback HTTP (`127.0.0.1:9876`). It never binds to public interfaces. +* **Authentication & RBAC**: + - **UDS Peer Credential Identification**: Local connections inspect kernel peer credentials (`SO_PEERCRED`). Callers in `homelab-operators` or `wheel` receive read-only viewer privileges automatically without requiring secrets on disk. + - **Cryptographic Bearer Tokens**: Mutating actions require Bearer tokens defined in SOPS (`/run/secrets/appctl/tokens.json`). Tokens are validated using `hmac.compare_digest` against SHA-256 digests. + - **Three-Tier RBAC**: Granular role enforcement distinguishes read-only inspectors (`viewer`), workload managers (`operator`), and core platform administrators (`admin`). +* **Per-Target Concurrency Control (`flock`)**: Non-blocking file locks (`/run/lock/homelab/.lock`) serialize mutating actions per workload, returning HTTP 409 Conflict if an operation is already in flight. +* **Fail-Closed Structured Audit Logging**: Every operational command is appended synchronously to a tamper-evident audit log (`/var/log/homelab/appctl/audit.jsonl`, mode `0600`). If disk writing fails, the daemon fails closed and rejects the request. + --- ## 2. Threat Model & Operational Considerations @@ -57,3 +66,6 @@ This document outlines the security controls, container isolation rules, and ope - [x] Invariant test runner (`./scripts/test`) passing on changes. - [x] `config/letsencrypt/acme.json` permissions set to `0600`. - [x] Host firewall ports restricted to declared services in `nixos/modules/homeserver.nix`. +- [x] Control plane daemon (`homelab-appctl.service`) isolated to UDS (`0660`) and loopback HTTP. +- [x] Operational audit log (`/var/log/homelab/appctl/audit.jsonl`) append-only with strict `0600` permissions. +- [x] Control plane mutation endpoints enforce per-target `flock` and SHA-256 Bearer tokens. diff --git a/docs/appctl.md b/docs/appctl.md index 8264beb..ef87a94 100644 --- a/docs/appctl.md +++ b/docs/appctl.md @@ -111,7 +111,7 @@ appctl: Save and exit your editor (SOPS will re-encrypt the file), then project the updated secrets: ```bash -sudo nixos-rebuild switch --flake ~/Core#server +sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure ``` This updates `/run/secrets/appctl/tokens.json` (owned by `homelab-appctl:homelab-operators`, mode `0400`), which `homelab-appctl.service` consumes. @@ -135,7 +135,7 @@ Verify permissions using both unauthenticated and authenticated queries: To rotate an operator token: 1. Run `python3 scripts/bootstrap_token.py --force --token-id "operator-admin-$(date +%Y%m%d)"`. 2. Open `sops nixos/secrets.yaml` and add the new descriptor to `appctl.tokens_json`. Keep the old entry temporarily if multiple sessions share it, or replace it immediately. -3. Run `sudo nixos-rebuild switch --flake ~/Core#server` to apply the updated token store. +3. Run `sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure` to apply the updated token store. 4. Verify CLI operations (`appctl config docs`). 5. Remove the deprecated token descriptor from `nixos/secrets.yaml` and re-run `nixos-rebuild switch`. diff --git a/docs/secrets-and-state.md b/docs/secrets-and-state.md index a17eb49..d2a1b79 100644 --- a/docs/secrets-and-state.md +++ b/docs/secrets-and-state.md @@ -103,7 +103,7 @@ brevo: ### 3. Save and Apply Changes Saving the file in your editor automatically re-encrypts it with Age. Apply the updated templates to running services: ```bash -sudo nixos-rebuild switch --flake ~/Core#server +sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure ``` --- From 178a0c89906057e4215996f8b07b300fdd5b3572 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 14:04:28 -0500 Subject: [PATCH 31/43] fix(compose): enforce host containment on dictionary volumes and reject variable interpolation - Default dictionary volume declarations omitting 'type: bind' to host containment checks when 'source' is specified (CR-DI-01) - Reject volume host paths containing dynamic variable interpolation (${...}) to prevent runtime boundary escapes (CR-DI-02) - Add security regression tests in tests/security/test_gitops_security.py --- scripts/gitops_dispatcher.py | 19 ++++-- tests/security/test_gitops_security.py | 92 ++++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 5 deletions(-) diff --git a/scripts/gitops_dispatcher.py b/scripts/gitops_dispatcher.py index 18e992d..239948d 100755 --- a/scripts/gitops_dispatcher.py +++ b/scripts/gitops_dispatcher.py @@ -110,7 +110,9 @@ def execute_deployment_via_daemon( timeout=330.0, ) if resp.success: - logger.info(f"✨ Deployment of '{target}' via daemon completed successfully.") + logger.info( + f"✨ Deployment of '{target}' via daemon completed successfully." + ) return True err_msg = resp.error.message if resp.error else "Unknown daemon error" logger.error(f"❌ Deployment of '{target}' via daemon failed: {err_msg}") @@ -286,7 +288,7 @@ def get_trusted_repository_mapping() -> dict[str, Path]: if not raw_path: continue if raw_path.startswith("~/Sites/") or raw_path == "~/Sites": - sub = raw_path[len("~/Sites"):].lstrip("/") + sub = raw_path[len("~/Sites") :].lstrip("/") p = (SITES_DIR / sub).resolve() if sub else SITES_DIR.resolve() else: p = Path(raw_path).expanduser().resolve() @@ -407,8 +409,6 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]: return target_dir, deployment_config - - PROHIBITED_HOST_NAMESPACES = {"host"} DANGEROUS_SECURITY_OPTS = {"unconfined", "apparmor:unconfined", "seccomp:unconfined"} @@ -607,6 +607,8 @@ def validate_compose_security( ) if ":" in vol: host_path = vol.split(":")[0].strip() + else: + host_path = vol.strip() elif isinstance(vol, dict): src = str(vol.get("source", "")) if "/var/run/docker.sock" in src: @@ -614,12 +616,19 @@ def validate_compose_security( False, f"Service '{svc_name}' directly mounts Docker socket: {src}.", ) - if vol.get("type") == "bind": + vol_type = vol.get("type") + if vol_type in ("bind", "volume") or (vol_type is None and src): host_path = src if not host_path: continue + if "${" in host_path or "}" in host_path: + return ( + False, + f"Service '{svc_name}' specifies prohibited variable interpolation in volume host path: '{host_path}'.", + ) + # Declared top-level named volume without path separators if host_path in top_volumes and not ( host_path.startswith((".", "/", "~")) diff --git a/tests/security/test_gitops_security.py b/tests/security/test_gitops_security.py index 29eb91f..097053a 100644 --- a/tests/security/test_gitops_security.py +++ b/tests/security/test_gitops_security.py @@ -1068,3 +1068,95 @@ services: ) assert valid is False assert err is not None and "security_opt" in err.lower() + + +def test_validate_compose_security_rejects_dict_volume_without_type_bind( + tmp_path: Path, +): + """Ensure dictionary volume declarations without explicit type: bind enforce host containment (CR-DI-01).""" + compose_file = tmp_path / "docker-compose.yml" + compose_file.write_text( + """ +services: + app: + image: alpine + volumes: + - source: /etc/shadow + target: /app/shadow +""", + encoding="utf-8", + ) + valid, err = gitops_dispatcher.validate_compose_security( + compose_file, tmp_path, app_name="my-app" + ) + assert valid is False + assert err is not None and "prohibited host bind mount" in err.lower() + + +def test_validate_compose_security_rejects_variable_interpolation_in_volume_host_path( + tmp_path: Path, +): + """Ensure volume host paths containing variable interpolation (${...}) fail closed (CR-DI-02).""" + compose_file = tmp_path / "docker-compose.yml" + compose_file.write_text( + """ +services: + app: + image: alpine + volumes: + - "${HOST_DIR}/data:/data" +""", + encoding="utf-8", + ) + valid, err = gitops_dispatcher.validate_compose_security( + compose_file, tmp_path, app_name="my-app" + ) + assert valid is False + assert err is not None and "variable interpolation" in err.lower() + + +def test_validate_compose_security_rejects_variable_interpolation_in_dict_volume_source( + tmp_path: Path, +): + """Ensure dictionary volume source containing variable interpolation (${...}) fails closed (CR-DI-02).""" + compose_file = tmp_path / "docker-compose.yml" + compose_file.write_text( + """ +services: + app: + image: alpine + volumes: + - source: "${HOST_DIR}/data" + target: /data +""", + encoding="utf-8", + ) + valid, err = gitops_dispatcher.validate_compose_security( + compose_file, tmp_path, app_name="my-app" + ) + assert valid is False + assert err is not None and "variable interpolation" in err.lower() + + +def test_validate_compose_security_allows_valid_dict_volume_within_workload( + tmp_path: Path, +): + """Ensure valid dictionary volume within workload root is accepted even without type: bind.""" + (tmp_path / "data").mkdir() + compose_file = tmp_path / "docker-compose.yml" + compose_file.write_text( + """ +services: + app: + image: alpine + volumes: + - source: ./data + target: /data +""", + encoding="utf-8", + ) + valid, err = gitops_dispatcher.validate_compose_security( + compose_file, tmp_path, app_name="my-app" + ) + assert valid is True + assert err is None From d0213d720948d650b5088a1361acd17f7059a0ee Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 14:06:09 -0500 Subject: [PATCH 32/43] security(router): prevent workload .env override of reserved platform configuration - Add platform routing, networking, and Docker config keys to RESERVED_ENV_KEYS (CR-DI-07) - Add unit tests verifying rejection of reserved platform variables in manifest.env --- scripts/core_manifest.py | 22 ++++++++++++++++------ tests/unit/test_core_manifest.py | 23 +++++++++++++++++++---- 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/scripts/core_manifest.py b/scripts/core_manifest.py index 590b582..efb4735 100644 --- a/scripts/core_manifest.py +++ b/scripts/core_manifest.py @@ -72,10 +72,25 @@ RESERVED_ENV_KEYS = { "SITES_DIR", "ENV_FILE", "HOMESERVER_ENV", + "HOMELAB_DOMAIN", + "DOMAIN_SUFFIX", + "DOMAIN", + "PROXY_NETWORK", + "CERT_RESOLVER", + "DOCKER_CONFIG", + "SERVICE_NAME", + "CONTAINER_NAME", + "SERVICE_DOMAIN", } ALLOWED_STRATEGIES = {"compose"} -ALLOWED_ACTIONS = {"git_pull", "compose_pull", "compose_up", "compose_build", "compose_restart"} +ALLOWED_ACTIONS = { + "git_pull", + "compose_pull", + "compose_up", + "compose_build", + "compose_restart", +} def validate_transport(url: str) -> tuple[TransportScheme, str]: @@ -168,13 +183,11 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]: return RefType.BRANCH, ref - class SourceConfig(BaseModel): """Upstream source provenance descriptor.""" model_config = ConfigDict(extra="forbid", ignored_types=(dict,)) - url: str ref: str = "main" type: str = "git" @@ -223,7 +236,6 @@ class DeploymentConfig(BaseModel): model_config = ConfigDict(extra="forbid", ignored_types=(dict,)) - strategy: str = "compose" branch: str = "main" actions: list[str] = Field(default_factory=lambda: ["git_pull", "compose_up"]) @@ -264,7 +276,6 @@ class HomepageConfig(BaseModel): model_config = ConfigDict(extra="forbid", ignored_types=(dict,)) - title: str group: str = "Applications" icon: str = "default.png" @@ -295,7 +306,6 @@ class Manifest(BaseModel): ignored_types=(dict,), ) - name: str schema_version: str = Field(default="1.0", alias="schemaVersion") domain: str = "" diff --git a/tests/unit/test_core_manifest.py b/tests/unit/test_core_manifest.py index edf2f5e..af9905a 100644 --- a/tests/unit/test_core_manifest.py +++ b/tests/unit/test_core_manifest.py @@ -66,7 +66,9 @@ def test_validate_transport_rejects_http(insecure_url: str): ], ) def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url): - with pytest.raises(ManifestValidationError, match=r"^Source URL cannot be empty\.$"): + with pytest.raises( + ManifestValidationError, match=r"^Source URL cannot be empty\.$" + ): validate_transport(empty_or_invalid_url) # type: ignore[arg-type] @@ -77,7 +79,9 @@ def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url): ("ssh://git.example.com/", "SSH"), ], ) -def test_validate_transport_rejects_root_repository_path(root_path_url: str, scheme: str): +def test_validate_transport_rejects_root_repository_path( + root_path_url: str, scheme: str +): with pytest.raises( ManifestValidationError, match=rf"^Malformed {scheme} source URL \(missing repository path\)", @@ -132,8 +136,10 @@ def test_classify_ref_branches(): "feat/manifest-engine", ) assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0") - assert classify_ref("custom-adhoc-branch") == (RefType.BRANCH, "custom-adhoc-branch") - + assert classify_ref("custom-adhoc-branch") == ( + RefType.BRANCH, + "custom-adhoc-branch", + ) def test_classify_ref_tags(): @@ -271,6 +277,15 @@ def test_parse_manifest_from_path(tmp_path: Path): "IFS", "CORE_DIR", "SITES_DIR", + "HOMELAB_DOMAIN", + "DOMAIN_SUFFIX", + "DOMAIN", + "PROXY_NETWORK", + "CERT_RESOLVER", + "DOCKER_CONFIG", + "SERVICE_NAME", + "CONTAINER_NAME", + "SERVICE_DOMAIN", ], ) def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str): From 5dfebac35cbc11df766914a8d46b3b350cc0b1dc Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 14:06:39 -0500 Subject: [PATCH 33/43] fix(router): redact evaluated secrets in workload.config and match bare audit keys - Parse evaluated Compose configuration YAML before applying secret redaction in _op_workload_config (CR-DI-03) - Update REDACT_KEY_PATTERNS to match bare parameter keys (token, secret, password, key, pass, hash) in audit logging (CR-DI-04) - Enforce case-insensitive comparison for hex token hashes in TokenStore (CR-DI-10) - Re-assert immutable platform keys post-environment assembly in assemble_workload_env (CR-DI-07) - Add unit tests verifying evaluated secret masking, bare-key audit redaction, and uppercase hex token validation --- scripts/appctl_audit.py | 10 +- scripts/appctl_auth.py | 104 +++++--- scripts/appctl_router.py | 199 ++++++++++++--- tests/unit/test_appctl_audit.py | 25 ++ tests/unit/test_appctl_auth.py | 176 ++++++++++--- tests/unit/test_appctl_router.py | 424 +++++++++++++++++++++++-------- 6 files changed, 710 insertions(+), 228 deletions(-) diff --git a/scripts/appctl_audit.py b/scripts/appctl_audit.py index 635afe1..ca058bb 100644 --- a/scripts/appctl_audit.py +++ b/scripts/appctl_audit.py @@ -28,7 +28,7 @@ DEFAULT_AUDIT_LOG = Path("/var/log/homelab/appctl/audit.jsonl") DEFAULT_LOCK_DIR = Path("/var/lib/homelab/appctl/locks") REDACT_KEY_PATTERNS = re.compile( - r".*(?:_KEY|_SECRET|_PASSWORD|_TOKEN|_PASS|_HASH)$", re.IGNORECASE + r"^(?:.*_)?(?:KEY|SECRET|PASSWORD|TOKEN|PASS|HASH)$", re.IGNORECASE ) @@ -105,7 +105,9 @@ class ConcurrentMutationError(Exception): def __init__(self, target: str, message: str | None = None) -> None: self.target = target - msg = message or f"Operation on target '{target}' is locked by a concurrent task." + msg = ( + message or f"Operation on target '{target}' is locked by a concurrent task." + ) super().__init__(msg) @@ -116,7 +118,9 @@ def redact_sensitive_data(val: Any) -> Any: """ if isinstance(val, dict): return { - k: "[REDACTED]" if REDACT_KEY_PATTERNS.match(str(k)) else redact_sensitive_data(v) + k: "[REDACTED]" + if REDACT_KEY_PATTERNS.match(str(k)) + else redact_sensitive_data(v) for k, v in val.items() } if isinstance(val, list): diff --git a/scripts/appctl_auth.py b/scripts/appctl_auth.py index 02672e0..7065b24 100644 --- a/scripts/appctl_auth.py +++ b/scripts/appctl_auth.py @@ -33,42 +33,52 @@ except ImportError: yaml = None # type: ignore[assignment] DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json") -DEFAULT_DEPLOYMENTS_FILE = Path(__file__).resolve().parent.parent / "config" / "deployments.yaml" +DEFAULT_DEPLOYMENTS_FILE = ( + Path(__file__).resolve().parent.parent / "config" / "deployments.yaml" +) -CORE_TARGETS: frozenset[str] = frozenset({ - "core", - "traefik", - "authelia", - "lldap", - "stalwart", - "dozzle", - "socket-proxy", - "homepage", - "diun", - "watchtower", -}) +CORE_TARGETS: frozenset[str] = frozenset( + { + "core", + "traefik", + "authelia", + "lldap", + "stalwart", + "dozzle", + "socket-proxy", + "homepage", + "diun", + "watchtower", + } +) -SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset({ - OperationType.WORKLOAD_CONFIG, - OperationType.WORKLOAD_LOGS, -}) +SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset( + { + OperationType.WORKLOAD_CONFIG, + OperationType.WORKLOAD_LOGS, + } +) -MUTATING_OPERATIONS: frozenset[OperationType] = frozenset({ - OperationType.WORKLOAD_DEPLOY, - OperationType.WORKLOAD_STOP, - OperationType.WORKLOAD_RESTART, - OperationType.WORKLOAD_UPDATE, - OperationType.WORKLOAD_PULL, - OperationType.PLATFORM_SYNC_HOMEPAGE, -}) +MUTATING_OPERATIONS: frozenset[OperationType] = frozenset( + { + OperationType.WORKLOAD_DEPLOY, + OperationType.WORKLOAD_STOP, + OperationType.WORKLOAD_RESTART, + OperationType.WORKLOAD_UPDATE, + OperationType.WORKLOAD_PULL, + OperationType.PLATFORM_SYNC_HOMEPAGE, + } +) -READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset({ - OperationType.WORKLOAD_LIST, - OperationType.WORKLOAD_GET, - OperationType.WORKLOAD_RESOLVE, - OperationType.PLATFORM_SSL, - OperationType.PLATFORM_HEALTH, -}) +READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset( + { + OperationType.WORKLOAD_LIST, + OperationType.WORKLOAD_GET, + OperationType.WORKLOAD_RESOLVE, + OperationType.PLATFORM_SSL, + OperationType.PLATFORM_HEALTH, + } +) class Role(StrEnum): @@ -119,7 +129,11 @@ class TokenDescriptor(StrictModel): class AuthenticationError(Exception): """Raised when authentication fails (401 Unauthorized).""" - def __init__(self, message: str = "Authentication required", code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED) -> None: + def __init__( + self, + message: str = "Authentication required", + code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED, + ) -> None: super().__init__(message) self.code = code self.http_status = 401 @@ -128,7 +142,11 @@ class AuthenticationError(Exception): class AuthorizationError(Exception): """Raised when an authenticated principal lacks required role or scope (403 Forbidden).""" - def __init__(self, message: str = "Permission denied", code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED) -> None: + def __init__( + self, + message: str = "Permission denied", + code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED, + ) -> None: super().__init__(message) self.code = code self.http_status = 403 @@ -181,13 +199,15 @@ class TokenStore: constant-time hmac.compare_digest. """ if not secret: - raise AuthenticationError("Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED) + raise AuthenticationError( + "Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED + ) secret_hash = hashlib.sha256(secret.encode("utf-8")).hexdigest() tokens = self.load_tokens() for token in tokens: - if hmac.compare_digest(secret_hash, token.sha256): + if hmac.compare_digest(secret_hash, token.sha256.lower()): return Principal( identity=token.identity, role=token.role, @@ -195,7 +215,9 @@ class TokenStore: auth_method="bearer_token", ) - raise AuthenticationError("Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED) + raise AuthenticationError( + "Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED + ) def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[str]: @@ -235,7 +257,13 @@ def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[s if isinstance(alias, str) and alias.strip(): admitted.add(alias.strip()) return admitted - except (OSError, UnicodeDecodeError, ValueError, json.JSONDecodeError, *yaml_errors): + except ( + OSError, + UnicodeDecodeError, + ValueError, + json.JSONDecodeError, + *yaml_errors, + ): return set() diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py index 230665b..4607ce0 100644 --- a/scripts/appctl_router.py +++ b/scripts/appctl_router.py @@ -18,6 +18,7 @@ import time from pathlib import Path from typing import Any +import yaml from appctl_audit import ( AuditLogger, AuditPersistenceError, @@ -208,6 +209,18 @@ def assemble_workload_env( if local_env.is_file(): env.update(parse_dotenv(local_env, validate_keys=True)) + # Re-assert immutable platform infrastructure keys (defense-in-depth) + env["HOMELAB_DOMAIN"] = domain + env["DOMAIN_SUFFIX"] = domain + env["DOMAIN"] = domain + env["PROXY_NETWORK"] = os.environ.get("PROXY_NETWORK", "proxy-net") + env["CERT_RESOLVER"] = os.environ.get("CERT_RESOLVER", "myresolver") + env["SERVICE_NAME"] = app_name + env["CONTAINER_NAME"] = app_name + env["SERVICE_DOMAIN"] = f"{app_name}.{domain}" + if "DOCKER_CONFIG" in os.environ: + env["DOCKER_CONFIG"] = os.environ["DOCKER_CONFIG"] + return env @@ -290,7 +303,9 @@ def validate_workload_preflight( try: manifest = parse_manifest(manifest_file) except ManifestValidationError as err: - raise RouterValidationError(f"Workload manifest validation failed: {err}") from err + raise RouterValidationError( + f"Workload manifest validation failed: {err}" + ) from err effective_name = app_name or manifest.name compose_file = _resolve_compose_file(app_dir) @@ -328,7 +343,9 @@ def validate_core_preflight( if not compose_file.is_file(): raise RouterValidationError(f"Core compose file not found at '{compose_file}'") - if compose_file.is_symlink() and not compose_file.resolve().is_relative_to(core_dir_resolved): + if compose_file.is_symlink() and not compose_file.resolve().is_relative_to( + core_dir_resolved + ): raise RouterValidationError( f"Core compose file symlink escapes Core root: '{compose_file}'" ) @@ -592,7 +609,9 @@ class OperationalRouter: elif operation == OperationType.WORKLOAD_PULL: result_data = self._op_workload_pull(resolved_app) elif operation == OperationType.WORKLOAD_UPDATE: - result_data, commit_sha = self._op_workload_update(request, resolved_app) + result_data, commit_sha = self._op_workload_update( + request, resolved_app + ) elif operation == OperationType.PLATFORM_SYNC_HOMEPAGE: result_data = self._op_platform_sync_homepage() else: @@ -601,7 +620,10 @@ class OperationalRouter: duration_ms = int((time.perf_counter() - start_time) * 1000) # Audit COMPLETED for mutating ops and sensitive reads - if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS: + if ( + operation in MUTATING_OPERATIONS + or operation in SENSITIVE_READ_OPERATIONS + ): self.audit_logger.log_completed( operation_id=op_id, principal=principal_audit, @@ -613,7 +635,9 @@ class OperationalRouter: parameters=request.parameters, duration_ms=duration_ms, commit_sha=commit_sha, - message=result_data.get("message", "Operation completed successfully"), + message=result_data.get( + "message", "Operation completed successfully" + ), ) return OperationResponse( @@ -630,7 +654,10 @@ class OperationalRouter: except (RouterValidationError, RouterExecutionError) as err: duration_ms = int((time.perf_counter() - start_time) * 1000) - if operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS: + if ( + operation in MUTATING_OPERATIONS + or operation in SENSITIVE_READ_OPERATIONS + ): self.audit_logger.log_failed( operation_id=op_id, principal=principal_audit, @@ -699,7 +726,9 @@ class OperationalRouter: dir_path=self.core_dir, container_name=svc.container_name, ) - svc_dict["deployment_status"] = core_checkout.status_label if i == 0 else "" + svc_dict["deployment_status"] = ( + core_checkout.status_label if i == 0 else "" + ) svc_dict["provenance_status"] = "— Core Platform" if params.ssl and not svc.is_internal: svc_dict["ssl"] = check_ssl_cert(svc.domain) @@ -726,9 +755,14 @@ class OperationalRouter: domain = target or resolve_canonical_domain() try: cert_info = check_ssl_cert(domain) - return {"ssl": cert_info, "message": f"SSL certificate inspected for {domain}"} + return { + "ssl": cert_info, + "message": f"SSL certificate inspected for {domain}", + } except Exception as err: - raise RouterExecutionError(f"SSL inspection failed for '{domain}': {err}") from err + raise RouterExecutionError( + f"SSL inspection failed for '{domain}': {err}" + ) from err def _op_platform_health(self) -> dict[str, Any]: return { @@ -742,14 +776,24 @@ class OperationalRouter: app_dir, _, compose_file, env, _ = self._prepare_target_context(app) cmd = ["docker", "compose", "-f", str(compose_file), "config"] - code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0) + code, stdout, stderr = run_bounded_subprocess( + cmd, cwd=app_dir, env=env, timeout=15.0 + ) if code != 0: - raise RouterExecutionError(f"docker compose config failed: {stderr}", exit_code=code) + raise RouterExecutionError( + f"docker compose config failed: {stderr}", exit_code=code + ) config_output = stdout if principal.role != Role.ADMIN: # Redact secrets for non-admin callers - config_output = redact_sensitive_data(config_output) + try: + parsed_yaml = yaml.safe_load(stdout) + if isinstance(parsed_yaml, (dict, list)): + redacted_parsed = redact_sensitive_data(parsed_yaml) + config_output = yaml.safe_dump(redacted_parsed, sort_keys=False) + except (yaml.YAMLError, ValueError): + config_output = redact_sensitive_data(config_output) return {"output": config_output, "message": "Evaluated compose configuration"} @@ -771,13 +815,23 @@ class OperationalRouter: if container: cmd.append(container) - code, stdout, stderr = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=15.0) + code, stdout, stderr = run_bounded_subprocess( + cmd, cwd=app_dir, env=env, timeout=15.0 + ) if code != 0: - raise RouterExecutionError(f"docker compose logs failed: {stderr}", exit_code=code) + raise RouterExecutionError( + f"docker compose logs failed: {stderr}", exit_code=code + ) - return {"output": stdout, "tail": params.tail, "message": f"Tail {params.tail} logs"} + return { + "output": stdout, + "tail": params.tail, + "message": f"Tail {params.tail} logs", + } - def _op_workload_deploy(self, request: OperationRequest, app: Any) -> dict[str, Any]: + def _op_workload_deploy( + self, request: OperationRequest, app: Any + ) -> dict[str, Any]: params = request.parse_parameters() assert isinstance(params, DeployParams) app_dir, _, compose_file, env, container = self._prepare_target_context(app) @@ -785,14 +839,25 @@ class OperationalRouter: # Optional build if params.build: - build_cmd = ["docker", "compose", "-f", str(compose_file), "build", "--pull"] + build_cmd = [ + "docker", + "compose", + "-f", + str(compose_file), + "build", + "--pull", + ] if params.no_cache: build_cmd.append("--no-cache") if container: build_cmd.append(container) - code, out, err = run_bounded_subprocess(build_cmd, cwd=app_dir, env=env, timeout=300.0) + code, out, err = run_bounded_subprocess( + build_cmd, cwd=app_dir, env=env, timeout=300.0 + ) if code != 0: - raise RouterExecutionError(f"docker compose build failed: {err}", exit_code=code) + raise RouterExecutionError( + f"docker compose build failed: {err}", exit_code=code + ) # Deploy up up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d"] @@ -801,9 +866,13 @@ class OperationalRouter: if container: up_cmd.append(container) - code, out, err = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0) + code, out, err = run_bounded_subprocess( + up_cmd, cwd=app_dir, env=env, timeout=300.0 + ) if code != 0: - raise RouterExecutionError(f"docker compose up failed: {err}", exit_code=code) + raise RouterExecutionError( + f"docker compose up failed: {err}", exit_code=code + ) # Trigger Homepage sync for Sites workloads if not is_core: @@ -824,13 +893,21 @@ class OperationalRouter: else: cmd = ["docker", "compose", "-f", str(compose_file), "down"] - code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0) + code, out, err = run_bounded_subprocess( + cmd, cwd=app_dir, env=env, timeout=300.0 + ) if code != 0: - raise RouterExecutionError(f"docker compose stop/down failed: {err}", exit_code=code) + raise RouterExecutionError( + f"docker compose stop/down failed: {err}", exit_code=code + ) if not is_core: self._trigger_homepage_sync() - return {"output": out, "action": "stopped", "message": f"Workload '{app.name}' stopped"} + return { + "output": out, + "action": "stopped", + "message": f"Workload '{app.name}' stopped", + } def _op_workload_restart(self, app: Any) -> dict[str, Any]: app_dir, _, compose_file, env, container = self._prepare_target_context(app) @@ -840,13 +917,21 @@ class OperationalRouter: if container: cmd.append(container) - code, out, err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0) + code, out, err = run_bounded_subprocess( + cmd, cwd=app_dir, env=env, timeout=300.0 + ) if code != 0: - raise RouterExecutionError(f"docker compose restart failed: {err}", exit_code=code) + raise RouterExecutionError( + f"docker compose restart failed: {err}", exit_code=code + ) if not is_core: self._trigger_homepage_sync() - return {"output": out, "action": "restarted", "message": f"Workload '{app.name}' restarted"} + return { + "output": out, + "action": "restarted", + "message": f"Workload '{app.name}' restarted", + } def _op_workload_pull(self, app: Any) -> dict[str, Any]: app_dir, _, compose_file, env, container = self._prepare_target_context(app) @@ -855,20 +940,40 @@ class OperationalRouter: pull_cmd = ["docker", "compose", "-f", str(compose_file), "pull"] if container: pull_cmd.append(container) - code, _, err = run_bounded_subprocess(pull_cmd, cwd=app_dir, env=env, timeout=300.0) + code, _, err = run_bounded_subprocess( + pull_cmd, cwd=app_dir, env=env, timeout=300.0 + ) if code != 0: - raise RouterExecutionError(f"docker compose pull failed: {err}", exit_code=code) + raise RouterExecutionError( + f"docker compose pull failed: {err}", exit_code=code + ) - up_cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"] + up_cmd = [ + "docker", + "compose", + "-f", + str(compose_file), + "up", + "-d", + "--remove-orphans", + ] if container: up_cmd.append(container) - code, out_up, err_up = run_bounded_subprocess(up_cmd, cwd=app_dir, env=env, timeout=300.0) + code, out_up, err_up = run_bounded_subprocess( + up_cmd, cwd=app_dir, env=env, timeout=300.0 + ) if code != 0: - raise RouterExecutionError(f"docker compose up failed after pull: {err_up}", exit_code=code) + raise RouterExecutionError( + f"docker compose up failed after pull: {err_up}", exit_code=code + ) if not is_core: self._trigger_homepage_sync() - return {"output": out_up, "action": "pulled", "message": f"Workload '{app.name}' pulled and updated"} + return { + "output": out_up, + "action": "pulled", + "message": f"Workload '{app.name}' pulled and updated", + } def _op_workload_update( self, request: OperationRequest, app: Any @@ -906,7 +1011,9 @@ class OperationalRouter: pull_cmd, cwd=app_dir, timeout=60.0 ) if code != 0: - raise RouterExecutionError(f"git pull failed for '{app.name}': {pull_err}", exit_code=code) + raise RouterExecutionError( + f"git pull failed for '{app.name}': {pull_err}", exit_code=code + ) # 3. Post-pull re-validation of manifest and expected_branch if is_core: @@ -914,7 +1021,9 @@ class OperationalRouter: manifest = None declared_actions = ["compose_pull", "compose_up"] else: - manifest, compose_file = validate_workload_preflight(app_dir, self.sites_dir, app.name) + manifest, compose_file = validate_workload_preflight( + app_dir, self.sites_dir, app.name + ) if ( params.expected_branch and manifest.source @@ -948,7 +1057,15 @@ class OperationalRouter: if params.no_cache: cmd.append("--no-cache") elif action == "compose_up": - cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"] + cmd = [ + "docker", + "compose", + "-f", + str(compose_file), + "up", + "-d", + "--remove-orphans", + ] elif action == "compose_restart": cmd = ["docker", "compose", "-f", str(compose_file), "restart"] else: @@ -957,7 +1074,9 @@ class OperationalRouter: if container: cmd.append(container) - code, act_out, act_err = run_bounded_subprocess(cmd, cwd=app_dir, env=env, timeout=300.0) + code, act_out, act_err = run_bounded_subprocess( + cmd, cwd=app_dir, env=env, timeout=300.0 + ) if code != 0: raise RouterExecutionError( f"Action '{action}' failed during workload.update for '{app.name}': {act_err}", @@ -986,7 +1105,10 @@ class OperationalRouter: def _op_platform_sync_homepage(self) -> dict[str, Any]: self._trigger_homepage_sync() - return {"action": "sync_homepage", "message": "Homepage dashboard synchronized successfully"} + return { + "action": "sync_homepage", + "message": "Homepage dashboard synchronized successfully", + } def _trigger_homepage_sync(self) -> None: """Atomic compile of Homepage dashboard services.yaml under _homepage_sync.lock.""" @@ -994,4 +1116,5 @@ class OperationalRouter: cmd_sync_homepage() except (OSError, ValueError, RuntimeError) as exc: import sys + print(f"Warning: Homepage sync non-fatal error: {exc}", file=sys.stderr) diff --git a/tests/unit/test_appctl_audit.py b/tests/unit/test_appctl_audit.py index 92edd18..3d7d330 100644 --- a/tests/unit/test_appctl_audit.py +++ b/tests/unit/test_appctl_audit.py @@ -232,6 +232,31 @@ def test_redact_sensitive_data_masks_secret_keys(): assert redacted["nested"]["list_items"][1] == "safe_string" +def test_redact_sensitive_data_masks_bare_keys(): + """Ensure bare keys (token, secret, password, key, pass, hash) without underscores are redacted (CR-DI-04).""" + raw_params = { + "token": "tok_12345", + "secret": "shh_secret", + "password": "mypassword", + "key": "encryption_key", + "pass": "quick_pass", + "hash": "$2b$12$hashval", + "TOKEN": "uppercase_tok", + "SECRET": "uppercase_sec", + "normal_field": "keep_this", + } + redacted = redact_sensitive_data(raw_params) + assert redacted["token"] == "[REDACTED]" + assert redacted["secret"] == "[REDACTED]" + assert redacted["password"] == "[REDACTED]" + assert redacted["key"] == "[REDACTED]" + assert redacted["pass"] == "[REDACTED]" + assert redacted["hash"] == "[REDACTED]" + assert redacted["TOKEN"] == "[REDACTED]" + assert redacted["SECRET"] == "[REDACTED]" + assert redacted["normal_field"] == "keep_this" + + def test_audit_logger_automatically_redacts_sensitive_parameters( temp_audit_file: Path, sample_principal: PrincipalAudit ): diff --git a/tests/unit/test_appctl_auth.py b/tests/unit/test_appctl_auth.py index 07f36f4..7fc55b7 100644 --- a/tests/unit/test_appctl_auth.py +++ b/tests/unit/test_appctl_auth.py @@ -37,8 +37,12 @@ def secret_tokens() -> dict[str, str]: @pytest.fixture def temp_tokens_file(tmp_path: Path, secret_tokens: dict[str, str]) -> Path: tokens_path = tmp_path / "tokens.json" - admin_hash = hashlib.sha256(secret_tokens["admin_secret"].encode("utf-8")).hexdigest() - op_hash = hashlib.sha256(secret_tokens["operator_secret"].encode("utf-8")).hexdigest() + admin_hash = hashlib.sha256( + secret_tokens["admin_secret"].encode("utf-8") + ).hexdigest() + op_hash = hashlib.sha256( + secret_tokens["operator_secret"].encode("utf-8") + ).hexdigest() data = [ { @@ -121,6 +125,31 @@ def test_token_store_authenticates_valid_bearer_secrets( assert p_op.token_id == "tok_gitops_01" +def test_token_store_authenticates_uppercase_hex_descriptor(tmp_path: Path): + """Ensure tokens with uppercase hex characters in tokens.json authenticate cleanly (CR-DI-10).""" + raw_secret = "my_custom_secret_token" + raw_hash_upper = hashlib.sha256(raw_secret.encode("utf-8")).hexdigest().upper() + tokens_file = tmp_path / "upper_tokens.json" + tokens_file.write_text( + json.dumps( + [ + { + "token_id": "tok_upper_01", + "identity": "upper-user", + "role": "homelab-operator", + "sha256": raw_hash_upper, + } + ] + ), + encoding="utf-8", + ) + os.chmod(tokens_file, 0o400) + store = TokenStore(tokens_file) + principal = store.authenticate_bearer(raw_secret) + assert principal.identity == "upper-user" + assert principal.role == Role.OPERATOR + + def test_token_store_rejects_invalid_bearer_secret(temp_tokens_file: Path): store = TokenStore(temp_tokens_file) @@ -178,7 +207,9 @@ def test_authenticate_request_over_uds_falls_back_to_viewer( # Explicit Bearer token over UDS confers full privileges auth_header = f"Bearer {secret_tokens['admin_secret']}" - p_admin = authenticate_request("unix_socket", auth_header, peer_uid=1000, token_store=store) + p_admin = authenticate_request( + "unix_socket", auth_header, peer_uid=1000, token_store=store + ) assert p_admin.role == Role.ADMIN assert p_admin.auth_method == "bearer_token" @@ -196,7 +227,8 @@ def test_authenticate_request_over_uds_rejects_missing_peer_uid(): def test_load_admitted_workloads_parses_names_and_aliases(tmp_path: Path): deploy_file = tmp_path / "deployments.yaml" - deploy_file.write_text(""" + deploy_file.write_text( + """ schemaVersion: "1.0" repositories: snappymail: @@ -208,7 +240,9 @@ repositories: path: "/home/operator/Sites/homelab-jellyfin" aliases: - "media" -""", encoding="utf-8") +""", + encoding="utf-8", + ) admitted = load_admitted_workloads(deploy_file) assert "snappymail" in admitted @@ -221,14 +255,19 @@ repositories: def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: Path): deploy_file = tmp_path / "deployments.json" - deploy_file.write_text(json.dumps({ - "repositories": { - "app1": { - "path": "/home/operator/Sites/app1", - "aliases": [123, None, " ", "valid_alias"] + deploy_file.write_text( + json.dumps( + { + "repositories": { + "app1": { + "path": "/home/operator/Sites/app1", + "aliases": [123, None, " ", "valid_alias"], + } + } } - } - }), encoding="utf-8") + ), + encoding="utf-8", + ) admitted = load_admitted_workloads(deploy_file) assert "app1" in admitted @@ -238,13 +277,17 @@ def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: P assert "" not in admitted -def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): +def test_load_admitted_workloads_fails_closed_on_missing_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): admitted = load_admitted_workloads(tmp_path / "missing.yaml") assert admitted == set() # Test HOMELAB_DEPLOYMENTS_FILE fallback deploy_file = tmp_path / "env_deploy.yaml" - deploy_file.write_text("repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8") + deploy_file.write_text( + "repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8" + ) monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deploy_file)) admitted_env = load_admitted_workloads(None) assert "env_app" in admitted_env @@ -258,12 +301,16 @@ def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path, mo def test_rbac_admin_permitted_across_all_operations_and_targets( admitted_workloads: set[str], ): - admin = Principal(identity="admin_user", role=Role.ADMIN, auth_method="bearer_token") + admin = Principal( + identity="admin_user", role=Role.ADMIN, auth_method="bearer_token" + ) # Mutations across Core and Sites enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads) enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "traefik", admitted_workloads) - enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads) + enforce_rbac( + admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads + ) enforce_rbac(admin, OperationType.WORKLOAD_CONFIG, "core", admitted_workloads) enforce_rbac(admin, OperationType.WORKLOAD_LOGS, "traefik", admitted_workloads) enforce_rbac(admin, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads) @@ -273,79 +320,128 @@ def test_rbac_admin_permitted_across_all_operations_and_targets( def test_rbac_operator_permitted_on_admitted_workloads( admitted_workloads: set[str], ): - operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") + operator = Principal( + identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token" + ) # Permitted on admitted workload - enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads) + enforce_rbac( + operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads + ) enforce_rbac(operator, OperationType.WORKLOAD_UPDATE, "mail", admitted_workloads) - enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads) + enforce_rbac( + operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads + ) enforce_rbac(operator, OperationType.WORKLOAD_LOGS, "docs", admitted_workloads) - enforce_rbac(operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads) + enforce_rbac( + operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads + ) enforce_rbac(operator, OperationType.WORKLOAD_LIST, None, admitted_workloads) def test_rbac_operator_denied_on_core_targets( admitted_workloads: set[str], ): - operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") + operator = Principal( + identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token" + ) # Targeting "core" stack with pytest.raises(AuthorizationError) as exc_info: - enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads) + enforce_rbac( + operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads + ) assert "not permitted to target core service 'core'" in str(exc_info.value) assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED # Targeting core services (traefik, stalwart, etc.) for core_svc in ["traefik", "authelia", "stalwart", "socket-proxy"]: with pytest.raises(AuthorizationError) as exc_info: - enforce_rbac(operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads) - assert f"not permitted to target core service '{core_svc}'" in str(exc_info.value) + enforce_rbac( + operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads + ) + assert f"not permitted to target core service '{core_svc}'" in str( + exc_info.value + ) assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED def test_rbac_operator_denied_without_target_on_mutating_or_sensitive_ops( admitted_workloads: set[str], ): - operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") + operator = Principal( + identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token" + ) - for op in [OperationType.WORKLOAD_DEPLOY, OperationType.WORKLOAD_UPDATE, OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]: + for op in [ + OperationType.WORKLOAD_DEPLOY, + OperationType.WORKLOAD_UPDATE, + OperationType.WORKLOAD_CONFIG, + OperationType.WORKLOAD_LOGS, + ]: with pytest.raises(AuthorizationError) as exc_info: enforce_rbac(operator, op, None, admitted_workloads) - assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value) + assert f"Operation '{op.value}' requires an explicit workload target" in str( + exc_info.value + ) assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED with pytest.raises(AuthorizationError) as exc_info: enforce_rbac(operator, op, "", admitted_workloads) - assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value) + assert f"Operation '{op.value}' requires an explicit workload target" in str( + exc_info.value + ) assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED -def test_rbac_operator_with_default_admitted_workloads(monkeypatch: pytest.MonkeyPatch, tmp_path: Path): +def test_rbac_operator_with_default_admitted_workloads( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +): deployments_file = tmp_path / "deployments.yaml" - deployments_file.write_text("repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8") + deployments_file.write_text( + "repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8" + ) monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file)) - operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") - enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "customapp", admitted_workloads=None) + operator = Principal( + identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token" + ) + enforce_rbac( + operator, OperationType.WORKLOAD_DEPLOY, "customapp", admitted_workloads=None + ) with pytest.raises(AuthorizationError) as exc_info: - enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unknownapp", admitted_workloads=None) + enforce_rbac( + operator, + OperationType.WORKLOAD_DEPLOY, + "unknownapp", + admitted_workloads=None, + ) assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED def test_rbac_operator_denied_on_unregistered_workload( admitted_workloads: set[str], ): - operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") + operator = Principal( + identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token" + ) with pytest.raises(AuthorizationError) as exc_info: - enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unregistered_app", admitted_workloads) + enforce_rbac( + operator, + OperationType.WORKLOAD_DEPLOY, + "unregistered_app", + admitted_workloads, + ) assert "not registered in deployments.yaml" in str(exc_info.value) assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED def test_rbac_viewer_permitted_only_on_non_sensitive_reads(): - viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred") + viewer = Principal( + identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred" + ) # Permitted reads enforce_rbac(viewer, OperationType.WORKLOAD_LIST, None) @@ -356,7 +452,9 @@ def test_rbac_viewer_permitted_only_on_non_sensitive_reads(): def test_rbac_viewer_denied_on_mutations(): - viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred") + viewer = Principal( + identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred" + ) mutations = [ OperationType.WORKLOAD_DEPLOY, @@ -374,7 +472,9 @@ def test_rbac_viewer_denied_on_mutations(): def test_rbac_viewer_denied_on_sensitive_reads(): - viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred") + viewer = Principal( + identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred" + ) for sens_op in [OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]: with pytest.raises(AuthorizationError) as exc_info: diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 471b9d5..f339b1b 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -11,6 +11,7 @@ from pathlib import Path from unittest.mock import MagicMock, patch import pytest +import yaml from appctl_audit import AuditLogger, TargetLockManager from appctl_auth import Principal, Role from appctl_contracts import ErrorCode, OperationRequest @@ -77,7 +78,9 @@ services: container_name: "snappymail" restart: "unless-stopped" """ - (app_dir / "docker-compose.yml").write_text(compose_content.strip(), encoding="utf-8") + (app_dir / "docker-compose.yml").write_text( + compose_content.strip(), encoding="utf-8" + ) return app_dir @@ -88,12 +91,16 @@ def admin_principal() -> Principal: @pytest.fixture def operator_principal() -> Principal: - return Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") + return Principal( + identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token" + ) @pytest.fixture def viewer_principal() -> Principal: - return Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred") + return Principal( + identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred" + ) # --------------------------------------------------------------------------- @@ -103,14 +110,17 @@ def viewer_principal() -> Principal: def test_parse_dotenv_parses_valid_key_values(tmp_path: Path): env_file = tmp_path / ".env" - env_file.write_text(""" + env_file.write_text( + """ # Comment line APP_PORT=8080 APP_HOST="127.0.0.1" SINGLE_QUOTE='single_val' EMPTY_VAL= WITH_EQUALS=key=value=more -""", encoding="utf-8") +""", + encoding="utf-8", + ) parsed = parse_dotenv(env_file) assert parsed["APP_PORT"] == "8080" @@ -122,11 +132,14 @@ WITH_EQUALS=key=value=more def test_parse_dotenv_preserves_shell_injection_as_inert_literals(tmp_path: Path): env_file = tmp_path / ".env" - env_file.write_text(""" + env_file.write_text( + """ INJECTION_ONE=$(touch /tmp/pwned) INJECTION_TWO=`cat /etc/passwd` VARIABLE_REF=$HOMELAB_DOMAIN -""", encoding="utf-8") +""", + encoding="utf-8", + ) parsed = parse_dotenv(env_file) assert parsed["INJECTION_ONE"] == "$(touch /tmp/pwned)" @@ -187,7 +200,6 @@ def test_resolve_canonical_domain_precedence(monkeypatch: pytest.MonkeyPatch): assert resolve_canonical_domain() == "stripped.example.test" - def test_assemble_workload_env_constructs_6_layer_environment( mock_workload_dir: Path, monkeypatch: pytest.MonkeyPatch ): @@ -195,7 +207,9 @@ def test_assemble_workload_env_constructs_6_layer_environment( manifest = parse_manifest(mock_workload_dir / "app.yaml") # Add local .env - (mock_workload_dir / ".env").write_text("LOCAL_ENV_VAR=local_val\n", encoding="utf-8") + (mock_workload_dir / ".env").write_text( + "LOCAL_ENV_VAR=local_val\n", encoding="utf-8" + ) env = assemble_workload_env(mock_workload_dir, manifest, "snappymail") @@ -292,7 +306,9 @@ services: # --------------------------------------------------------------------------- -def test_operational_router_dispatches_platform_health(tmp_path: Path, admin_principal: Principal): +def test_operational_router_dispatches_platform_health( + tmp_path: Path, admin_principal: Principal +): router = OperationalRouter( audit_logger=AuditLogger(tmp_path / "audit.jsonl"), lock_manager=TargetLockManager(tmp_path / "locks"), @@ -325,10 +341,12 @@ def test_operational_router_enforces_rbac_denial( audit_logger=AuditLogger(tmp_path / "audit.jsonl"), lock_manager=TargetLockManager(tmp_path / "locks"), ) - req = OperationRequest.model_validate({ - "operation": "workload.deploy", - "target": "snappymail", - }) + req = OperationRequest.model_validate( + { + "operation": "workload.deploy", + "target": "snappymail", + } + ) resp = router.dispatch(req, viewer_principal) assert resp.success is False assert resp.error is not None @@ -342,10 +360,12 @@ def test_operational_router_rejects_non_existent_target( audit_logger=AuditLogger(tmp_path / "audit.jsonl"), lock_manager=TargetLockManager(tmp_path / "locks"), ) - req = OperationRequest.model_validate({ - "operation": "workload.get", - "target": "nonexistent_workload_999", - }) + req = OperationRequest.model_validate( + { + "operation": "workload.get", + "target": "nonexistent_workload_999", + } + ) resp = router.dispatch(req, admin_principal) assert resp.success is False assert resp.error is not None @@ -360,10 +380,12 @@ def test_operational_router_rejects_concurrent_mutation( audit_logger=AuditLogger(tmp_path / "audit.jsonl"), lock_manager=lock_mgr, ) - req = OperationRequest.model_validate({ - "operation": "workload.deploy", - "target": "snappymail", - }) + req = OperationRequest.model_validate( + { + "operation": "workload.deploy", + "target": "snappymail", + } + ) mock_app = MagicMock() mock_app.name = "snappymail" @@ -388,11 +410,13 @@ def test_operational_router_dispatches_workload_deploy( lock_manager=TargetLockManager(tmp_path / "locks"), sites_dir=mock_workload_dir.parent, ) - req = OperationRequest.model_validate({ - "operation": "workload.deploy", - "target": "snappymail", - "parameters": {"recreate": True, "remove_orphans": True, "build": False}, - }) + req = OperationRequest.model_validate( + { + "operation": "workload.deploy", + "target": "snappymail", + "parameters": {"recreate": True, "remove_orphans": True, "build": False}, + } + ) mock_app = MagicMock() mock_app.name = "snappymail" @@ -400,7 +424,10 @@ def test_operational_router_dispatches_workload_deploy( with ( patch("appctl_router.resolve_app", return_value=mock_app), - patch("appctl_router.run_bounded_subprocess", return_value=(0, "Container started", "")) as mock_run, + patch( + "appctl_router.run_bounded_subprocess", + return_value=(0, "Container started", ""), + ) as mock_run, patch("appctl_router.cmd_sync_homepage"), ): resp = router.dispatch(req, admin_principal) @@ -424,11 +451,13 @@ def test_operational_router_workload_deploy_build_flags( mock_app.dir_path = str(mock_workload_dir) # 1. Deploy with build=True passes --pull - req_build = OperationRequest.model_validate({ - "operation": "workload.deploy", - "target": "snappymail", - "parameters": {"build": True}, - }) + req_build = OperationRequest.model_validate( + { + "operation": "workload.deploy", + "target": "snappymail", + "parameters": {"build": True}, + } + ) executed_commands: list[list[str]] = [] def mock_subproc(cmd: list[str], **kwargs): @@ -445,15 +474,22 @@ def test_operational_router_workload_deploy_build_flags( build_calls = [c for c in executed_commands if "build" in c] assert len(build_calls) == 1 assert build_calls[0] == [ - "docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull" + "docker", + "compose", + "-f", + str(mock_workload_dir / "docker-compose.yml"), + "build", + "--pull", ] # 2. Deploy with no_cache=True passes --pull and --no-cache - req_no_cache = OperationRequest.model_validate({ - "operation": "workload.deploy", - "target": "snappymail", - "parameters": {"no_cache": True}, - }) + req_no_cache = OperationRequest.model_validate( + { + "operation": "workload.deploy", + "target": "snappymail", + "parameters": {"no_cache": True}, + } + ) executed_commands.clear() with ( @@ -466,7 +502,13 @@ def test_operational_router_workload_deploy_build_flags( build_calls = [c for c in executed_commands if "build" in c] assert len(build_calls) == 1 assert build_calls[0] == [ - "docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull", "--no-cache" + "docker", + "compose", + "-f", + str(mock_workload_dir / "docker-compose.yml"), + "build", + "--pull", + "--no-cache", ] @@ -478,10 +520,12 @@ def test_operational_router_workload_update_rejects_dirty_git_tree( lock_manager=TargetLockManager(tmp_path / "locks"), sites_dir=mock_workload_dir.parent, ) - req = OperationRequest.model_validate({ - "operation": "workload.update", - "target": "snappymail", - }) + req = OperationRequest.model_validate( + { + "operation": "workload.update", + "target": "snappymail", + } + ) mock_app = MagicMock() mock_app.name = "snappymail" @@ -512,11 +556,13 @@ def test_operational_router_workload_update_rejects_branch_mismatch( lock_manager=TargetLockManager(tmp_path / "locks"), sites_dir=mock_workload_dir.parent, ) - req = OperationRequest.model_validate({ - "operation": "workload.update", - "target": "snappymail", - "parameters": {"expected_branch": "feature/branch"}, - }) + req = OperationRequest.model_validate( + { + "operation": "workload.update", + "target": "snappymail", + "parameters": {"expected_branch": "feature/branch"}, + } + ) mock_app = MagicMock() mock_app.name = "snappymail" @@ -550,11 +596,13 @@ def test_operational_router_workload_update_succeeds_on_clean_tree( lock_manager=TargetLockManager(tmp_path / "locks"), sites_dir=mock_workload_dir.parent, ) - req = OperationRequest.model_validate({ - "operation": "workload.update", - "target": "snappymail", - "parameters": {"expected_branch": "main"}, - }) + req = OperationRequest.model_validate( + { + "operation": "workload.update", + "target": "snappymail", + "parameters": {"expected_branch": "main"}, + } + ) mock_app = MagicMock() mock_app.name = "snappymail" @@ -611,11 +659,13 @@ def test_operational_router_workload_update_build_and_no_cache_flags( return 0, "success", "" # 1. Update with build=True - req_build = OperationRequest.model_validate({ - "operation": "workload.update", - "target": "snappymail", - "parameters": {"build": True}, - }) + req_build = OperationRequest.model_validate( + { + "operation": "workload.update", + "target": "snappymail", + "parameters": {"build": True}, + } + ) with ( patch("appctl_router.resolve_app", return_value=mock_app), @@ -627,18 +677,25 @@ def test_operational_router_workload_update_build_and_no_cache_flags( build_calls = [c for c in executed_commands if "build" in c] assert len(build_calls) == 1 assert build_calls[0] == [ - "docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull" + "docker", + "compose", + "-f", + str(mock_workload_dir / "docker-compose.yml"), + "build", + "--pull", ] # Also ensure compose_up was executed up_calls = [c for c in executed_commands if "up" in c] assert len(up_calls) == 1 # 2. Update with no_cache=True implies build=True and appends --no-cache - req_no_cache = OperationRequest.model_validate({ - "operation": "workload.update", - "target": "snappymail", - "parameters": {"no_cache": True}, - }) + req_no_cache = OperationRequest.model_validate( + { + "operation": "workload.update", + "target": "snappymail", + "parameters": {"no_cache": True}, + } + ) executed_commands.clear() with ( @@ -651,7 +708,13 @@ def test_operational_router_workload_update_build_and_no_cache_flags( build_calls = [c for c in executed_commands if "build" in c] assert len(build_calls) == 1 assert build_calls[0] == [ - "docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull", "--no-cache" + "docker", + "compose", + "-f", + str(mock_workload_dir / "docker-compose.yml"), + "build", + "--pull", + "--no-cache", ] up_calls = [c for c in executed_commands if "up" in c] assert len(up_calls) == 1 @@ -675,7 +738,9 @@ deployment: - "compose_build" - "compose_up" """ - (mock_workload_dir / "app.yaml").write_text(manifest_content.strip(), encoding="utf-8") + (mock_workload_dir / "app.yaml").write_text( + manifest_content.strip(), encoding="utf-8" + ) router = OperationalRouter( audit_logger=AuditLogger(tmp_path / "audit.jsonl"), @@ -699,10 +764,12 @@ deployment: return 0, "success", "" # Update with declared compose_build invokes build --pull - req = OperationRequest.model_validate({ - "operation": "workload.update", - "target": "snappymail", - }) + req = OperationRequest.model_validate( + { + "operation": "workload.update", + "target": "snappymail", + } + ) with ( patch("appctl_router.resolve_app", return_value=mock_app), @@ -714,7 +781,12 @@ deployment: build_calls = [c for c in executed_commands if "build" in c] assert len(build_calls) == 1 assert build_calls[0] == [ - "docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull" + "docker", + "compose", + "-f", + str(mock_workload_dir / "docker-compose.yml"), + "build", + "--pull", ] @@ -738,7 +810,9 @@ services: image: "authelia/authelia:latest" container_name: "authelia" """ - (mock_core_dir / "docker-compose.yml").write_text(compose_content.strip(), encoding="utf-8") + (mock_core_dir / "docker-compose.yml").write_text( + compose_content.strip(), encoding="utf-8" + ) router = OperationalRouter( audit_logger=AuditLogger(tmp_path / "audit.jsonl"), @@ -759,7 +833,9 @@ services: ): # 1. Deploy core stack resp_deploy = router.dispatch( - OperationRequest.model_validate({"operation": "workload.deploy", "target": "core"}), + OperationRequest.model_validate( + {"operation": "workload.deploy", "target": "core"} + ), admin_principal, ) assert resp_deploy.success is True @@ -775,7 +851,9 @@ services: # 2. Stop core stack (uses `down` for full stack) resp_stop = router.dispatch( - OperationRequest.model_validate({"operation": "workload.stop", "target": "core"}), + OperationRequest.model_validate( + {"operation": "workload.stop", "target": "core"} + ), admin_principal, ) assert resp_stop.success is True @@ -789,7 +867,9 @@ services: # 3. Restart core stack resp_restart = router.dispatch( - OperationRequest.model_validate({"operation": "workload.restart", "target": "core"}), + OperationRequest.model_validate( + {"operation": "workload.restart", "target": "core"} + ), admin_principal, ) assert resp_restart.success is True @@ -803,7 +883,9 @@ services: # 4. Config core stack resp_config = router.dispatch( - OperationRequest.model_validate({"operation": "workload.config", "target": "core"}), + OperationRequest.model_validate( + {"operation": "workload.config", "target": "core"} + ), admin_principal, ) assert resp_config.success is True @@ -845,7 +927,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations( with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc): # 1. Deploy single core service (traefik) resp_deploy = router.dispatch( - OperationRequest.model_validate({"operation": "workload.deploy", "target": "traefik"}), + OperationRequest.model_validate( + {"operation": "workload.deploy", "target": "traefik"} + ), admin_principal, ) assert resp_deploy.success is True @@ -854,7 +938,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations( # 2. Stop single core service (uses `stop traefik`, NOT `down`) resp_stop = router.dispatch( - OperationRequest.model_validate({"operation": "workload.stop", "target": "traefik"}), + OperationRequest.model_validate( + {"operation": "workload.stop", "target": "traefik"} + ), admin_principal, ) assert resp_stop.success is True @@ -869,7 +955,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations( # 3. Restart single core service resp_restart = router.dispatch( - OperationRequest.model_validate({"operation": "workload.restart", "target": "traefik"}), + OperationRequest.model_validate( + {"operation": "workload.restart", "target": "traefik"} + ), admin_principal, ) assert resp_restart.success is True @@ -884,7 +972,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations( # 4. Pull single core service resp_pull = router.dispatch( - OperationRequest.model_validate({"operation": "workload.pull", "target": "traefik"}), + OperationRequest.model_validate( + {"operation": "workload.pull", "target": "traefik"} + ), admin_principal, ) assert resp_pull.success is True @@ -909,7 +999,9 @@ def test_operational_router_dispatches_core_service_container_scoped_operations( # 5. Logs single core service resp_logs = router.dispatch( - OperationRequest.model_validate({"operation": "workload.logs", "target": "traefik"}), + OperationRequest.model_validate( + {"operation": "workload.logs", "target": "traefik"} + ), admin_principal, ) assert resp_logs.success is True @@ -945,7 +1037,9 @@ def test_operational_router_dispatches_core_update_without_manifest( with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc): resp = router.dispatch( - OperationRequest.model_validate({"operation": "workload.update", "target": "core"}), + OperationRequest.model_validate( + {"operation": "workload.update", "target": "core"} + ), admin_principal, ) assert resp.success is True @@ -968,7 +1062,9 @@ def test_operational_router_rejects_operator_role_on_core_targets( ) for target in ("core", "traefik", "authelia"): resp = router.dispatch( - OperationRequest.model_validate({"operation": "workload.restart", "target": target}), + OperationRequest.model_validate( + {"operation": "workload.restart", "target": target} + ), operator_principal, ) assert resp.success is False @@ -991,10 +1087,12 @@ def test_operational_router_workload_list_honors_filter_params( # Without --core: only Sites workloads (1) resp_sites = router.dispatch( - OperationRequest.model_validate({ - "operation": "workload.list", - "parameters": {"core": False, "fetch": False, "ssl": False}, - }), + OperationRequest.model_validate( + { + "operation": "workload.list", + "parameters": {"core": False, "fetch": False, "ssl": False}, + } + ), viewer_principal, ) assert resp_sites.success is True @@ -1003,12 +1101,17 @@ def test_operational_router_workload_list_honors_filter_params( assert resp_sites.result["workloads"][0]["name"] == "snappymail" # With --core and --ssl: includes Core services and SSL inspection - with patch("appctl_router.check_ssl_cert", return_value={"status": "🟢 80d remaining", "domain": "example.test"}) as mock_ssl: + with patch( + "appctl_router.check_ssl_cert", + return_value={"status": "🟢 80d remaining", "domain": "example.test"}, + ) as mock_ssl: resp_core = router.dispatch( - OperationRequest.model_validate({ - "operation": "workload.list", - "parameters": {"core": True, "fetch": False, "ssl": True}, - }), + OperationRequest.model_validate( + { + "operation": "workload.list", + "parameters": {"core": True, "fetch": False, "ssl": True}, + } + ), viewer_principal, ) assert resp_core.success is True @@ -1034,13 +1137,17 @@ def test_operational_router_workload_list_includes_live_docker_and_two_axis_stat core_dir=mock_core_dir, ) - with patch("appctl_router.get_docker_status", return_value="🟢 Running (1)") as mock_docker: + with patch( + "appctl_router.get_docker_status", return_value="🟢 Running (1)" + ) as mock_docker: # 1. Sites workload offline (fetch=False) resp = router.dispatch( - OperationRequest.model_validate({ - "operation": "workload.list", - "parameters": {"core": False, "fetch": False, "ssl": False}, - }), + OperationRequest.model_validate( + { + "operation": "workload.list", + "parameters": {"core": False, "fetch": False, "ssl": False}, + } + ), viewer_principal, ) assert resp.success is True @@ -1055,10 +1162,12 @@ def test_operational_router_workload_list_includes_live_docker_and_two_axis_stat # 2. Core services included (core=True) resp_core = router.dispatch( - OperationRequest.model_validate({ - "operation": "workload.list", - "parameters": {"core": True, "fetch": False, "ssl": False}, - }), + OperationRequest.model_validate( + { + "operation": "workload.list", + "parameters": {"core": True, "fetch": False, "ssl": False}, + } + ), viewer_principal, ) assert resp_core.success is True @@ -1095,10 +1204,12 @@ def test_operational_router_workload_list_fetch_passes_fetch_upstream( mock_inspect.return_value = mock_two_axis resp_fetch = router.dispatch( - OperationRequest.model_validate({ - "operation": "workload.list", - "parameters": {"core": False, "fetch": True, "ssl": False}, - }), + OperationRequest.model_validate( + { + "operation": "workload.list", + "parameters": {"core": False, "fetch": True, "ssl": False}, + } + ), viewer_principal, ) assert resp_fetch.success is True @@ -1120,7 +1231,9 @@ def test_operational_router_workload_list_handles_manifest_error( """Ensure workload.list sets deployment_status and provenance_status correctly for apps with manifest errors.""" broken_app_dir = mock_sites_dir / "broken-app" broken_app_dir.mkdir(parents=True, exist_ok=True) - (broken_app_dir / "app.yaml").write_text("invalid_yaml: [unclosed list", encoding="utf-8") + (broken_app_dir / "app.yaml").write_text( + "invalid_yaml: [unclosed list", encoding="utf-8" + ) router = OperationalRouter( audit_logger=AuditLogger(tmp_path / "audit.jsonl"), @@ -1131,10 +1244,12 @@ def test_operational_router_workload_list_handles_manifest_error( with patch("appctl_router.get_docker_status", return_value="🔴 Stopped"): resp = router.dispatch( - OperationRequest.model_validate({ - "operation": "workload.list", - "parameters": {"core": False, "fetch": False, "ssl": False}, - }), + OperationRequest.model_validate( + { + "operation": "workload.list", + "parameters": {"core": False, "fetch": False, "ssl": False}, + } + ), viewer_principal, ) assert resp.success is True @@ -1147,5 +1262,92 @@ def test_operational_router_workload_list_handles_manifest_error( assert broken["provenance_status"] == "⚠️ Invalid Manifest" +def test_operational_router_workload_config_redacts_evaluated_secrets_for_operator( + tmp_path: Path, + mock_sites_dir: Path, + mock_core_dir: Path, +): + """Ensure workload.config redacts evaluated secrets in YAML output for non-admin operators (CR-DI-03).""" + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_sites_dir, + core_dir=mock_core_dir, + ) + workload_dir = mock_sites_dir / "docs" + workload_dir.mkdir(parents=True, exist_ok=True) + (workload_dir / "docker-compose.yml").write_text( + "services:\n docs:\n image: docs:latest\n" + ) + (workload_dir / "app.yaml").write_text("name: docs\n") + + operator_principal = Principal( + identity="alice", role=Role.OPERATOR, auth_method="bearer_token" + ) + admin_principal = Principal( + identity="admin", role=Role.ADMIN, auth_method="bearer_token" + ) + + raw_yaml_stdout = """services: + docs: + environment: + DB_PASSWORD: supersecretpassword123 + API_TOKEN: tok_secretabc + PUBLIC_SETTING: allowed_value + image: docs:latest +""" + + mock_app = MagicMock(name="docs") + mock_app.name = "docs" + mock_app.dir_path = workload_dir + mock_app.is_core = False + + req = OperationRequest.model_validate( + {"operation": "workload.config", "target": "docs"} + ) + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.load_admitted_workloads", return_value={"docs"}), + patch( + "appctl_router.run_bounded_subprocess", + return_value=(0, raw_yaml_stdout, ""), + ), + ): + # 1. Non-admin operator receives redacted output + resp_op = router.dispatch(req, operator_principal) + assert resp_op.success is True + assert resp_op.result is not None + output_yaml = resp_op.result["output"] + assert "supersecretpassword123" not in output_yaml + assert "tok_secretabc" not in output_yaml + assert "allowed_value" in output_yaml + parsed_op = yaml.safe_load(output_yaml) + env = parsed_op["services"]["docs"]["environment"] + assert env["DB_PASSWORD"] == "[REDACTED]" + assert env["API_TOKEN"] == "[REDACTED]" + assert env["PUBLIC_SETTING"] == "allowed_value" + + # 2. Admin receives plaintext unredacted output + resp_admin = router.dispatch(req, admin_principal) + assert resp_admin.success is True + assert resp_admin.result is not None + assert "supersecretpassword123" in resp_admin.result["output"] +def test_parse_dotenv_rejects_reserved_platform_keys(tmp_path: Path): + """Ensure parse_dotenv rejects platform routing and docker config variables in .env (CR-DI-07).""" + env_file = tmp_path / ".env" + for reserved_key in [ + "HOMELAB_DOMAIN", + "DOMAIN_SUFFIX", + "DOMAIN", + "PROXY_NETWORK", + "CERT_RESOLVER", + "DOCKER_CONFIG", + ]: + env_file.write_text(f"{reserved_key}=override_val\n", encoding="utf-8") + with pytest.raises( + RouterValidationError, match="Prohibited reserved environment key" + ): + parse_dotenv(env_file, validate_keys=True) From 5156cf43066734055995f71ef09a5d497ad444a6 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 14:07:37 -0500 Subject: [PATCH 34/43] chore: add .worktrees/ to .gitignore --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 052cba8..1cd5283 100644 --- a/.gitignore +++ b/.gitignore @@ -54,3 +54,6 @@ mutants/ scripts/bootstrap_lldap_users.py scripts/bootstrap_*.py !scripts/bootstrap_token.py + +# Worktrees & Slices +.worktrees/ From c8c79bef89fc651eaee3937b58739fa53bf6b848 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 20:23:48 -0500 Subject: [PATCH 35/43] fix(router): validate deployment branch instead of source ref during post-pull verification --- scripts/appctl_router.py | 8 +-- tests/unit/test_appctl_router.py | 115 +++++++++++++++++++++++++++++++ 2 files changed, 119 insertions(+), 4 deletions(-) diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py index 4607ce0..883f10b 100644 --- a/scripts/appctl_router.py +++ b/scripts/appctl_router.py @@ -1006,7 +1006,7 @@ class OperationalRouter: # 2. git pull --ff-only pull_cmd = ["git", "-C", str(app_dir), "pull", "--ff-only"] if params.expected_branch: - pull_cmd.extend(["origin", params.expected_branch]) + pull_cmd.extend(["origin", "--", params.expected_branch]) code, pull_out, pull_err = run_bounded_subprocess( pull_cmd, cwd=app_dir, timeout=60.0 ) @@ -1026,12 +1026,12 @@ class OperationalRouter: ) if ( params.expected_branch - and manifest.source - and manifest.source.ref != params.expected_branch + and manifest.deployment + and manifest.deployment.branch != params.expected_branch ): raise RouterValidationError( f"Post-pull branch mismatch for '{app.name}': expected '{params.expected_branch}', " - f"manifest declared '{manifest.source.ref}'" + f"manifest declared '{manifest.deployment.branch}'" ) declared_actions = manifest.deployment.actions or ["compose_up"] diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index f339b1b..4b9dde8 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -1351,3 +1351,118 @@ def test_parse_dotenv_rejects_reserved_platform_keys(tmp_path: Path): RouterValidationError, match="Prohibited reserved environment key" ): parse_dotenv(env_file, validate_keys=True) + + +def test_operational_router_workload_update_succeeds_when_source_ref_is_tag_and_deployment_branch_matches( + tmp_path: Path, admin_principal: Principal, mock_sites_dir: Path +): + """Ensure workload.update validates deployment.branch (Tier 2) and does not conflate with source.ref (Tier 1) (CR-SS-01).""" + app_dir = mock_sites_dir / "bitetrack" + app_dir.mkdir(parents=True, exist_ok=True) + manifest_content = """ +name: "bitetrack" +source: + type: "git" + url: "https://github.com/example/bitetrack.git" + ref: "v2.5.0" +deployment: + strategy: "compose" + branch: "main" + actions: + - "compose_up" +""" + (app_dir / "app.yaml").write_text(manifest_content.strip(), encoding="utf-8") + (app_dir / "docker-compose.yml").write_text("services:\n app:\n image: app:latest\n", encoding="utf-8") + + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_sites_dir, + ) + req = OperationRequest.model_validate({ + "operation": "workload.update", + "target": "bitetrack", + "parameters": {"expected_branch": "main"}, + }) + + mock_app = MagicMock() + mock_app.name = "bitetrack" + mock_app.dir_path = str(app_dir) + + executed_cmds: list[list[str]] = [] + + def mock_subproc(cmd: list[str], **kwargs): + executed_cmds.append(cmd) + if "status" in cmd: + return 0, "", "" + if "pull" in cmd and "git" in cmd: + return 0, "Fast-forward", "" + if "rev-parse" in cmd: + return 0, "1234567", "" + return 0, "ok", "" + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), + patch("appctl_router.cmd_sync_homepage"), + ): + resp = router.dispatch(req, admin_principal) + assert resp.success is True + assert resp.result is not None + pull_calls = [c for c in executed_cmds if "pull" in c and "git" in c] + assert len(pull_calls) == 1 + assert pull_calls[0] == ["git", "-C", str(app_dir), "pull", "--ff-only", "origin", "--", "main"] + + +def test_operational_router_workload_update_rejects_deployment_branch_mismatch_image_only( + tmp_path: Path, admin_principal: Principal, mock_sites_dir: Path +): + """Ensure workload.update validates deployment.branch for image-only workloads with source=None (CR-SS-01).""" + app_dir = mock_sites_dir / "imageonly" + app_dir.mkdir(parents=True, exist_ok=True) + manifest_content = """ +name: "imageonly" +deployment: + strategy: "compose" + branch: "production" + actions: + - "compose_up" +""" + (app_dir / "app.yaml").write_text(manifest_content.strip(), encoding="utf-8") + (app_dir / "docker-compose.yml").write_text("services:\n app:\n image: app:latest\n", encoding="utf-8") + + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_sites_dir, + ) + req = OperationRequest.model_validate({ + "operation": "workload.update", + "target": "imageonly", + "parameters": {"expected_branch": "main"}, + }) + + mock_app = MagicMock() + mock_app.name = "imageonly" + mock_app.dir_path = str(app_dir) + + def mock_subproc(cmd: list[str], **kwargs): + if "status" in cmd: + return 0, "", "" + if "pull" in cmd and "git" in cmd: + return 0, "Fast-forward", "" + if "rev-parse" in cmd: + return 0, "1234567", "" + return 0, "ok", "" + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), + ): + resp = router.dispatch(req, admin_principal) + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_VALIDATION_FAILED + assert "Post-pull branch mismatch" in resp.error.message + assert "expected 'main'" in resp.error.message + assert "declared 'production'" in resp.error.message From 55acf00c10446d3b94168b5048a6fd6126756b74 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 20:24:35 -0500 Subject: [PATCH 36/43] fix(daemon): catch unhandled exceptions, preserve audit trail, and serialize homepage sync --- scripts/appctl_auth.py | 2 +- scripts/appctl_daemon.py | 28 ++++++-- scripts/appctl_engine.py | 6 +- scripts/appctl_router.py | 111 ++++++++++++++++++++++--------- tests/unit/test_appctl_auth.py | 11 +++ tests/unit/test_appctl_router.py | 50 ++++++++++++++ 6 files changed, 167 insertions(+), 41 deletions(-) diff --git a/scripts/appctl_auth.py b/scripts/appctl_auth.py index 7065b24..3d41b7e 100644 --- a/scripts/appctl_auth.py +++ b/scripts/appctl_auth.py @@ -338,7 +338,7 @@ def enforce_rbac( return # Target checks for operations targeting infrastructure - if target is not None and target in CORE_TARGETS: + if target is not None and target.strip().lower() in CORE_TARGETS: raise AuthorizationError( f"Role 'homelab-operator' is not permitted to target core service '{target}'", code=ErrorCode.ERR_PERMISSION_DENIED, diff --git a/scripts/appctl_daemon.py b/scripts/appctl_daemon.py index b720b41..bba84e9 100755 --- a/scripts/appctl_daemon.py +++ b/scripts/appctl_daemon.py @@ -386,13 +386,27 @@ class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler): return # Dispatch operation to OperationalRouter - resp = self.appctl_server.router.dispatch( - request=req, - principal=principal, - transport=transport, - origin=origin, - client=client_header, - ) + try: + resp = self.appctl_server.router.dispatch( + request=req, + principal=principal, + transport=transport, + origin=origin, + client=client_header, + ) + except Exception as exc: + logger.exception("Top-level unhandled exception during operation dispatch") + self._send_operation_error( + status_code=500, + error=OperationError( + code=ErrorCode.ERR_EXECUTION_FAILED, + message=f"Internal daemon execution error: {exc}", + ), + operation=req.operation, + target=req.target, + op_id=generate_operation_id(), + ) + return status_code = resp.error.code.http_status if (not resp.success and resp.error) else 200 self._send_operation_response(status_code, resp) diff --git a/scripts/appctl_engine.py b/scripts/appctl_engine.py index c03bb7a..af16215 100755 --- a/scripts/appctl_engine.py +++ b/scripts/appctl_engine.py @@ -742,8 +742,12 @@ def cmd_sync_homepage(args: list[str] | None = None) -> None: lines.append("") content = "\n".join(lines).strip() + "\n" - with open(services_yaml_path, "w", encoding="utf-8") as f: + tmp_services_path = services_yaml_path + ".tmp" + with open(tmp_services_path, "w", encoding="utf-8") as f: f.write(content) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp_services_path, services_yaml_path) print( f"✨ Homepage synchronized successfully ({len(visible_apps)} visible apps in {len(sorted_groups)} groups)" diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py index 883f10b..50a9764 100644 --- a/scripts/appctl_router.py +++ b/scripts/appctl_router.py @@ -12,6 +12,7 @@ Implements the single command execution pipeline for homelab-appctl.service: from __future__ import annotations +import logging import os import subprocess import time @@ -19,6 +20,8 @@ from pathlib import Path from typing import Any import yaml + +logger = logging.getLogger("appctl_router") from appctl_audit import ( AuditLogger, AuditPersistenceError, @@ -619,26 +622,30 @@ class OperationalRouter: duration_ms = int((time.perf_counter() - start_time) * 1000) + # Audit COMPLETED for mutating ops and sensitive reads # Audit COMPLETED for mutating ops and sensitive reads if ( operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS ): - self.audit_logger.log_completed( - operation_id=op_id, - principal=principal_audit, - action=operation.value, - target=target, - transport=transport, - origin=origin, - client=client, - parameters=request.parameters, - duration_ms=duration_ms, - commit_sha=commit_sha, - message=result_data.get( - "message", "Operation completed successfully" - ), - ) + try: + self.audit_logger.log_completed( + operation_id=op_id, + principal=principal_audit, + action=operation.value, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=request.parameters, + duration_ms=duration_ms, + commit_sha=commit_sha, + message=result_data.get( + "message", "Operation completed successfully" + ), + ) + except AuditPersistenceError as audit_err: + logger.error("Failed to persist COMPLETED audit record: %s", audit_err) return OperationResponse( version="1.0", @@ -658,20 +665,23 @@ class OperationalRouter: operation in MUTATING_OPERATIONS or operation in SENSITIVE_READ_OPERATIONS ): - self.audit_logger.log_failed( - operation_id=op_id, - principal=principal_audit, - action=operation.value, - target=target, - transport=transport, - origin=origin, - client=client, - parameters=request.parameters, - duration_ms=duration_ms, - exit_code=getattr(err, "exit_code", 1), - error_code=err.code.value, - message=str(err), - ) + try: + self.audit_logger.log_failed( + operation_id=op_id, + principal=principal_audit, + action=operation.value, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=request.parameters, + duration_ms=duration_ms, + exit_code=getattr(err, "exit_code", 1), + error_code=err.code.value, + message=str(err), + ) + except AuditPersistenceError as audit_err: + logger.error("Failed to persist FAILED audit record: %s", audit_err) return OperationResponse( version="1.0", success=False, @@ -681,6 +691,42 @@ class OperationalRouter: duration_ms=duration_ms, error=OperationError(code=err.code, message=str(err)), ) + except Exception as err: + logger.exception("Unexpected execution error in router") + duration_ms = int((time.perf_counter() - start_time) * 1000) + if ( + operation in MUTATING_OPERATIONS + or operation in SENSITIVE_READ_OPERATIONS + ): + try: + self.audit_logger.log_failed( + operation_id=op_id, + principal=principal_audit, + action=operation.value, + target=target, + transport=transport, + origin=origin, + client=client, + parameters=request.parameters, + duration_ms=duration_ms, + exit_code=1, + error_code=ErrorCode.ERR_EXECUTION_FAILED.value, + message=f"Unexpected execution failure: {err}", + ) + except AuditPersistenceError as audit_err: + logger.error("Failed to persist FAILED audit record: %s", audit_err) + return OperationResponse( + version="1.0", + success=False, + operation_id=op_id, + operation=operation, + target=target, + duration_ms=duration_ms, + error=OperationError( + code=ErrorCode.ERR_EXECUTION_FAILED, + message=f"Unexpected execution failure: {err}", + ), + ) # ----------------------------------------------------------------------- # Domain Operation Implementations @@ -1104,7 +1150,7 @@ class OperationalRouter: }, commit_sha def _op_platform_sync_homepage(self) -> dict[str, Any]: - self._trigger_homepage_sync() + cmd_sync_homepage() return { "action": "sync_homepage", "message": "Homepage dashboard synchronized successfully", @@ -1113,8 +1159,9 @@ class OperationalRouter: def _trigger_homepage_sync(self) -> None: """Atomic compile of Homepage dashboard services.yaml under _homepage_sync.lock.""" try: - cmd_sync_homepage() - except (OSError, ValueError, RuntimeError) as exc: + with self.lock_manager.homepage_sync_lock(): + cmd_sync_homepage() + except (OSError, ValueError, RuntimeError, ConcurrentMutationError) as exc: import sys print(f"Warning: Homepage sync non-fatal error: {exc}", file=sys.stderr) diff --git a/tests/unit/test_appctl_auth.py b/tests/unit/test_appctl_auth.py index 7fc55b7..97c9b15 100644 --- a/tests/unit/test_appctl_auth.py +++ b/tests/unit/test_appctl_auth.py @@ -366,6 +366,17 @@ def test_rbac_operator_denied_on_core_targets( assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED +def test_rbac_operator_denied_on_case_variant_core_targets(admitted_workloads: set[str]): + """Ensure case variants ('Core', 'TRAEFIK', 'Authelia') are rejected for operator role (CR-DI-06).""" + operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token") + for variant in ["Core", "CORE", "Traefik", "TRAEFIK", "Authelia"]: + with pytest.raises(AuthorizationError) as exc_info: + enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, variant, admitted_workloads) + assert "not permitted to target core service" in str(exc_info.value) + assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED + + + def test_rbac_operator_denied_without_target_on_mutating_or_sensitive_ops( admitted_workloads: set[str], ): diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 4b9dde8..753a436 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -7,6 +7,7 @@ test___ from __future__ import annotations +import json from pathlib import Path from unittest.mock import MagicMock, patch @@ -1466,3 +1467,52 @@ deployment: assert "Post-pull branch mismatch" in resp.error.message assert "expected 'main'" in resp.error.message assert "declared 'production'" in resp.error.message + + +def test_operational_router_catches_unhandled_runtime_exceptions_and_records_failed_audit( + tmp_path: Path, admin_principal: Principal, mock_sites_dir: Path +): + """Ensure unexpected exceptions in router return 500 ERR_EXECUTION_FAILED and log FAILED audit (CR-SO-04).""" + audit_file = tmp_path / "audit.jsonl" + router = OperationalRouter( + audit_logger=AuditLogger(audit_file), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_sites_dir, + ) + req = OperationRequest.model_validate({ + "operation": "platform.sync_homepage", + }) + + with patch("appctl_router.cmd_sync_homepage", side_effect=RuntimeError("Corrupt filesystem")): + resp = router.dispatch(req, admin_principal) + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED + assert "Unexpected execution failure" in resp.error.message + + events = [json.loads(line) for line in audit_file.read_text().splitlines() if line.strip()] + assert len(events) == 2 + assert events[0]["phase"] == "DISPATCHED" + assert events[1]["phase"] == "FAILED" + assert events[1]["result"]["error_code"] == ErrorCode.ERR_EXECUTION_FAILED.value + + +def test_trigger_homepage_sync_acquires_homepage_sync_lock(tmp_path: Path, mock_sites_dir: Path): + """Ensure _trigger_homepage_sync executes under homepage_sync_lock (CR-DI-05).""" + lock_mgr = TargetLockManager(tmp_path / "locks") + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=lock_mgr, + sites_dir=mock_sites_dir, + ) + lock_acquired = False + + def mock_sync(): + nonlocal lock_acquired + lock_file = lock_mgr.lock_dir / "_homepage_sync.lock" + assert lock_file.exists() + lock_acquired = True + + with patch("appctl_router.cmd_sync_homepage", side_effect=mock_sync): + router._trigger_homepage_sync() + assert lock_acquired is True From c740ed8c711a4e6b9bfbc6d9f233b91c4e57e212 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 20:48:53 -0500 Subject: [PATCH 37/43] chore: add .worktrees/ to .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 1cd5283..900da52 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,7 @@ config/homepage/custom.js Thumbs.db .vscode/ .idea/ +.worktrees/ # Python & Testing Caches __pycache__/ From 4622392ca510b8615018d67573e1c3b66409cfb9 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 20:54:36 -0500 Subject: [PATCH 38/43] fix(nixos): add tmpfiles state dir, optional sandbox paths, and gitops service ordering (#22) --- nixos/modules/homeserver.nix | 15 +++--- tests/security/test_security_invariants.py | 56 ++++++++++++++++++++++ 2 files changed, 64 insertions(+), 7 deletions(-) diff --git a/nixos/modules/homeserver.nix b/nixos/modules/homeserver.nix index 09cc54d..ae955ee 100644 --- a/nixos/modules/homeserver.nix +++ b/nixos/modules/homeserver.nix @@ -103,8 +103,8 @@ # Declarative Dynamic GitOps Webhook Service (Internal Port 9000) systemd.services.homelab-gitops = { description = "Dynamic Homelab GitOps Webhook Dispatcher"; - after = [ "network-online.target" "docker.service" ]; - wants = [ "network-online.target" ]; + after = [ "network-online.target" "docker.service" "homelab-appctl.service" ]; + wants = [ "network-online.target" "homelab-appctl.service" ]; wantedBy = [ "multi-user.target" ]; path = with pkgs; [ @@ -154,7 +154,7 @@ ReadWritePaths = [ config.homelab.sitesDir "/home/${config.homelab.operatorUser}/.local/state/homelab" - "/run/homelab" + "-/run/homelab" ]; }; }; @@ -226,11 +226,11 @@ ProtectControlGroups = true; ReadWritePaths = [ config.homelab.sitesDir - "/home/${config.homelab.operatorUser}/var/lib/homelab" - "${config.homelab.coreDir}/config/homepage" + "-/home/${config.homelab.operatorUser}/var/lib/homelab" + "-${config.homelab.coreDir}/config/homepage" "/var/log/homelab/appctl" - "/var/lib/homelab/appctl" - "/run/homelab" + "-/var/lib/homelab/appctl" + "-/run/homelab" ]; }; }; @@ -242,6 +242,7 @@ "d ${config.homelab.sitesDir} 0755 ${config.homelab.operatorUser} users -" "d /home/${config.homelab.operatorUser}/.local/state/homelab/gitops 0755 ${config.homelab.operatorUser} users -" "d /home/${config.homelab.operatorUser}/.local/state/homelab/docker 0755 ${config.homelab.operatorUser} users -" + "d /home/${config.homelab.operatorUser}/var/lib/homelab 0755 ${config.homelab.operatorUser} users -" # POSIX ACLs granting homelab-appctl traverse and access to operator sites & homepage config "a+ /home/${config.homelab.operatorUser} - - - - u:homelab-appctl:x" "a+ ${config.homelab.coreDir} - - - - u:homelab-appctl:x" diff --git a/tests/security/test_security_invariants.py b/tests/security/test_security_invariants.py index b03178c..4720d80 100644 --- a/tests/security/test_security_invariants.py +++ b/tests/security/test_security_invariants.py @@ -2,6 +2,7 @@ Security invariant tests for Docker Compose and container isolation. """ +import json import os import shutil import subprocess @@ -291,6 +292,61 @@ def test_nixos_tmpfiles_rules_use_recursive_acls(): ) +def test_nixos_tmpfiles_rules_creates_operator_var_lib_homelab(): + """Ensure tmpfiles.rules creates operator var/lib/homelab state dir before ACL assignment (#22).""" + homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix" + content = homeserver_nix.read_text(encoding="utf-8") + + expected_create = '"d /home/${config.homelab.operatorUser}/var/lib/homelab 0755 ${config.homelab.operatorUser} users -"' + expected_acl = '"A+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"' + + assert expected_create in content, ( + "tmpfiles.rules must declare creation of operator var/lib/homelab directory" + ) + assert expected_acl in content, ( + "tmpfiles.rules must declare ACLs for operator var/lib/homelab directory" + ) + assert content.index(expected_create) < content.index(expected_acl), ( + "operator var/lib/homelab directory creation must precede its ACL rule" + ) + + +def test_nixos_appctl_readwritepaths_optional_prefixes(): + """Ensure appctl service ReadWritePaths uses '-' prefix for optional runtime paths (#22).""" + homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix" + content = homeserver_nix.read_text(encoding="utf-8") + + assert '"-/home/${config.homelab.operatorUser}/var/lib/homelab"' in content + assert '"-${config.homelab.coreDir}/config/homepage"' in content + assert '"-/var/lib/homelab/appctl"' in content + assert '"-/run/homelab"' in content + + +def test_nixos_gitops_orders_after_appctl(): + """Ensure homelab-gitops service declares after and wants dependency on homelab-appctl.service (#22).""" + homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix" + content = homeserver_nix.read_text(encoding="utf-8") + + assert '"homelab-appctl.service"' in content + + nix_bin = shutil.which("nix") + if nix_bin and not os.environ.get("NIX_BUILD_TOP"): + for attr in ["after", "wants"]: + cmd = [ + nix_bin, + "eval", + f".#nixosConfigurations.server.config.systemd.services.homelab-gitops.{attr}", + "--json", + ] + res = subprocess.run( + cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True + ) + data = json.loads(res.stdout) + assert "homelab-appctl.service" in data, ( + f"homelab-gitops {attr} must include homelab-appctl.service" + ) + + def test_default_homelab_domain_evaluates_to_example_test(): """Assert default homelab.domain in NixOS config evaluates to 'example.test'.""" homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix" From 1fea9024f1fca398f11cc29d5423913f71f20304 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 20:57:31 -0500 Subject: [PATCH 39/43] docs(operations): document token bootstrapping and core update policy in cutover runbook (#23) --- docs/operations.md | 114 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 96 insertions(+), 18 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 4badb88..7fa71bd 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -145,9 +145,8 @@ appctl restart docs appctl restart traefik appctl restart authelia -# Sequential stack update (clean working tree check -> git pull -> compose pull -> up -> sync) +# Sequential stack update for independent Sites workloads (clean tree check -> git pull -> compose pull -> up -> sync) appctl update docs -appctl update core # Stream live container logs appctl logs docs @@ -157,6 +156,37 @@ appctl logs -f stalwart appctl config docs ``` +### Workload vs. Core Update Policy + +Homelab enforces a strict architectural boundary between independent application workloads (`~/Sites/`) and Homelab Core (`~/Core`): + +#### 1. Independent Sites Workloads (`~/Sites/`) +- **Automated Lifecycle**: Workloads declare their lifecycle via `app.yaml` manifests and Compose definitions. +- **Update Command**: `appctl update ` performs pre-flight verification, branch matching, `git pull --ff-only`, container image pull, stack reload, and dashboard synchronization. +- **GitOps Webhook Dispatch**: Workloads registered in `config/deployments.yaml` can be triggered automatically via authenticated GitOps webhooks on Gitea push events. +- **Daemon Permissions**: `homelab-appctl.service` holds read-write permissions over `~/Sites` to manage files, compose configurations, and workload state. + +#### 2. Homelab Core Platform Stack (`~/Core`) +- **Host Foundation & Invariant Boundary**: Core defines NixOS host definitions, platform secrets, edge ingress, and security sandboxes. +- **No Untrusted Webhooks**: Core does **not** register for webhook dispatch in `config/deployments.yaml`. External push events can never trigger an automated deployment or rebuild of Core. +- **Read-Only Sandbox**: Under NixOS systemd sandboxing (`ProtectHome = "read-only"`), `homelab-appctl.service` has strictly read-only access to `/home/operator/Core`. The daemon cannot mutate the Core Git repository or run `git pull` on Core. +- **Operator-Driven Update Workflow**: Core updates must be executed explicitly by the operator: + 1. Review and pull repository changes: + ```bash + cd ~/Core && git pull --ff-only + ``` + 2. If NixOS modules or secrets changed, evaluate and activate the new system generation: + ```bash + sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure + ``` + 3. If Compose definitions changed, restart the platform stack: + ```bash + docker compose up -d --remove-orphans + # or via systemd: + sudo systemctl restart homeserver-core + ``` + 4. Individual platform services can be restarted via appctl using an authenticated admin token (`appctl restart traefik`, `appctl restart authelia`). + --- ## 4. User Identity & Access Management (LLDAP & Authelia) @@ -437,7 +467,51 @@ Activate the declarative configuration under the `operator` profile: chmod 600 /home/operator/Core/nixos/instance.nix ``` -2. **Rebuild NixOS host configuration**: +2. **Bootstrap appctl control plane tokens (CR-SO-08)**: + The `homelab-appctl.service` control plane daemon enforces 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`) authenticated via SHA-256 Bearer tokens stored in `/run/secrets/appctl/tokens.json`. + + Generate the operator administrator token and local CLI credentials: + ```bash + sudo -u operator python3 /home/operator/Core/scripts/bootstrap_token.py + ``` + This command: + - Creates `~/.config/homelab/token` (mode `0600`) owned by `operator:homelab-operators` containing the raw Bearer token used automatically by the `appctl` CLI. + - Outputs the JSON token descriptor containing the SHA-256 digest: + ```json + { + "token_id": "operator-admin", + "identity": "operator", + "role": "homelab-admin", + "sha256": "<64-character-sha256-digest>" + } + ``` + + > [!IMPORTANT] + > **Unprovisioned Token Behavior & RBAC Fallback**: + > If tokens are not provisioned in `/run/secrets/appctl/tokens.json`, local UDS connections (`/run/homelab/appctl.sock`) fall back to Linux `SO_PEERCRED` socket credentials, granting callers in `homelab-operators` the read-only `homelab-viewer` role. + > Under `homelab-viewer`, safe queries succeed (`appctl list`, `appctl status`, `appctl health`). + > However, **all mutating and privileged operations** (`appctl up`, `appctl down`, `appctl restart`, `appctl update`, `appctl deploy`, `appctl config`, `appctl info`) **strictly require** a valid Bearer token with `homelab-operator` or `homelab-admin` role. If tokens are not enrolled in SOPS, attempting mutating actions fails with HTTP 403 `ERR_PERMISSION_DENIED`. + + Enroll the token descriptor into SOPS secrets: + ```bash + sops /home/operator/Core/nixos/secrets.yaml + ``` + Under `appctl.tokens_json`, insert the descriptor into the JSON array: + ```yaml + appctl: + tokens_json: | + [ + { + "token_id": "operator-admin", + "identity": "operator", + "role": "homelab-admin", + "sha256": "" + } + ] + ``` + *(Optional: If GitOps webhook dispatch is enabled, generate and enroll a `gitops-webhook` token with `homelab-operator` role using `python3 scripts/bootstrap_token.py --identity gitops --role homelab-operator --token-id gitops-webhook --print-json`).* + +3. **Rebuild NixOS host configuration**: Execute the rebuild from the new canonical Core path using `--impure` and the `path:` scheme to import the untracked instance profile: ```bash cd /home/operator/Core @@ -445,10 +519,10 @@ Activate the declarative configuration under the `operator` profile: ``` > [!NOTE] - > The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index, ensuring untracked/gitignored `nixos/instance.nix` is evaluated. (If using `/etc/nixos/homelab-instance.nix`, bare `--flake .#server --impure` works directly). + > The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index, ensuring untracked/gitignored `nixos/instance.nix` is evaluated. (If using `/etc/nixos/homelab-instance.nix`, bare `--flake .#server --impure` works directly). Rebuilding also decrypts and projects `/run/secrets/appctl/tokens.json` via `sops-nix`. -3. **Restart platform services**: - Restart the Core Compose stack and control plane services to consume updated paths: +4. **Restart platform services**: + Restart the Core Compose stack and control plane services to consume updated paths and secrets: ```bash sudo systemctl restart homeserver-core sudo systemctl restart homelab-appctl @@ -467,22 +541,26 @@ Validate system health and operational readiness under the `operator` identity: sudo -u operator git -C /home/operator/Sites/ status ``` -2. **Verify appctl control plane status**: - Execute CLI inspection using both UDS peercred authentication and token authentication: - ```bash - # Peercred UDS inspection - sudo -u operator appctl list --core - - # Workload health check - sudo -u operator appctl status - ``` - -3. **Verify SOPS secrets and tokens**: - Ensure `/run/secrets/appctl/tokens.json` is readable by `homelab-appctl` and valid tokens exist for operator administration: +2. **Verify SOPS secrets and tokens projection**: + Ensure `/run/secrets/appctl/tokens.json` is readable by `homelab-appctl` (mode `0400`, owned by `homelab-appctl:homelab-operators`) and contains valid descriptors: ```bash sudo ls -l /run/secrets/appctl/tokens.json ``` +3. **Verify appctl control plane status & RBAC authentication**: + Execute CLI inspection using both UDS peercred authentication (read-only viewer fallback) and authenticated admin token operations: + ```bash + # 1. Peercred UDS inspection (demonstrates viewer fallback for read-only actions) + sudo -u operator appctl list --core + sudo -u operator appctl status + sudo -u operator appctl health + + # 2. Authenticated operator admin verification (requires homelab-admin Bearer token) + sudo -u operator appctl info docs + sudo -u operator appctl config docs + ``` + Confirm that `info` and `config` return resolved configuration without `ERR_PERMISSION_DENIED`, verifying that `~/.config/homelab/token` matches the provisioned SHA-256 digest in `/run/secrets/appctl/tokens.json`. + 4. **Verify container reachability & proxy routing**: Check that external endpoints and internal reverse proxies resolve: ```bash From b7b19ad7f1dfb97da7c0dcd25ab90022117aa468 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 21:08:49 -0500 Subject: [PATCH 40/43] test(daemon): replace tautological subprocess.run patches with run_bounded_subprocess seam (#24) --- tests/unit/test_appctl_daemon.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/tests/unit/test_appctl_daemon.py b/tests/unit/test_appctl_daemon.py index 0e4d776..4f9b4b7 100644 --- a/tests/unit/test_appctl_daemon.py +++ b/tests/unit/test_appctl_daemon.py @@ -287,7 +287,7 @@ def test_auth_missing_token_fails_closed(daemon_env): """ deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs") - with patch("subprocess.run") as mock_subproc: + with patch("appctl_router.run_bounded_subprocess") as mock_subproc: # Over HTTP without token resp_http = send_daemon_request( endpoint=daemon_env.http_url, @@ -401,7 +401,7 @@ def test_daemon_preflight_and_dotenv_safety(daemon_env): deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs") - with patch("subprocess.run") as mock_subproc: + with patch("appctl_router.run_bounded_subprocess") as mock_subproc: resp = send_daemon_request( endpoint=daemon_env.socket_path, operation_request=deploy_req, @@ -470,7 +470,7 @@ def test_audit_failure_blocks_mutation(daemon_env): daemon_env.audit_file.chmod(0o400) deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs") - with patch("subprocess.run") as mock_subproc: + with patch("appctl_router.run_bounded_subprocess") as mock_subproc: resp = send_daemon_request( endpoint=daemon_env.socket_path, operation_request=deploy_req, @@ -515,13 +515,20 @@ def test_gitops_dispatcher_delegates_to_daemon(daemon_env, monkeypatch): monkeypatch.setenv("GITOPS_APPCTL_TOKEN", OPERATOR_SECRET) monkeypatch.setenv("APPCTL_SOCKET_PATH", str(daemon_env.socket_path)) - with patch.object(daemon_env.daemon.router, "_op_workload_update") as mock_update: - mock_update.return_value = ({"action": "updated", "message": "Updated via daemon"}, "sha12345") + def mock_subproc(cmd, *args, **kwargs): + if "status" in cmd: + return (0, "", "") + if "rev-parse" in cmd: + return (0, "sha12345", "") + return (0, "ok", "") + with patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc) as mock_sub, patch( + "appctl_router.OperationalRouter._trigger_homepage_sync" + ): success = gitops_dispatcher.execute_deployment( target_dir=daemon_env.docs_dir, deployment_config={"branch": "main", "actions": ["git_pull", "compose_up"]}, branch="main", ) assert success is True - assert mock_update.call_count == 1 + assert mock_sub.call_count >= 1 From af82d4b26dc080222d31c3f2399b2cee89e26741 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 21:11:25 -0500 Subject: [PATCH 41/43] test(daemon): add true multi-threaded lock contention concurrency test (#24) --- tests/unit/test_appctl_daemon.py | 52 ++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/tests/unit/test_appctl_daemon.py b/tests/unit/test_appctl_daemon.py index 4f9b4b7..c1b60f5 100644 --- a/tests/unit/test_appctl_daemon.py +++ b/tests/unit/test_appctl_daemon.py @@ -18,9 +18,12 @@ Asserts: from __future__ import annotations +import concurrent.futures import hashlib import json import socket +import threading +import time from pathlib import Path from unittest.mock import patch @@ -435,6 +438,55 @@ def test_concurrent_mutation_conflict(daemon_env): assert resp.error.code.http_status == 409 +def test_daemon_multi_threaded_lock_contention_rejects_concurrent_mutation(daemon_env): + """ + Simultaneous mutating requests for the same target result in one 200 SUCCESS + and one 409 ERR_CONCURRENT_MUTATION via multi-threaded lock contention. + """ + deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs") + first_started = threading.Event() + + def slow_subproc(cmd, *args, **kwargs): + first_started.set() + time.sleep(0.2) + return (0, "Started", "") + + def send_first(): + return send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=deploy_req, + token=ADMIN_SECRET, + ) + + def send_second(): + first_started.wait(timeout=2.0) + return send_daemon_request( + endpoint=daemon_env.socket_path, + operation_request=deploy_req, + token=ADMIN_SECRET, + ) + + with ( + patch("appctl_router.run_bounded_subprocess", side_effect=slow_subproc), + patch("appctl_router.OperationalRouter._trigger_homepage_sync"), + concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor, + ): + fut1 = executor.submit(send_first) + fut2 = executor.submit(send_second) + resp1 = fut1.result(timeout=5.0) + resp2 = fut2.result(timeout=5.0) + + responses = [resp1, resp2] + successes = [r for r in responses if r.success] + conflicts = [r for r in responses if not r.success and r.error and r.error.code == ErrorCode.ERR_CONCURRENT_MUTATION] + + assert len(successes) == 1 + assert len(conflicts) == 1 + assert successes[0].result is not None + assert successes[0].result["action"] == "deployed" + assert conflicts[0].error.code.http_status == 409 + + def test_execution_failure_audit(daemon_env): """ Failing Docker subprocess returns 500 ERR_EXECUTION_FAILED and records phase: FAILED. From c034afd0f86493f80d91fa3c0e26e3ceb885b225 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 21:14:01 -0500 Subject: [PATCH 42/43] test(router): verify non-zero subprocess exit and diagnostic stderr propagation (#24) --- tests/unit/test_appctl_router.py | 102 +++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 753a436..de9bbb0 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -1336,6 +1336,108 @@ def test_operational_router_workload_config_redacts_evaluated_secrets_for_operat assert "supersecretpassword123" in resp_admin.result["output"] +@pytest.mark.parametrize( + ("exit_code", "stderr_msg"), + [ + (1, "Error: container failed to start: port in use"), + (2, "Error response from daemon: network homelab_edge not found"), + ], +) +def test_operational_router_workload_deploy_propagates_non_zero_exit_and_stderr( + tmp_path: Path, + admin_principal: Principal, + mock_workload_dir: Path, + exit_code: int, + stderr_msg: str, +): + audit_file = tmp_path / "audit.jsonl" + router = OperationalRouter( + audit_logger=AuditLogger(audit_file), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_workload_dir.parent, + ) + req = OperationRequest.model_validate({ + "operation": "workload.deploy", + "target": "snappymail", + }) + + mock_app = MagicMock() + mock_app.name = "snappymail" + mock_app.dir_path = str(mock_workload_dir) + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", return_value=(exit_code, "", stderr_msg)), + patch("appctl_router.cmd_sync_homepage"), + ): + resp = router.dispatch(req, admin_principal) + + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED + assert stderr_msg in resp.error.message + + audit_lines = [json.loads(line) for line in audit_file.read_text(encoding="utf-8").splitlines() if line.strip()] + failed_events = [ev for ev in audit_lines if ev.get("phase") == "FAILED"] + assert len(failed_events) >= 1 + failed_event = failed_events[-1] + assert failed_event["target"] == "snappymail" + assert failed_event["result"]["exit_code"] == exit_code + assert failed_event["result"]["error_code"] == ErrorCode.ERR_EXECUTION_FAILED.value + assert stderr_msg in failed_event["result"]["message"] + + +def test_operational_router_workload_update_propagates_non_zero_exit_and_stderr( + tmp_path: Path, + operator_principal: Principal, + mock_workload_dir: Path, +): + audit_file = tmp_path / "audit.jsonl" + router = OperationalRouter( + audit_logger=AuditLogger(audit_file), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_workload_dir.parent, + ) + req = OperationRequest.model_validate({ + "operation": "workload.update", + "target": "snappymail", + "parameters": {"expected_branch": "main"}, + }) + + mock_app = MagicMock() + mock_app.name = "snappymail" + mock_app.dir_path = str(mock_workload_dir) + + def mock_subproc(cmd: list[str], **kwargs): + if "status" in cmd: + return (0, "", "") + if "pull" in cmd: + return (2, "", "fatal: unable to access repository: connection refused") + return (0, "", "") + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), + patch("appctl_router.cmd_sync_homepage"), + ): + resp = router.dispatch(req, operator_principal) + + assert resp.success is False + assert resp.error is not None + assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED + assert "fatal: unable to access repository: connection refused" in resp.error.message + + audit_lines = [json.loads(line) for line in audit_file.read_text(encoding="utf-8").splitlines() if line.strip()] + failed_events = [ev for ev in audit_lines if ev.get("phase") == "FAILED"] + assert len(failed_events) >= 1 + failed_event = failed_events[-1] + assert failed_event["result"]["exit_code"] == 2 + assert "fatal: unable to access repository: connection refused" in failed_event["result"]["message"] + + + + + def test_parse_dotenv_rejects_reserved_platform_keys(tmp_path: Path): """Ensure parse_dotenv rejects platform routing and docker config variables in .env (CR-DI-07).""" env_file = tmp_path / ".env" From 76df30747d0967b3ade09e24aa5aa8362cc719da Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 31 Oct 2026 22:29:52 -0500 Subject: [PATCH 43/43] test(harness): ensure portable socket path length and root-invariant audit failure handling --- tests/unit/test_appctl_audit.py | 43 +++++++++++++------------------- tests/unit/test_appctl_cli.py | 5 +++- tests/unit/test_appctl_daemon.py | 20 +++++++++------ 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/tests/unit/test_appctl_audit.py b/tests/unit/test_appctl_audit.py index 3d7d330..2ef385a 100644 --- a/tests/unit/test_appctl_audit.py +++ b/tests/unit/test_appctl_audit.py @@ -8,7 +8,6 @@ test___ from __future__ import annotations import json -import os import stat from pathlib import Path @@ -285,32 +284,24 @@ def test_audit_logger_automatically_redacts_sensitive_parameters( def test_audit_logger_fails_closed_when_audit_log_unwritable( tmp_path: Path, sample_principal: PrincipalAudit ): - read_only_dir = tmp_path / "readonly_audit" - read_only_dir.mkdir(parents=True, exist_ok=True) - unwritable_file = read_only_dir / "audit.jsonl" - unwritable_file.touch(mode=0o400) - os.chmod(unwritable_file, 0o400) + # Using a directory as the audit path causes os.open with O_WRONLY to fail with + # EISDIR / OSError across all platforms and environments (including root containers). + unwritable_target = tmp_path / "unwritable_audit_dir" + unwritable_target.mkdir(parents=True, exist_ok=True) - # In addition, make directory read-only - os.chmod(read_only_dir, 0o500) - - try: - logger = AuditLogger(unwritable_file) - with pytest.raises(AuditPersistenceError) as exc_info: - logger.log_dispatched( - operation_id="op_105", - principal=sample_principal, - action="workload.deploy", - target="jellyfin", - transport="unix_socket", - origin="peer_uid_1000", - client="appctl-cli/2.0", - parameters={"recreate": True}, - ) - assert "Failed to persist audit event" in str(exc_info.value) - finally: - os.chmod(read_only_dir, 0o700) - os.chmod(unwritable_file, 0o600) + logger = AuditLogger(unwritable_target) + with pytest.raises(AuditPersistenceError) as exc_info: + logger.log_dispatched( + operation_id="op_105", + principal=sample_principal, + action="workload.deploy", + target="jellyfin", + transport="unix_socket", + origin="peer_uid_1000", + client="appctl-cli/2.0", + parameters={"recreate": True}, + ) + assert "Failed to persist audit event" in str(exc_info.value) # --------------------------------------------------------------------------- diff --git a/tests/unit/test_appctl_cli.py b/tests/unit/test_appctl_cli.py index 43558af..e940457 100644 --- a/tests/unit/test_appctl_cli.py +++ b/tests/unit/test_appctl_cli.py @@ -473,9 +473,11 @@ def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path, import socket as std_socket import subprocess import sys + import tempfile bash_bin = shutil.which("bash") or "bash" - sock_path = tmp_path / "appctl.sock" + sock_dir = tempfile.TemporaryDirectory(prefix="appctl_sock_", dir="/tmp") + sock_path = Path(sock_dir.name) / "appctl.sock" srv = std_socket.socket(std_socket.AF_UNIX, std_socket.SOCK_STREAM) srv.bind(str(sock_path)) try: @@ -512,6 +514,7 @@ def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path, assert "core" in res_words.stdout finally: srv.close() + sock_dir.cleanup() def test_appctl_wrapper_fails_closed_when_socket_is_missing(tmp_path: Path): diff --git a/tests/unit/test_appctl_daemon.py b/tests/unit/test_appctl_daemon.py index c1b60f5..9f8b0d0 100644 --- a/tests/unit/test_appctl_daemon.py +++ b/tests/unit/test_appctl_daemon.py @@ -22,6 +22,7 @@ import concurrent.futures import hashlib import json import socket +import tempfile import threading import time from pathlib import Path @@ -29,7 +30,7 @@ from unittest.mock import patch import gitops_dispatcher import pytest -from appctl_audit import AuditLogger, TargetLockManager +from appctl_audit import AuditLogger, AuditPersistenceError, TargetLockManager from appctl_auth import Role, TokenDescriptor, TokenStore from appctl_contracts import ErrorCode, OperationRequest, OperationType from appctl_daemon import ( @@ -64,7 +65,8 @@ def daemon_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): - Valid 0600 audit log file """ monkeypatch.setenv("HOMELAB_DOMAIN", "example.test") - socket_path = tmp_path / "appctl.sock" + sock_dir = tempfile.TemporaryDirectory(prefix="appctl_sock_", dir="/tmp") + socket_path = Path(sock_dir.name) / "appctl.sock" http_port = get_free_port() http_host = "127.0.0.1" @@ -191,6 +193,7 @@ def daemon_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): yield ctx finally: daemon.stop() + sock_dir.cleanup() def test_health_endpoint(daemon_env): @@ -519,10 +522,16 @@ def test_audit_failure_blocks_mutation(daemon_env): Unwritable audit.jsonl aborts mutating command with 500 ERR_EXECUTION_FAILED and zero Docker invocations. """ - daemon_env.audit_file.chmod(0o400) deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs") - with patch("appctl_router.run_bounded_subprocess") as mock_subproc: + with ( + patch.object( + daemon_env.daemon.audit_logger, + "emit_event", + side_effect=AuditPersistenceError("Simulated disk full or permission error"), + ), + patch("appctl_router.run_bounded_subprocess") as mock_subproc, + ): resp = send_daemon_request( endpoint=daemon_env.socket_path, operation_request=deploy_req, @@ -534,9 +543,6 @@ def test_audit_failure_blocks_mutation(daemon_env): assert resp.error.code.http_status == 500 assert mock_subproc.call_count == 0 - # Restore write permission for teardown - daemon_env.audit_file.chmod(0o600) - def test_daemon_restart_preserves_state(daemon_env): """