#!/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 import time 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") # Exact create-only recovery body reviewed for the orphan-marker migration. # Any source change requires a fresh review before this exception can apply. KYVERNO_RECOVERY_SHA256 = "ae8fc238d55b0e5551c37eda2db94c16072f36994ca034552e4339cb4fedcf38" 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 failure_diagnostic(directory, operation, result): path = Path(directory) / f"{operation}-{time.time_ns()}-{os.getpid()}.json" private_write(path, {"operation": operation, "exit_code": result.returncode, "stdout": result.stdout, "stderr": result.stderr}) return path def safe_error_titles(output): # Print only recognized static headings. HCL source snippets and provider # responses can include secrets and remain in the private diagnostic file. titles = { "Invalid backend configuration argument", "Failed to get existing workspaces", "Failed to load state", "Failed to read state", "Error refreshing state", "Failed to install provider", "Failed to query available provider packages", "Inconsistent dependency lock file", "Error acquiring the state lock", "Unsupported Terraform Core version", "Unsupported OpenTofu Core version", "Backend configuration changed", "Unsupported block type", "Invalid expression", "Missing required argument", "Duplicate provider configuration", "Failed to create local state file", "Failed to update workspace", "Invalid single-argument block definition", "Invalid backend configuration", } clean = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", output) found = [] for line in clean.splitlines(): match = re.match(r"^[\s│╷╵]*Error:\s*(.+?)\s*$", line) if match and match[1] in titles and match[1] not in found: found.append(match[1]) return found def capture(command, *, text=None, env=None, diagnostic_dir=None): try: result = subprocess.run(command, input=text, text=True, capture_output=True, timeout=90, env=env, check=False) except subprocess.TimeoutExpired as error: def decoded(value): return value.decode(errors="replace") if isinstance(value, bytes) else value or "" result = subprocess.CompletedProcess(command, 124, decoded(error.stdout), decoded(error.stderr) + "\nCommand timed out after 90 seconds.") 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") detail = "" if diagnostic_dir is not None: headings = safe_error_titles(result.stdout + "\n" + result.stderr) if headings: detail += "; " + "; ".join(headings) try: path = failure_diagnostic(diagnostic_dir, operation, result) detail += f"\nPrivate diagnostic (mode 0600): {path}" except OSError: detail += "\nPrivate diagnostic could not be written; check profile-directory permissions and free space." raise Refused(f"{Path(command[0]).name} {operation} failed: {reason} (exit {result.returncode}); requested action was not started{detail}") 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: os.fchmod(descriptor, 0o600) 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 verify_backend_metadata(path, state): metadata = document(path) backend = metadata.get("backend") or {} target = backend.get("config", {}).get("path") if backend.get("type") != "local" or not isinstance(target, str) or not Path(target).is_absolute() or Path(target).resolve() != state.resolve(): raise Refused("Cached backend does not point to this profile's scoped state; refusing initialization") def initialize_scoped_backend(tool, directory, context, name, env, init_args): """Initialize backend metadata without exposing legacy files to init. OpenTofu 1.12.6 treats -reconfigure as first initialization and scans the configuration directory for default local state. Seed its metadata using an empty configuration directory, then reuse it in the real module. Never approve a copy from the retained legacy state into the scoped state. """ state = context.state(name) metadata = Path(env["TF_DATA_DIR"]) / "terraform.tfstate" before = state.read_bytes() if state.exists() else None diagnostics = context.root / "diagnostics" / name backend_args = [f"-backend-config=path={state}"] try: if metadata.exists(): verify_backend_metadata(metadata, state) else: dependency_lock = directory / ".terraform.lock.hcl" if before and document(state).get("resources") and not dependency_lock.is_file(): raise Refused("A dependency lock file is required before initializing migrated state") with tempfile.TemporaryDirectory(prefix=f"backend-init-{name}-", dir=context.root) as temporary: bootstrap = Path(temporary) (bootstrap / "main.tf").write_text('terraform {\n backend "local" {}\n}\n') # init also considers providers referenced in state. Preserve # the real module's locked versions rather than selecting latest. if dependency_lock.is_file(): shutil.copyfile(dependency_lock, bootstrap / ".terraform.lock.hcl") capture([tool, f"-chdir={bootstrap}", "init", "-input=false", "-no-color", "-get=false", "-lockfile=readonly", *backend_args], env=env, diagnostic_dir=diagnostics) verify_backend_metadata(metadata, state) # Do not pass -reconfigure here: it would discard the verified metadata # and discover the repository's legacy terraform.tfstate again. capture([tool, f"-chdir={directory}", "init", "-input=false", "-no-color", *backend_args, *init_args], env=env, diagnostic_dir=diagnostics) verify_backend_metadata(metadata, state) finally: if before is not None and (not state.exists() or state.read_bytes() != before): raise Refused("Initialization unexpectedly changed scoped state; refusing further operations. Preserve the diagnostic and both state snapshots for review.") 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", "-reconfigure", "-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) init_args = args[1:] if args[0] == "init" else [] initialize_scoped_backend(tool, directory, context, name, env, init_args) 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, diagnostic_dir=context.root / "diagnostics" / name)) # 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 orphan_kyverno_helper(resource, instance, state, stack): """A create-only recovery marker is not a Helm resource ownership claim. Deliberately scoped to the observed root-level orphan. Do not generalize this exception to other helpers or to tracked infrastructure resources. """ if stack != "platform" or resource.get("module") or resource.get("type") != "null_resource" or resource.get("name") != "kyverno_helm_recovery": return False if resource.get("mode", "managed") != "managed" or instance.get("index_key") is not None: return False if len(resource.get("instances", [])) != 1 or not instance.get("attributes", {}).get("id"): return False if sum(not item.get("module") and item.get("mode", "managed") == "managed" and item.get("type") == "null_resource" and item.get("name") == "kyverno_helm_recovery" for item in state.get("resources", [])) != 1: return False if any(item.get("type") == "helm_release" and item.get("name") == "kyverno" and item.get("instances") for item in state.get("resources", [])): return False triggers = instance.get("attributes", {}).get("triggers") or {} if triggers.get("release_name") != "kyverno" or not triggers.get("namespace"): return False source = (REPO / "bootstrap/platform/main.tf").read_text() marker = 'resource "null_resource" "kyverno_helm_recovery" {' if source.count(marker) != 1: return False block = re.split(r"(?m)^resource\s", source.split(marker, 1)[1], maxsplit=1)[0] return hashlib.sha256((marker + block).encode()).hexdigest() == KYVERNO_RECOVERY_SHA256 def legacy_hints(state, context, stack=None): stale_helpers = [] 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): address = ".".join(filter(None, [resource.get("module"), resource.get("type"), resource.get("name")])) if orphan_kyverno_helper(resource, instance, state, stack): stale_helpers.append({ "address": address, "historical_kubeconfig": path, "planned_kubeconfig": context.kubeconfig, "state_id": attributes["id"], "action": "exclude-from-scoped-copy", "reason": "Create-only orphan marker; no tracked Kyverno Helm release. Original state retains the record; the new helper will use the selected profile.", }) else: raise Refused(f"Legacy {address} 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") return stale_helpers 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") stale_helpers = legacy_hints(value, context, args.stack) excluded = {item["address"] for item in stale_helpers} copied = dict(value) copied["resources"] = [resource for resource in value["resources"] if resource.get("mode", "managed") != "managed" or ".".join(filter(None, [resource.get("module"), resource.get("type"), resource.get("name")])) not in excluded] if excluded: copied["serial"] = value["serial"] + 1 destination = context.state(args.stack) print(json.dumps({"source": str(source), "destination": str(destination), "lineage": value.get("lineage"), "resources": len(value["resources"]), "copied_resources": len(copied["resources"]), "source_serial": value["serial"], "destination_serial": copied["serial"], "cluster": observed, "stale_execution_helpers": stale_helpers}, 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) == copied: 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, copied) if not record_path.exists(): private_write(record_path, dict(observed, source=str(source), sha256=hashlib.sha256(raw).hexdigest(), stale_execution_helpers=stale_helpers)) 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)