From 6a0be198818258ff84cf3cea6c36da6df0392f60 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Tue, 3 Nov 2026 08:16:13 -0600 Subject: [PATCH] Break the registry verifier bootstrap cycle without globally weakening admission --- .../local-registry-image-policy.yaml | 9 ++ bootstrap/apps/README.md | 7 ++ docs/app-ops.md | 10 ++ docs/templates/app-ops.md.tmpl | 10 ++ lib/jeannie/pipeline.sh | 5 + scripts/supply-chain-bootstrap-reconcile.py | 107 ++++++++++++++++++ tests/jeannie/test_supply_chain_bootstrap.py | 45 ++++++++ 7 files changed, 193 insertions(+) create mode 100644 scripts/supply-chain-bootstrap-reconcile.py create mode 100644 tests/jeannie/test_supply_chain_bootstrap.py diff --git a/apps/supply-chain-policy/local-registry-image-policy.yaml b/apps/supply-chain-policy/local-registry-image-policy.yaml index cb560c9..ca75b3e 100644 --- a/apps/supply-chain-policy/local-registry-image-policy.yaml +++ b/apps/supply-chain-policy/local-registry-image-policy.yaml @@ -21,6 +21,15 @@ spec: background: enabled: false matchConstraints: + # The registry and verifier must be able to recover without the verifier. + # Application namespaces retain the normal fail-closed policy behavior. + namespaceSelector: + matchExpressions: + - key: kubernetes.io/metadata.name + operator: NotIn + values: + - container-registry + - kyverno resourceRules: - apiGroups: - "" diff --git a/bootstrap/apps/README.md b/bootstrap/apps/README.md index 4588bc8..c42bca4 100644 --- a/bootstrap/apps/README.md +++ b/bootstrap/apps/README.md @@ -89,6 +89,13 @@ the declared hypervisor-host capability and checks that all VMs are stopped. It does not remove Pimox or rewrite `vmbr0`. Packaged K3s Traefik, ServiceLB and metrics-server are disabled so platform charts own those components. +The local image policy excludes its registry and Kyverno bootstrap namespaces. +The app pipeline reconciles the exact policy-generated webhook namespace filters +before requiring Argo readiness, backing up old objects and leaving failure +policies and other webhook entries unchanged. This prevents a down verifier +from blocking its own recovery or registry replacement. It is not a disk-pressure +cleanup mechanism, and it does not delete retained registry directories or images. + `./jeannie cluster-runtime check` performs read-only SSH probes of physical host services, API listeners and VM state. Deploy/start pipelines and guarded Tofu mutations refuse active conflicts or unverifiable host state. Stop commands diff --git a/docs/app-ops.md b/docs/app-ops.md index a3354c7..fa8d6ce 100644 --- a/docs/app-ops.md +++ b/docs/app-ops.md @@ -102,6 +102,16 @@ retired before installing the selected route. Other laptop PVC contents are preserved locally and are not automatically restored into the new cluster. See [registry migration](../bootstrap/apps/README.md). +The local image policy excludes only `container-registry` and `kyverno` from its +namespace scope so those dependencies can recover without calling an unavailable +verifier. Other namespaces retain `failurePolicy: Fail` and signature/SBOM checks. +Apps reconciles this policy's exact generated webhook entries before waiting for +Argo CD; it preserves other selectors and all other webhooks, uses version-tested +patches and saves private backups. This repairs legacy scope while Kyverno is +unavailable rather than deleting webhook configurations or globally failing open. +It does not resolve node storage pressure: inspect the actual full filesystem +before pruning anything or moving a K3s datastore. + The native profile requires `/data` to be its declared writable mount, not a directory on the eMMC root filesystem. After remounting a data disk, the pipeline compares the host registry directory with the running pod's mounted directory diff --git a/docs/templates/app-ops.md.tmpl b/docs/templates/app-ops.md.tmpl index ce63b01..f87f464 100644 --- a/docs/templates/app-ops.md.tmpl +++ b/docs/templates/app-ops.md.tmpl @@ -102,6 +102,16 @@ retired before installing the selected route. Other laptop PVC contents are preserved locally and are not automatically restored into the new cluster. See [registry migration](../bootstrap/apps/README.md). +The local image policy excludes only `container-registry` and `kyverno` from its +namespace scope so those dependencies can recover without calling an unavailable +verifier. Other namespaces retain `failurePolicy: Fail` and signature/SBOM checks. +Apps reconciles this policy's exact generated webhook entries before waiting for +Argo CD; it preserves other selectors and all other webhooks, uses version-tested +patches and saves private backups. This repairs legacy scope while Kyverno is +unavailable rather than deleting webhook configurations or globally failing open. +It does not resolve node storage pressure: inspect the actual full filesystem +before pruning anything or moving a K3s datastore. + The native profile requires `/data` to be its declared writable mount, not a directory on the eMMC root filesystem. After remounting a data disk, the pipeline compares the host registry directory with the running pod's mounted directory diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index 8ba4e6c..0cd99e2 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -7917,6 +7917,11 @@ apps() { ensure_pimox_kubeconfig cluster_context_require || return 1 + # This exact policy must not prevent its registry/verifier from recovering + # when admission or image storage is unavailable. Preserve all other scope. + python3 "${REPO_ROOT}/scripts/supply-chain-bootstrap-reconcile.py" \ + --kubeconfig "${KUBECONFIG_PATH}" \ + --state-dir "${HOMELAB_STATE_DIR}/clusters/${LAB_CLUSTER_PROFILE}" || return 1 require_argocd_application_controller || return 1 require_pimox_app_worker_capacity "${app_selector}" if [[ "${deploy_website}" == "true" || "${deploy_demos}" == "true" || "${deploy_registry}" == "true" ]]; then diff --git a/scripts/supply-chain-bootstrap-reconcile.py b/scripts/supply-chain-bootstrap-reconcile.py new file mode 100644 index 0000000..0920386 --- /dev/null +++ b/scripts/supply-chain-bootstrap-reconcile.py @@ -0,0 +1,107 @@ +#!/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) diff --git a/tests/jeannie/test_supply_chain_bootstrap.py b/tests/jeannie/test_supply_chain_bootstrap.py new file mode 100644 index 0000000..e4af645 --- /dev/null +++ b/tests/jeannie/test_supply_chain_bootstrap.py @@ -0,0 +1,45 @@ +"""Narrow bootstrap admission recovery. Run on the Debian host.""" + +import copy +import importlib.util +from pathlib import Path +import unittest + + +SPEC = importlib.util.spec_from_file_location( + "supply_chain_bootstrap", Path(__file__).resolve().parents[2] / "scripts/supply-chain-bootstrap-reconcile.py" +) +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + + +class SupplyChainBootstrapTests(unittest.TestCase): + def webhook(self): + return {"name": "ivpol.mutate.kyverno.svc-fail-finegrained-" + MODULE.POLICY, + "failurePolicy": "Fail", "clientConfig": {"service": { + "namespace": "kyverno", "path": "/ivpol/mutate/" + MODULE.POLICY}}} + + def test_only_exact_policy_and_service_are_owned(self): + self.assertTrue(MODULE.owns_webhook(self.webhook())) + for field, value in (("namespace", "another-verifier"), ("path", "/ivpol/mutate/another-policy")): + webhook = self.webhook() + webhook["clientConfig"]["service"][field] = value + self.assertFalse(MODULE.owns_webhook(webhook)) + webhook = self.webhook() + webhook["name"] += "-another-policy" + self.assertFalse(MODULE.owns_webhook(webhook)) + + def test_existing_scope_is_preserved_and_reconciliation_is_idempotent(self): + selector = {"matchLabels": {"team": "apps"}, "matchExpressions": [ + {"key": "environment", "operator": "In", "values": ["homelab"]}]} + original = copy.deepcopy(selector) + desired = MODULE.selector_with_exclusion(selector) + self.assertEqual(selector, original) + self.assertEqual(desired["matchLabels"], selector["matchLabels"]) + self.assertEqual(desired["matchExpressions"][0], selector["matchExpressions"][0]) + self.assertEqual(desired["matchExpressions"][-1]["values"], ["container-registry", "kyverno"]) + self.assertEqual(MODULE.selector_with_exclusion(desired), desired) + + +if __name__ == "__main__": + unittest.main()