From 46449119af6f26e5e1aff24b0603373d7562da98 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Fri, 30 Oct 2026 22:52:39 -0600 Subject: [PATCH] Initialize scoped backends without migrating retained legacy state --- docs/cluster-context.md | 9 ++++ scripts/cluster-context.py | 54 +++++++++++++++++-- tests/jeannie/test_cluster_context.py | 78 +++++++++++++++++++++++++++ 3 files changed, 137 insertions(+), 4 deletions(-) diff --git a/docs/cluster-context.md b/docs/cluster-context.md index a5fa726..e35db88 100644 --- a/docs/cluster-context.md +++ b/docs/cluster-context.md @@ -58,6 +58,15 @@ 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. +On a fresh profile cache, Jeannie initializes local-backend metadata from an +empty temporary configuration directory, using the real stack's provider lock +file in read-only mode. It then verifies the backend points to the scoped state +and initializes the real stack without `-reconfigure`. This avoids OpenTofu +1.12.6 treating the retained repository state as a migration source. Neither +`-force-copy` nor an automatic migration approval is used. Initialization checks +that an existing scoped state remains byte-for-byte unchanged. Cached metadata +pointing elsewhere is refused. Legacy snapshots remain at their original paths. + An unassigned legacy state blocks using an empty scoped state. Review each legacy file before copying it into the enrolled profile: diff --git a/scripts/cluster-context.py b/scripts/cluster-context.py index 848af7b..5d480f0 100644 --- a/scripts/cluster-context.py +++ b/scripts/cluster-context.py @@ -338,6 +338,54 @@ def positionals(args): return result +def verify_backend_metadata(path, state): + metadata = document(path) + backend = metadata.get("backend") or {} + target = backend.get("config", {}).get("path") + if backend.get("type") != "local" or not isinstance(target, str) or not Path(target).is_absolute() or Path(target).resolve() != state.resolve(): + raise Refused("Cached backend does not point to this profile's scoped state; refusing initialization") + + +def initialize_scoped_backend(tool, directory, context, name, env, init_args): + """Initialize backend metadata without exposing legacy files to init. + + OpenTofu 1.12.6 treats -reconfigure as first initialization and scans + the configuration directory for default local state. Seed its metadata + using an empty configuration directory, then reuse it in the real module. + Never approve a copy from the retained legacy state into the scoped state. + """ + state = context.state(name) + metadata = Path(env["TF_DATA_DIR"]) / "terraform.tfstate" + before = state.read_bytes() if state.exists() else None + diagnostics = context.root / "diagnostics" / name + backend_args = [f"-backend-config=path={state}"] + try: + if metadata.exists(): + verify_backend_metadata(metadata, state) + else: + dependency_lock = directory / ".terraform.lock.hcl" + if before and document(state).get("resources") and not dependency_lock.is_file(): + raise Refused("A dependency lock file is required before initializing migrated state") + with tempfile.TemporaryDirectory(prefix=f"backend-init-{name}-", dir=context.root) as temporary: + bootstrap = Path(temporary) + (bootstrap / "main.tf").write_text('terraform {\n backend "local" {}\n}\n') + # init also considers providers referenced in state. Preserve + # the real module's locked versions rather than selecting latest. + if dependency_lock.is_file(): + shutil.copyfile(dependency_lock, bootstrap / ".terraform.lock.hcl") + capture([tool, f"-chdir={bootstrap}", "init", "-input=false", "-no-color", "-get=false", + "-lockfile=readonly", *backend_args], env=env, diagnostic_dir=diagnostics) + verify_backend_metadata(metadata, state) + # Do not pass -reconfigure here: it would discard the verified metadata + # and discover the repository's legacy terraform.tfstate again. + capture([tool, f"-chdir={directory}", "init", "-input=false", "-no-color", *backend_args, *init_args], + env=env, diagnostic_dir=diagnostics) + verify_backend_metadata(metadata, state) + finally: + if before is not None and (not state.exists() or state.read_bytes() != before): + raise Refused("Initialization unexpectedly changed scoped state; refusing further operations. Preserve the diagnostic and both state snapshots for review.") + + def proxy_tofu(args): directory = Path.cwd().resolve() if args and args[0].startswith("-chdir="): @@ -369,7 +417,7 @@ def proxy_tofu(args): 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): + if any(arg.split("=", 1)[0] in ("-state", "-state-out", "-backup", "-backend-config", "-backend", "-migrate-state", "-force-copy", "-reconfigure", "-config") for arg in args): raise Refused("State/backend overrides are refused; use cluster-context migrate for reviewed legacy state") legacy = directory / "terraform.tfstate" if not state.exists() and legacy.exists(): @@ -389,10 +437,8 @@ def proxy_tofu(args): 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", "-no-color", "-reconfigure", f"-backend-config=path={state}", *init_args], env=env, - diagnostic_dir=context.root / "diagnostics" / name) + initialize_scoped_backend(tool, directory, context, name, env, init_args) command = args[0] if command == "init": return 0 diff --git a/tests/jeannie/test_cluster_context.py b/tests/jeannie/test_cluster_context.py index 3168fb2..8dcb9c4 100644 --- a/tests/jeannie/test_cluster_context.py +++ b/tests/jeannie/test_cluster_context.py @@ -56,6 +56,10 @@ class ClusterContextTests(unittest.TestCase): def read(self, command, **kwargs): self.calls.append(command) if "init" in command: + metadata = Path(kwargs["env"]["TF_DATA_DIR"]) / "terraform.tfstate" + if not metadata.exists(): + target = next(arg.split("=", 2)[2] for arg in command if arg.startswith("-backend-config=path=")) + MODULE.private_write(metadata, {"backend": {"type": "local", "config": {"path": target}}}) return "" if "console" in command: return json.dumps(json.dumps(self.context.kubeconfig)) @@ -293,6 +297,80 @@ class ClusterContextTests(unittest.TestCase): self.assertFalse(other.state("platform").exists()) +class ScopedBackendInitializationTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.module = self.root / "module" + self.module.mkdir() + self.legacy = self.module / "terraform.tfstate" + self.legacy.write_text('{"resources":[{"name":"legacy-orphan"}]}') + (self.module / ".terraform.lock.hcl").write_text("pinned provider selections\n") + self.state = self.root / "scoped.tfstate" + self.state.write_text('{"version":4,"resources":[{"name":"reviewed"}]}') + self.context = SimpleNamespace(root=self.root, state=lambda name: self.state) + self.env = {"TF_DATA_DIR": str(self.root / "metadata")} + self.metadata = Path(self.env["TF_DATA_DIR"]) / "terraform.tfstate" + self.calls = [] + + def sdk(self, command, **kwargs): + self.calls.append(command) + directory = Path(command[1].split("=", 1)[1]) + if directory != self.module: + self.assertFalse((directory / "terraform.tfstate").exists()) + self.assertEqual((directory / ".terraform.lock.hcl").read_bytes(), + (self.module / ".terraform.lock.hcl").read_bytes()) + self.assertIn('-lockfile=readonly', command) + MODULE.private_write(self.metadata, {"backend": {"type": "local", "config": {"path": str(self.state)}}}) + else: + self.assertTrue(self.metadata.exists()) + for unsafe in ("-reconfigure", "-force-copy", "-migrate-state"): + self.assertNotIn(unsafe, command) + return "" + + def initialize(self): + MODULE.initialize_scoped_backend("/mock/tofu", self.module, self.context, "platform", self.env, []) + + def test_seed_then_reuse_preserves_both_different_state_snapshots(self): + original = self.legacy.read_bytes(), self.state.read_bytes() + with patch.object(MODULE, "capture", side_effect=self.sdk): + self.initialize() + self.initialize() + self.assertEqual(len(self.calls), 3) + self.assertEqual(self.calls[-1][1], f"-chdir={self.module}") + self.assertEqual(original, (self.legacy.read_bytes(), self.state.read_bytes())) + + def test_wrong_cached_backend_refuses_without_sdk_calls(self): + MODULE.private_write(self.metadata, {"backend": {"type": "local", "config": {"path": str(self.legacy)}}}) + with patch.object(MODULE, "capture") as capture: + with self.assertRaisesRegex(MODULE.Refused, "Cached backend"): + self.initialize() + capture.assert_not_called() + + def test_unexpected_scoped_state_write_is_detected(self): + def changed(command, **kwargs): + self.sdk(command, **kwargs) + self.state.write_text("unexpected state write") + + with patch.object(MODULE, "capture", side_effect=changed): + with self.assertRaisesRegex(MODULE.Refused, "unexpectedly changed scoped state"): + self.initialize() + + def test_provider_failure_propagates_and_retry_reuses_verified_metadata(self): + def failed(command, **kwargs): + self.sdk(command, **kwargs) + raise MODULE.Refused("provider download failed") + + with patch.object(MODULE, "capture", side_effect=failed): + with self.assertRaisesRegex(MODULE.Refused, "provider download failed"): + self.initialize() + with patch.object(MODULE, "capture", side_effect=self.sdk): + self.initialize() + self.assertEqual(len(self.calls), 2) + self.assertEqual(self.calls[-1][1], f"-chdir={self.module}") + + class InitializationDiagnosticsTests(unittest.TestCase): def test_init_failure_keeps_private_details_and_prints_only_safe_heading(self): secret = "sensitive-provider-detail"