#!/usr/bin/env python3 """Break only the local image-policy bootstrap cycle, preserving fail-closed app admission.""" import argparse import copy import json import os from pathlib import Path import subprocess import sys import time POLICY = "homelab-local-registry-supply-chain" EXCLUSION = {"key": "kubernetes.io/metadata.name", "operator": "NotIn", "values": ["container-registry", "kyverno"]} def selector_with_exclusion(selector): result = copy.deepcopy(selector or {}) expressions = result.setdefault("matchExpressions", []) if EXCLUSION not in expressions: expressions.append(copy.deepcopy(EXCLUSION)) return result def owns_webhook(webhook): name = webhook.get("name", "") service = webhook.get("clientConfig", {}).get("service", {}) return (name.startswith(("ivpol.mutate.", "ivpol.validate.")) and name.endswith("-" + POLICY) and service.get("namespace") == "kyverno" and service.get("path") in ("/ivpol/mutate/" + POLICY, "/ivpol/validate/" + POLICY)) def run(command): result = subprocess.run(command, text=True, capture_output=True, timeout=45) if result.returncode: raise RuntimeError(f"Kubernetes bootstrap-policy operation failed (exit {result.returncode}); no broad webhook bypass attempted") return result.stdout def save_backup(directory, kind, document): directory.mkdir(parents=True, exist_ok=True, mode=0o700) path = directory / f"{kind}-{time.time_ns()}.json" descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(descriptor, "w") as handle: json.dump(document, handle) handle.write("\n") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--kubeconfig", required=True) parser.add_argument("--state-dir", required=True) args = parser.parse_args() kubectl = ["kubectl", "--kubeconfig", args.kubeconfig, "--request-timeout=20s"] backups = Path(args.state_dir) / "diagnostics/supply-chain-bootstrap" raw = run(kubectl + ["get", "imagevalidatingpolicies.policies.kyverno.io", POLICY, "--ignore-not-found", "-o", "json"]) if not raw.strip(): print("Local image policy is not installed; normal bootstrap can continue.") return # Patch only entries tied to this exact policy/service path. The controller # may be unavailable, so updating the policy alone cannot repair its webhook. for kind in ("mutatingwebhookconfigurations", "validatingwebhookconfigurations"): configurations = json.loads(run(kubectl + ["get", kind, "-o", "json"])) for configuration in configurations.get("items") or []: patch = [{"op": "test", "path": "/metadata/resourceVersion", "value": configuration["metadata"]["resourceVersion"]}] for index, webhook in enumerate(configuration.get("webhooks") or []): if not owns_webhook(webhook): continue desired = selector_with_exclusion(webhook.get("namespaceSelector")) if desired == (webhook.get("namespaceSelector") or {}): continue patch.extend([ {"op": "test", "path": f"/webhooks/{index}/name", "value": webhook["name"]}, {"op": "add", "path": f"/webhooks/{index}/namespaceSelector", "value": desired}, ]) if len(patch) > 1: save_backup(backups, kind, configuration) run(kubectl + ["patch", kind, configuration["metadata"]["name"], "--type=json", "-p", json.dumps(patch)]) print(f"Reconciled local image-policy bootstrap scope in {configuration['metadata']['name']}; failure policies unchanged.") # Policy validation itself can depend on Kyverno. Repair Pod admission # first, then update the source policy without a stale resourceVersion. policy = json.loads(run(kubectl + ["get", "imagevalidatingpolicies.policies.kyverno.io", POLICY, "-o", "json"])) constraints = policy.get("spec", {}).get("matchConstraints", {}) desired = selector_with_exclusion(constraints.get("namespaceSelector")) if desired != (constraints.get("namespaceSelector") or {}): save_backup(backups, "image-policy", policy) patch = [ {"op": "test", "path": "/metadata/resourceVersion", "value": policy["metadata"]["resourceVersion"]}, {"op": "add", "path": "/spec/matchConstraints/namespaceSelector", "value": desired}, ] run(kubectl + ["patch", "imagevalidatingpolicies.policies.kyverno.io", POLICY, "--type=json", "-p", json.dumps(patch)]) print("Local image policy now excludes only registry/verifier bootstrap namespaces.") if __name__ == "__main__": try: main() except (RuntimeError, OSError, ValueError, KeyError, subprocess.SubprocessError) as error: print(f"Supply-chain bootstrap reconciliation refused: {error}", file=sys.stderr) sys.exit(1)