From abc531afcefdb59e3c4108cdf9ce046e81850bec Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Fri, 30 Oct 2026 22:42:19 -0600 Subject: [PATCH] Preserve private diagnostics for scoped OpenTofu initialization failures --- docs/cluster-context.md | 10 +++++ scripts/cluster-context.py | 59 ++++++++++++++++++++++++--- tests/jeannie/test_cluster_context.py | 37 +++++++++++++++++ 3 files changed, 101 insertions(+), 5 deletions(-) diff --git a/docs/cluster-context.md b/docs/cluster-context.md index 3412e83..a5fa726 100644 --- a/docs/cluster-context.md +++ b/docs/cluster-context.md @@ -107,6 +107,16 @@ forgetting resource ownership. ## Guard coverage +Failed OpenTofu initialization and provider-target evaluation preserve their +stdout/stderr in owner-only JSON diagnostics under +`$HOMELAB_STATE_DIR/clusters//diagnostics//`. The refusal names +the diagnostic file and prints recognized static error headings. Raw HCL +snippets and provider responses stay in that file because they can contain +sensitive values. The diagnostic contains captured output and exit code, not +an environment or argument dump. Timeout failures use the same diagnostic path. +These diagnostics do not change state, retry initialization, or weaken identity +checks. Inspect a diagnostic locally on Debian before sharing excerpts. + 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 diff --git a/scripts/cluster-context.py b/scripts/cluster-context.py index 8805238..848af7b 100644 --- a/scripts/cluster-context.py +++ b/scripts/cluster-context.py @@ -14,6 +14,7 @@ import ssl import subprocess import sys import tempfile +import time from pathlib import Path from urllib.parse import urlsplit @@ -44,8 +45,43 @@ def binary(tool): 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) +def failure_diagnostic(directory, operation, result): + path = Path(directory) / f"{operation}-{time.time_ns()}-{os.getpid()}.json" + private_write(path, {"operation": operation, "exit_code": result.returncode, + "stdout": result.stdout, "stderr": result.stderr}) + return path + + +def safe_error_titles(output): + # Print only recognized static headings. HCL source snippets and provider + # responses can include secrets and remain in the private diagnostic file. + titles = { + "Invalid backend configuration argument", "Failed to get existing workspaces", + "Failed to load state", "Failed to read state", "Error refreshing state", + "Failed to install provider", "Failed to query available provider packages", + "Inconsistent dependency lock file", "Error acquiring the state lock", + "Unsupported Terraform Core version", "Unsupported OpenTofu Core version", + "Backend configuration changed", "Unsupported block type", "Invalid expression", + "Missing required argument", "Duplicate provider configuration", + "Failed to create local state file", "Failed to update workspace", + "Invalid single-argument block definition", "Invalid backend configuration", + } + clean = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", output) + found = [] + for line in clean.splitlines(): + match = re.match(r"^[\s│╷╵]*Error:\s*(.+?)\s*$", line) + if match and match[1] in titles and match[1] not in found: + found.append(match[1]) + return found + + +def capture(command, *, text=None, env=None, diagnostic_dir=None): + try: + result = subprocess.run(command, input=text, text=True, capture_output=True, timeout=90, env=env, check=False) + except subprocess.TimeoutExpired as error: + def decoded(value): + return value.decode(errors="replace") if isinstance(value, bytes) else value or "" + result = subprocess.CompletedProcess(command, 124, decoded(error.stdout), decoded(error.stderr) + "\nCommand timed out after 90 seconds.") if result.returncode: # Do not expose kubeconfig credentials, tokens, or Terraform values. reason = "read/configuration failure" @@ -56,7 +92,17 @@ def capture(command, *, text=None, env=None): 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") + detail = "" + if diagnostic_dir is not None: + headings = safe_error_titles(result.stdout + "\n" + result.stderr) + if headings: + detail += "; " + "; ".join(headings) + try: + path = failure_diagnostic(diagnostic_dir, operation, result) + detail += f"\nPrivate diagnostic (mode 0600): {path}" + except OSError: + detail += "\nPrivate diagnostic could not be written; check profile-directory permissions and free space." + raise Refused(f"{Path(command[0]).name} {operation} failed: {reason} (exit {result.returncode}); requested action was not started{detail}") return result.stdout @@ -68,6 +114,7 @@ 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: + os.fchmod(descriptor, 0o600) with os.fdopen(descriptor, "w") as handle: json.dump(value, handle, indent=2, sort_keys=True) handle.write("\n") @@ -344,7 +391,8 @@ def proxy_tofu(args): 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) + capture(base + ["init", "-input=false", "-no-color", "-reconfigure", f"-backend-config=path={state}", *init_args], env=env, + diagnostic_dir=context.root / "diagnostics" / name) command = args[0] if command == "init": return 0 @@ -354,7 +402,8 @@ def proxy_tofu(args): 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)) + kubeconfig = json.loads(capture(base + ["console", *variable_args(args)], text=expression + "\n", env=env, + diagnostic_dir=context.root / "diagnostics" / name)) # jsonencode() returns a JSON string inside the console string. kubeconfig = json.loads(kubeconfig) if name == "cluster": diff --git a/tests/jeannie/test_cluster_context.py b/tests/jeannie/test_cluster_context.py index 25ad9d0..3168fb2 100644 --- a/tests/jeannie/test_cluster_context.py +++ b/tests/jeannie/test_cluster_context.py @@ -17,6 +17,7 @@ SPEC = importlib.util.spec_from_file_location( ) MODULE = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(MODULE) +REAL_CAPTURE = MODULE.capture class ClusterContextTests(unittest.TestCase): @@ -292,5 +293,41 @@ class ClusterContextTests(unittest.TestCase): self.assertFalse(other.state("platform").exists()) +class InitializationDiagnosticsTests(unittest.TestCase): + def test_init_failure_keeps_private_details_and_prints_only_safe_heading(self): + secret = "sensitive-provider-detail" + failure = MODULE.subprocess.CompletedProcess([], 1, stdout="Provider download output", stderr="Error: Failed to query available provider packages\n" + secret) + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) / "diagnostics" + with patch.object(MODULE.subprocess, "run", return_value=failure): + with self.assertRaises(MODULE.Refused) as refused: + REAL_CAPTURE(["/mock/tofu", "init"], diagnostic_dir=directory) + self.assertIn("Failed to query available provider packages", str(refused.exception)) + self.assertNotIn(secret, str(refused.exception)) + reports = list(directory.glob("*.json")) + self.assertEqual(len(reports), 1) + report = MODULE.document(reports[0]) + self.assertEqual(report["stderr"], failure.stderr) + self.assertEqual(report["stdout"], failure.stdout) + self.assertEqual(reports[0].stat().st_mode & 0o777, 0o600) + + def test_dynamic_error_headings_are_not_printed(self): + output = "\x1b[31mError: Failed to install provider\x1b[0m\nError: private-dynamic-value\n" + self.assertEqual(MODULE.safe_error_titles(output), ["Failed to install provider"]) + + def test_timeout_diagnostic_does_not_echo_sensitive_command_arguments(self): + command = ["/mock/tofu", "console", "-var=password=private-value"] + timeout = MODULE.subprocess.TimeoutExpired(command, 90, output=b"partial output", stderr=b"partial error") + with tempfile.TemporaryDirectory() as temporary: + with patch.object(MODULE.subprocess, "run", side_effect=timeout): + with self.assertRaises(MODULE.Refused) as refused: + REAL_CAPTURE(command, diagnostic_dir=Path(temporary)) + self.assertNotIn("private-value", str(refused.exception)) + report = MODULE.document(next(Path(temporary).glob("*.json"))) + self.assertEqual(report["exit_code"], 124) + self.assertEqual(report["stdout"], "partial output") + self.assertIn("timed out", report["stderr"]) + + if __name__ == "__main__": unittest.main()