328 lines
19 KiB
Python
328 lines
19 KiB
Python
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_and_malformed_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)
|
|
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 many_fields(self):
|
|
value = copy.deepcopy(self.info)
|
|
value["Mounts"].extend({"Destination": "/mount" + str(i), "Source": "/data" + str(i), "RW": False} for i in range(6))
|
|
value["HostConfig"]["Ulimits"] = [{"Name": "limit%02d" % i, "Soft": 1024, "Hard": 4096} for i in range(16)]
|
|
return value
|
|
|
|
def cross_sample_orders(self):
|
|
target = self.many_fields()
|
|
for values in (target["Mounts"], target["HostConfig"]["Ulimits"]):
|
|
values[:] = values[::2] + values[1::2]
|
|
a, b = copy.deepcopy(target), copy.deepcopy(target)
|
|
a["HostConfig"]["Ulimits"].sort(key=lambda x: x["Name"])
|
|
b["Mounts"].sort(key=lambda x: x["Destination"])
|
|
return target, a, b
|
|
|
|
def test_large_lists_direct_match_does_not_require_factorial_search(self):
|
|
info = self.many_fields()
|
|
evidence = {}
|
|
self.assertTrue(RUNNER.gitea_actions_prove_legacy_order(info, RUNNER.gitea_actions_fingerprint(info), evidence))
|
|
self.assertEqual(evidence["mountCount"], 8)
|
|
self.assertEqual(evidence["ulimitCount"], 16)
|
|
self.assertEqual(len(evidence.get("tested", set())), 0)
|
|
|
|
def test_cross_sample_proof_recovers_exact_hash_with_large_lists(self):
|
|
target, a, b = self.cross_sample_orders()
|
|
expected = RUNNER.gitea_actions_fingerprint(target)
|
|
evidence = {}
|
|
self.assertNotEqual(RUNNER.gitea_actions_fingerprint(a), expected)
|
|
self.assertNotEqual(RUNNER.gitea_actions_fingerprint(b), expected)
|
|
self.assertFalse(RUNNER.gitea_actions_prove_legacy_order(a, expected, evidence))
|
|
self.assertTrue(RUNNER.gitea_actions_prove_legacy_order(b, expected, evidence))
|
|
self.assertLessEqual(len(evidence["tested"]), 65536)
|
|
# A cached proof is not transferable to changed values.
|
|
b["HostConfig"]["Ulimits"][0]["Hard"] += 1
|
|
with self.assertRaisesRegex(RUNNER.DeployError, "runtime changed"):
|
|
RUNNER.gitea_actions_prove_legacy_order(b, expected, evidence)
|
|
|
|
def test_repeated_observations_do_not_repeat_hash_search(self):
|
|
info = self.many_fields()
|
|
evidence = {}
|
|
self.assertFalse(RUNNER.gitea_actions_prove_legacy_order(info, "0" * 64, evidence))
|
|
attempts = len(evidence["tested"])
|
|
for _ in range(64):
|
|
self.assertFalse(RUNNER.gitea_actions_prove_legacy_order(info, "0" * 64, evidence))
|
|
self.assertEqual(len(evidence["tested"]), attempts)
|
|
self.assertLessEqual(attempts, 65536)
|
|
|
|
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, "runtime changed"):
|
|
RUNNER.preflight_gitea_actions_recovery()
|
|
self.mutation.assert_not_called()
|
|
self.restart.assert_not_called()
|
|
|
|
def test_readonly_reconciliation_handles_cross_sample_proof_and_two_confirmations(self):
|
|
self.recovery_fixture()
|
|
target, a, b = self.cross_sample_orders()
|
|
receipt_path = RUNNER.BACKUPS_DIR / RUNNER.GITEA_ACTIONS_FAILED_BACKUP / "gitea-actions-before.json"
|
|
receipt = json.loads(receipt_path.read_text())
|
|
receipt["fingerprint"] = RUNNER.gitea_actions_fingerprint(target)
|
|
receipt_path.write_text(json.dumps(receipt))
|
|
self.inspect.side_effect = [a,b,a,b]
|
|
with redirect_stdout(io.StringIO()) as output:
|
|
before = RUNNER.preflight_gitea_actions_recovery()
|
|
self.assertEqual(self.inspect.call_count, 4)
|
|
self.assertFalse(before["mutationStarted"])
|
|
report = json.loads(output.getvalue().split("gitea_actions_readonly_audit=")[1])
|
|
self.assertTrue(report["exactLegacyProof"])
|
|
self.assertEqual(report["sampleCount"], 4)
|
|
self.assertEqual(report["ulimitCount"], 16)
|
|
self.assertTrue(all(s["matchesSavedStateByOrderOnly"] for s in report["samples"]))
|
|
self.mutation.assert_not_called()
|
|
self.restart.assert_not_called()
|
|
|
|
def test_unproven_stable_drift_exhausts_readonly_samples_without_mutation(self):
|
|
self.recovery_fixture()
|
|
self.reordered["HostConfig"]["Memory"] = 123
|
|
self.inspect.side_effect = None
|
|
self.inspect.return_value = self.reordered
|
|
with redirect_stdout(io.StringIO()) as output, self.assertRaisesRegex(RUNNER.DeployError, "cannot prove order-only"):
|
|
RUNNER.preflight_gitea_actions_recovery()
|
|
self.assertEqual(self.inspect.call_count, 64)
|
|
report = json.loads(output.getvalue().split("gitea_actions_readonly_audit=")[1])
|
|
self.assertFalse(report["exactLegacyProof"])
|
|
self.assertFalse(report["mutation"])
|
|
self.assertEqual(report["sampleCount"], 64)
|
|
self.assertNotIn("fixture-keep-private", output.getvalue())
|
|
self.mutation.assert_not_called()
|
|
self.restart.assert_not_called()
|
|
|
|
def test_proof_on_last_search_sample_still_requires_two_fresh_confirmations(self):
|
|
self.recovery_fixture()
|
|
target, a, b = self.cross_sample_orders()
|
|
receipt_path = RUNNER.BACKUPS_DIR / RUNNER.GITEA_ACTIONS_FAILED_BACKUP / "gitea-actions-before.json"
|
|
receipt = json.loads(receipt_path.read_text())
|
|
receipt["fingerprint"] = RUNNER.gitea_actions_fingerprint(target)
|
|
receipt_path.write_text(json.dumps(receipt))
|
|
self.inspect.side_effect = [a] * 63 + [b,a,b]
|
|
with redirect_stdout(io.StringIO()) as output:
|
|
RUNNER.preflight_gitea_actions_recovery()
|
|
self.assertEqual(self.inspect.call_count, 66)
|
|
report = json.loads(output.getvalue().split("gitea_actions_readonly_audit=")[1])
|
|
self.assertTrue(report["exactLegacyProof"])
|
|
self.assertEqual(report["sampleCount"], 66)
|
|
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()
|