Skip to content

Commit 3bac126

Browse files
committed
fix(evidence): close E4 review findings (decode-total + non-empty)
1 parent 014b158 commit 3bac126

2 files changed

Lines changed: 269 additions & 22 deletions

File tree

‎scripts/verify_round_receipt.py‎

Lines changed: 56 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,15 @@
3838
``"PENDING-P11LAB"``-style values are legal during bring-up; equality is
3939
what matters). ``*_hash`` + ``evidence_digest`` + ``bundle_identity`` +
4040
wheel values MUST match ``^[0-9a-f]{64}$``. ``attempt`` is int >= 1.
41-
``job_ids`` must be an object (contents opaque).
41+
``job_ids`` must be an object (contents opaque). ``lanes`` must be a
42+
non-empty object (rule 5).
4243
4344
Bundle binding (PINNED): ``bundle_identity`` MUST equal the sha256 hex
4445
over the concatenation, sorted by lane name, of
4546
``lane + "\\0" + evidence_digest + "\\0"`` (UTF-8) for every lane in
46-
``receipt.lanes``. An empty lanes object hashes ``b""`` (but empty lanes
47-
fails the tier-closure check first anyway).
47+
``receipt.lanes``. ``compute_bundle_identity({})`` is the sha256 of
48+
``b""`` by construction, but an empty lanes object never reaches
49+
recomputation: it fails the non-empty-closure check (rule 5) first.
4850
4951
Lock schema (PINNED; this file lives at
5052
``.github/provider-round.lock.json``)::
@@ -54,8 +56,9 @@
5456
"tiers": {"pr-smoke": {"lanes": [...], "quorum": {...}, "budgets": {...}},
5557
"nightly": {...}, "release": {...}}}
5658
57-
Tier objects carry a ``lanes`` list plus ``quorum``/``budgets`` objects
58-
(presence-checked only — shapes and thresholds are TBD-E5). Staged
59+
Tier objects carry a non-empty ``lanes`` list of non-empty strings plus
60+
``quorum``/``budgets`` objects (presence-checked only — shapes and
61+
thresholds are TBD-E5). Staged
5962
Windows/macOS lanes (``win-softhsm2``, ``win-bouncyhsm``,
6063
``mac-softhsm2``) are NOT in the initial lock; they land as staged
6164
additions in E5.
@@ -66,16 +69,19 @@
6669
3. ``p11lab_sha`` == lock ``p11lab_ref``; ``evaluator_sha`` == lock
6770
``evaluator_fw_ref``; ``baseline_fw_sha`` == lock ``baseline_fw_sha``
6871
("stale baseline" = rule 3c).
69-
4. ``tier`` is one of the lock tiers; the tier object has a ``lanes``
70-
list plus ``quorum``/``budgets`` objects. The lock is OUR file, so a
71-
malformed lock (bad JSON or bad schema) is a config error -> exit 2.
72-
5. Closed lane roster: receipt lane keys == tier lanes EXACTLY — a
73-
missing lane fails AND an unexpected lane fails (never
74-
generated-from-found).
72+
4. ``tier`` is one of the lock tiers; the tier object has a non-empty
73+
``lanes`` list of non-empty strings plus ``quorum``/``budgets``
74+
objects. The lock is OUR file, so a malformed lock (bad JSON or bad
75+
schema) is a config error -> exit 2.
76+
5. Closed lane roster: receipt ``lanes`` is a non-empty object whose keys
77+
== tier lanes EXACTLY — a missing lane fails AND an unexpected lane
78+
fails (never generated-from-found).
7579
6. Per lane: ``verdict`` in {pass, fail}; ``admitted`` is a bool;
7680
``evidence_digest`` is 64-hex; ``verdict == "pass"`` with
7781
``admitted == false`` fails (unadmitted lane marked pass).
78-
7. Bundle recomputation matches ``bundle_identity``.
82+
7. Bundle recomputation matches ``bundle_identity`` (skipped without
83+
cascading noise when any lane name is UTF-8-unencodable or any
84+
digest is not 64-hex — rules 5/6 already report those).
7985
8. Well-formedness: all ``*_hash`` 64-hex; identities non-empty;
8086
``wheel_hashes`` a non-empty object of 64-hex values;
8187
``run_id``/``attempt``/``job_ids`` typed as above.
@@ -164,10 +170,12 @@ def _validate_lock_tier(tier: object, spec: Any) -> list[str]:
164170
lanes = spec.get("lanes")
165171
if lanes is None:
166172
errors.append(_missing(f"{prefix}.lanes"))
167-
elif not isinstance(lanes, list) or any(
168-
not isinstance(name, str) or not name for name in lanes
173+
elif (
174+
not isinstance(lanes, list)
175+
or not lanes
176+
or any(not isinstance(name, str) or not name for name in lanes)
169177
):
170-
errors.append(f"{prefix}.lanes: must be a list of non-empty strings")
178+
errors.append(f"{prefix}.lanes: must be a non-empty list of non-empty strings")
171179
for field in ("quorum", "budgets"):
172180
shape = spec.get(field)
173181
if shape is None:
@@ -192,8 +200,8 @@ def validate_receipt(receipt: Any, lock: dict[str, Any], expect_fw: str) -> list
192200
lanes = receipt.get("lanes")
193201
if lanes is None:
194202
failures.append(_missing("lanes"))
195-
elif not isinstance(lanes, dict):
196-
failures.append("lanes: must be an object")
203+
elif not isinstance(lanes, dict) or not lanes:
204+
failures.append("lanes: must be a non-empty object")
197205
elif tier.name is not None:
198206
failures.extend(_check_roster(tier.name, lanes, lock))
199207
failures.extend(_check_lane_entries(lanes))
@@ -285,6 +293,14 @@ def _check_lane_entries(lanes: dict[str, Any]) -> list[str]:
285293
return failures
286294

287295

296+
def _is_utf8_encodable(value: str) -> bool:
297+
try:
298+
value.encode("utf-8")
299+
except UnicodeEncodeError:
300+
return False
301+
return True
302+
303+
288304
def _check_bundle(receipt: dict[str, Any], lanes: dict[str, Any]) -> list[str]:
289305
bundle = receipt.get("bundle_identity")
290306
if not isinstance(bundle, str):
@@ -294,6 +310,15 @@ def _check_bundle(receipt: dict[str, Any], lanes: dict[str, Any]) -> list[str]:
294310
if not isinstance(entry, dict) or not isinstance(entry.get("evidence_digest"), str):
295311
return []
296312
digests[name] = entry["evidence_digest"]
313+
# No-cascade rule (R29): recomputation is only meaningful over fully
314+
# valid inputs. Rules 5/6 already emit diagnostics for unexpected lanes
315+
# and non-hex digests, so skip here when any lane name is
316+
# UTF-8-unencodable (e.g. a lone surrogate) or any digest is not 64-hex
317+
# (a 64-hex digest is ASCII by construction, hence encodable) — instead
318+
# of crashing on .encode("utf-8") or piling on a spurious mismatch.
319+
for name, digest in digests.items():
320+
if not _is_utf8_encodable(name) or not _is_hex64(digest):
321+
return []
297322
if bundle != compute_bundle_identity(digests):
298323
return ["bundle_identity: does not match recomputed lane binding"]
299324
return []
@@ -354,11 +379,22 @@ def _check_wheel_hashes(wheels: Any) -> list[str]:
354379
def _read_json_file(path: Path, kind: str) -> tuple[Any, str | None]:
355380
try:
356381
text = path.read_text(encoding="utf-8")
382+
return json.loads(text), None
357383
except OSError as exc:
358384
return None, f"cannot read {kind} file {path}: {exc.strerror or exc}"
359-
try:
360-
return json.loads(text), None
361-
except json.JSONDecodeError as exc:
385+
except RecursionError:
386+
# Parser blew the call stack on hostile nesting: keep the handler
387+
# trivial and RecursionError-safe — static message plus the class
388+
# name only, never str(exc)/repr of attacker-controlled input.
389+
return None, (
390+
f"{kind} file {path} is not valid JSON: "
391+
"RecursionError (input nesting exceeds parser limits)"
392+
)
393+
except (UnicodeDecodeError, ValueError) as exc:
394+
# UnicodeDecodeError: file is not valid UTF-8. ValueError: parser
395+
# failures beyond JSONDecodeError, e.g. the 4300-digit int string
396+
# conversion limit (JSONDecodeError subclasses ValueError, so it is
397+
# covered here too).
362398
return None, f"{kind} file {path} is not valid JSON: {exc}"
363399

364400

‎tests/test_round_receipt_verify.py‎

Lines changed: 213 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,22 @@
66

77
from __future__ import annotations
88

9+
import hashlib
910
import json
1011
import subprocess
1112
import sys
1213
from pathlib import Path
1314
from typing import Any
1415

16+
import pytest
17+
1518
from scripts.verify_round_receipt import (
1619
EXIT_INVALID,
1720
EXIT_USAGE,
1821
EXIT_VALID,
1922
RECEIPT_CONTRACT_V,
2023
compute_bundle_identity,
24+
main,
2125
)
2226

2327
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -163,11 +167,20 @@ def test_contract_version_mismatch(tmp_path: Path) -> None:
163167

164168

165169
def test_missing_required_lane(tmp_path: Path) -> None:
166-
receipt, lock = _valid_pair(tmp_path)
170+
# Two-lane tier so the roster stays non-empty after deleting one lane
171+
# (R29: an empty receipt roster fails the non-empty rule instead).
172+
lock_payload = make_lock()
173+
lock_payload["tiers"]["pr-smoke"]["lanes"] = ["softhsm2", "kryoptic"]
174+
lock = _write(tmp_path / "lock.json", lock_payload)
167175
payload = make_receipt()
176+
payload["lanes"]["kryoptic"] = {
177+
"verdict": "pass",
178+
"admitted": True,
179+
"evidence_digest": _hex64("a"),
180+
}
168181
del payload["lanes"]["softhsm2"]
169182
_recompute_bundle(payload)
170-
_write(receipt, payload)
183+
receipt = _write(tmp_path / "receipt.json", payload)
171184
result = _run(receipt, lock)
172185
assert result.returncode == EXIT_INVALID, result.stderr
173186
assert "lanes.softhsm2" in result.stderr
@@ -269,3 +282,201 @@ def test_empty_expect_fw(tmp_path: Path) -> None:
269282
receipt, lock = _valid_pair(tmp_path)
270283
result = _run(receipt, lock, expect_fw="")
271284
assert result.returncode == EXIT_USAGE, result.stderr
285+
286+
287+
# --- Fix round 1 (review R1): decode/parser INFRA, total bundle check,
288+
# --- non-empty lanes (R29), and hardening coverage.
289+
290+
291+
def test_receipt_with_invalid_utf8_bytes_is_infra(tmp_path: Path) -> None:
292+
_, lock = _valid_pair(tmp_path)
293+
receipt = tmp_path / "receipt.json"
294+
receipt.write_bytes(b'{"receipt_contract_v": \xff}')
295+
result = _run(receipt, lock)
296+
assert result.returncode == EXIT_USAGE, result.stderr
297+
assert "error:" in result.stderr
298+
assert "Traceback" not in result.stderr
299+
300+
301+
def test_lock_with_invalid_utf8_bytes_is_infra(tmp_path: Path) -> None:
302+
receipt, _ = _valid_pair(tmp_path)
303+
lock = tmp_path / "lock.json"
304+
lock.write_bytes(b'{"receipt_contract_v": \xff}')
305+
result = _run(receipt, lock)
306+
assert result.returncode == EXIT_USAGE, result.stderr
307+
assert "error:" in result.stderr
308+
assert "Traceback" not in result.stderr
309+
310+
311+
def test_lock_with_huge_integer_is_infra(tmp_path: Path) -> None:
312+
receipt, _ = _valid_pair(tmp_path)
313+
raw = json.dumps(make_lock())
314+
needle = '"receipt_contract_v": 1'
315+
assert needle in raw
316+
lock = tmp_path / "lock.json"
317+
lock.write_text(raw.replace(needle, f'"receipt_contract_v": {"9" * 5000}'), encoding="utf-8")
318+
result = _run(receipt, lock)
319+
assert result.returncode == EXIT_USAGE, result.stderr
320+
assert "error:" in result.stderr
321+
assert "Traceback" not in result.stderr
322+
323+
324+
def test_deeply_nested_receipt_never_tracebacks(tmp_path: Path) -> None:
325+
# Reviewer probe shape (10k nested arrays). Where the parser raises
326+
# RecursionError (this venv's 3.13, like the reviewer's interpreter)
327+
# the exit is 2 via the INFRA handler; where it parses (3.14's
328+
# iterative scanner handles >=200k levels) the non-object top level
329+
# fails validation with exit 1. Either way: handled, an error: line,
330+
# zero tracebacks.
331+
_, lock = _valid_pair(tmp_path)
332+
receipt = tmp_path / "receipt.json"
333+
receipt.write_text("[" * 10000 + "]" * 10000, encoding="utf-8")
334+
result = _run(receipt, lock)
335+
assert result.returncode in (EXIT_INVALID, EXIT_USAGE), result.stderr
336+
assert "error:" in result.stderr
337+
assert "Traceback" not in result.stderr
338+
339+
340+
def test_recursion_error_maps_to_infra_exit(
341+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
342+
) -> None:
343+
# Deterministic pin of the RecursionError -> exit 2 path on every
344+
# interpreter (the real parser only raises it on some versions).
345+
def _boom(_text: str) -> Any:
346+
raise RecursionError("maximum recursion depth exceeded")
347+
348+
monkeypatch.setattr(json, "loads", _boom)
349+
receipt, lock = _valid_pair(tmp_path)
350+
assert main([str(receipt), "--lock", str(lock), "--expect-fw", FW_SHA]) == EXIT_USAGE
351+
assert "error:" in capsys.readouterr().err
352+
353+
354+
def test_surrogate_digest_reports_rule6_without_crash(tmp_path: Path) -> None:
355+
receipt, lock = _valid_pair(tmp_path)
356+
payload = make_receipt()
357+
payload["lanes"]["softhsm2"]["evidence_digest"] = chr(0xD800)
358+
_write(receipt, payload)
359+
result = _run(receipt, lock)
360+
assert result.returncode == EXIT_INVALID, result.stderr
361+
assert "Traceback" not in result.stderr
362+
assert "lanes.softhsm2.evidence_digest" in result.stderr
363+
assert result.stderr.count("error:") == 1, result.stderr
364+
365+
366+
def test_surrogate_digest_preserves_other_diagnostics(tmp_path: Path) -> None:
367+
receipt, lock = _valid_pair(tmp_path)
368+
payload = make_receipt()
369+
payload["lanes"]["softhsm2"]["evidence_digest"] = chr(0xD800)
370+
payload["policy_hash"] = "bad"
371+
payload["attempt"] = 0
372+
_write(receipt, payload)
373+
result = _run(receipt, lock)
374+
assert result.returncode == EXIT_INVALID, result.stderr
375+
assert "Traceback" not in result.stderr
376+
assert "lanes.softhsm2.evidence_digest" in result.stderr
377+
assert "policy_hash" in result.stderr
378+
assert "attempt" in result.stderr
379+
assert result.stderr.count("error:") == 3, result.stderr
380+
381+
382+
def test_surrogate_lane_name_reports_unexpected_lane(tmp_path: Path) -> None:
383+
receipt, lock = _valid_pair(tmp_path)
384+
payload = make_receipt()
385+
payload["lanes"][f"{chr(0xD800)}evil"] = {
386+
"verdict": "pass",
387+
"admitted": True,
388+
"evidence_digest": _hex64("a"),
389+
}
390+
# Bundle intentionally NOT recomputed: the check must skip (no-cascade),
391+
# not crash on the unencodable name nor emit a spurious mismatch.
392+
_write(receipt, payload)
393+
result = _run(receipt, lock)
394+
assert result.returncode == EXIT_INVALID, result.stderr
395+
assert "Traceback" not in result.stderr
396+
assert "unexpected lane" in result.stderr
397+
assert result.stderr.count("error:") == 1, result.stderr
398+
399+
400+
def test_empty_tier_lanes_rejects_lock(tmp_path: Path) -> None:
401+
receipt, _ = _valid_pair(tmp_path)
402+
bad_lock = make_lock()
403+
bad_lock["tiers"]["pr-smoke"]["lanes"] = []
404+
lock = _write(tmp_path / "lock.json", bad_lock)
405+
result = _run(receipt, lock)
406+
assert result.returncode == EXIT_USAGE, result.stderr
407+
assert "tiers.pr-smoke.lanes" in result.stderr
408+
409+
410+
def test_empty_receipt_lanes_rejected(tmp_path: Path) -> None:
411+
receipt, lock = _valid_pair(tmp_path)
412+
payload = make_receipt()
413+
payload["lanes"] = {}
414+
payload["bundle_identity"] = hashlib.sha256(b"").hexdigest()
415+
_write(receipt, payload)
416+
result = _run(receipt, lock)
417+
assert result.returncode == EXIT_INVALID, result.stderr
418+
assert "lanes: must be a non-empty object" in result.stderr
419+
420+
421+
def test_empty_tier_and_empty_receipt_rejected_at_lock(tmp_path: Path) -> None:
422+
# The green-on-empty hole (empty tier + empty roster + empty-sha bundle
423+
# previously exited 0): the lock gate must fire first with exit 2.
424+
bad_lock = make_lock()
425+
bad_lock["tiers"]["pr-smoke"]["lanes"] = []
426+
lock = _write(tmp_path / "lock.json", bad_lock)
427+
payload = make_receipt()
428+
payload["lanes"] = {}
429+
payload["bundle_identity"] = hashlib.sha256(b"").hexdigest()
430+
receipt = _write(tmp_path / "receipt.json", payload)
431+
result = _run(receipt, lock)
432+
assert result.returncode == EXIT_USAGE, result.stderr
433+
assert "tiers.pr-smoke.lanes" in result.stderr
434+
435+
436+
# Independent bundle golden: canonical bytes for lanes a -> "1"*64,
437+
# z -> "2"*64 are `a\0<1x64>\0z\0<2x64>\0` (134 bytes); hashed via
438+
# `printf ... | sha256sum` in the shell (fix-round-1 report). Matches the
439+
# reviewer's independently computed value.
440+
BUNDLE_GOLDEN_AZ = "4b8e992c3a69482dc6cf017bd0a2766fb0d3b142d29aacf22bc745992a80bd8e"
441+
442+
443+
def test_bundle_golden_matches_shell_sha256() -> None:
444+
assert compute_bundle_identity({"a": _hex64("1"), "z": _hex64("2")}) == BUNDLE_GOLDEN_AZ
445+
446+
447+
def test_bundle_binding_is_order_independent() -> None:
448+
assert compute_bundle_identity({"z": _hex64("2"), "a": _hex64("1")}) == BUNDLE_GOLDEN_AZ
449+
450+
451+
def test_multi_fault_receipt_reports_every_violation(tmp_path: Path) -> None:
452+
# Fail-loud batch: six distinct faults, all six lines, no cascade.
453+
receipt, lock = _valid_pair(tmp_path)
454+
payload = make_receipt()
455+
payload["framework_sha"] = "0" * 40
456+
payload["policy_hash"] = "bad"
457+
payload["attempt"] = 0
458+
payload["run_id"] = ""
459+
payload["wheel_hashes"] = {}
460+
payload["lanes"]["softhsm2"]["admitted"] = False
461+
_write(receipt, payload)
462+
result = _run(receipt, lock)
463+
assert result.returncode == EXIT_INVALID, result.stderr
464+
for field in (
465+
"framework_sha",
466+
"policy_hash",
467+
"attempt",
468+
"run_id",
469+
"wheel_hashes",
470+
"lanes.softhsm2.admitted",
471+
):
472+
assert field in result.stderr, field
473+
assert result.stderr.count("error:") == 6, result.stderr
474+
475+
476+
def test_unknown_top_level_keys_ignored(tmp_path: Path) -> None:
477+
receipt, lock = _valid_pair(tmp_path)
478+
payload = make_receipt()
479+
payload["future_field"] = {"nested": [1, 2, 3]}
480+
_write(receipt, payload)
481+
result = _run(receipt, lock)
482+
assert result.returncode == EXIT_VALID, result.stderr

0 commit comments

Comments
 (0)