Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions docs/QUOTA_V2_GENESIS_QUARANTINE_HANDOFF.md
Original file line number Diff line number Diff line change
Expand Up @@ -559,8 +559,14 @@ history or a legacy fallback is NOT a signed empty history statement.
The local birth index and complete WAL digests are re-read around the strict-PQ
request, with every alias's nonce/PID-authenticated cumulative MAIN/CDN cap
counters reconciled to local WAL sums. If anything changed or the signed time
window expired, the check fails. For a nonempty index the readback proves
equality of **birth history**, not equality of off-host charge byte counters.
window expired, the check fails. Version 2 also binds a canonical sorted manifest digest of each committed
charge head (filename, exact reservation/user/class, last sequence, last
digest and cumulative conservative bytes). A fresh authentic signature
covering the same birth index but a lagging charge head is refused, as is
a manifest missing any local stream. Empty manifests use SHA-256 of the
canonical empty array. The V1 birth-only signature is no longer accepted
by the V2 verifier. This proves equality of **conservative pre-send intent
heads**, not delivered-byte accounting.
The signature cannot prove pre-bootstrap historical completeness, actual
delivery of every recorded intent, future absence of revocation, or terminal
meter finality. The check returns no permit even on success.
Expand Down
52 changes: 41 additions & 11 deletions experiments/quota-v2-physical-stop/public_tls_wal_watch.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
Only a pinned strict-PQ response can distinguish signed empty remote history
from a committed birth index. Reconcile that snapshot against the original
isolated PID's complete private journal, exact first grants and live counters.
Each local stream must match its exact committed SQL charge head, even if
the immutable birth index has not changed since an earlier append.
This is NOT terminal WAL finality, pre-bootstrap completeness, or an
atomic public bind. No installer, service or public activation calls this.
"""
Expand All @@ -22,7 +24,7 @@
import qualified_runtime_image as qualification
import wal_transport as wal

DOMAIN = b"XMESH_QUOTA_V2_PUBLIC_TLS_WAL_HEAD_V1\x00"
DOMAIN = b"XMESH_QUOTA_V2_PUBLIC_TLS_WAL_HEAD_V2\x00"
MAX_WIRE = 8192
MAX_SCAN = 64 << 20
MAX_CHECK_NS = 9_000_000_000
Expand Down Expand Up @@ -157,7 +159,8 @@ def read_meter(dfd, name):
for email in emails}
totals = {user: [0, 0] for user in roster._grants}
digests = {}
for name, (last, digest, _) in raw_wal.items():
heads = []
for name, (last, digest, _) in sorted(raw_wal.items()):
email = last["email"]
if last["runtimeId"] != roster.runtime_id or email not in aliases:
raise ValueError("meter WAL is outside original measured signed roster")
Expand All @@ -168,6 +171,19 @@ def read_meter(dfd, name):
if total[0] > 2**63 - 1:
raise ValueError("meter WAL total overflows signed counter")
digests[name] = digest
user = aliases[email]
# Filename commits runtime, alias and direction. Bind the exact
# signed lease owner and class too; a matching birth count or
# stale prefix of this stream is not a complete SQL charge.
heads.append({
"filename": name,
"reservationId": roster._grants[user][1]["reservationId"],
"userId": user,
"lastSequence": last["sequence"],
"lastDigest": last["digest"],
"streamBytes": last["nextBytes"],
"isCdn": email.endswith("--vless-cdn"),
})
# A re-bound directory cannot masquerade as an unchanged empty one.
current = os.stat(directory, follow_symlinks=False)
if (current.st_dev, current.st_ino) != (anchor.st_dev, anchor.st_ino):
Expand All @@ -183,6 +199,8 @@ def read_meter(dfd, name):
"tail": next(reversed(entries.values()))["digest"] if entries else "0"*64,
"totals": totals,
"wal": digests,
"chargeHeadsSha256": hashlib.sha256(
wal.observed.canonical(heads)).hexdigest(),
}
finally:
os.close(fd)
Expand Down Expand Up @@ -265,24 +283,31 @@ def _verify(raw, request, pinned, snapshot, now):
expected.update({key: proof[key] for key in
("challenge", "containerId", "hostPid", "startedAt")})
expected.update({
"schemaVersion": 1, "kind": "xmesh.quota-v2.public-tls-wal-head",
"historyState": ("committed_birth_index" if snapshot["sequence"]
else "empty_remote_history"),
"inventorySequence": snapshot["sequence"],
"inventorySha256": snapshot["sha256"], "inventoryTailDigest": snapshot["tail"],
"schemaVersion": 2, "kind": "xmesh.quota-v2.public-tls-wal-head",
"preBootstrapHistoryCompletenessVerified": False,
"liveMeterVerified": False, "finalMeterVerified": False,
"canServePublic": False, "canSpend": False, "canStart": False,
"canResume": False, "authorizedBytes": 0, "refundableBytes": 0,
})
local_history = {
"historyState": ("committed_birth_index" if snapshot["sequence"]
else "empty_remote_history"),
"inventorySequence": snapshot["sequence"],
"inventorySha256": snapshot["sha256"], "inventoryTailDigest": snapshot["tail"],
"committedChargeStreamCount": snapshot["sequence"],
"committedChargeHeadsSha256": snapshot["chargeHeadsSha256"],
}
p = doc["payload"]
if (not isinstance(p, dict)
or set(p) != set(expected) | {"issuedAtMs", "validUntilMs",
"committedChargeStreamCount"}
or set(p) != set(expected) | set(local_history) | {"issuedAtMs", "validUntilMs"}
or any(type(p.get(k)) is not type(v) or p[k] != v
for k, v in expected.items())
or type(p["committedChargeStreamCount"]) is not int
or not 0 <= p["committedChargeStreamCount"] <= snapshot["sequence"]
or any(type(p.get(k)) is not type(v) for k, v in local_history.items())
or not 0 <= p["committedChargeStreamCount"] <= p["inventorySequence"] <= wal.registry.MAX_ENTRIES
or p["historyState"] != ("committed_birth_index" if p["inventorySequence"]
else "empty_remote_history")
or any(not wal._hex(p[k], 64) for k in ("inventorySha256", "inventoryTailDigest",
"committedChargeHeadsSha256"))
or type(p["issuedAtMs"]) is not int or type(p["validUntilMs"]) is not int
or not 0 < p["issuedAtMs"] <= now < p["validUntilMs"]
or now - p["issuedAtMs"] > MAX_AGE_MS
Expand All @@ -292,6 +317,11 @@ def _verify(raw, request, pinned, snapshot, now):
public = Path(temp) / "nexus.pem"
wal._write_public(pinned, public)
wal.verifier.verify_nexus_signature(DOMAIN, p, doc["signature"], public)
# The mismatch is reported ONLY after authenticating the exact fresh
# server response. Fake/expired/malformed responses cannot masquerade
# as evidence that a genuine SQL snapshot is lagging the actual meter.
if any(p[key] != value for key, value in local_history.items()):
raise ValueError("signed Nexus WAL history does not match complete local conservative tails")
return p["validUntilMs"]


Expand Down
46 changes: 44 additions & 2 deletions tests/test_quota_v2_public_tls_wal_watch.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def reply(self, request, snapshot, changes=None, *, domain=watch.DOMAIN):
proof = request["proof"]
now = time.time_ns() // 1_000_000
p = {
"schemaVersion": 1, "kind": "xmesh.quota-v2.public-tls-wal-head",
"schemaVersion": 2, "kind": "xmesh.quota-v2.public-tls-wal-head",
"nodeId": scope["nodeId"], "userId": scope["userId"],
"activationReceiptSha256": scope["activationReceiptSha256"],
"genesisPolicySha256": scope["genesisPolicySha256"],
Expand All @@ -84,6 +84,7 @@ def reply(self, request, snapshot, changes=None, *, domain=watch.DOMAIN):
"inventorySha256": snapshot["sha256"],
"inventoryTailDigest": snapshot["tail"],
"committedChargeStreamCount": snapshot["sequence"],
"committedChargeHeadsSha256": snapshot["chargeHeadsSha256"],
"preBootstrapHistoryCompletenessVerified": False,
"liveMeterVerified": False, "finalMeterVerified": False,
"canServePublic": False, "canSpend": False, "canStart": False,
Expand Down Expand Up @@ -151,6 +152,7 @@ def test_real_signature_is_not_authority_or_a_substitute_for_fresh_scope(self):
("historyState", "committed_birth_index"), ("inventorySequence", 1),
("inventorySha256", "f"*64), ("inventoryTailDigest", "f"*64),
("committedChargeStreamCount", 1), ("committedChargeStreamCount", True),
("committedChargeHeadsSha256", "f"*64), ("schemaVersion", 1),
("validUntilMs", 1), ("validUntilMs", time.time_ns()//1_000_000 + 30000),
("issuedAtMs", time.time_ns()//1_000_000 - 5000),
):
Expand All @@ -172,7 +174,7 @@ def test_signed_empty_cannot_hide_nonzero_counters_or_lost_wal(self):
self.check()
empty = self.snapshot()
self.create_wal()
with self.assertRaisesRegex(ValueError, "mismatched Nexus WAL"):
with self.assertRaisesRegex(ValueError, "signed Nexus WAL history does not match"):
self.check(lambda request: self.reply(request, empty))
# Deleting one indexed stream, or the entire index, cannot pass.
index = self.directory / watch.wal.registry.NAME
Expand All @@ -186,6 +188,46 @@ def test_signed_empty_cannot_hide_nonzero_counters_or_lost_wal(self):
with self.assertRaisesRegex(ValueError, "missing previously"):
self.snapshot()

def test_same_birth_index_and_count_cannot_hide_later_unacknowledged_wal(self):
self.create_wal()
old = self.snapshot()
path = next(p for p in self.directory.glob("meter-*.jsonl")
if b'"email":"xmesh-u100--vless-main","direction":"uplink"' in p.read_bytes())
dfd = os.open(self.directory, os.O_RDONLY | os.O_DIRECTORY)
try:
previous, _, _ = watch.wal.journal._read_meter_wal(dfd, path.name)
finally:
os.close(dfd)
record = dict(previous)
record.update(sequence=previous["sequence"]+1, previousBytes=previous["nextBytes"],
nextBytes=previous["nextBytes"]+13, previousDigest=previous["digest"], digest="")
record["digest"] = hashlib.sha256(watch.wal.journal._canonical_go(record)).hexdigest()
with path.open("ab") as handle:
handle.write(watch.wal.journal._canonical_go(record))
handle.flush()
os.fsync(handle.fileno())
self.counters = (64, 7)
new = self.snapshot()
for key in ("sequence", "sha256", "tail"):
self.assertEqual(old[key], new[key])
self.assertNotEqual(old["chargeHeadsSha256"], new["chargeHeadsSha256"])
# Both signatures genuine and fresh, only the committed tails lag.
with self.assertRaisesRegex(ValueError, "signed Nexus WAL history does not match"):
self.check(lambda request: self.reply(request, old))
with self.assertRaises(ValueError) as bad:
self.check(lambda request: self.reply(request, old, domain=b"wrong-signing-domain"))
self.assertNotIn("signed Nexus WAL history does not match", str(bad.exception))
with self.assertRaisesRegex(ValueError, "signed Nexus WAL history does not match"):
self.check(lambda request: self.reply(request, new, {
"committedChargeStreamCount": new["sequence"]-1}))
self.assertIsNone(self.check())
# V1 was birth-index-only; never accept a downgrade.
request = watch._request(self.roster, 100, self.measured)
with self.assertRaises(ValueError):
watch._verify(self.reply(request, new, {"schemaVersion": 1},
domain=b"XMESH_QUOTA_V2_PUBLIC_TLS_WAL_HEAD_V1\0"),
request, self.roster.pinned, new, time.time_ns()//1_000_000)

def test_foreign_runtime_and_alias_never_match_original(self):
self.create_wal(runtime="f"*64)
with self.assertRaisesRegex(ValueError, "outside original"):
Expand Down
Loading