Prove legacy Gitea state from observed inspect orders

This commit is contained in:
Codex
2026-09-29 16:44:22 +03:00
parent ae5adfbd63
commit d87a0c48b4
3 changed files with 201 additions and 33 deletions
+73 -23
View File
@@ -8,7 +8,6 @@ import grp
import hashlib import hashlib
import http.client import http.client
import io import io
import itertools
import json import json
import os import os
import pwd import pwd
@@ -31568,25 +31567,70 @@ def gitea_actions_context_fingerprint(info, before):
else gitea_actions_fingerprint(info)) else gitea_actions_fingerprint(info))
def gitea_actions_prove_legacy_order(info, expected): def gitea_actions_order_variants(observed, canonical, key):
if observed is None:
yield (), None
return
# Reuse validated deep-copied values, never retain mutable inspect objects.
values = {item[key]: item for item in canonical}
observed_keys = tuple(item[key] for item in observed)
canonical_keys = tuple(item[key] for item in canonical)
for order in (observed_keys, canonical_keys, canonical_keys[::-1]):
for offset in range(max(1, len(order))):
rotated = order[offset:] + order[:offset]
yield rotated, [values[name] for name in rotated]
def gitea_actions_prove_legacy_order(info, expected, evidence=None):
# Find an exact legacy preimage using observed orders, not factorial enumeration.
evidence = {} if evidence is None else evidence
fields = gitea_actions_ordered_fields(info) fields = gitea_actions_ordered_fields(info)
mounts, limits = fields["Mounts"], fields["HostConfig"].get("Ulimits") canonical = hashlib.sha256(json.dumps(fields, sort_keys=True).encode()).hexdigest()
count = 1 if evidence.setdefault("canonicalFingerprint", canonical) != canonical or evidence.setdefault("expected", expected) != expected:
for length in (len(mounts), len(limits or [])): die("Gitea Actions runtime changed during read-only order audit")
for factor in range(2, length + 1): evidence["mountCount"] = len(fields["Mounts"])
count *= factor evidence["ulimitCount"] = len(fields["HostConfig"].get("Ulimits") or [])
if count > 4096: if evidence.get("matched"):
die("Gitea Actions order audit exceeds bounded permutation limit") return True
for mount_order in itertools.permutations(mounts): if gitea_actions_fingerprint(info) == expected:
fields["Mounts"] = list(mount_order) evidence["matched"] = True
for limit_order in itertools.permutations(limits or []): return True
if limits is not None: mounts = evidence.setdefault("mountOrders", {})
fields["HostConfig"]["Ulimits"] = list(limit_order) limits = evidence.setdefault("limitOrders", {})
for catalog, observed, normalized, key in (
(mounts, info["Mounts"], fields["Mounts"], "Destination"),
(limits, info["HostConfig"].get("Ulimits"), fields["HostConfig"].get("Ulimits"), "Name")):
for order, values in gitea_actions_order_variants(observed, normalized, key):
if len(catalog) < 256:
catalog.setdefault(order, values)
tested = evidence.setdefault("tested", set())
for mount_key, mount_order in mounts.items():
fields["Mounts"] = mount_order
for limit_key, limit_order in limits.items():
pair = (mount_key, limit_key)
if pair in tested:
continue
if len(tested) >= 65536:
return False
tested.add(pair)
if limit_order is not None:
fields["HostConfig"]["Ulimits"] = limit_order
if hashlib.sha256(json.dumps(fields, sort_keys=True).encode()).hexdigest() == expected: if hashlib.sha256(json.dumps(fields, sort_keys=True).encode()).hexdigest() == expected:
evidence["matched"] = True
return True return True
return False return False
def gitea_actions_order_audit_report(evidence, samples):
return {"mutation": False, "method": "observed-orders-and-cyclic-variants",
"sampleCount": len(samples), "samples": samples[-3:],
"mountCount": evidence.get("mountCount"), "ulimitCount": evidence.get("ulimitCount"),
"mountOrders": len(evidence.get("mountOrders", {})),
"ulimitOrders": len(evidence.get("limitOrders", {})),
"combinationsChecked": len(evidence.get("tested", set())),
"exactLegacyProof": bool(evidence.get("matched"))}
def preflight_gitea_actions_recovery(): def preflight_gitea_actions_recovery():
# Read-only reconciliation of one known failure, never a generic drift override. # Read-only reconciliation of one known failure, never a generic drift override.
backup = BACKUPS_DIR / GITEA_ACTIONS_FAILED_BACKUP backup = BACKUPS_DIR / GITEA_ACTIONS_FAILED_BACKUP
@@ -31619,18 +31663,23 @@ def preflight_gitea_actions_recovery():
gitea_actions_transform(data) gitea_actions_transform(data)
if old.get("configBeforeSha256") != GITEA_ACTIONS_BEFORE or old.get("configAfterSha256") != GITEA_ACTIONS_AFTER: if old.get("configBeforeSha256") != GITEA_ACTIONS_BEFORE or old.get("configAfterSha256") != GITEA_ACTIONS_AFTER:
die("Gitea Actions recovery config evidence mismatch") die("Gitea Actions recovery config evidence mismatch")
samples = [] samples, evidence, confirmations = [], {}, 0
for _ in range(3): for _ in range(66):
info = gitea_actions_container() info = gitea_actions_container()
matched = (info["Id"] == old.get("containerId") if info["Id"] != old.get("containerId"):
and gitea_actions_prove_legacy_order(info, old.get("fingerprint"))) die("Gitea Actions recovery container identity changed")
matched = gitea_actions_prove_legacy_order(info, old.get("fingerprint"), evidence)
sample = {"legacyFingerprint": gitea_actions_fingerprint(info), sample = {"legacyFingerprint": gitea_actions_fingerprint(info),
"canonicalFingerprint": gitea_actions_fingerprint_v2(info), "canonicalFingerprint": gitea_actions_fingerprint_v2(info),
"matchesSavedStateByOrderOnly": matched} "matchesSavedStateByOrderOnly": matched}
samples.append(sample) samples.append(sample)
if not matched: if matched:
print("gitea_actions_readonly_audit=" + json.dumps({"samples": samples, "mutation": False}, sort_keys=True)) confirmations += 1
die("Gitea Actions recovery cannot prove order-only difference; runtime mutation forbidden") if confirmations == 3:
break
elif len(samples) >= 64:
print("gitea_actions_readonly_audit=" + json.dumps(gitea_actions_order_audit_report(evidence, samples), sort_keys=True))
die("Gitea Actions recovery cannot prove order-only difference from observed orders; runtime mutation forbidden")
if len({sample["canonicalFingerprint"] for sample in samples}) != 1: if len({sample["canonicalFingerprint"] for sample in samples}) != 1:
die("Gitea Actions recovery runtime changed during read-only audit") die("Gitea Actions recovery runtime changed during read-only audit")
if (info["Image"] != inspect_local_image(GITEA_ACTIONS_IMAGE, "Gitea Actions recovery image") if (info["Image"] != inspect_local_image(GITEA_ACTIONS_IMAGE, "Gitea Actions recovery image")
@@ -31645,8 +31694,9 @@ def preflight_gitea_actions_recovery():
inventory.pop(info["Id"], None) inventory.pop(info["Id"], None)
if inventory != old.get("inventory"): if inventory != old.get("inventory"):
die("Gitea Actions recovery preserved inventory mismatch") die("Gitea Actions recovery preserved inventory mismatch")
print("gitea_actions_readonly_audit=" + json.dumps({"samples": samples, "mutation": False, report = gitea_actions_order_audit_report(evidence, samples)
"configUnchanged": True, "otherContainersUnchanged": True, "healthy": True}, sort_keys=True)) report.update({"configUnchanged": True, "otherContainersUnchanged": True, "healthy": True})
print("gitea_actions_readonly_audit=" + json.dumps(report, sort_keys=True))
return {"config": data, "metadata": metadata, "containerId": info["Id"], return {"config": data, "metadata": metadata, "containerId": info["Id"],
"fingerprint": samples[0]["canonicalFingerprint"], "fingerprintVersion": 2, "fingerprint": samples[0]["canonicalFingerprint"], "fingerprintVersion": 2,
"mutationStarted": False, "inventory": inventory} "mutationStarted": False, "inventory": inventory}
+26 -4
View File
@@ -145,10 +145,32 @@ NAS must prove that it explains this specific attempt before another apply.
attempt. Its read-only `plan` checks the failed journal, failed archive and saved attempt. Its read-only `plan` checks the failed journal, failed archive and saved
receipt digests, unchanged disabled config, leftover v1 descriptor, fixed Compose receipt digests, unchanged disabled config, leftover v1 descriptor, fixed Compose
context, same healthy Gitea and all other container identities/uptimes. For each context, same healthy Gitea and all other container identities/uptimes. For each
of three fresh inspections it must reconstruct the saved legacy fingerprint by of the fresh inspections it must reconstruct the saved legacy fingerprint by
permuting only Mounts and HostConfig.Ulimits, retaining every field and value. changing only Mounts and HostConfig.Ulimits order, retaining every field and value.
The search is capped at 4096 permutations and rejects duplicate mount destinations Duplicate mount destinations or limit names are rejected. Any unexplained
or limit names. Any unexplained difference rejects the plan before mutation. difference rejects the plan before mutation.
The initial v2 plan exposed a second algorithm defect: its up-front factorial
count exceeded 4096 before any matching was attempted. The corrected audit does
not enumerate permutations. It collects the actual orders returned by Docker,
their cyclic rotations, and rotations of canonical/reversed order. It tests
combinations of the two catalogs against the exact saved SHA-256; it never
assumes that an unobserved ordering is correct without that hash match. Each
fresh sample must have the same canonical fingerprint, so values from different
runtime configurations cannot be mixed into a proof. A direct legacy hash match
is also accepted without searching.
The audit collects at most 64 samples for the search and two further samples to
confirm a found proof. Each catalog has at most 256 orders, and at most 65536
distinct combinations are hashed; identical observations do not repeat the
search. These are bounds on read-only evidence collection, not on valid list
lengths via factorial size. An incomplete search fails closed with counts and
the last three fingerprint samples. The report never includes raw inspect data
or credentials. Regression tests cover 8 mounts/16 limits, a proof requiring
different observations for the two collections, changing values during sampling,
and exhaustion of the read-only search without mutation. This is an exact-match
search over a bounded candidate set, not an exhaustive solver for arbitrary
permutations; absence of a match is not itself proof of runtime drift.
Only after that plan has been reviewed can a separate apply repeat the audit 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 under the deploy lock and perform the same one-boolean transition. New comparison
+102 -6
View File
@@ -54,7 +54,7 @@ class ActionsRecoveryTests(unittest.TestCase):
self.assertFalse(RUNNER.gitea_actions_prove_legacy_order(changed, fingerprint)) self.assertFalse(RUNNER.gitea_actions_prove_legacy_order(changed, fingerprint))
self.assertNotEqual(RUNNER.gitea_actions_fingerprint_v2(old), RUNNER.gitea_actions_fingerprint_v2(changed)) self.assertNotEqual(RUNNER.gitea_actions_fingerprint_v2(old), RUNNER.gitea_actions_fingerprint_v2(changed))
def test_duplicate_malformed_and_unbounded_runtime_fields_rejected(self): def test_duplicate_and_malformed_runtime_fields_rejected(self):
duplicate = self.with_limits() duplicate = self.with_limits()
duplicate["Mounts"].append(copy.deepcopy(duplicate["Mounts"][0])) duplicate["Mounts"].append(copy.deepcopy(duplicate["Mounts"][0]))
with self.assertRaisesRegex(RUNNER.DeployError, "duplicate"): with self.assertRaisesRegex(RUNNER.DeployError, "duplicate"):
@@ -63,15 +63,58 @@ class ActionsRecoveryTests(unittest.TestCase):
malformed["HostConfig"] = None malformed["HostConfig"] = None
with self.assertRaisesRegex(RUNNER.DeployError, "malformed"): with self.assertRaisesRegex(RUNNER.DeployError, "malformed"):
RUNNER.gitea_actions_fingerprint_v2(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, []): for value in (None, []):
info = copy.deepcopy(self.info) info = copy.deepcopy(self.info)
info["HostConfig"]["Ulimits"] = value info["HostConfig"]["Ulimits"] = value
self.assertTrue(RUNNER.gitea_actions_prove_legacy_order(info, RUNNER.gitea_actions_fingerprint(info))) 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): 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(), self.assertEqual(hashlib.sha256(build_actions_artifact.bundle(RUNNER.GITEA_ACTIONS_FAILED_ID)).hexdigest(),
"2ae874cfc6015378246e0bb7b24d4594a749e4136fbd82dbe9db0b57356d2162") "2ae874cfc6015378246e0bb7b24d4594a749e4136fbd82dbe9db0b57356d2162")
@@ -150,11 +193,64 @@ class ActionsRecoveryTests(unittest.TestCase):
def test_readonly_reconciliation_rejects_drift_without_mutation(self): def test_readonly_reconciliation_rejects_drift_without_mutation(self):
self.recovery_fixture() self.recovery_fixture()
self.reordered["HostConfig"]["Memory"] = 123 self.reordered["HostConfig"]["Memory"] = 123
with redirect_stdout(io.StringIO()), self.assertRaisesRegex(RUNNER.DeployError, "cannot prove order-only"): with redirect_stdout(io.StringIO()), self.assertRaisesRegex(RUNNER.DeployError, "runtime changed"):
RUNNER.preflight_gitea_actions_recovery() RUNNER.preflight_gitea_actions_recovery()
self.mutation.assert_not_called() self.mutation.assert_not_called()
self.restart.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): def test_reconciliation_rejects_wrong_ledger_before_inspection(self):
ledger, row = self.recovery_fixture() ledger, row = self.recovery_fixture()
row["rollback_status"] = "ok:gitea-actions-config" row["rollback_status"] = "ok:gitea-actions-config"