#!/usr/bin/env python3 """Pinned cluster identities and profile-scoped local OpenTofu state for Jeannie.""" import argparse import base64 import contextlib import fcntl import hashlib import json import os import re import shutil import ssl import subprocess import sys import tempfile from pathlib import Path from urllib.parse import urlsplit REPO = Path(__file__).resolve().parents[1] STACKS = {"cluster", "platform", "apps"} IDENTITY_FIELDS = ("profile", "endpoint", "ca_sha256", "kube_system_uid") class Refused(RuntimeError): pass def binary(tool): components = [] for item in os.environ.get("PATH", "").split(os.pathsep): candidate = (Path(item) / tool).resolve() if candidate.parent.name == "guarded-bin" and candidate.parent.parent.name == "scripts": continue # Also skip guards inherited from a different checkout. components.append(item) path = os.pathsep.join(components) found = shutil.which(tool, path=path) if not found: raise Refused(f"{tool} is required on the deployment host") return found def capture(command, *, text=None, env=None): result = subprocess.run(command, input=text, text=True, capture_output=True, timeout=90, env=env, check=False) if result.returncode: # Do not expose kubeconfig credentials, tokens, or Terraform values. reason = "read/configuration failure" for signature, category in (("Forbidden", "RBAC denied"), ("Unauthorized", "authentication denied"), ("certificate", "TLS verification failure"), ("connection refused", "API unavailable"), ("timed out", "request timed out"), ("timeout", "request timed out")): if signature.lower() in result.stderr.lower(): reason = category break operation = next((word for word in ("init", "console", "namespace", "node", "view") if word in command), "read") raise Refused(f"{Path(command[0]).name} {operation} failed: {reason} (exit {result.returncode}); requested action was not started") return result.stdout def document(path): return json.loads(Path(path).read_text()) def private_write(path, value): path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) descriptor, temporary = tempfile.mkstemp(prefix=".context-", dir=path.parent) try: with os.fdopen(descriptor, "w") as handle: json.dump(value, handle, indent=2, sort_keys=True) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.link(temporary, path) # Atomic publication; never overwrite an identity or state. finally: os.unlink(temporary) @contextlib.contextmanager def locked(path): path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) descriptor = os.open(path, os.O_RDWR | os.O_CREAT, 0o600) with os.fdopen(descriptor, "w") as handle: fcntl.flock(handle, fcntl.LOCK_EX) yield def endpoint(value): parsed = urlsplit(value) if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ("", "/"): raise Refused("Cluster endpoint must be an explicit HTTPS API endpoint") host = parsed.hostname.lower() if ":" in host: host = f"[{host}]" return f"https://{host}:{parsed.port or 443}" def ca_fingerprint(pem): certificates = re.findall(r"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----", pem, flags=re.S) if len(certificates) != 1: raise Refused("Expected exactly one pinned cluster CA certificate; review CA rotation separately") der = ssl.PEM_cert_to_DER_cert(certificates[0]) return hashlib.sha256(der).hexdigest() class Context: def __init__(self, profile=None, kubeconfig=None, kube_context=None): import yaml try: inventory = yaml.safe_load(Path(os.environ.get("HOMELAB_INVENTORY_FILE", REPO / "homelab.yml")).read_text()) except yaml.YAMLError as error: raise Refused("Invalid homelab inventory YAML") from error if not isinstance(inventory, dict): raise Refused("Homelab inventory must be a mapping") if os.environ.get("KUBERNETES_MASTER"): raise Refused("KUBERNETES_MASTER connection overrides are refused") cluster = inventory.get("cluster", {}) self.profile = profile or os.environ.get("LAB_CLUSTER_PROFILE") or cluster.get("active_profile") if not self.profile or not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}", self.profile): raise Refused("Select a valid, declared LAB_CLUSTER_PROFILE") control = cluster.get("profiles", {}).get(self.profile, {}).get("control_plane") if not control or not all(control.get(key) for key in ("lan_ip", "node_name", "kubeconfig")): raise Refused(f"Profile {self.profile} has no explicit control-plane address and node in homelab.yml") self.expected_endpoint = endpoint(control.get("api_endpoint", f"https://{control['lan_ip']}:6443")) self.expected_host = control["lan_ip"] self.expected_node = control["node_name"] state_root = Path(os.environ.get("HOMELAB_STATE_DIR", Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / "homelab")) if not state_root.is_absolute(): raise Refused("HOMELAB_STATE_DIR/XDG_DATA_HOME must resolve to an absolute state directory") self.root = state_root.resolve() / "clusters" / self.profile self.binding = self.root / "identity.json" selected_config = kubeconfig if kubeconfig is not None else control["kubeconfig"] if not selected_config or os.pathsep in selected_config or not Path(selected_config).expanduser().is_absolute(): raise Refused("Use one explicit, absolute kubeconfig path; empty paths and merged configs are refused") self.kubeconfig = str(Path(selected_config).expanduser().resolve()) self.kube_context = kube_context def client(self): command = [binary("kubectl"), "--kubeconfig", self.kubeconfig] if self.kube_context: command.extend(["--context", self.kube_context]) return command def observed(self): client = self.client() config = json.loads(capture(client + ["config", "view", "--raw", "--minify", "--flatten", "-o", "json"])) clusters = config.get("clusters", []) if len(clusters) != 1: raise Refused("Kubeconfig must resolve to exactly one cluster") cluster = clusters[0]["cluster"] actual_endpoint = endpoint(cluster["server"]) if actual_endpoint != self.expected_endpoint: raise Refused(f"Profile {self.profile}: endpoint mismatch; expected {self.expected_endpoint}, got {actual_endpoint}") if cluster.get("insecure-skip-tls-verify") or cluster.get("proxy-url") or cluster.get("tls-server-name"): raise Refused("Insecure TLS, kubeconfig proxies, and alternate TLS names are not allowed for pinned clusters") if not cluster.get("certificate-authority-data"): raise Refused("Kubeconfig must contain an explicit cluster CA") ca = ca_fingerprint(base64.b64decode(cluster["certificate-authority-data"], validate=True).decode()) # Endpoint/CA are compared before issuing any authenticated API read. if self.binding.exists(): bound = document(self.binding) if bound.get("profile") != self.profile or bound.get("endpoint") != actual_endpoint or bound.get("ca_sha256") != ca: raise Refused(f"Profile {self.profile}: pinned endpoint or CA fingerprint mismatch") request = client + ["--request-timeout=10s"] namespace = json.loads(capture(request + ["get", "namespace", "kube-system", "-o", "json"])) uid = namespace.get("metadata", {}).get("uid") if not uid: raise Refused("kube-system UID is absent") node = json.loads(capture(request + ["get", "node", self.expected_node, "-o", "json"])) labels = node.get("metadata", {}).get("labels", {}) if not any(key in labels for key in ("node-role.kubernetes.io/control-plane", "node-role.kubernetes.io/master")): raise Refused(f"Expected node {self.expected_node} is not a control plane") return {"profile": self.profile, "endpoint": actual_endpoint, "ca_sha256": ca, "kube_system_uid": uid} def check(self): if not self.binding.is_file(): raise Refused(f"Profile {self.profile} is not enrolled. Review ./jeannie cluster-context enroll, then enroll --yes") observed = self.observed() bound = document(self.binding) if any(observed[field] != bound.get(field) for field in IDENTITY_FIELDS): differences = "; ".join(f"{field}: expected {bound.get(field)}, got {observed[field]}" for field in IDENTITY_FIELDS if observed[field] != bound.get(field)) raise Refused(f"Profile {self.profile}: cluster identity mismatch; {differences}; refusing mutation") return observed def state(self, stack): if stack not in STACKS: raise Refused("Unknown profile-scoped stack") return self.root / "stacks" / stack / "terraform.tfstate" def connection_options(args, tool): config = None context = None for index, arg in enumerate(args): if arg == "--": break flag, separator, value = arg.partition("=") if arg.startswith("-s") or flag in ("--server", "--cluster", "--user", "--certificate-authority", "--client-certificate", "--client-key", "--tls-server-name", "--insecure-skip-tls-verify", "--kube-apiserver", "--kube-ca-file", "--kube-tls-server-name", "--kube-insecure-skip-tls-verify"): raise Refused(f"Connection override {flag} is not allowed for guarded {tool}") if flag not in ("--kubeconfig", "--context", "--kube-context"): continue if not separator: if index + 1 >= len(args): raise Refused(f"Missing value for {flag}") value = args[index + 1] if not value: raise Refused(f"Empty {flag} overrides are refused") if flag == "--kubeconfig": config = value else: context = value return config, context def command_word(args): takes_value = {"--kubeconfig", "--context", "--kube-context", "--namespace", "-n", "--request-timeout", "--token", "--as", "--as-group", "--as-uid", "--cache-dir", "--v", "-v"} skip = False for arg in args: if skip: skip = False continue if arg in takes_value: skip = True elif not arg.startswith("-"): return arg return "help" def proxy_client(tool, args): word = command_word(args) readonly = {"get", "describe", "logs", "api-resources", "api-versions", "version", "cluster-info", "explain", "top", "wait", "kustomize", "completion", "options", "help", "config"} helm_readonly = {"get", "list", "status", "history", "show", "template", "lint", "pull", "package", "dependency", "repo", "search", "env", "version", "completion", "help"} writes = word not in (readonly if tool == "kubectl" else helm_readonly) if writes: if os.environ.get("KUBERNETES_MASTER"): raise Refused("KUBERNETES_MASTER connection overrides are refused") config, kube_context = connection_options(args, tool) if tool == "helm": if any(os.environ.get(key) for key in ("HELM_KUBEAPISERVER", "HELM_KUBECAFILE", "HELM_KUBEINSECURE_SKIP_TLS_VERIFY", "HELM_KUBETLS_SERVER_NAME")): raise Refused("Helm endpoint/CA/TLS environment overrides are refused") kube_context = kube_context or os.environ.get("HELM_KUBECONTEXT") context = Context(kubeconfig=config or os.environ.get("KUBECONFIG"), kube_context=kube_context) context.check() if not config: args = ["--kubeconfig", context.kubeconfig, *args] os.execv(binary(tool), [binary(tool), *args]) def variable_args(args): result = [] for index, arg in enumerate(args): if arg in ("-var", "-var-file"): result.extend([arg, args[index + 1]]) elif arg.startswith(("-var=", "-var-file=")): result.append(arg) return result def plan_path(args, directory): for index, arg in enumerate(args): if arg == "-out": return (directory / args[index + 1]).resolve() if arg.startswith("-out="): return (directory / arg.split("=", 1)[1]).resolve() return None def legacy_record(context, source): key = hashlib.sha256(str(source.resolve()).encode()).hexdigest() return context.root.parent / "legacy-adoptions" / (key + ".json") def positionals(args): result = [] skip = False end = False for arg in args: if end: result.append(arg) elif arg == "--": end = True elif skip: skip = False elif arg in ("-var", "-var-file", "-target", "-replace", "-parallelism", "-lock-timeout"): skip = True elif not arg.startswith("-"): result.append(arg) return result def proxy_tofu(args): directory = Path.cwd().resolve() if args and args[0].startswith("-chdir="): directory = Path(args.pop(0).split("=", 1)[1]).resolve() elif args and args[0] == "-chdir": directory = Path(args[1]).resolve() args = args[2:] tool = binary("tofu") name = directory.name if directory.parent.name == "bootstrap" and name in STACKS and directory.parent != REPO / "bootstrap": raise Refused("Cross-checkout Kubernetes operation refused; use that checkout's Jeannie entry point") if directory.parent != REPO / "bootstrap" or name not in STACKS or not args or args[0] in ("fmt", "version", "help", "-help", "-version"): env = dict(os.environ) if env.get("JEANNIE_PROFILE_TF_DATA") == env.get("TF_DATA_DIR"): env.pop("TF_DATA_DIR", None) env.pop("JEANNIE_PROFILE_TF_DATA", None) os.execve(tool, [tool, f"-chdir={directory}", *args], env) context = Context(kubeconfig=os.environ.get("TF_VAR_kubeconfig_path") or os.environ.get("KUBECONFIG")) state = context.state(name) if any(key.startswith("TF_CLI_ARGS") and value for key, value in os.environ.items()): raise Refused("Use explicit OpenTofu flags for scoped stacks; TF_CLI_ARGS overrides are refused") if os.environ.get("TF_WORKSPACE", "default") != "default": raise Refused("Profiles use separate state files, not TF_WORKSPACE; unset TF_WORKSPACE") if args[0] == "workspace": raise Refused("Workspace commands are disabled for profile-scoped stacks") if args[0] == "test": raise Refused("OpenTofu test can override providers; it is not supported through the cluster deployment guard") if args[0] == "state" and len(args) > 1 and args[1] == "push": raise Refused("Arbitrary state pushes have no cluster identity proof; use reviewed migration/recovery") if any(os.environ.get(key) for key in ("KUBE_HOST", "KUBE_CLUSTER_CA_CERT_DATA", "KUBE_INSECURE", "KUBE_TLS_SERVER_NAME", "KUBE_CONFIG_PATH", "KUBE_CONFIG_PATHS", "KUBE_CTX", "KUBE_CTX_CLUSTER", "KUBE_CTX_AUTH_INFO", "KUBE_CONFIG_CONTEXT", "KUBE_PROXY_URL", "KUBERNETES_MASTER")): raise Refused("Kubernetes provider endpoint/CA/context environment overrides are refused") if any(arg.split("=", 1)[0] in ("-state", "-state-out", "-backup", "-backend-config", "-backend", "-migrate-state", "-force-copy", "-config") for arg in args): raise Refused("State/backend overrides are refused; use cluster-context migrate for reviewed legacy state") legacy = directory / "terraform.tfstate" if not state.exists() and legacy.exists(): record = legacy_record(context, legacy) owner = document(record) if record.exists() else {} owner_profile = owner.get("profile", "") owner_binding = context.root.parent / owner_profile / "identity.json" if re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}", owner_profile) else None owner_identity = document(owner_binding) if owner_binding and owner_binding.exists() else {} owned_elsewhere = bool(owner_identity) and owner_profile != context.profile and owner.get("sha256") == hashlib.sha256(legacy.read_bytes()).hexdigest() owned_elsewhere = owned_elsewhere and all(owner.get(field) == owner_identity.get(field) for field in IDENTITY_FIELDS) owned_elsewhere = owned_elsewhere and (context.root.parent / owner_profile / "stacks" / name / "terraform.tfstate").exists() if not owned_elsewhere: raise Refused(f"Legacy {name} state is preserved and is not safely assigned elsewhere. Review ./jeannie cluster-context migrate --stack {name}, then migrate --stack {name} --yes") env = dict(os.environ, TF_DATA_DIR=str(context.root / ".terraform" / name), TF_WORKSPACE="default") env["JEANNIE_PROFILE_TF_DATA"] = env["TF_DATA_DIR"] env["TF_VAR_kubeconfig_path"] = context.kubeconfig base = [tool, f"-chdir={directory}"] with locked(context.root / f".{name}.operation.lock"): state.parent.mkdir(parents=True, exist_ok=True, mode=0o700) # Initialization is local; it never moves legacy state automatically. init_args = args[1:] if args[0] == "init" else [] capture(base + ["init", "-input=false", "-reconfigure", f"-backend-config=path={state}", *init_args], env=env) command = args[0] if command == "init": return 0 mutable = command in ("apply", "destroy", "import", "refresh", "force-unlock", "taint", "untaint") or command == "state" and len(args) > 1 and args[1] not in ("list", "show", "pull") observed = context.check() if mutable else None if command in ("apply", "destroy", "import", "refresh", "plan"): expression = "jsonencode(var.kubeconfig_path)" if name == "cluster": expression = "jsonencode({kubeconfig = var.kubeconfig_path, node = var.control_plane_node_name, host = var.control_plane_host, address = var.control_plane_advertise_address})" kubeconfig = json.loads(capture(base + ["console", *variable_args(args)], text=expression + "\n", env=env)) # jsonencode() returns a JSON string inside the console string. kubeconfig = json.loads(kubeconfig) if name == "cluster": if kubeconfig["node"] != context.expected_node or any(kubeconfig[key] != context.expected_host for key in ("host", "address")): raise Refused("Control-plane provisioner host/name/address does not match the selected profile") kubeconfig = kubeconfig["kubeconfig"] effective = Context(kubeconfig=kubeconfig) # Plans can evaluate declarative imports; validate those reads too. observed = effective.check() saved = [arg for arg in positionals(args[1:]) if (directory / arg).is_file()] if command == "apply" and saved: if len(saved) != 1: raise Refused("Ambiguous saved-plan arguments") saved_path = (directory / saved[0]).resolve() receipt = document(Path(str(saved_path) + ".jeannie-context.json")) observed = Context(kubeconfig=receipt["kubeconfig"]).check() if receipt.get("sha256") != hashlib.sha256(saved_path.read_bytes()).hexdigest() or receipt.get("state") != str(state) or any(receipt.get(field) != observed[field] for field in IDENTITY_FIELDS): raise Refused("Saved plan belongs to a different identity, profile, state, or content") result = subprocess.run(base + args, env=env, check=False) output = plan_path(args, directory) if command == "plan" else None if result.returncode in (0, 2) and output and output.exists(): verified = Context(kubeconfig=kubeconfig).check() receipt_path = Path(str(output) + ".jeannie-context.json") if receipt_path.exists(): receipt_path.unlink() private_write(receipt_path, dict(verified, kubeconfig=kubeconfig, state=str(state), sha256=hashlib.sha256(output.read_bytes()).hexdigest())) return result.returncode def legacy_hints(state, context): for resource in state.get("resources", []): for instance in resource.get("instances", []): attributes = instance.get("attributes", {}) triggers = attributes.get("triggers") or {} path = triggers.get("kubeconfig_path") if path and Path(path).expanduser().resolve() != Path(context.kubeconfig): raise Refused("Legacy state contains a different kubeconfig path; ownership is ambiguous") if resource.get("name") == "kubeadm_control_plane": if triggers.get("node_name") != context.expected_node or triggers.get("advertise_address") != context.expected_host: raise Refused("Legacy control-plane identity does not match the selected profile") def manage(args): context = Context(args.profile, args.kubeconfig) if args.action == "check": print(json.dumps(context.check(), sort_keys=True)) elif args.action == "check-local-host": observed = context.check() addresses = json.loads(capture([binary("ip"), "-j", "address", "show"])) expected_host = context.expected_host if not any(a.get("local") == expected_host for interface in addresses for a in interface.get("addr_info", [])): raise Refused("Local host does not own the selected control-plane address; refusing local cleanup") local_ca = capture([binary("sudo"), "-n", "cat", "/etc/kubernetes/pki/ca.crt"]) if ca_fingerprint(local_ca) != observed["ca_sha256"]: raise Refused("Local control-plane CA does not match the pinned profile; refusing cleanup") elif args.action == "enroll": observed = context.observed() print(json.dumps(dict(observed, identity_file=str(context.binding), kubeconfig=context.kubeconfig), indent=2, sort_keys=True)) if context.binding.exists(): context.check() print("Existing identity matches; no change.") elif args.yes: with locked(context.root.parent / ".enrollment.lock"): if context.binding.exists(): context.check() print("Concurrent enrollment already pinned the same identity; no change.") return 0 for path in context.root.parent.glob("*/identity.json"): if document(path).get("kube_system_uid") == observed["kube_system_uid"]: raise Refused("This cluster is already bound to another profile") private_write(context.binding, observed) print(f"Pinned identity at {context.binding}") else: print("Review these values, then repeat enroll --yes. Nothing was enrolled.") elif args.action == "status": print(json.dumps({"profile": context.profile, "kubeconfig": context.kubeconfig, "identity": document(context.binding) if context.binding.exists() else None, "states": {s: str(context.state(s)) for s in sorted(STACKS)}}, indent=2, sort_keys=True)) elif args.action == "migrate": observed = context.check() source = REPO / "bootstrap" / args.stack / "terraform.tfstate" raw = source.read_bytes() value = json.loads(raw) if not isinstance(value, dict) or value.get("version") != 4 or not value.get("lineage") or not isinstance(value.get("serial"), int) or not isinstance(value.get("resources"), list): raise Refused("Migration requires a complete, unencrypted version-4 infrastructure state snapshot") legacy_hints(value, context) destination = context.state(args.stack) print(json.dumps({"source": str(source), "destination": str(destination), "lineage": value.get("lineage"), "resources": len(value.get("resources", [])), "cluster": observed}, indent=2)) if args.yes: with locked(context.root.parent / ".migration.lock"), locked(context.root / f".{args.stack}.operation.lock"): record_path = legacy_record(context, source) if record_path.exists(): owner = document(record_path) if owner.get("profile") != context.profile or owner.get("sha256") != hashlib.sha256(raw).hexdigest(): raise Refused("Legacy snapshot already has different ownership/content; refusing duplicate adoption") if destination.exists(): if document(destination) == value: print("Identical state already migrated; no change.") else: raise Refused("Scoped state already exists; refusing overwrite") lock = source.with_name(".terraform.tfstate.lock.info") if lock.exists() or source.read_bytes() != raw: raise Refused("Legacy state is locked or changed during review; stop its active operation before migration") if not destination.exists(): private_write(destination, value) if not record_path.exists(): private_write(record_path, dict(observed, source=str(source), sha256=hashlib.sha256(raw).hexdigest())) print("Copied reviewed state; original is retained unchanged.") else: print("Review ownership before repeating migrate --stack NAME --yes. Nothing was copied.") return 0 def main(): if len(sys.argv) >= 3 and sys.argv[1] == "tool": tool = sys.argv[2] if tool == "tofu": return proxy_tofu(sys.argv[3:]) if tool in ("kubectl", "helm"): proxy_client(tool, sys.argv[3:]) raise Refused("Unsupported guarded tool") parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("status", "check", "check-local-host", "enroll", "migrate")) parser.add_argument("--profile") parser.add_argument("--kubeconfig") parser.add_argument("--stack", choices=sorted(STACKS)) parser.add_argument("--yes", action="store_true") args = parser.parse_args() if args.action == "migrate" and not args.stack: parser.error("migrate requires --stack") return manage(args) if __name__ == "__main__": try: sys.exit(main()) except (Refused, OSError, ValueError, KeyError, TypeError, ImportError, subprocess.TimeoutExpired) as error: print(f"Cluster context refused: {error}", file=sys.stderr) sys.exit(1)