From 7235704ae6039ec7816f6dcf547f1f7837847d0f Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Fri, 27 Nov 2026 08:21:26 +0300 Subject: [PATCH] Archive the exact signed Nexus readback after original first-meter exit --- docs/QUOTA_V2_GENESIS_QUARANTINE_HANDOFF.md | 11 ++- .../public_tls_meter_retirement.py | 99 ++++++++++++++++++- .../public_tls_wal_watch.py | 6 +- ...st_quota_v2_public_tls_meter_retirement.py | 66 +++++++++++++ 4 files changed, 176 insertions(+), 6 deletions(-) diff --git a/docs/QUOTA_V2_GENESIS_QUARANTINE_HANDOFF.md b/docs/QUOTA_V2_GENESIS_QUARANTINE_HANDOFF.md index 678d9718..22ede7dc 100644 --- a/docs/QUOTA_V2_GENESIS_QUARANTINE_HANDOFF.md +++ b/docs/QUOTA_V2_GENESIS_QUARANTINE_HANDOFF.md @@ -600,7 +600,16 @@ released lock without creating a file, and identical independently verified denial/WAL digests. This is local historical evidence only: not a re-start permit, proof of delivery, complete pre-bootstrap history, terminal settlement or a refund. No installer, persistent service or public issuer -uses it. Real installed two-Node retirement still requires hosted qualification. +uses it. The hosted installed two-Node rehearsal has verified physical meter +retirement. The follow-up archive retains the exact original signed response, +challenge/request, captured receipt time and retirement summary in one +root-private fsynced no-replace file keyed by original runtime identity. A +conflicting replay, symlink or unsafe archive inode fails closed. The same +lifetime lock remains acquired through archive publication and re-audit. +The archive does **not** sign local pidfd/fence observations with the enrolled +Node key; only the embedded Nexus WAL response is signed. Historical +re-verification proves that response, not present liveness, delivery or a +refund; off-host qualification is still required. ## Sealed TLS material before any future public spawn diff --git a/experiments/quota-v2-physical-stop/public_tls_meter_retirement.py b/experiments/quota-v2-physical-stop/public_tls_meter_retirement.py index 78d9df86..e0d4f94f 100644 --- a/experiments/quota-v2-physical-stop/public_tls_meter_retirement.py +++ b/experiments/quota-v2-physical-stop/public_tls_meter_retirement.py @@ -16,6 +16,7 @@ import os from pathlib import Path import select +import secrets import stat import time import uuid @@ -28,6 +29,78 @@ DIRECTORY = Path("/var/lib/xmesh-first-meter/runtime/ledger") FENCE_NAMESPACE = uuid.UUID("74df852d-a5a6-47d8-bac9-55f84d9b102a") MAX_RETIRE_NS = 30_000_000_000 +RECORD_DIRECTORY = Path("/opt/xmesh-ci-namespace-proof") +MAX_RECORD = 64 << 10 + + +def _record_name(runtime): + if not wal._hex(runtime, 64): + raise ValueError("invalid archived runtime identity") + return f"retirement-{runtime}.json" + + +def _retain_record(record): + """No-replace fsynced diagnostic archive, NOT a signed Node attestation. + + Root can still fabricate local observations. Only the embedded Nexus + witness is cryptographically authentic; nothing here may authorize a + successor or serve as a terminal checkpoint. + """ + _require_disposable() + raw = wal.observed.canonical(record) + if not 0 < len(raw) <= MAX_RECORD: + raise ValueError("retirement archive exceeds bound") + target = _record_name(record["result"]["runtimeId"]) + fd = journal._validate_directory(RECORD_DIRECTORY) + tmp = None + try: + anchor = _directory_identity(fd) + + def check_directory(): + named = os.stat(RECORD_DIRECTORY, follow_symlinks=False) + if (not stat.S_ISDIR(named.st_mode) + or (named.st_dev, named.st_ino) != anchor + or _directory_identity(fd) != anchor): + raise ValueError("retirement archive directory changed") + + def verify_existing(): + try: + digest = _file_hash(fd, target, MAX_RECORD) + except FileNotFoundError: + return False + if digest != hashlib.sha256(raw).hexdigest(): + raise ValueError("conflicting retirement record; cannot overwrite") + return True + + check_directory() + if not verify_existing(): + candidate = ".retirement-" + secrets.token_hex(16) + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC + output_fd = os.open(candidate, flags, 0o600, dir_fd=fd) + tmp = candidate + with os.fdopen(output_fd, "wb") as output: + output.write(raw) + output.flush() + os.fsync(output.fileno()) + check_directory() + try: + os.link(tmp, target, src_dir_fd=fd, dst_dir_fd=fd, follow_symlinks=False) + except FileExistsError: + # Only an exact replay under the same incarnation is accepted. + pass + os.unlink(tmp, dir_fd=fd) + tmp = None + if not verify_existing(): + raise ValueError("retirement archive was not installed") + os.fsync(fd) + check_directory() + if not verify_existing(): + raise ValueError("retirement archive disappeared") + return hashlib.sha256(raw).hexdigest() + finally: + if tmp is not None: + os.unlink(tmp, dir_fd=fd) + os.close(fd) def _require_disposable(): @@ -184,7 +257,7 @@ def readback_deadline(): if not 0 <= time.monotonic_ns() - readback_start < watch.MAX_CHECK_NS: raise ValueError("first-Genesis WAL readback exceeded time budget") - self._snapshot, self._witness_sha = watch._checked_evidence( + self._snapshot, self._witness = watch._checked_evidence( roster, user, measured, os.fspath(DIRECTORY), remeasure, readback_deadline) if self._snapshot["identity"] != self._identity: raise ValueError("WAL witness used another directory") @@ -284,7 +357,7 @@ def fence_all(self): self._live() self._prestop = evidence - def verify_exited(self): + def verify_exited(self, *, retain=False): """Observe physical exit; do NOT interpret charged bytes as delivery.""" if self._prestop is None or self._pidfd is None or not _poll_exit(self._pidfd): raise ValueError("original meter pidfd has not exited after durable full-roster denial") @@ -295,11 +368,12 @@ def verify_exited(self): self._bound(False) if not _poll_exit(self._pidfd): raise ValueError("original meter pidfd exit could not be confirmed") - return { + result = { "kind": "xmesh.quota-v2.nonfinal-first-meter-retirement", "runtimeId": self._measured[3], "containerId": self._measured[0], "startedAt": self._measured[1], - "signedWalReadbackSha256": self._witness_sha, + "signedWalReadbackSha256": hashlib.sha256( + self._witness["signedResponse"].encode("utf-8")).hexdigest(), "inventorySha256": self._snapshot["sha256"], "committedChargeHeadsSha256": self._snapshot["chargeHeadsSha256"], "durableUserDenials": dict(self._prestop), @@ -309,6 +383,23 @@ def verify_exited(self): "settlementEligible": False, "canResume": False, "refundableBytes": 0, } + if not retain: + return result + # Hold the exact released lifetime lock across publication. The + # original kernel witness is checked again before reporting success. + record = { + "schemaVersion": 1, + "kind": "xmesh.quota-v2.historical-retirement-archive", + "result": result, + "walReadback": self._witness, + } + digest = _retain_record(record) + if self._ledger(docker) != self._prestop: + raise ValueError("retirement ledger changed during archival") + self._bound(False) + if not _poll_exit(self._pidfd): + raise ValueError("original pidfd exit changed during archival") + return {"result": result, "archiveSha256": digest} def close(self): for name in ("_directory_fd", "_pidfd"): diff --git a/experiments/quota-v2-physical-stop/public_tls_wal_watch.py b/experiments/quota-v2-physical-stop/public_tls_wal_watch.py index e0aeacab..d66e6bab 100644 --- a/experiments/quota-v2-physical-stop/public_tls_wal_watch.py +++ b/experiments/quota-v2-physical-stop/public_tls_wal_watch.py @@ -348,7 +348,11 @@ def _checked_evidence(roster, user, measured, directory, remeasure, deadline): raise ValueError("Nexus WAL witness expired or clock changed") # Private historical evidence for the disposable retirement verifier. # The bytes/digest do not establish terminality or grant any authority. - return before, hashlib.sha256(raw).hexdigest() + return before, { + "request": request, + "signedResponse": raw.decode("utf-8"), + "receivedAtMs": received_wall, + } def _check(roster, user, measured, directory, remeasure, deadline): diff --git a/tests/test_quota_v2_public_tls_meter_retirement.py b/tests/test_quota_v2_public_tls_meter_retirement.py index 5f20c3b5..ebac4306 100644 --- a/tests/test_quota_v2_public_tls_meter_retirement.py +++ b/tests/test_quota_v2_public_tls_meter_retirement.py @@ -6,6 +6,7 @@ """ from contextlib import ExitStack import hashlib +import json import os from pathlib import Path import subprocess @@ -161,6 +162,71 @@ def test_real_original_exit_with_same_flocked_ledger_and_signed_heads(self): self.assertEqual(result["refundableBytes"], 0) self.assertEqual(proof.verify_exited(), result) + def test_archive_only_after_real_exit_preserves_exact_signed_response(self): + with tempfile.TemporaryDirectory(prefix="xmesh-retirement-archive-") as folder: + with mock.patch.object(retirement, "RECORD_DIRECTORY", Path(folder)): + proof = self.fenced() + with self.assertRaisesRegex(ValueError, "pidfd has not exited"): + proof.verify_exited(retain=True) + self.assertFalse(list(Path(folder).iterdir())) + self.stop_child() + published = proof.verify_exited(retain=True) + path = Path(folder) / retirement._record_name(self.runtime) + raw = path.read_bytes() + record = json.loads(raw) + self.assertEqual(raw, retirement.wal.observed.canonical(record)) + self.assertEqual(published["archiveSha256"], hashlib.sha256(raw).hexdigest()) + self.assertEqual(record["result"], published["result"]) + evidence = record["walReadback"] + signed = evidence["signedResponse"].encode() + self.assertEqual(hashlib.sha256(signed).hexdigest(), + record["result"]["signedWalReadbackSha256"]) + # Independent signature verification at captured historical + # receive time, not a present-time freshness assertion. + watch._verify(signed, evidence["request"], self.roster.pinned, + proof._snapshot, evidence["receivedAtMs"]) + # Altering signed bytes cannot survive signature verification. + altered = json.loads(signed) + envelope = json.loads(altered["signedEnvelope"]) + envelope["signature"] = "0"*128 + altered["signedEnvelope"] = retirement.wal.observed.canonical(envelope).decode()+"\n" + with self.assertRaises(Exception): + watch._verify(retirement.wal.observed.canonical(altered), + evidence["request"], self.roster.pinned, + proof._snapshot, evidence["receivedAtMs"]) + self.assertEqual(path.stat().st_mode & 0o777, 0o600) + self.assertEqual(path.stat().st_nlink, 1) + self.assertEqual(proof.verify_exited(retain=True), published) + changed = dict(record, schemaVersion=2) + with self.assertRaisesRegex(ValueError, "conflicting retirement"): + retirement._retain_record(changed) + self.assertEqual(path.read_bytes(), raw) + + def test_archive_rejects_symlink_unsafe_mode_and_hardlink(self): + with tempfile.TemporaryDirectory(prefix="xmesh-retirement-archive-") as folder: + root = Path(folder) + with mock.patch.object(retirement, "RECORD_DIRECTORY", root): + proof = self.fenced() + self.stop_child() + published = proof.verify_exited(retain=True) + path = root / retirement._record_name(self.runtime) + raw = path.read_bytes() + old = root / "other" + path.rename(old) + path.symlink_to(old) + with self.assertRaises(OSError): + proof.verify_exited(retain=True) + path.unlink() + os.link(old, path) + with self.assertRaisesRegex(ValueError, "invalid original WAL file"): + proof.verify_exited(retain=True) + old.unlink() + path.chmod(0o644) + with self.assertRaisesRegex(ValueError, "invalid original WAL file"): + proof.verify_exited(retain=True) + self.assertEqual(path.read_bytes(), raw) + self.assertEqual(hashlib.sha256(raw).hexdigest(), published["archiveSha256"]) + def test_false_Docker_stopped_metadata_cannot_replace_real_pidfd(self): proof = self.fenced() self.running = False