Quarantine orphan Kyverno recovery marker during reviewed state migration
Homelab Main / validate (push) Waiting to run Details
Homelab Main / running-update (push) Blocked by required conditions Details
Homelab Main / debian-ops (push) Blocked by required conditions Details

This commit is contained in:
juvenal.diaz 2026-10-30 22:31:54 -06:00
parent 7daa120bae
commit ca57abeaf3
3 changed files with 126 additions and 9 deletions

View File

@ -68,14 +68,29 @@ legacy file before copying it into the enrolled profile:
```
Known control-plane or kubeconfig hints that conflict with the profile cause a
refusal. The preview reports source, destination, lineage, resource count, and
refusal. One narrowly audited exception is the root-level
`null_resource.kyverno_helm_recovery` marker when no Kyverno Helm release is
tracked in that state. This create-only helper has no infrastructure identity
and no destroy provisioner. Its historical kubeconfig is reported in
`stale_execution_helpers` and recorded in the adoption ledger. The original
state retains the marker; the scoped copy excludes it so a historical
kubeconfig cannot become an active provisioner target. This increments only
the destination serial and leaves tracked infrastructure unchanged. The
preview shows both serials and resource counts. The exception requires the exact reviewed helper source;
a source change, tracked Kyverno release, other helper, or other stack keeps the
normal refusal. It never rewrites a cluster binding or authorizes access to the
historical cluster. A later apply uses the selected profile's planned helper
configuration and normal identity guards.
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
the original file, lineage, and tracked infrastructure. Serial and resources are
copied unchanged except for the explicitly reported orphan-marker quarantine; 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.

View File

@ -21,6 +21,9 @@ 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):
@ -381,17 +384,55 @@ def proxy_tofu(args):
return result.returncode
def legacy_hints(state, context):
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):
raise Refused("Legacy state contains a different kubeconfig path; ownership is ambiguous")
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):
@ -436,10 +477,17 @@ def manage(args):
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)
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.get("resources", [])), "cluster": observed}, indent=2))
"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)
@ -448,7 +496,7 @@ def manage(args):
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:
if document(destination) == copied:
print("Identical state already migrated; no change.")
else:
raise Refused("Scoped state already exists; refusing overwrite")
@ -456,9 +504,9 @@ def manage(args):
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)
private_write(destination, copied)
if not record_path.exists():
private_write(record_path, dict(observed, source=str(source), sha256=hashlib.sha256(raw).hexdigest()))
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.")

View File

@ -140,6 +140,60 @@ class ClusterContextTests(unittest.TestCase):
with self.assertRaisesRegex(MODULE.Refused, "control-plane identity"):
MODULE.legacy_hints(state, self.context)
def orphan_helper(self):
return {"type": "null_resource", "name": "kyverno_helm_recovery", "instances": [{"attributes": {
"id": "historical-recovery-marker",
"triggers": {"kubeconfig_path": "/historical/debian-config", "namespace": "kyverno", "release_name": "kyverno"}
}}]}
def test_orphan_create_only_helper_is_reported_without_rewriting_state(self):
state = {"resources": [self.orphan_helper()]}
before = json.dumps(state, sort_keys=True)
notices = MODULE.legacy_hints(state, self.context, "platform")
self.assertEqual(notices[0]["address"], "null_resource.kyverno_helm_recovery")
self.assertEqual(notices[0]["historical_kubeconfig"], "/historical/debian-config")
self.assertEqual(json.dumps(state, sort_keys=True), before)
def test_helper_mismatch_is_not_ignored_when_release_is_tracked(self):
state = {"resources": [self.orphan_helper(), {"type": "helm_release", "name": "kyverno", "instances": [{"attributes": {"id": "kyverno"}}]}]}
with self.assertRaisesRegex(MODULE.Refused, "ownership is ambiguous"):
MODULE.legacy_hints(state, self.context, "platform")
def test_other_helpers_and_stacks_keep_strict_path_checks(self):
resource = self.orphan_helper()
with self.assertRaises(MODULE.Refused):
MODULE.legacy_hints({"resources": [resource]}, self.context, "cluster")
resource["name"] = "argocd_ready"
with self.assertRaises(MODULE.Refused):
MODULE.legacy_hints({"resources": [resource]}, self.context, "platform")
def test_changed_recovery_source_requires_fresh_review(self):
resource = self.orphan_helper()
with patch.object(MODULE, "KYVERNO_RECOVERY_SHA256", "unreviewed"):
with self.assertRaises(MODULE.Refused):
MODULE.legacy_hints({"resources": [resource]}, self.context, "platform")
def test_migration_quarantines_only_orphan_marker_and_preserves_source(self):
self.pin()
repo, directory = self.stack()
(directory / "main.tf").write_text((MODULE.REPO / "bootstrap/platform/main.tf").read_text())
infrastructure = {"type": "helm_release", "name": "argocd", "instances": [{"attributes": {"id": "argocd"}}]}
state = {"version": 4, "lineage": "original", "serial": 7, "resources": [infrastructure, self.orphan_helper()]}
raw = json.dumps(state)
source = directory / "terraform.tfstate"
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)
copied = MODULE.document(self.context.state("platform"))
self.assertEqual(source.read_text(), raw)
self.assertEqual(copied["resources"], [infrastructure])
self.assertEqual(copied["lineage"], state["lineage"])
self.assertEqual(copied["serial"], 8)
record = MODULE.document(MODULE.legacy_record(self.context, source))
self.assertEqual(record["stale_execution_helpers"][0]["state_id"], "historical-recovery-marker")
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")