diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index 907860b..81393d3 100755 --- a/infra/deploy-runner/nodedc-deploy +++ b/infra/deploy-runner/nodedc-deploy @@ -8,6 +8,7 @@ import grp import hashlib import http.client import io +import itertools import json import os import pwd @@ -72,6 +73,9 @@ GITEA_CI_V4_SOURCE_SHA256 = { } GITEA_ACTIONS_ROOT = Path("/volume1/docker/nodedc-gitea-actions") GITEA_ACTIONS_ENTRY = "deployment/actions-enable-v1.json" +GITEA_ACTIONS_V2_ENTRY = "deployment/actions-enable-v2.json" +GITEA_ACTIONS_FAILED_ID = "gitea-actions-enable-v1-20260929-001" +GITEA_ACTIONS_FAILED_BACKUP = "gitea-actions-config-gitea-actions-enable-v1-20260929-001-20260929-160304" GITEA_ACTIONS_LEGACY = Path("/volume1/docker/gitea-clean-standalone-v1") GITEA_ACTIONS_CONFIG = Path("/volume1/docker/gitea-clean-20260820/config/app.ini") GITEA_ACTIONS_CONTAINER = "clean-gitea-20260820" @@ -4958,7 +4962,7 @@ def allowed_payload_path(component, rel): die(f"path rejected: {rel}: {reason}") if component == "gitea-actions-config": - if rel in ("deployment", GITEA_ACTIONS_ENTRY): + if rel in ("deployment", GITEA_ACTIONS_ENTRY, GITEA_ACTIONS_V2_ENTRY): return True die("Gitea Actions accepts only its activation descriptor") if component == "gitea-ci": @@ -31431,13 +31435,18 @@ def rollback_map_access(root, backup_dir, entries, current_stamp): def validate_gitea_actions_payload(payload_dir, entries, release_id): - if tuple(entries) != (GITEA_ACTIONS_ENTRY,) or not re.fullmatch( - r"gitea-actions-enable-v1-[a-zA-Z0-9._-]{1,65}", release_id): + recovery = tuple(entries) == (GITEA_ACTIONS_V2_ENTRY,) + version = "v2" if recovery else "v1" + entry = GITEA_ACTIONS_V2_ENTRY if recovery else GITEA_ACTIONS_ENTRY + if tuple(entries) != (entry,) or not re.fullmatch( + r"gitea-actions-enable-" + version + r"-[a-zA-Z0-9._-]{1,65}", release_id): die("Gitea Actions transition identity mismatch") - expected = {"schemaVersion": "nodedc.gitea.actions-enable.v1", "releaseId": release_id, + expected = {"schemaVersion": "nodedc.gitea.actions-enable." + version, "releaseId": release_id, "action": "enable-instance-actions", "service": "gitea", "productionDeployEnabled": False} - if read_strict_json(payload_dir / GITEA_ACTIONS_ENTRY, "Gitea Actions descriptor") != expected: + if recovery: + expected["reconcilesFailedAttempt"] = GITEA_ACTIONS_FAILED_ID + if read_strict_json(payload_dir / entry, "Gitea Actions descriptor") != expected: die("Gitea Actions descriptor mismatch") @@ -31531,7 +31540,121 @@ def gitea_actions_fingerprint(info): return hashlib.sha256(json.dumps(fields, sort_keys=True).encode()).hexdigest() -def preflight_gitea_actions(): +def gitea_actions_ordered_fields(info): + fields = {key: info.get(key) for key in ("Id", "Image", "Config", "HostConfig", "Mounts")} + fields = json.loads(json.dumps(fields)) + if not isinstance(fields["HostConfig"], dict): + die("Gitea Actions HostConfig is malformed") + mounts = fields["Mounts"] + limits = fields["HostConfig"].get("Ulimits") + for values, key in ((mounts, "Destination"), (limits, "Name")): + if values is None and key == "Name": + continue + if not isinstance(values, list) or any(not isinstance(x, dict) or not isinstance(x.get(key), str) for x in values): + die("Gitea Actions unordered runtime field is malformed") + if len({x[key] for x in values}) != len(values): + die("Gitea Actions duplicate runtime entries rejected") + values.sort(key=lambda x: json.dumps(x, sort_keys=True)) + fields["networks"] = sorted(info.get("NetworkSettings", {}).get("Networks", {})) + return fields + + +def gitea_actions_fingerprint_v2(info): + return hashlib.sha256(json.dumps(gitea_actions_ordered_fields(info), sort_keys=True).encode()).hexdigest() + + +def gitea_actions_context_fingerprint(info, before): + return (gitea_actions_fingerprint_v2(info) if before.get("fingerprintVersion") == 2 + else gitea_actions_fingerprint(info)) + + +def gitea_actions_prove_legacy_order(info, expected): + fields = gitea_actions_ordered_fields(info) + mounts, limits = fields["Mounts"], fields["HostConfig"].get("Ulimits") + count = 1 + for length in (len(mounts), len(limits or [])): + for factor in range(2, length + 1): + count *= factor + if count > 4096: + die("Gitea Actions order audit exceeds bounded permutation limit") + for mount_order in itertools.permutations(mounts): + fields["Mounts"] = list(mount_order) + for limit_order in itertools.permutations(limits or []): + if limits is not None: + fields["HostConfig"]["Ulimits"] = list(limit_order) + if hashlib.sha256(json.dumps(fields, sort_keys=True).encode()).hexdigest() == expected: + return True + return False + + +def preflight_gitea_actions_recovery(): + # Read-only reconciliation of one known failure, never a generic drift override. + backup = BACKUPS_DIR / GITEA_ACTIONS_FAILED_BACKUP + record = [json.loads(line) for line in FAILED_STATE_FILE.read_text().splitlines() if line.strip()] + record = [row for row in record if row.get("id") == GITEA_ACTIONS_FAILED_ID] + if len(record) != 1 or any(record[0].get(key) != value for key, value in { + "component": "gitea-actions-config", "sha256": "2ae874cfc6015378246e0bb7b24d4594a749e4136fbd82dbe9db0b57356d2162", + "status": "failed", "artifact": "nodedc-gitea-actions-enable-v1-20260929-001.tgz.20260929-160304", + "backup_id": GITEA_ACTIONS_FAILED_BACKUP, "rollback_status": "failed:DeployError", + "message": "Gitea Actions runtime changed before mutation", "started_apply": True}.items()): + die("Gitea Actions recovery failed-attempt evidence mismatch") + receipt_path = backup / "gitea-actions-before.json" + for path, expected in ((receipt_path, "7b45f822d5afb165f49f0fd4575d92c930ed079cf286a685350f75c61364e0fe"), + (FAILED_DIR / record[0]["artifact"], record[0]["sha256"])): + if (any(p.is_symlink() for p in (path, *path.parents)) or not path.is_file() + or sha256_file(path) != expected): + die("Gitea Actions recovery archived evidence mismatch") + old = read_strict_json(receipt_path, "Gitea Actions recovery receipt", max_bytes=131072) + old_descriptor = GITEA_ACTIONS_ROOT / GITEA_ACTIONS_ENTRY + if (not old_descriptor.is_file() or any(p.is_symlink() for p in (old_descriptor, *old_descriptor.parents)) + or sha256_file(old_descriptor) != "4bc516559ac7a3b62c8d90d8ebc1423ec2039e14591be62eb81fde76bb6751be" + or (GITEA_ACTIONS_ROOT / GITEA_ACTIONS_V2_ENTRY).exists()): + die("Gitea Actions recovery metadata predecessor mismatch") + for rel, expected in {"compose.yaml": "c21ef87833f87623f8352477d2b541d0a0f48769d8f9f79251d58033e90197ff", + "production.env": "9ebbf8638e035dddca25fd455b2ac4d4b6db306e1a6a4debd973b133fdeb5bb7"}.items(): + path = GITEA_ACTIONS_LEGACY / rel + if any(p.is_symlink() for p in (path, *path.parents)) or sha256_file(path) != expected: + die("Gitea Actions recovery Compose context mismatch") + data, metadata = gitea_actions_read_config() + gitea_actions_transform(data) + if old.get("configBeforeSha256") != GITEA_ACTIONS_BEFORE or old.get("configAfterSha256") != GITEA_ACTIONS_AFTER: + die("Gitea Actions recovery config evidence mismatch") + samples = [] + for _ in range(3): + info = gitea_actions_container() + matched = (info["Id"] == old.get("containerId") + and gitea_actions_prove_legacy_order(info, old.get("fingerprint"))) + sample = {"legacyFingerprint": gitea_actions_fingerprint(info), + "canonicalFingerprint": gitea_actions_fingerprint_v2(info), + "matchesSavedStateByOrderOnly": matched} + samples.append(sample) + if not matched: + print("gitea_actions_readonly_audit=" + json.dumps({"samples": samples, "mutation": False}, sort_keys=True)) + die("Gitea Actions recovery cannot prove order-only difference; runtime mutation forbidden") + if len({sample["canonicalFingerprint"] for sample in samples}) != 1: + die("Gitea Actions recovery runtime changed during read-only audit") + if (info["Image"] != inspect_local_image(GITEA_ACTIONS_IMAGE, "Gitea Actions recovery image") + or info.get("State", {}).get("Health", {}).get("Status") != "healthy"): + die("Gitea Actions recovery image or health mismatch") + if gitea_actions_http("http://172.22.27.2:3000", "/api/v1/version") != (200, {"version": "1.27.2"}): + die("Gitea Actions recovery version mismatch") + status, _ = gitea_actions_http("http://172.22.27.2:3000", GITEA_ACTIONS_PING, ping=True) + if status != 404: + die("Gitea Actions recovery requires unchanged disabled RPC") + inventory = gitea_ci_inventory() + inventory.pop(info["Id"], None) + if inventory != old.get("inventory"): + die("Gitea Actions recovery preserved inventory mismatch") + print("gitea_actions_readonly_audit=" + json.dumps({"samples": samples, "mutation": False, + "configUnchanged": True, "otherContainersUnchanged": True, "healthy": True}, sort_keys=True)) + return {"config": data, "metadata": metadata, "containerId": info["Id"], + "fingerprint": samples[0]["canonicalFingerprint"], "fingerprintVersion": 2, + "mutationStarted": False, "inventory": inventory} + + +def preflight_gitea_actions(entries=None): + if tuple(entries or ()) == (GITEA_ACTIONS_V2_ENTRY,): + return preflight_gitea_actions_recovery() expected = {"compose.yaml": "c21ef87833f87623f8352477d2b541d0a0f48769d8f9f79251d58033e90197ff", "production.env": "9ebbf8638e035dddca25fd455b2ac4d4b6db306e1a6a4debd973b133fdeb5bb7"} for rel, digest in expected.items(): @@ -31601,10 +31724,14 @@ def apply_gitea_actions(before, backup_dir): fsync_directory(private.parent) fsync_directory(RUNTIME_DIR) receipt = {key: before[key] for key in ("containerId", "fingerprint", "inventory")} + if before.get("fingerprintVersion") == 2: + receipt["fingerprintVersion"] = 2 + receipt["reconcilesFailedAttempt"] = GITEA_ACTIONS_FAILED_ID receipt.update({"configBeforeSha256": GITEA_ACTIONS_BEFORE, "configAfterSha256": GITEA_ACTIONS_AFTER}) (backup_dir / "gitea-actions-before.json").write_text(json.dumps(receipt, sort_keys=True) + "\n") - if gitea_actions_fingerprint(gitea_actions_container()) != before["fingerprint"]: + if gitea_actions_context_fingerprint(gitea_actions_container(), before) != before["fingerprint"]: die("Gitea Actions runtime changed before mutation") + before["mutationStarted"] = True gitea_actions_replace(GITEA_ACTIONS_BEFORE, gitea_actions_transform(before["config"]), before["metadata"]) subprocess.run([str(DOCKER), "restart", "--time", "60", before["containerId"]], check=True, capture_output=True, timeout=90) @@ -31615,7 +31742,7 @@ def accept_gitea_actions(before, enabled=True): while True: try: info = gitea_actions_container() - if gitea_actions_fingerprint(info) != before["fingerprint"]: + if gitea_actions_context_fingerprint(info, before) != before["fingerprint"]: die("Gitea Actions runtime configuration drift") expected = GITEA_ACTIONS_AFTER if enabled else GITEA_ACTIONS_BEFORE if sha256_file(GITEA_ACTIONS_CONFIG) != expected: @@ -31646,9 +31773,15 @@ def accept_gitea_actions(before, enabled=True): def rollback_gitea_actions(root, backup_dir, entries, current_stamp, before, runtime_started): if runtime_started: info = gitea_actions_container(require_running=False) - if gitea_actions_fingerprint(info) != before["fingerprint"]: + if gitea_actions_context_fingerprint(info, before) != before["fingerprint"]: die("Gitea Actions rollback runtime drift") current = sha256_file(GITEA_ACTIONS_CONFIG) + if before.get("fingerprintVersion") == 2 and not before.get("mutationStarted"): + if current != GITEA_ACTIONS_BEFORE: + die("Gitea Actions pre-mutation rollback found unexpected config change") + accept_gitea_actions(before, enabled=False) + restore_overlay_source(root, backup_dir, entries, current_stamp) + return if current == GITEA_ACTIONS_AFTER: gitea_actions_replace(GITEA_ACTIONS_AFTER, before["config"], before["metadata"]) elif current != GITEA_ACTIONS_BEFORE: @@ -32135,7 +32268,7 @@ def plan_artifact(artifact): if manifest["component"] == "gitea-ci": preflight_gitea_ci(entries) if manifest["component"] == "gitea-actions-config": - preflight_gitea_actions() + preflight_gitea_actions(entries) reject_failed_artifact_replay(manifest, sha) reject_terminal_engine_l2_failed_artifact(manifest, sha) reject_terminal_device_plane_foundation_artifact(manifest, sha) @@ -32720,6 +32853,8 @@ def plan_artifact(artifact): print(f"type={manifest['type']}") print(f"payload_root={root}") if component == "gitea-actions-config": + if tuple(entries) == (GITEA_ACTIONS_V2_ENTRY,): + print("gitea_actions_recovery=exact-failed-attempt;read-only-order-equivalence-proven") print("gitea_actions_transition=disabled-to-enabled;production_deploy=false") print("gitea_actions_runtime=restart-existing-clean-gitea-20260820;brief-web-and-ssh-interruption") print("gitea_actions_config=one-boolean-only;owner-and-mode=preserved") @@ -38280,7 +38415,7 @@ process.stdout.write('engine-l2-closed-loop:0.7.0:cas+safe-profile+external-plan def run_healthchecks(component, entries=None, services=None): if component == "gitea-actions-config": - if tuple(services or ()) != ("gitea",) or tuple(entries or ()) != (GITEA_ACTIONS_ENTRY,): + if tuple(services or ()) != ("gitea",) or tuple(entries or ()) not in ((GITEA_ACTIONS_ENTRY,), (GITEA_ACTIONS_V2_ENTRY,)): die("Gitea Actions service/entry set mismatch") # Context-aware acceptance runs in apply immediately after the restart. return @@ -39439,7 +39574,7 @@ def apply_artifact(artifact): if component == "gitea-ci": gitea_ci_before = preflight_gitea_ci(entries) if component == "gitea-actions-config": - gitea_actions_before = preflight_gitea_actions() + gitea_actions_before = preflight_gitea_actions(entries) artifact_only = component_artifact_only(component) defer_bootstrap_root = is_gitea_bootstrap_slice( component, diff --git a/infra/gitea-ci/README.md b/infra/gitea-ci/README.md index b9562de..1dafbe8 100644 --- a/infra/gitea-ci/README.md +++ b/infra/gitea-ci/README.md @@ -125,6 +125,49 @@ startup-error categories/counts, never raw container logs or tokens. python3 infra/gitea-ci/build_actions_artifact.py --patch-id gitea-actions-enable-v1- --source-commit --output-dir ``` +### Recovery of Actions enable attempt 20260929-001 + +The first Actions apply stopped before replacing `app.ini` or restarting Gitea, +with `Gitea Actions runtime changed before mutation`. Its rollback repeated the +same fingerprint comparison and failed. Treat the failed archive, journal and +backup as evidence, not as permission to replay the artifact. + +The legacy fingerprint compares `docker inspect` JSON including array order. +Docker 24.0.2 constructs +[mount points from a Go map](https://github.com/moby/moby/blob/v24.0.2/container/container_unix.go#L425-L440) +and [default ulimits from a map](https://github.com/moby/moby/blob/v24.0.2/daemon/oci_linux.go#L1012-L1026). +Their order can change without changing the container. Local tests reproduce the +false drift and preserve rejection of changed values, ordered command/env arrays, +image, ports and container identity. This explains a possible failure; the live +NAS must prove that it explains this specific attempt before another apply. + +`actions-enable.v2` is a separate, bounded recovery for exactly that failed +attempt. Its read-only `plan` checks the failed journal, failed archive and saved +receipt digests, unchanged disabled config, leftover v1 descriptor, fixed Compose +context, same healthy Gitea and all other container identities/uptimes. For each +of three fresh inspections it must reconstruct the saved legacy fingerprint by +permuting only Mounts and HostConfig.Ulimits, retaining every field and value. +The search is capped at 4096 permutations and rejects duplicate mount destinations +or limit names. Any unexplained difference rejects the plan before mutation. + +Only after that plan has been reviewed can a separate apply repeat the audit +under the deploy lock and perform the same one-boolean transition. New comparison +and acceptance sort the two unordered collections. All other preservation checks +stay in force. A pre-mutation failure performs no Docker restart. A failure after +mutation restores the disabled config and removes only the v2 source descriptor; +the v1 marker and original failed evidence remain intact. The v2 backup records +the fingerprint version and reconciled attempt. Historical artifact bytes and +legacy Gitea recovery branches remain unchanged. + +```sh +python3 infra/gitea-ci/build_actions_artifact.py --patch-id gitea-actions-enable-v2- --source-commit --output-dir +``` + +At preparation time, live order equivalence is still unverified and instance +Actions, build-runner registration and automatic production deployment remain +unfinished. Promote the reviewed root runner, run only a fresh read-only v2 plan, +review its three audit samples, and then decide the next registered action. + From a clean Platform commit: ```sh diff --git a/infra/gitea-ci/actions-enable-v2.json b/infra/gitea-ci/actions-enable-v2.json new file mode 100644 index 0000000..9d0d40b --- /dev/null +++ b/infra/gitea-ci/actions-enable-v2.json @@ -0,0 +1,8 @@ +{ + "schemaVersion": "nodedc.gitea.actions-enable.v2", + "releaseId": "__PATCH_ID__", + "action": "enable-instance-actions", + "service": "gitea", + "productionDeployEnabled": false, + "reconcilesFailedAttempt": "gitea-actions-enable-v1-20260929-001" +} diff --git a/infra/gitea-ci/build_actions_artifact.py b/infra/gitea-ci/build_actions_artifact.py index 6efdf7b..afe1160 100644 --- a/infra/gitea-ci/build_actions_artifact.py +++ b/infra/gitea-ci/build_actions_artifact.py @@ -15,15 +15,21 @@ SOURCE = Path(__file__).resolve().parent ENTRY = "deployment/actions-enable-v1.json" -def bundle(patch_id): - if not re.fullmatch(r"gitea-actions-enable-v1-[a-zA-Z0-9._-]{1,65}", patch_id): +def descriptor_entry(patch_id): + match = re.fullmatch(r"gitea-actions-enable-(v[12])-[a-zA-Z0-9._-]{1,65}", patch_id) + if not match: raise ValueError("invalid_actions_transition_identity") - descriptor = json.loads((SOURCE / "actions-enable-v1.json").read_text()) + return "deployment/actions-enable-" + match.group(1) + ".json" + + +def bundle(patch_id): + entry = descriptor_entry(patch_id) + descriptor = json.loads((SOURCE / Path(entry).name).read_text()) descriptor["releaseId"] = patch_id files = { "manifest.env": ("id=" + patch_id + "\ncomponent=gitea-actions-config\ntype=app-overlay\n").encode(), - "files.txt": (ENTRY + "\n").encode(), - "payload/" + ENTRY: (json.dumps(descriptor, indent=2) + "\n").encode(), + "files.txt": (entry + "\n").encode(), + "payload/" + entry: (json.dumps(descriptor, indent=2) + "\n").encode(), } output = io.BytesIO() with gzip.GzipFile(fileobj=output, mode="wb", filename="", mtime=0) as compressed: @@ -51,7 +57,7 @@ def main(): stream.write(data) print(json.dumps({"artifact": str(path.resolve()), "patchId": args.patch_id, "component": "gitea-actions-config", "sourceCommit": actual, - "sha256": hashlib.sha256(data).hexdigest(), "entries": [ENTRY], + "sha256": hashlib.sha256(data).hexdigest(), "entries": [descriptor_entry(args.patch_id)], "services": ["gitea"], "newPorts": [], "productionDeployEnabled": False})) diff --git a/infra/gitea-ci/test_actions_enable.py b/infra/gitea-ci/test_actions_enable.py index af117cd..1912bb0 100644 --- a/infra/gitea-ci/test_actions_enable.py +++ b/infra/gitea-ci/test_actions_enable.py @@ -177,7 +177,7 @@ class ActionsEnableTests(unittest.TestCase): self.assertNotIn(secret, data + output.getvalue()) self.assertIn("actions-disabled-or-route", data) - def full_apply(self, fail_acceptance=False): + def full_apply(self, fail_acceptance=False, version="v1"): host = self.root / "host" host.mkdir() paths = {name: host / name.lower() for name in ( @@ -196,7 +196,12 @@ class ActionsEnableTests(unittest.TestCase): "compose_root": legacy, "compose_files": (legacy / "compose.yaml",), "compose_env_file": legacy / "production.env"} artifact = paths["INBOX"] / "actions.tgz" - artifact.write_bytes(build_actions_artifact.bundle("gitea-actions-enable-v1-full-test")) + artifact.write_bytes(build_actions_artifact.bundle("gitea-actions-enable-" + version + "-full-test")) + if version == "v2": + (root / RUNNER.GITEA_ACTIONS_ENTRY).parent.mkdir(parents=True) + (root / RUNNER.GITEA_ACTIONS_ENTRY).write_bytes(b"preserved failed-attempt marker") + self.before.update({"fingerprint": RUNNER.gitea_actions_fingerprint_v2(self.info), + "fingerprintVersion": 2, "mutationStarted": False}) with ExitStack() as stack: for name, value in paths.items(): stack.enter_context(mock.patch.object(RUNNER, name, value)) diff --git a/infra/gitea-ci/test_actions_recovery.py b/infra/gitea-ci/test_actions_recovery.py new file mode 100644 index 0000000..9cf5717 --- /dev/null +++ b/infra/gitea-ci/test_actions_recovery.py @@ -0,0 +1,231 @@ +import copy +from contextlib import redirect_stdout +import hashlib +import io +import json +from pathlib import Path +import unittest +from unittest import mock + +import build_actions_artifact +import test_actions_enable as base +from test_bootstrap import RUNNER + + +class ActionsRecoveryTests(unittest.TestCase): + setUp = base.ActionsEnableTests.setUp + full_apply = base.ActionsEnableTests.full_apply + + def with_limits(self): + value = copy.deepcopy(self.info) + value["HostConfig"]["Ulimits"] = [ + {"Name": "nofile", "Soft": 1024, "Hard": 4096}, + {"Name": "nproc", "Soft": 1024, "Hard": 2048}] + return value + + def test_mount_and_ulimit_order_is_the_only_difference_allowed(self): + old = self.with_limits() + changed = copy.deepcopy(old) + changed["Mounts"].reverse() + changed["HostConfig"]["Ulimits"].reverse() + snapshot = copy.deepcopy(changed) + self.assertNotEqual(RUNNER.gitea_actions_fingerprint(old), RUNNER.gitea_actions_fingerprint(changed)) + self.assertEqual(RUNNER.gitea_actions_fingerprint_v2(old), RUNNER.gitea_actions_fingerprint_v2(changed)) + self.assertTrue(RUNNER.gitea_actions_prove_legacy_order(changed, RUNNER.gitea_actions_fingerprint(old))) + self.assertEqual(changed, snapshot, "normalization must not mutate the inspected object") + + def test_order_proof_rejects_all_real_configuration_changes(self): + old = self.with_limits() + old["Config"]["Env"].append("USER=gitea") + mutations = [lambda x: x.update(Id="other"), lambda x: x.update(Image="other"), + lambda x: x["Mounts"][0].update(Source="/other"), + lambda x: x["Mounts"][0].update(RW=True), + lambda x: x["HostConfig"]["Ulimits"][0].update(Hard=999), + lambda x: x["HostConfig"].update(Memory=123), + lambda x: x["HostConfig"]["PortBindings"]["3000/tcp"][0].update(HostPort="3001"), + lambda x: x["Config"]["Env"].reverse(), + lambda x: x["Config"]["Cmd"].reverse(), + lambda x: x["NetworkSettings"]["Networks"].update(other={})] + fingerprint = RUNNER.gitea_actions_fingerprint(old) + for i, mutate in enumerate(mutations): + changed = copy.deepcopy(old) + mutate(changed) + with self.subTest(mutation=i): + self.assertFalse(RUNNER.gitea_actions_prove_legacy_order(changed, fingerprint)) + self.assertNotEqual(RUNNER.gitea_actions_fingerprint_v2(old), RUNNER.gitea_actions_fingerprint_v2(changed)) + + def test_duplicate_malformed_and_unbounded_runtime_fields_rejected(self): + duplicate = self.with_limits() + duplicate["Mounts"].append(copy.deepcopy(duplicate["Mounts"][0])) + with self.assertRaisesRegex(RUNNER.DeployError, "duplicate"): + RUNNER.gitea_actions_fingerprint_v2(duplicate) + malformed = copy.deepcopy(self.info) + malformed["HostConfig"] = None + with self.assertRaisesRegex(RUNNER.DeployError, "malformed"): + RUNNER.gitea_actions_fingerprint_v2(malformed) + many = copy.deepcopy(self.info) + many["Mounts"] = [{"Destination": "/mount" + str(i)} for i in range(8)] + with self.assertRaisesRegex(RUNNER.DeployError, "bounded"): + RUNNER.gitea_actions_prove_legacy_order(many, "0" * 64) + for value in (None, []): + info = copy.deepcopy(self.info) + info["HostConfig"]["Ulimits"] = value + self.assertTrue(RUNNER.gitea_actions_prove_legacy_order(info, RUNNER.gitea_actions_fingerprint(info))) + + def test_v1_archive_unchanged_and_v2_has_one_data_descriptor(self): + self.assertEqual(hashlib.sha256(build_actions_artifact.bundle(RUNNER.GITEA_ACTIONS_FAILED_ID)).hexdigest(), + "2ae874cfc6015378246e0bb7b24d4594a749e4136fbd82dbe9db0b57356d2162") + patch = "gitea-actions-enable-v2-test-001" + data = build_actions_artifact.bundle(patch) + self.assertEqual(data, build_actions_artifact.bundle(patch)) + artifact = self.root / "recovery.tgz" + artifact.write_bytes(data) + work = self.root / "work" + work.mkdir() + manifest, entries, payload = RUNNER.load_artifact(artifact, work) + self.assertEqual(entries, [RUNNER.GITEA_ACTIONS_V2_ENTRY]) + self.assertEqual(RUNNER.component_services(manifest["component"], entries), ("gitea",)) + self.assertEqual(RUNNER.component_builds(manifest["component"], entries), ()) + path = payload / entries[0] + descriptor = json.loads(path.read_text()) + descriptor["reconcilesFailedAttempt"] = "another-failure" + path.write_text(json.dumps(descriptor)) + with self.assertRaisesRegex(RUNNER.DeployError, "descriptor"): + RUNNER.validate_gitea_actions_payload(payload, entries, patch) + + def recovery_fixture(self): + backups = self.root / "backups" + backup = backups / RUNNER.GITEA_ACTIONS_FAILED_BACKUP + backup.mkdir(parents=True) + failed = self.root / "failed" + failed.mkdir() + ledger = self.root / "failed.jsonl" + row = {"id": RUNNER.GITEA_ACTIONS_FAILED_ID, "component": "gitea-actions-config", + "artifact": "nodedc-gitea-actions-enable-v1-20260929-001.tgz.20260929-160304", + "status": "failed", "sha256": "2ae874cfc6015378246e0bb7b24d4594a749e4136fbd82dbe9db0b57356d2162", + "backup_id": RUNNER.GITEA_ACTIONS_FAILED_BACKUP, "rollback_status": "failed:DeployError", + "message": "Gitea Actions runtime changed before mutation", "started_apply": True} + ledger.write_text(json.dumps(row) + "\n") + (failed / row["artifact"]).write_bytes(build_actions_artifact.bundle(RUNNER.GITEA_ACTIONS_FAILED_ID)) + self.old = self.with_limits() + self.reordered = copy.deepcopy(self.old) + self.reordered["Mounts"].reverse() + self.reordered["HostConfig"]["Ulimits"].reverse() + receipt = {"containerId": self.old["Id"], "fingerprint": RUNNER.gitea_actions_fingerprint(self.old), + "configBeforeSha256": RUNNER.GITEA_ACTIONS_BEFORE, + "configAfterSha256": RUNNER.GITEA_ACTIONS_AFTER, "inventory": self.before["inventory"]} + (backup / "gitea-actions-before.json").write_text(json.dumps(receipt)) + marker = RUNNER.GITEA_ACTIONS_ROOT / RUNNER.GITEA_ACTIONS_ENTRY + marker.parent.mkdir(parents=True) + marker.write_bytes(b"fixture") + for key, val in {"BACKUPS_DIR": backups, "FAILED_DIR": failed, "FAILED_STATE_FILE": ledger}.items(): + self.stack.enter_context(mock.patch.object(RUNNER, key, val)) + hashes = {"compose.yaml": "c21ef87833f87623f8352477d2b541d0a0f48769d8f9f79251d58033e90197ff", + "production.env": "9ebbf8638e035dddca25fd455b2ac4d4b6db306e1a6a4debd973b133fdeb5bb7", + "actions-enable-v1.json": "4bc516559ac7a3b62c8d90d8ebc1423ec2039e14591be62eb81fde76bb6751be", + "gitea-actions-before.json": "7b45f822d5afb165f49f0fd4575d92c930ed079cf286a685350f75c61364e0fe"} + real_sha = RUNNER.sha256_file + self.stack.enter_context(mock.patch.object(RUNNER, "sha256_file", side_effect=lambda p: hashes[p.name] if p.name in hashes else real_sha(p))) + self.inspect = self.stack.enter_context(mock.patch.object(RUNNER, "inspect_container", side_effect=[self.reordered,self.old,self.reordered])) + self.stack.enter_context(mock.patch.object(RUNNER, "inspect_local_image", return_value=self.info["Image"])) + self.stack.enter_context(mock.patch.object(RUNNER, "gitea_actions_http", side_effect=[(200,{"version":"1.27.2"}),(404,None)])) + self.inventory = self.stack.enter_context(mock.patch.object(RUNNER, "gitea_ci_inventory", return_value=copy.deepcopy(self.before["inventory"]))) + self.mutation = self.stack.enter_context(mock.patch.object(RUNNER, "gitea_actions_replace")) + self.restart = self.stack.enter_context(mock.patch.object(RUNNER.subprocess, "run")) + return ledger, row + + def test_readonly_reconciliation_proves_saved_hash_for_three_order_variations(self): + self.recovery_fixture() + with redirect_stdout(io.StringIO()) as output: + result = RUNNER.preflight_gitea_actions([RUNNER.GITEA_ACTIONS_V2_ENTRY]) + self.assertEqual(self.inspect.call_count, 3) + self.assertEqual(result["fingerprintVersion"], 2) + self.assertFalse(result["mutationStarted"]) + self.assertEqual(result["config"], self.original) + self.assertIn('"matchesSavedStateByOrderOnly": true', output.getvalue()) + self.assertNotIn("fixture-keep-private", output.getvalue()) + self.mutation.assert_not_called() + self.restart.assert_not_called() + + def test_readonly_reconciliation_rejects_drift_without_mutation(self): + self.recovery_fixture() + self.reordered["HostConfig"]["Memory"] = 123 + with redirect_stdout(io.StringIO()), self.assertRaisesRegex(RUNNER.DeployError, "cannot prove order-only"): + RUNNER.preflight_gitea_actions_recovery() + self.mutation.assert_not_called() + self.restart.assert_not_called() + + def test_reconciliation_rejects_wrong_ledger_before_inspection(self): + ledger, row = self.recovery_fixture() + row["rollback_status"] = "ok:gitea-actions-config" + ledger.write_text(json.dumps(row) + "\n") + with self.assertRaisesRegex(RUNNER.DeployError, "failed-attempt evidence"): + RUNNER.preflight_gitea_actions_recovery() + self.inspect.assert_not_called() + self.restart.assert_not_called() + + def test_reconciliation_rejects_changed_config_and_other_containers(self): + self.recovery_fixture() + self.config.write_bytes(self.original + b"# drift") + with self.assertRaisesRegex(RUNNER.DeployError, "predecessor"): + RUNNER.preflight_gitea_actions_recovery() + self.inspect.assert_not_called() + self.config.write_bytes(self.original) + self.inventory.return_value = {"other": {"running": False}} + with self.assertRaisesRegex(RUNNER.DeployError, "preserved inventory"): + RUNNER.preflight_gitea_actions_recovery() + self.restart.assert_not_called() + + def test_pre_mutation_failure_restores_only_source_without_restart(self): + self.before.update({"fingerprint": RUNNER.gitea_actions_fingerprint_v2(self.info), + "fingerprintVersion": 2, "mutationStarted": False}) + with mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info), mock.patch.object(RUNNER.subprocess, "run") as restart, mock.patch.object(RUNNER, "accept_gitea_actions") as accept, mock.patch.object(RUNNER, "restore_overlay_source") as restore: + RUNNER.rollback_gitea_actions(self.root, self.backup, [RUNNER.GITEA_ACTIONS_V2_ENTRY], "stamp", self.before, True) + restart.assert_not_called() + accept.assert_called_once_with(self.before, enabled=False) + restore.assert_called_once() + self.assertEqual(self.config.read_bytes(), self.original) + + def test_apply_and_accept_keep_working_when_inspect_array_order_changes(self): + old = self.with_limits() + reordered = copy.deepcopy(old) + reordered["Mounts"].reverse() + reordered["HostConfig"]["Ulimits"].reverse() + self.before.update({"fingerprint": RUNNER.gitea_actions_fingerprint_v2(old), + "fingerprintVersion": 2, "mutationStarted": False}) + with mock.patch.object(RUNNER.os, "chown"), mock.patch.object(RUNNER.os, "fchown"), mock.patch.object(RUNNER, "gitea_actions_container", side_effect=[reordered,old]), mock.patch.object(RUNNER.subprocess, "run") as restart, mock.patch.object(RUNNER, "gitea_actions_http", side_effect=[(200,{"version":"1.27.2"}),(200,{"data":"Hello, nodedc-ci-probe!"})]), mock.patch.object(RUNNER, "gitea_ci_inventory", return_value=self.before["inventory"]), redirect_stdout(io.StringIO()): + RUNNER.apply_gitea_actions(self.before, self.backup) + RUNNER.accept_gitea_actions(self.before) + restart.assert_called_once() + self.assertEqual(self.config.read_bytes(), self.target) + + def test_reconciliation_rejects_changed_failed_archive_before_inspection(self): + _, row = self.recovery_fixture() + (RUNNER.FAILED_DIR / row["artifact"]).write_bytes(b"changed") + with self.assertRaisesRegex(RUNNER.DeployError, "archived evidence"): + RUNNER.preflight_gitea_actions_recovery() + self.inspect.assert_not_called() + self.restart.assert_not_called() + + def test_full_v2_apply_preserves_v1_marker_and_records_fingerprint_version(self): + paths, root = self.full_apply(version="v2") + row = json.loads(paths["STATE_FILE"].read_text()) + self.assertEqual(row["status"], "ok") + self.assertEqual(self.config.read_bytes(), self.target) + self.assertTrue((root / RUNNER.GITEA_ACTIONS_V2_ENTRY).is_file()) + self.assertEqual((root / RUNNER.GITEA_ACTIONS_ENTRY).read_bytes(), b"preserved failed-attempt marker") + receipt = json.loads((paths["BACKUPS_DIR"] / row["backup_id"] / "gitea-actions-before.json").read_text()) + self.assertEqual(receipt["fingerprintVersion"], 2) + + def test_full_v2_failed_acceptance_restores_disabled_config_and_keeps_v1_marker(self): + paths, root = self.full_apply(fail_acceptance=True, version="v2") + row = json.loads(paths["FAILED_STATE_FILE"].read_text()) + self.assertEqual(row["rollback_status"], "ok:gitea-actions-config") + self.assertEqual(self.config.read_bytes(), self.original) + self.assertFalse((root / RUNNER.GITEA_ACTIONS_V2_ENTRY).exists()) + self.assertEqual((root / RUNNER.GITEA_ACTIONS_ENTRY).read_bytes(), b"preserved failed-attempt marker") + self.assertFalse(paths["STATE_FILE"].exists()) + + +if __name__ == "__main__": + unittest.main()