From 7daa120baef1028bbe3696ec47f03923b94b265a Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Fri, 30 Oct 2026 22:19:28 -0600 Subject: [PATCH] Isolate Kubernetes profile state and pin cluster identities before mutations --- bootstrap/apps/main.tf | 1 + bootstrap/cluster/main.tf | 1 + bootstrap/platform/README.md | 4 + bootstrap/platform/main.tf | 1 + docs/cluster-context.md | 151 +++++++ jeannie | 27 +- lib/jeannie/cluster-context.sh | 15 + lib/jeannie/commands.sh | 46 +- lib/jeannie/pipeline.sh | 16 +- scripts/cluster-context.py | 493 +++++++++++++++++++++ scripts/guarded-bin/helm | 2 + scripts/guarded-bin/kubectl | 2 + scripts/guarded-bin/tofu | 2 + scripts/heal | 12 + scripts/homelab-backup | 7 + scripts/jeannie-eventd | 16 + scripts/monitoring-readiness.py | 8 + scripts/state-status | 9 +- scripts/workers | 6 + tests/jeannie/test_cluster_context.py | 242 ++++++++++ tests/jeannie/test_monitoring_readiness.py | 13 +- tests/jeannie/test_self_heal_context.py | 10 + 22 files changed, 1051 insertions(+), 33 deletions(-) create mode 100644 docs/cluster-context.md create mode 100644 lib/jeannie/cluster-context.sh create mode 100644 scripts/cluster-context.py create mode 100755 scripts/guarded-bin/helm create mode 100755 scripts/guarded-bin/kubectl create mode 100755 scripts/guarded-bin/tofu create mode 100644 tests/jeannie/test_cluster_context.py diff --git a/bootstrap/apps/main.tf b/bootstrap/apps/main.tf index 0e45186..88d8953 100644 --- a/bootstrap/apps/main.tf +++ b/bootstrap/apps/main.tf @@ -1,4 +1,5 @@ terraform { + backend "local" {} required_version = ">= 1.0" required_providers { kubernetes = { diff --git a/bootstrap/cluster/main.tf b/bootstrap/cluster/main.tf index 3eb639b..d8e626d 100644 --- a/bootstrap/cluster/main.tf +++ b/bootstrap/cluster/main.tf @@ -1,4 +1,5 @@ terraform { + backend "local" {} required_version = ">= 1.0" required_providers { null = { diff --git a/bootstrap/platform/README.md b/bootstrap/platform/README.md index b045c6c..eddb67c 100644 --- a/bootstrap/platform/README.md +++ b/bootstrap/platform/README.md @@ -1,5 +1,9 @@ # Platform components +Kubernetes stacks use [pinned cluster identities and profile-specific state](../../docs/cluster-context.md). +Enroll the intended cluster and review legacy state migration before the first +deployment with this guard. Identity mismatches never trigger automatic adoption. + The platform stack keeps one OpenTofu state file, but Jeannie exposes isolated component applies. A component apply passes only that component's resource addresses as `-target` arguments; OpenTofu includes required dependencies and diff --git a/bootstrap/platform/main.tf b/bootstrap/platform/main.tf index ae8c255..4b8734f 100644 --- a/bootstrap/platform/main.tf +++ b/bootstrap/platform/main.tf @@ -1,4 +1,5 @@ terraform { + backend "local" {} required_version = ">= 1.0" required_providers { helm = { diff --git a/docs/cluster-context.md b/docs/cluster-context.md new file mode 100644 index 0000000..4cb2db9 --- /dev/null +++ b/docs/cluster-context.md @@ -0,0 +1,151 @@ +# Cluster identities and profile-specific state + +Jeannie treats `homelab.yml` as the source of declared cluster profiles. Each +profile has one immutable, locally enrolled binding containing: + +- The exact HTTPS API endpoint (LAN address and port 6443 by default). +- SHA-256 of the DER-encoded cluster CA certificate. +- The UID of the live `kube-system` namespace. +- The profile name. + +The selected inventory control-plane node must also exist with a control-plane +role label. A reused address, replaced CA, or new cluster UID never silently +updates an existing binding. Kubeconfigs must use explicit CA verification and +a single absolute file path. Context aliases are allowed only when they resolve +to the same pinned identity. TLS bypasses and endpoint/CA overrides are refused. + +## Enroll the existing cluster once + +Run on Debian after pulling the change. Preview enrollment first: + +```bash +export LAB_CLUSTER_PROFILE=pimox +./jeannie cluster-context enroll +``` + +Compare the reported endpoint, CA fingerprint, and namespace UID with the +intended cluster. The preview reads the API and writes no identity. After +review, explicitly enroll and verify: + +```bash +./jeannie cluster-context enroll --yes +./jeannie cluster-context check +./jeannie cluster-context status +``` + +Enrollment requires TLS-verified access to the declared endpoint, an explicit +CA, and the declared control-plane node. This first enrollment is an operator +trust decision, not an independent attestation that a never-before-seen cluster +is correct. Repeating it is idempotent for the same identity. `--yes` cannot +replace a mismatched binding, and the same namespace UID cannot be enrolled +under a second profile. There is no automatic rotation or force bypass. + +## Migrate existing state without changing infrastructure + +The Kubernetes stacks `cluster`, `platform`, and `apps` use: + +```text +$HOMELAB_STATE_DIR/clusters//identity.json +$HOMELAB_STATE_DIR/clusters//stacks//terraform.tfstate +$HOMELAB_STATE_DIR/clusters//.terraform// +``` + +`HOMELAB_STATE_DIR` defaults to `~/.local/share/homelab`. Both the local backend +path and `TF_DATA_DIR` are separate per profile and stack. Non-default Terraform +workspaces, arbitrary state pushes, state-file overrides, hidden `TF_CLI_ARGS` overrides, and alternate +import configuration directories are refused for these stacks. The wrapper +serializes each stack's commands in addition to OpenTofu's own backend lock. +OCI foundations, provisioning, and edge are shared infrastructure; their state +locations remain unchanged. + +An unassigned legacy state blocks using an empty scoped state. Review each +legacy file before copying it into the enrolled profile: + +```bash +./jeannie cluster-context migrate --stack cluster +./jeannie cluster-context migrate --stack platform +./jeannie cluster-context migrate --stack apps +``` + +Known control-plane or kubeconfig hints that conflict with the profile cause a +refusal. The preview reports source, destination, lineage, resource count, and +the verified cluster identity. Namespace/release IDs alone cannot establish +which cluster an old state file belongs to: inspect its ownership before +accepting the copy. After reviewing each preview, repeat the same command with +`--yes`. Do not migrate a file that belongs to the other cluster. + +Migration supports complete unencrypted version-4 state snapshots. It preserves +the original file, lineage, serial, and resources; it never +imports, applies, merges, or overwrites newer scoped state. It refuses active +legacy locks or a source that changes during the operation. A content-hashed +ownership ledger prevents assigning the same legacy snapshot to two profiles. +Once a snapshot belongs to one profile, another profile can initialize its own +independent state without consuming that snapshot. An unexplained change in an +unmigrated snapshot blocks automatic adoption. Stop raw legacy writers during +migration; processes launched outside Jeannie do not honor its operation lock. + +State status and both backup collectors include the scoped paths and identity +records. Provider caches and operation locks are excluded from backups. Nuke +no longer deletes shared state paths or kills unrelated OpenTofu processes. +It retains identity and state for reviewed recovery rather than silently +forgetting resource ownership. + +## Guard coverage + +Jeannie prepends repo-owned `tofu`, `kubectl`, and `helm` launchers to its child +process PATH. Kubernetes OpenTofu applies, destroys, imports, and state mutations +verify the binding before the underlying command runs. The effective +`var.kubeconfig_path` is evaluated using the same variable arguments, rather +than trusting a shell default. Cluster provisioner name, host, and advertise +address must match the selected inventory control plane. + +Saved plans get a sidecar receipt bound to their content hash, profile, +identity, provider kubeconfig, and backend path. Applying an unrecognized or +modified saved plan is refused. The provider kubeconfig is verified again at +apply time. The scheduling preflight's temporary plans receive the same checks. + +Mutating kubectl/Helm commands verify their actual kubeconfig/context, including +commands launched by Jeannie child scripts. Host start/stop, worker actions, +local destructive cleanup, pod cleanup, Grafana recovery, and self-heal webhook +apply paths also have explicit entry guards. Local control-plane deletion +additionally checks the host's address and CA. Debian retirement requires +verified identities for both the active Pimox cluster and the retired Debian +cluster; former force/skip-check environment flags do not bypass this guard. + +Read-only kubectl diagnostics and `cluster-context status` remain available +without enrollment. OpenTofu plans also verify identity because they can +evaluate declarative imports. No check result is +cached across mutations. Failed API reads or unavailable authentication are +failures, not evidence of a missing cluster. An unreachable API therefore blocks +mutations, including automatic API-start healing: the guard cannot prove the +current namespace UID offline. First cluster bootstrap, cluster recreation, +CA rotation, and offline recovery need a separately reviewed trust transition; +existing lifecycle commands cannot silently reenroll a replacement cluster. +`rebuild-cluster` therefore refuses before destroying anything; this change +does not provide an automatic new-cluster trust transition. + +This is an accident-prevention boundary for Jeannie-managed operations, not a +sandbox. Direct absolute binary invocations, tools outside Jeannie, privileged +manual file edits, and arbitrary third-party plugins can bypass it. A provider +operation or remote provisioner is verified before it starts; the guard cannot +make a long-running operation atomic with a cluster identity change. Use +Jeannie entry points rather than raw OpenTofu commands for these stacks. + +## Validation on Debian + +No local application or unit tests are run on the development laptop. The +regression suite mocks Kubernetes/Tofu interactions and uses temporary files: + +```bash +python3 -m unittest discover -s tests/jeannie -p 'test_cluster_context.py' +python3 -m unittest discover -s tests/jeannie -p 'test_self_heal_context.py' +python3 -m unittest discover -s tests/jeannie -p 'test_monitoring_readiness.py' +``` + +Live `cluster-context check` verifies the enrolled binding. Test a mismatched +context using that read-only check; do not issue a real apply to demonstrate a +refusal. Check platform/cluster/apps plans only after their state migration is +reviewed. Existing scoped state is never replaced to make a plan pass. + +Backend design references: [OpenTofu local backend](https://opentofu.org/docs/language/settings/backends/local/) +and [OpenTofu CLI environment variables](https://opentofu.org/docs/cli/config/environment-variables/). diff --git a/jeannie b/jeannie index b5445a8..e688c23 100755 --- a/jeannie +++ b/jeannie @@ -22,6 +22,7 @@ JEANNIE_STEP_TOTAL=0 source "${REPO_ROOT}/scripts/report-ui" source "${REPO_ROOT}/lib/jeannie/core.sh" source "${REPO_ROOT}/lib/jeannie/env.sh" +source "${REPO_ROOT}/lib/jeannie/cluster-context.sh" source "${REPO_ROOT}/lib/jeannie/toolchain.sh" source "${REPO_ROOT}/lib/jeannie/pimox.sh" source "${REPO_ROOT}/lib/jeannie/preflight.sh" @@ -38,6 +39,7 @@ oci_foundation_load_config load_homelab_inventory_defaults export_homelab_inventory_tf_vars KUBECONFIG_PATH="${KUBECONFIG_PATH:-${TF_VAR_kubeconfig_path:-${LAB_KUBECONFIG_PATH:-/home/jv/.kube/config}}}" +cluster_context_enable print_usage() { cat <<'EOF' @@ -48,6 +50,8 @@ Base, Inventory, And Planning validate Run repo validation checks. inventory-check Validate the canonical homelab inventory. cluster-profile Print the resolved active cluster profile. + cluster-context {status|check|enroll|migrate} [--yes] [--stack NAME] + Review pinned cluster identity and scoped state. preflight Run non-mutating infrastructure preflight checks. doctor-preapply Run deeper pre-apply safety checks. plan [all|provisioning|cluster|platform|apps|edge] @@ -82,7 +86,7 @@ Build And Bootstrap golden-ledger {show|check} Show or validate Pimox golden image versions. Cluster Lifecycle - rebuild-cluster Recreate the cluster through the guarded path. + rebuild-cluster Refuses automatic rebuild until an identity transition is reviewed. stop-cluster Stop Kubernetes and worker VMs without destroy. start-cluster Start Kubernetes and desired worker VMs. shutdown {plan|apply --yes} Stop homelab services on every managed host; keep Jeannie API. @@ -226,7 +230,28 @@ if [[ "${JEANNIE_LIBRARY_MODE:-false}" == "true" ]]; then return 0 2>/dev/null || exit 0 fi +# Guard operations that also mutate hosts over SSH, beyond kubectl/Tofu. case "${1:-}" in + up|stop-cluster|start-cluster|nuke|cleanup-debian-k8s|move-prometheus-stack-workers) + cluster_context_require || exit 1 + ;; + rebuild-cluster) + cluster_context_require || exit 1 + echo "Automatic rebuild changes the pinned cluster identity; refusing before destruction. A reviewed bootstrap/re-enrollment transition is required." >&2 + exit 1 + ;; + start|shutdown) + if [[ "${2:-plan}" == "apply" ]]; then cluster_context_require || exit 1; fi + ;; + __up-task) + if [[ "${2:-}" == "pimox-workers" ]]; then cluster_context_require || exit 1; fi + ;; +esac + +case "${1:-}" in + cluster-context) + python3 "${REPO_ROOT}/scripts/cluster-context.py" "${@:2}" + ;; __up-task) up_task "${2:-}" ;; diff --git a/lib/jeannie/cluster-context.sh b/lib/jeannie/cluster-context.sh new file mode 100644 index 0000000..dca0081 --- /dev/null +++ b/lib/jeannie/cluster-context.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +cluster_context_require() { + python3 "${REPO_ROOT}/scripts/cluster-context.py" check \ + --profile "${LAB_CLUSTER_PROFILE:?Missing active cluster profile}" \ + --kubeconfig "${KUBECONFIG_PATH}" >/dev/null +} + +cluster_context_enable() { + export HOMELAB_STATE_DIR LAB_CLUSTER_PROFILE KUBECONFIG_PATH + case ":${PATH}:" in + *":${REPO_ROOT}/scripts/guarded-bin:"*) ;; + *) export PATH="${REPO_ROOT}/scripts/guarded-bin:${PATH}" ;; + esac +} diff --git a/lib/jeannie/commands.sh b/lib/jeannie/commands.sh index f48bb95..803f603 100644 --- a/lib/jeannie/commands.sh +++ b/lib/jeannie/commands.sh @@ -129,6 +129,8 @@ EOF cluster_profile_report() { cat </dev/null 2>&1; then - echo "kubectl is required to verify the Pimox cluster before Debian cleanup." >&2 - return 1 - fi - if ! kubectl --kubeconfig "${KUBECONFIG_PATH}" get node "${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-pimox-cp-01}" >/dev/null 2>&1; then - echo "Pimox control-plane node is not reachable through ${KUBECONFIG_PATH}; refusing Debian cleanup." >&2 - return 1 - fi + if ! sudo test -e /etc/kubernetes/pki/ca.crt && ! sudo test -d /var/lib/etcd/member; then + echo "No Debian control-plane data remains; skipping retirement cleanup." + return 0 fi + # Retirement touches a different cluster from the active Pimox profile. + python3 "${REPO_ROOT}/scripts/cluster-context.py" check-local-host --profile debian || return 1 echo "Cleaning Debian-hosted Kubernetes runtime now that the active cluster profile is Pimox..." echo "--> Disabling kubelet so the old local control plane does not restart on reboot..." @@ -2977,11 +2978,10 @@ EOF chmod 0600 "${worker_known_hosts_file}" fi - echo "--> Terminating local OpenTofu tasks..." - killall tofu terraform 2>/dev/null || true + echo "OpenTofu processes for other profiles are preserved; state locks remain authoritative." echo "--> Eviscerating local Kubernetes components..." - cleanup_node + cleanup_node || return 1 sudo rm -f "${KUBECONFIG_PATH}" for target in "${CLUSTER_WORKER_TARGETS[@]}"; do @@ -3097,19 +3097,7 @@ EOF echo "--> Backing up local OpenTofu tracking state files..." backup_tofu_state - echo "--> Deleting OpenTofu tracking state files..." - rm -rf "${REPO_ROOT}"/bootstrap/cluster/terraform.tfstate* - rm -f "${REPO_ROOT}"/bootstrap/cluster/.terraform.tfstate.lock.info - rm -rf "${REPO_ROOT}"/bootstrap/cluster/.terraform/ - rm -rf "${REPO_ROOT}"/bootstrap/platform/terraform.tfstate* - rm -f "${REPO_ROOT}"/bootstrap/platform/.terraform.tfstate.lock.info - rm -rf "${REPO_ROOT}"/bootstrap/platform/.terraform/ - rm -rf "${REPO_ROOT}"/bootstrap/apps/terraform.tfstate* - rm -f "${REPO_ROOT}"/bootstrap/apps/.terraform.tfstate.lock.info - rm -rf "${REPO_ROOT}"/bootstrap/apps/.terraform/ - rm -rf "${REPO_ROOT}"/bootstrap/edge/terraform.tfstate* - rm -f "${REPO_ROOT}"/bootstrap/edge/.terraform.tfstate.lock.info - rm -rf "${REPO_ROOT}"/bootstrap/edge/.terraform/ + echo "Profile identities, scoped states, legacy states and shared edge state are retained for reviewed recovery." rm -f "${REPO_ROOT}/.lab/pimox-workers.tsv" "${REPO_ROOT}/.lab/cluster-workers.auto.tfvars.json" echo "Destruction complete. Retained data under /data/openebs/local was left intact." @@ -3625,6 +3613,10 @@ self_heal() { echo "LAB_SELF_HEAL_APPLY must be true or false." >&2 return 2 fi + if [[ "${apply_mode}" == true ]]; then + python3 "${REPO_ROOT}/scripts/cluster-context.py" check \ + --profile "${LAB_CLUSTER_PROFILE}" --kubeconfig "${KUBECONFIG}" >/dev/null || return 1 + fi if [[ ! -r "${KUBECONFIG}" ]]; then echo "Self-heal kubeconfig is not readable: ${KUBECONFIG}" >&2 return 1 diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index 666af88..c926a55 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -944,6 +944,10 @@ run_tofu_stack() { local -a apply_args=() local target + if [[ "${stack}" == "bootstrap/cluster" || "${stack}" == "bootstrap/platform" || "${stack}" == "bootstrap/apps" ]]; then + cluster_context_require || return 1 + fi + # Component applies use OpenTofu targets. Dependencies inside the selected # component are included; cross-component prerequisites must already exist. while (($#)); do @@ -1559,6 +1563,7 @@ backup_tofu_state() { local timestamp local archive local -a paths=() + local -a scoped_paths=() local path timestamp="$(date +%Y%m%d-%H%M%S)" @@ -1588,12 +1593,16 @@ backup_tofu_state() { fi done - if ((${#paths[@]} == 0)); then + if [[ -d "${HOMELAB_STATE_DIR}/clusters" ]]; then + scoped_paths=(-C "${HOMELAB_STATE_DIR}" clusters) + fi + if ((${#paths[@]} == 0 && ${#scoped_paths[@]} == 0)); then echo "No local OpenTofu state files found to back up." return 0 fi - tar -C "${REPO_ROOT}" -czf "${archive}" "${paths[@]}" + tar --exclude='clusters/*/.terraform' --exclude='*.operation.lock' --exclude='.enrollment.lock' --exclude='.migration.lock' \ + -C "${REPO_ROOT}" -czf "${archive}" "${paths[@]}" "${scoped_paths[@]}" chmod 0600 "${archive}" echo "Backed up local OpenTofu state to ${archive}." } @@ -4672,6 +4681,9 @@ cleanup_mounts() { } cleanup_node() { + # A remote profile must never authorize wiping an unrelated local cluster. + python3 "${REPO_ROOT}/scripts/cluster-context.py" check-local-host \ + --profile "${LAB_CLUSTER_PROFILE}" || return 1 sudo kubeadm reset --force || true sudo systemctl stop kubelet 2>/dev/null || true sudo systemctl stop containerd 2>/dev/null || true diff --git a/scripts/cluster-context.py b/scripts/cluster-context.py new file mode 100644 index 0000000..01bea1e --- /dev/null +++ b/scripts/cluster-context.py @@ -0,0 +1,493 @@ +#!/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) diff --git a/scripts/guarded-bin/helm b/scripts/guarded-bin/helm new file mode 100755 index 0000000..c232eea --- /dev/null +++ b/scripts/guarded-bin/helm @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +exec python3 "$(dirname "${BASH_SOURCE[0]}")/../cluster-context.py" tool helm "$@" diff --git a/scripts/guarded-bin/kubectl b/scripts/guarded-bin/kubectl new file mode 100755 index 0000000..c646740 --- /dev/null +++ b/scripts/guarded-bin/kubectl @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +exec python3 "$(dirname "${BASH_SOURCE[0]}")/../cluster-context.py" tool kubectl "$@" diff --git a/scripts/guarded-bin/tofu b/scripts/guarded-bin/tofu new file mode 100755 index 0000000..83d87ac --- /dev/null +++ b/scripts/guarded-bin/tofu @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +exec python3 "$(dirname "${BASH_SOURCE[0]}")/../cluster-context.py" tool tofu "$@" diff --git a/scripts/heal b/scripts/heal index 03bae06..c4c7d94 100755 --- a/scripts/heal +++ b/scripts/heal @@ -413,6 +413,8 @@ def apply_plan(plan: list[dict[str, object]], yes: bool) -> int: if not yes: print(f"would run: {command}") else: + if not cluster_identity_ok(): + return 1 print(f"run: {command}") process = subprocess.run(command.split(), cwd=REPO_ROOT, text=True, check=False) if process.returncode != 0: @@ -564,6 +566,8 @@ def cleanup_stale_pods(yes: bool) -> int: return 0 for pod in pods: + if not cluster_identity_ok(): + return 1 command = [ "kubectl", "--kubeconfig", @@ -582,6 +586,14 @@ def cleanup_stale_pods(yes: bool) -> int: return 0 +def cluster_identity_ok() -> bool: + result = subprocess.run( + [sys.executable, str(REPO_ROOT / "scripts/cluster-context.py"), "check", "--kubeconfig", str(DEFAULT_KUBECONFIG)], + cwd=REPO_ROOT, text=True, stdout=subprocess.DEVNULL, check=False, + ) + return result.returncode == 0 + + def load_heal_state() -> dict[str, object]: if not HEAL_STATE_FILE.is_file(): return {"failed_actions": {}} diff --git a/scripts/homelab-backup b/scripts/homelab-backup index e3b0e6c..703b588 100755 --- a/scripts/homelab-backup +++ b/scripts/homelab-backup @@ -141,6 +141,13 @@ collect_tofu_state() { done latest_file "${TOFU_BACKUP_DIR}" 'tofu-state-*.tgz' >"${state_dir}/latest-tofu-backup.txt" || true + if [[ -d "${HOMELAB_STATE_DIR}/clusters" ]]; then + while IFS= read -r path; do + copy_if_present "${path}" "${state_dir}/clusters/${path#"${HOMELAB_STATE_DIR}/clusters/"}" + done < <(find "${HOMELAB_STATE_DIR}/clusters" -type d -name .terraform -prune -o \ + -type f \( -name identity.json -o -name terraform.tfstate -o -name terraform.tfstate.backup \ + -o -path '*/legacy-adoptions/*.json' \) -print) + fi } collect_gitea_backup_inventory() { diff --git a/scripts/jeannie-eventd b/scripts/jeannie-eventd index 12e342e..aa527c2 100755 --- a/scripts/jeannie-eventd +++ b/scripts/jeannie-eventd @@ -10,6 +10,7 @@ import json import os import re import subprocess +import sys from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from typing import Any @@ -185,6 +186,21 @@ def write_text(path: Path, text: str) -> None: def run_command(command: list[str], audit_dir: Path, name: str) -> subprocess.CompletedProcess[str]: + if name in {"disk-heal", "api-heal", "pod-heal", "heal-apply"}: + guard_command = [sys.executable, str(REPO_ROOT / "scripts/cluster-context.py"), "check"] + kubeconfig = os.environ.get("KUBECONFIG") or os.environ.get("LAB_KUBECONFIG_PATH") + if kubeconfig: + guard_command.extend(["--kubeconfig", kubeconfig]) + guard = subprocess.run( + guard_command, + cwd=REPO_ROOT, text=True, capture_output=True, check=False, + ) + if guard.returncode: + write_text(audit_dir / f"{name}.stderr.log", guard.stderr) + write_text(audit_dir / f"{name}.cmd", " ".join(command) + "\n") + write_text(audit_dir / f"{name}.status", str(guard.returncode) + "\n") + return subprocess.CompletedProcess(command, guard.returncode, "", guard.stderr) + write_text(audit_dir / f"{name}.identity.json", guard.stdout) process = subprocess.run( command, cwd=REPO_ROOT, diff --git a/scripts/monitoring-readiness.py b/scripts/monitoring-readiness.py index 37b36f1..a537665 100644 --- a/scripts/monitoring-readiness.py +++ b/scripts/monitoring-readiness.py @@ -6,6 +6,7 @@ import json import subprocess import sys import time +from pathlib import Path from urllib.parse import quote @@ -146,6 +147,13 @@ def recover_stale_grafana(args, items): "propagationPolicy": "Orphan", } path = "/api/v1/namespaces/" + quote(args.namespace, safe="") + "/pods/" + quote(metadata["name"], safe="") + guard = subprocess.run( + [sys.executable, str(Path(__file__).resolve().with_name("cluster-context.py")), + "check", "--kubeconfig", args.kubeconfig], + text=True, stdout=subprocess.DEVNULL, check=False, + ) + if guard.returncode: + raise RuntimeError("Cluster identity check refused Grafana recovery") print(f"Recovering stale unscheduled Grafana pod {metadata['name']}; PVC preserved.", flush=True) try: # UID/RV preconditions prevent deleting a replacement or a pod that diff --git a/scripts/state-status b/scripts/state-status index d798d06..a40cd62 100755 --- a/scripts/state-status +++ b/scripts/state-status @@ -8,6 +8,7 @@ import json import os import re import subprocess +import sys from pathlib import Path STACKS = { @@ -24,6 +25,11 @@ def inspect_stack(repo: Path, name: str, relative: str) -> dict: directory = repo / relative row = {"stack": name, "path": relative, "state": "missing", "lock": "clear", "drift": "unknown"} state_file = directory / "terraform.tfstate" + if name in {"cluster", "platform", "apps"} or relative in {"bootstrap/cluster", "bootstrap/platform", "bootstrap/apps"}: + context = json.loads(subprocess.check_output( + [sys.executable, str(repo / "scripts/cluster-context.py"), "status"], text=True, + )) + state_file = Path(context["states"][directory.name]) if relative == "bootstrap/oci" and os.environ.get("LAB_OCI_FOUNDATION_STATE_FILE"): state_file = Path(os.environ["LAB_OCI_FOUNDATION_STATE_FILE"]).expanduser() row["state_path"] = str(state_file) @@ -41,7 +47,8 @@ def inspect_stack(repo: Path, name: str, relative: str) -> dict: row["lock_info"] = {"detail": "lock metadata is not valid JSON"} command = [ - "tofu", + sys.executable, + str(repo / "scripts/cluster-context.py"), "tool", "tofu", f"-chdir={directory}", "plan", "-input=false", diff --git a/scripts/workers b/scripts/workers index f5a3bc2..ad7c83a 100755 --- a/scripts/workers +++ b/scripts/workers @@ -2,6 +2,7 @@ set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +export PATH="${REPO_ROOT}/scripts/guarded-bin:${PATH}" KUBECONFIG_PATH="${KUBECONFIG:-${LAB_KUBECONFIG_PATH:-/home/jv/.kube/config}}" PIMOX_HOST="${LAB_PIMOX_HOST:-192.168.100.80}" PIMOX_USER="${LAB_PIMOX_USER:-jv}" @@ -438,6 +439,11 @@ PY "${cmd[@]}" } +case "${1:-}" in + list|disk-status|recreate-plan|help|-h|--help|"") ;; + *) python3 "${REPO_ROOT}/scripts/cluster-context.py" check --kubeconfig "${KUBECONFIG_PATH}" >/dev/null || exit 1 ;; +esac + case "${1:-}" in list) list_workers diff --git a/tests/jeannie/test_cluster_context.py b/tests/jeannie/test_cluster_context.py new file mode 100644 index 0000000..8adce97 --- /dev/null +++ b/tests/jeannie/test_cluster_context.py @@ -0,0 +1,242 @@ +"""Cluster identity/state regressions. Execute on the Debian deployment host.""" + +import base64 +import importlib.util +import json +import os +import ssl +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + + +SPEC = importlib.util.spec_from_file_location( + "cluster_context", Path(__file__).resolve().parents[2] / "scripts/cluster-context.py" +) +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + + +class ClusterContextTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name).resolve() + profiles = { + name: {"control_plane": {"node_name": name + "-cp", "lan_ip": ip, + "kubeconfig": str(self.root / (name + ".yaml"))}} + for name, ip in (("pimox", "192.0.2.10"), ("debian", "192.0.2.20")) + } + inventory = self.root / "homelab.yml" + inventory.write_text(json.dumps({"cluster": {"active_profile": "pimox", "profiles": profiles}})) + self.environment = patch.dict(os.environ, { + "HOMELAB_INVENTORY_FILE": str(inventory), "HOMELAB_STATE_DIR": str(self.root / "state"), + "LAB_CLUSTER_PROFILE": "pimox", + }, clear=True) + self.environment.start() + self.addCleanup(self.environment.stop) + # Synthetic PEM bytes are sufficient for hashing tests. No TLS server + # is used; real kubectl performs certificate validation in deployment. + self.pem = ssl.DER_cert_to_PEM_cert(b"test-ca") + self.server = "https://192.0.2.10:6443" + self.uid = "cluster-original" + self.insecure = False + self.calls = [] + self.binary = patch.object(MODULE, "binary", side_effect=lambda name: "/mock/" + name) + self.binary.start() + self.addCleanup(self.binary.stop) + self.capture = patch.object(MODULE, "capture", side_effect=self.read) + self.capture.start() + self.addCleanup(self.capture.stop) + self.context = MODULE.Context() + + def read(self, command, **kwargs): + self.calls.append(command) + if "init" in command: + return "" + if "console" in command: + return json.dumps(json.dumps(self.context.kubeconfig)) + if "view" in command: + return json.dumps({"clusters": [{"cluster": { + "server": self.server, "insecure-skip-tls-verify": self.insecure, + "certificate-authority-data": base64.b64encode(self.pem.encode()).decode(), + }}]}) + if "namespace" in command: + return json.dumps({"metadata": {"uid": self.uid}}) + if "node" in command: + return json.dumps({"metadata": {"labels": {"node-role.kubernetes.io/control-plane": ""}}}) + raise AssertionError("Unexpected read") + + def pin(self): + value = self.context.observed() + MODULE.private_write(self.context.binding, value) + self.calls.clear() + return value + + def test_each_profile_has_different_state_and_backend_metadata_roots(self): + other = MODULE.Context(profile="debian") + self.assertNotEqual(other.state("platform"), self.context.state("platform")) + self.assertNotEqual(other.root / ".terraform", self.context.root / ".terraform") + + def test_unenrolled_mutations_are_refused_without_api_reads(self): + with self.assertRaisesRegex(MODULE.Refused, "not enrolled"): + self.context.check() + self.assertEqual(self.calls, []) + + def test_matching_endpoint_ca_and_uid_are_accepted(self): + pinned = self.pin() + self.assertEqual(self.context.check(), pinned) + + def test_wrong_endpoint_is_refused_before_authenticated_api_read(self): + self.pin() + self.server = "https://192.0.2.20:6443" + with self.assertRaisesRegex(MODULE.Refused, "endpoint mismatch"): + self.context.check() + self.assertEqual(len(self.calls), 1) + + def test_ca_change_is_refused_before_authenticated_api_read(self): + self.pin() + self.pem = ssl.DER_cert_to_PEM_cert(b"replaced-ca") + with self.assertRaisesRegex(MODULE.Refused, "CA fingerprint mismatch"): + self.context.check() + self.assertEqual(len(self.calls), 1) + + def test_recreated_cluster_with_same_endpoint_and_ca_is_refused(self): + original = self.pin() + self.uid = "cluster-recreated" + with self.assertRaisesRegex(MODULE.Refused, "identity mismatch"): + self.context.check() + self.assertEqual(MODULE.document(self.context.binding), original) + + def test_insecure_kubeconfig_is_refused(self): + self.insecure = True + with self.assertRaisesRegex(MODULE.Refused, "Insecure TLS"): + self.context.observed() + + def test_enrollment_is_review_only_until_yes(self): + MODULE.manage(SimpleNamespace(action="enroll", profile=None, kubeconfig=None, yes=False)) + self.assertFalse(self.context.binding.exists()) + + def test_repeat_enrollment_never_rebinds_a_different_uid(self): + original = self.pin() + self.uid = "replacement" + with self.assertRaises(MODULE.Refused): + MODULE.manage(SimpleNamespace(action="enroll", profile=None, kubeconfig=None, yes=True)) + self.assertEqual(MODULE.document(self.context.binding), original) + + def test_private_publication_cannot_overwrite_existing_record(self): + original = self.pin() + with self.assertRaises(FileExistsError): + MODULE.private_write(self.context.binding, dict(original, kube_system_uid="other")) + self.assertEqual(MODULE.document(self.context.binding), original) + self.assertEqual(list(self.context.root.glob(".context-*")), []) + + def test_legacy_state_with_other_profile_hints_is_refused(self): + state = {"resources": [{"name": "kubeadm_control_plane", "instances": [{"attributes": { + "triggers": {"node_name": "debian-cp", "advertise_address": "192.0.2.20"} + }}]}]} + with self.assertRaisesRegex(MODULE.Refused, "control-plane identity"): + MODULE.legacy_hints(state, self.context) + + def test_explicit_connection_override_is_refused(self): + with self.assertRaises(MODULE.Refused): + MODULE.connection_options(["--server=https://other:6443", "apply", "-f", "x.yaml"], "kubectl") + + def test_remote_exec_arguments_do_not_change_guarded_connection(self): + self.assertEqual(MODULE.connection_options(["exec", "pod", "--", "example", "--server=remote"], "kubectl"), (None, None)) + + def test_separate_var_file_is_not_a_saved_plan(self): + self.assertEqual(MODULE.positionals(["-var-file", "vars.tfvars", "-parallelism=1", "saved.plan"]), ["saved.plan"]) + + def stack(self): + repo = self.root / "repo" + directory = repo / "bootstrap/platform" + directory.mkdir(parents=True, exist_ok=True) + return repo, directory + + def test_legacy_state_prevents_an_empty_new_profile_apply(self): + repo, directory = self.stack() + (directory / "terraform.tfstate").write_text('{"resources": []}') + with patch.object(MODULE, "REPO", repo), patch.object(MODULE.subprocess, "run") as execute: + with self.assertRaisesRegex(MODULE.Refused, "Legacy platform state"): + MODULE.proxy_tofu([f"-chdir={directory}", "apply", "-auto-approve"]) + execute.assert_not_called() + + def test_identity_mismatch_prevents_underlying_tofu_apply(self): + self.pin() + self.uid = "replacement" + repo, directory = self.stack() + with patch.object(MODULE, "REPO", repo), patch.object(MODULE.subprocess, "run") as execute: + with self.assertRaisesRegex(MODULE.Refused, "identity mismatch"): + MODULE.proxy_tofu([f"-chdir={directory}", "apply", "-auto-approve"]) + execute.assert_not_called() + + def test_foreign_saved_plan_without_receipt_cannot_apply(self): + self.pin() + repo, directory = self.stack() + saved = directory / "foreign.plan" + saved.write_bytes(b"not a trusted plan") + with patch.object(MODULE, "REPO", repo), patch.object(MODULE.subprocess, "run") as execute: + with self.assertRaises(FileNotFoundError): + MODULE.proxy_tofu([f"-chdir={directory}", "apply", str(saved)]) + execute.assert_not_called() + + def test_reviewed_migration_preserves_original_and_is_idempotent(self): + self.pin() + repo, directory = self.stack() + source = directory / "terraform.tfstate" + raw = '{"version":4,"lineage":"original","serial":7,"resources":[]}' + source.write_text(raw) + args = SimpleNamespace(action="migrate", profile=None, kubeconfig=None, stack="platform", yes=True) + with patch.object(MODULE, "REPO", repo): + MODULE.manage(args) + MODULE.manage(args) + self.assertEqual(source.read_text(), raw) + self.assertEqual(MODULE.document(self.context.state("platform")), json.loads(raw)) + + def test_migration_will_not_overwrite_a_newer_scoped_state(self): + self.pin() + repo, directory = self.stack() + (directory / "terraform.tfstate").write_text('{"version":4,"lineage":"original","serial":1,"resources":[]}') + MODULE.private_write(self.context.state("platform"), {"version": 4, "lineage": "original", "serial": 2, "resources": []}) + args = SimpleNamespace(action="migrate", profile=None, kubeconfig=None, stack="platform", yes=True) + with patch.object(MODULE, "REPO", repo): + with self.assertRaisesRegex(MODULE.Refused, "refusing overwrite"): + MODULE.manage(args) + + def test_one_legacy_snapshot_cannot_be_adopted_into_two_profiles(self): + self.pin() + repo, directory = self.stack() + (directory / "terraform.tfstate").write_text('{"version":4,"lineage":"original","serial":1,"resources":[]}') + args = SimpleNamespace(action="migrate", profile="pimox", kubeconfig=None, stack="platform", yes=True) + with patch.object(MODULE, "REPO", repo): + MODULE.manage(args) + self.server = "https://192.0.2.20:6443" + self.uid = "other-cluster" + other = MODULE.Context(profile="debian") + MODULE.private_write(other.binding, other.observed()) + args.profile = "debian" + with self.assertRaisesRegex(MODULE.Refused, "different ownership"): + MODULE.manage(args) + self.assertFalse(other.state("platform").exists()) + + def test_another_profile_can_initialize_without_reusing_claimed_state(self): + self.pin() + repo, directory = self.stack() + (directory / "terraform.tfstate").write_text('{"version":4,"lineage":"original","serial":1,"resources":[]}') + args = SimpleNamespace(action="migrate", profile="pimox", kubeconfig=None, stack="platform", yes=True) + with patch.object(MODULE, "REPO", repo): + MODULE.manage(args) + self.server = "https://192.0.2.20:6443" + self.uid = "other-cluster" + other = MODULE.Context(profile="debian") + MODULE.private_write(other.binding, other.observed()) + with patch.dict(os.environ, {"LAB_CLUSTER_PROFILE": "debian"}): + self.assertEqual(MODULE.proxy_tofu([f"-chdir={directory}", "init"]), 0) + self.assertFalse(other.state("platform").exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/jeannie/test_monitoring_readiness.py b/tests/jeannie/test_monitoring_readiness.py index db420f2..808ec36 100644 --- a/tests/jeannie/test_monitoring_readiness.py +++ b/tests/jeannie/test_monitoring_readiness.py @@ -127,14 +127,23 @@ class StaleGrafanaRecoveryTests(unittest.TestCase): def test_only_pod_delete_with_uid_and_version_preconditions_is_sent(self): import json - args = SimpleNamespace(release="prometheus-stack", namespace="monitoring") - with patch.object(MODULE, "kubectl", side_effect=[{"items": [self.pod]}, self.sts, {}]) as call: + args = SimpleNamespace(release="prometheus-stack", namespace="monitoring", kubeconfig="/tmp/test-kubeconfig") + with patch.object(MODULE.subprocess, "run", return_value=SimpleNamespace(returncode=0)), \ + patch.object(MODULE, "kubectl", side_effect=[{"items": [self.pod]}, self.sts, {}]) as call: MODULE.recover_stale_grafana(args, [self.sts]) request = call.call_args self.assertEqual(request.args[1:], ("delete", "--raw", "/api/v1/namespaces/monitoring/pods/prometheus-stack-grafana-0", "-f", "-")) self.assertEqual(json.loads(request.kwargs["input_text"])["preconditions"], {"uid": "old-pod-uid", "resourceVersion": "42"}) + def test_identity_failure_prevents_recovery_delete(self): + args = SimpleNamespace(release="prometheus-stack", namespace="monitoring", kubeconfig="/tmp/test-kubeconfig") + with patch.object(MODULE.subprocess, "run", return_value=SimpleNamespace(returncode=1)), \ + patch.object(MODULE, "kubectl", side_effect=[{"items": [self.pod]}, self.sts]) as call: + with self.assertRaisesRegex(RuntimeError, "identity check refused"): + MODULE.recover_stale_grafana(args, [self.sts]) + self.assertEqual(call.call_count, 2) + if __name__ == "__main__": unittest.main() diff --git a/tests/jeannie/test_self_heal_context.py b/tests/jeannie/test_self_heal_context.py index 30a11cc..62c204f 100644 --- a/tests/jeannie/test_self_heal_context.py +++ b/tests/jeannie/test_self_heal_context.py @@ -71,6 +71,16 @@ class WebhookRoutingTests(unittest.TestCase): self.assertIn("OCI foundation config", (audit / "doctor.stderr.log").read_text()) self.assertEqual(run.call_args.kwargs["stderr"], subprocess.PIPE) + def test_identity_failure_prevents_webhook_mutation(self): + refused = subprocess.CompletedProcess([], 1, stdout="", stderr="cluster identity mismatch") + with tempfile.TemporaryDirectory() as temporary: + with patch.object(self.module.subprocess, "run", return_value=refused) as run: + result = self.module.run_command(["./jeannie", "start-cluster"], Path(temporary), "api-heal") + self.assertEqual(run.call_count, 1) + self.assertEqual(result.returncode, 1) + self.assertEqual((Path(temporary) / "api-heal.status").read_text(), "1\n") + self.assertIn("cluster-context.py", run.call_args.args[0][1]) + def test_eviction_alert_selects_cleanup_without_broad_doctor_or_restart(self): completed = subprocess.CompletedProcess([], 0, stdout="cleanup complete", stderr="") with tempfile.TemporaryDirectory() as temporary, \