| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772 |
- #!/usr/bin/env python3
- """TDD coverage for raw-first Prod2U evidence validation."""
- from __future__ import annotations
- import hashlib
- import importlib.util
- import json
- import sys
- import tempfile
- import unittest
- from pathlib import Path
- from types import SimpleNamespace
- from unittest import mock
- import jsonschema
- ROOT = Path(__file__).resolve().parents[2]
- VALIDATOR = ROOT / "tools" / "prod2u_validate.py"
- TOOLS = ROOT / "tools"
- if str(TOOLS) not in sys.path:
- sys.path.insert(0, str(TOOLS))
- def load_validator():
- if not VALIDATOR.is_file():
- raise AssertionError(f"missing validator: {VALIDATOR}")
- spec = importlib.util.spec_from_file_location("prod2u_validate_test", VALIDATOR)
- if spec is None or spec.loader is None:
- raise AssertionError("unable to load Prod2U validator")
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
- def program_receipt() -> dict:
- build_id = "1234ABCD"
- return {
- "schema": "prod2u-program-sram-receipt-v1",
- "status": "pass",
- "request": {
- "operation": "PROGRAM_SRAM",
- "target_chip": "EF2L45",
- "cable_index": 0,
- "speed_code": 2,
- "speed_hz": 200000,
- "attempt_limit": 1,
- "power_cycle_allowed": False,
- },
- "bitstream": {"path": f"C:/P2U/{build_id}/fw.bit", "sha256": "a" * 64, "build_id": build_id},
- "staging": {
- "expected_path": f"C:/P2U/{build_id}/fw.bit",
- "observed_path": f"C:/P2U/{build_id}/fw.bit",
- "matches_expected_path": True,
- },
- "execution": {
- "exit_code": 0,
- "timed_out": False,
- "attempt_count": 1,
- "retry_count": 0,
- "power_cycle_count": 0,
- "command_execution_attempted": True,
- "timeout_seconds": 60,
- "started_at": "2026-07-10T10:00:00Z",
- "finished_at": "2026-07-10T10:00:02Z",
- "duration_seconds": 2.0,
- },
- "parser": {
- "status": "pass",
- "exit_code_trusted": False,
- "ordered_markers": [
- "download_start",
- "chip_validation",
- "bit_to_vec_start",
- "bit_to_vec_finish",
- "program_start",
- "program_finish",
- "download_finish",
- ],
- "ordered_markers_complete": True,
- "observed_markers": [
- "download_start",
- "chip_validation",
- "bit_to_vec_start",
- "bit_to_vec_finish",
- "program_start",
- "program_finish",
- "download_finish",
- ],
- "observed_marker_lines": [1, 2, 3, 4, 5, 6, 7],
- "error_markers": [],
- "failures": [],
- "transcript_sha256": "9" * 64,
- },
- "tool": {"path": "C:/TD/bin/bw_commands_prompt.exe", "td_root": "C:/TD", "td_bin": "C:/TD/bin"},
- "mutex": {"name": "Global\\Prod2UProgramSram", "acquired": True},
- "process_cleanup": {"status": "pass", "td_root": "C:/TD", "wait_seconds": 5.0, "remaining": []},
- "artifacts": {
- "tcl": {"path": "program-sram.tcl", "size": 1, "sha256": "1" * 64},
- "stdout": {"path": "bitwriter-stdout.log", "size": 1, "sha256": "2" * 64},
- "stderr": {"path": "bitwriter-stderr.log", "size": 1, "sha256": "3" * 64},
- "log_delta": {"path": "bitwriter-log-delta.log", "size": 1, "sha256": "4" * 64},
- "log_delta_sources": [
- {
- "path": "C:/TD/log/bw_test.log",
- "start_offset": 0,
- "byte_count": 1,
- "sha256": "8" * 64,
- }
- ],
- },
- "safety": {
- "flash_attempted": False,
- "programs_nonvolatile": False,
- "power_cycle_attempted": False,
- "driver_install_attempted": False,
- "toggles_dtr_rts": False,
- "real_ptc_fan_action_attempted": False,
- "external_programming_command_executed": True,
- },
- }
- class Prod2UValidatorTests(unittest.TestCase):
- def build_fixture(self, root: Path) -> tuple[dict, dict, Path]:
- import prod2u_collector as collector
- from binary921 import CommandId, FrameType, build_host_command, encode_frame
- profile_id = 3
- build_id = "1234ABCD"
- command_wire = b"".join(
- build_host_command(
- seq=index,
- command=command,
- channel=channel,
- percent=percent,
- profile_id=profile_id,
- )
- for index, (_, command, channel, percent) in enumerate(collector.COMMAND_SEQUENCE, start=1)
- )
- ready = encode_frame(
- profile_id=profile_id,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=250000,
- payload=bytes([profile_id]) + int(build_id, 16).to_bytes(4, "little") + bytes([1, 0]),
- )
- acks = b"".join(
- encode_frame(
- profile_id=profile_id,
- frame_type=FrameType.HOST_ACK,
- seq=index,
- timestamp_tick=0,
- payload=bytes([1, command, 0, 0, 0x34, 0x12]),
- )
- for index, (_, command, _, _) in enumerate(collector.COMMAND_SEQUENCE, start=1)
- )
- bmc_payload_bytes = bytes([0x1E, 0x4B] + [0xFF] * 22 + [0x20, 0x19] + [0xFF] * 22)
- bmc_checksum = sum(bmc_payload_bytes) & 0xFFFF
- bmc = encode_frame(
- profile_id=profile_id,
- frame_type=FrameType.BMC_PAYLOAD,
- seq=30,
- timestamp_tick=0,
- payload=bytes(
- [48, 48, 1, 0, bmc_payload_bytes[0], bmc_payload_bytes[-1], bmc_checksum & 0xFF, bmc_checksum >> 8]
- ),
- )
- sensor = encode_frame(
- profile_id=profile_id,
- frame_type=FrameType.SENSOR_CACHE,
- seq=31,
- timestamp_tick=0,
- payload=bytes([profile_id, 0, 1, 0xFE, 0xEF, 0xFF, 2, 22]),
- )
- snapshot = encode_frame(
- profile_id=profile_id,
- frame_type=FrameType.MODULE_SNAPSHOT,
- seq=32,
- timestamp_tick=0,
- payload=bytes(
- [
- profile_id,
- 0,
- 12,
- 0,
- 0x1E,
- 0xFF,
- 0x08,
- 0x14,
- CommandId.DISABLE,
- 0,
- 0,
- 0,
- 0,
- 1,
- 2,
- 22,
- 0,
- 0,
- 30,
- 30,
- 0,
- 0x0F,
- 0,
- 0,
- ]
- ),
- )
- combined = ready + acks + bmc + sensor + snapshot
- (root / "combined-rx.raw").write_bytes(combined)
- (root / "host-command-wire.bin").write_bytes(command_wire)
- collector_manifest = {
- "schema": "prod2u-collector-manifest-v1",
- "status": "pass",
- "artifact_hashes": {
- "combined-rx.raw": hashlib.sha256(combined).hexdigest(),
- "host-command-wire.bin": hashlib.sha256(command_wire).hexdigest(),
- },
- "safety": {
- "flash_attempted": False,
- "programs_nonvolatile": False,
- "driver_install_attempted": False,
- "toggles_dtr_rts": False,
- },
- }
- source_manifest = {
- "schema": "prod2u-source-manifest-v1",
- "profile": "prod2u-bmc-replay-binary921",
- "source_manifest_sha256": "1234abcd" + "b" * 56,
- "build_id": build_id,
- }
- bmc_receipt = root / "bmc-replay-session.json"
- bmc_receipt.write_text(
- json.dumps(
- {
- "schema": "prod2u-bmc-replay-session-v1",
- "status": "pass",
- "bmc_source": "pc_replay_from_real_bmc_capture",
- "reply_sha256": hashlib.sha256(
- (" ".join(f"{value:02x}" for value in bmc_payload_bytes) + "\r\n").encode("ascii")
- ).hexdigest(),
- "payload_hex": [f"{value:02x}" for value in bmc_payload_bytes],
- "byte_count": 48,
- "valid_count": 2,
- "missing_count": 22,
- "matched_poll_count": 1,
- "reply_count": 1,
- "started_at": "2026-07-10T09:59:59Z",
- "last_reply_at": "2026-07-10T10:00:01Z",
- }
- ),
- encoding="utf-8",
- )
- return collector_manifest, source_manifest, bmc_receipt
- def test_raw_first_validator_passes_complete_software_chain(self) -> None:
- validator = load_validator()
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "pass", evidence["blockers"])
- self.assertEqual(evidence["startup_ready"]["build_id"], "1234ABCD")
- self.assertEqual(evidence["host_command_count"], 12)
- self.assertEqual(evidence["host_ack_matched_count"], 12)
- self.assertEqual(evidence["raw_validation"]["combined"]["status"], "pass")
- self.assertEqual(evidence["raw_validation"]["sensor_cache"]["valid_count"], 2)
- self.assertEqual(evidence["raw_validation"]["sensor_cache"]["missing_count"], 22)
- self.assertEqual(evidence["raw_validation"]["timeout_fallback"]["status"], "pass")
- def test_missing_bmc_replay_receipt_remains_schema_valid_blocked_evidence(self) -> None:
- validator = load_validator()
- schema = json.loads(
- (ROOT / "schemas" / "prod2u_evidence_manifest.schema.json").read_text(encoding="utf-8")
- )
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- bmc.unlink()
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "blocked_bmc_replay_not_run")
- self.assertEqual(
- evidence["bmc_replay"],
- {
- "status": "not_run",
- "bmc_source": "not_run",
- "payload_sha256": None,
- },
- )
- jsonschema.validate(evidence, schema)
- def test_missing_bmc_uart_frames_are_not_independent_failures_when_replay_was_not_run(self) -> None:
- validator = load_validator()
- from binary921 import FrameType, decode_stream
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- frames, remainder = decode_stream((root / "combined-rx.raw").read_bytes())
- self.assertEqual(remainder, b"")
- combined = b"".join(
- frame.raw
- for frame in frames
- if frame.frame_type not in (FrameType.BMC_PAYLOAD, FrameType.SENSOR_CACHE)
- )
- (root / "combined-rx.raw").write_bytes(combined)
- collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(combined).hexdigest()
- bmc.unlink()
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "blocked_bmc_replay_not_run")
- self.assertEqual(evidence["blockers"], ["bmc_replay_not_pass"])
- self.assertEqual(evidence["raw_validation"]["sensor_cache"]["status"], "not_run")
- def test_invalid_bmc_replay_receipt_remains_schema_valid_failed_evidence(self) -> None:
- validator = load_validator()
- schema = json.loads(
- (ROOT / "schemas" / "prod2u_evidence_manifest.schema.json").read_text(encoding="utf-8")
- )
- for invalid_payload in ("{", "[]"):
- with self.subTest(invalid_payload=invalid_payload), tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- bmc.write_text(invalid_payload, encoding="utf-8")
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "fail")
- self.assertEqual(evidence["bmc_replay"]["bmc_source"], "not_run")
- self.assertIsNone(evidence["bmc_replay"]["payload_sha256"])
- jsonschema.validate(evidence, schema)
- def test_ready_epoch_selects_last_matching_ready_in_the_post_callback_stream(self) -> None:
- validator = load_validator()
- from binary921 import FrameType, decode_stream, encode_frame
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- combined = (root / "combined-rx.raw").read_bytes()
- frames, remainder = decode_stream(combined)
- self.assertEqual(remainder, b"")
- first_ready_len = len(frames[0].raw)
- later_ready = encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=250001,
- payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, 2]),
- )
- combined = combined[:first_ready_len] + later_ready + combined[first_ready_len:]
- (root / "combined-rx.raw").write_bytes(combined)
- collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(combined).hexdigest()
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "pass", evidence["blockers"])
- self.assertEqual(evidence["startup_ready"]["announcement_seq"], 2)
- self.assertEqual(evidence["startup_ready"]["matching_ready_count"], 2)
- self.assertEqual(evidence["startup_ready"]["selection_policy"], "last_matching_ready")
- def test_collector_wait_selects_last_matching_ready_from_one_buffered_chunk(self) -> None:
- import prod2u_collector as collector
- from binary921 import FrameType, encode_frame
- ready_frames = b"".join(
- encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=250000 + announcement,
- payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, announcement]),
- )
- for announcement in (0, 2)
- )
- class BufferedSerial:
- def __init__(self, payload: bytes) -> None:
- self.payload = payload
- def read(self, _size: int) -> bytes:
- payload, self.payload = self.payload, b""
- return payload
- result = collector.wait_for_ready(
- BufferedSerial(ready_frames),
- timeout_sec=0.05,
- expected_profile_id=3,
- expected_build_id="1234ABCD",
- expected_epoch=1,
- expected_por_reason=1,
- max_announcement_seq=2,
- )
- self.assertEqual(result["status"], "pass")
- self.assertEqual(result["ready"]["decoded"]["announcement_seq"], 2)
- self.assertEqual(result["matching_ready_count"], 2)
- self.assertEqual(result["selection_policy"], "last_matching_ready")
- def test_collector_splits_corrupt_and_old_build_bytes_before_three_matching_ready_frames(self) -> None:
- import prod2u_collector as collector
- from binary921 import FrameType, encode_frame
- old_ready = encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=249999,
- payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
- )
- corrupt_ready = bytearray(old_ready)
- corrupt_ready[-1] ^= 1
- matching_ready = b"".join(
- encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=250000 + announcement,
- payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, announcement]),
- )
- for announcement in (0, 1, 2)
- )
- pre_ready = bytes(corrupt_ready) + old_ready
- stream = pre_ready + matching_ready
- class BufferedSerial:
- def __init__(self, payload: bytes) -> None:
- self.payload = payload
- def read(self, _size: int) -> bytes:
- payload, self.payload = self.payload, b""
- return payload
- result = collector.wait_for_ready(
- BufferedSerial(stream),
- timeout_sec=0.05,
- expected_profile_id=3,
- expected_build_id="1234ABCD",
- expected_epoch=1,
- expected_por_reason=1,
- max_announcement_seq=2,
- )
- self.assertEqual(result["status"], "pass")
- self.assertEqual(result["raw"], stream)
- self.assertEqual(result["pre_ready_raw"], pre_ready)
- self.assertEqual(result["epoch_start_offset"], len(pre_ready))
- self.assertEqual(result["epoch_raw"], matching_ready)
- self.assertEqual(result["matching_ready_count"], 3)
- self.assertEqual(result["ready"]["decoded"]["announcement_seq"], 2)
- def test_combined_collector_writes_pre_ready_diagnostics_and_formal_epoch_separately(self) -> None:
- import prod2u_collector as collector
- from binary921 import FrameType, encode_frame
- old_ready = encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=249999,
- payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
- )
- corrupt_ready = bytearray(old_ready)
- corrupt_ready[-1] ^= 1
- matching_ready = b"".join(
- encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=250000 + announcement,
- payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, announcement]),
- )
- for announcement in (0, 1, 2)
- )
- pre_ready = bytes(corrupt_ready) + old_ready
- class FakeSerial:
- def __init__(self, payload: bytes) -> None:
- self.payload = payload
- self.closed = False
- def read(self, _size: int) -> bytes:
- payload, self.payload = self.payload, b""
- return payload
- def write(self, payload: bytes) -> int:
- return len(payload)
- def flush(self) -> None:
- return None
- def close(self) -> None:
- self.closed = True
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- endpoint = FakeSerial(pre_ready + matching_ready)
- args = SimpleNamespace(
- output_dir=str(root),
- profile="prod2u-bmc-replay-binary921",
- transport="combined-single-com",
- combined_port="COM5",
- host_port="",
- expected_build_id="1234ABCD",
- expected_epoch=1,
- ready_timeout_sec=0.05,
- ack_window_sec=0.0,
- duration_sec=0.0,
- bmc_replay_receipt="",
- )
- with mock.patch.object(collector, "_open_serial", return_value=endpoint):
- manifest = collector.collect_live(args)
- self.assertTrue(endpoint.closed)
- self.assertEqual((root / "pre-ready-uart.raw").read_bytes(), pre_ready)
- self.assertEqual((root / "combined-rx.raw").read_bytes(), matching_ready)
- self.assertEqual((root / "combined-uart-binary921.raw").read_bytes(), pre_ready + matching_ready)
- preflight = json.loads((root / "startup-preflight.json").read_text(encoding="utf-8"))
- self.assertEqual(preflight["epoch_start_offset"], len(pre_ready))
- self.assertEqual(manifest["startup_ready"]["matching_ready_count"], 3)
- self.assertEqual(
- manifest["artifact_hashes"]["combined-rx.raw"],
- hashlib.sha256(matching_ready).hexdigest(),
- )
- self.assertEqual(
- manifest["artifact_hashes"]["pre-ready-uart.raw"],
- hashlib.sha256(pre_ready).hexdigest(),
- )
- def test_ready_timeout_preserves_diagnostics_without_creating_a_formal_epoch(self) -> None:
- import prod2u_collector as collector
- from binary921 import FrameType, encode_frame
- old_ready = encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=249999,
- payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
- )
- corrupt_ready = bytearray(old_ready)
- corrupt_ready[-1] ^= 1
- observed = bytes(corrupt_ready) + old_ready
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- manifest = collector.write_blocked_manifest(
- root,
- profile="prod2u-bmc-replay-binary921",
- status="blocked_waiting_for_binary921_ready",
- startup_raw=observed,
- startup_frames=[],
- error="build_mismatch",
- timeout_evidence={"status": "blocked_waiting_for_binary921_ready"},
- )
- self.assertEqual((root / "pre-ready-uart.raw").read_bytes(), observed)
- self.assertEqual((root / "combined-uart-binary921.raw").read_bytes(), observed)
- self.assertEqual((root / "combined-rx.raw").read_bytes(), b"")
- preflight = json.loads((root / "startup-preflight.json").read_text(encoding="utf-8"))
- self.assertIsNone(preflight["epoch_start_offset"])
- self.assertEqual(
- manifest["artifact_hashes"]["pre-ready-uart.raw"],
- hashlib.sha256(observed).hexdigest(),
- )
- def test_validator_rejects_formal_combined_rx_that_starts_before_matching_ready_epoch(self) -> None:
- validator = load_validator()
- from binary921 import FrameType, encode_frame
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- combined = (root / "combined-rx.raw").read_bytes()
- old_ready = encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=249999,
- payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
- )
- contaminated = old_ready + combined
- (root / "combined-rx.raw").write_bytes(contaminated)
- collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(contaminated).hexdigest()
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "fail")
- self.assertIn("formal_epoch_does_not_start_at_matching_ready", evidence["blockers"])
- def test_validator_strictly_decodes_post_epoch_artifact_and_ignores_pre_ready_diagnostics(self) -> None:
- validator = load_validator()
- from binary921 import FrameType, decode_stream, encode_frame
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- original = (root / "combined-rx.raw").read_bytes()
- frames, remainder = decode_stream(original)
- self.assertEqual(remainder, b"")
- ready_length = len(frames[0].raw)
- formal_tail = original[ready_length:]
- old_ready = encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=249999,
- payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
- )
- corrupt_ready = bytearray(old_ready)
- corrupt_ready[-1] ^= 1
- pre_ready = bytes(corrupt_ready) + old_ready
- matching_ready = b"".join(
- encode_frame(
- profile_id=3,
- frame_type=FrameType.READY,
- seq=1,
- timestamp_tick=250000 + announcement,
- payload=bytes([3])
- + int("1234ABCD", 16).to_bytes(4, "little")
- + bytes([1, announcement]),
- )
- for announcement in (0, 1, 2)
- )
- formal = matching_ready + formal_tail
- (root / "pre-ready-uart.raw").write_bytes(pre_ready)
- (root / "combined-rx.raw").write_bytes(formal)
- collector["artifact_hashes"]["pre-ready-uart.raw"] = hashlib.sha256(pre_ready).hexdigest()
- collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(formal).hexdigest()
- collector["startup_ready"] = {"epoch_start_offset": len(pre_ready)}
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "pass", evidence["blockers"])
- self.assertEqual(evidence["startup_ready"]["matching_ready_count"], 3)
- self.assertEqual(evidence["startup_ready"]["announcement_seq"], 2)
- self.assertEqual(evidence["startup_ready"]["epoch_start_offset"], len(pre_ready))
- self.assertEqual(evidence["raw_validation"]["combined"]["status"], "pass")
- def test_raw_corruption_sequence_gap_and_manifest_hash_mismatch_fail_closed(self) -> None:
- validator = load_validator()
- cases = (
- "corrupt_crc",
- "command_seq",
- "manifest_hash",
- "pre_ready_acks",
- "bmc_provenance",
- "malformed_bmc_counts",
- "stale_bmc_session",
- )
- for name in cases:
- with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- collector, source, bmc = self.build_fixture(root)
- if name == "corrupt_crc":
- raw = bytearray((root / "combined-rx.raw").read_bytes())
- raw[-1] ^= 1
- (root / "combined-rx.raw").write_bytes(raw)
- elif name == "command_seq":
- from binary921 import CommandId, build_host_command
- wire = (root / "host-command-wire.bin").read_bytes()
- first_len = 19
- replacement = build_host_command(seq=2, command=CommandId.SET_PTC, channel=1, percent=10, profile_id=3)
- (root / "host-command-wire.bin").write_bytes(replacement + wire[first_len:])
- elif name == "pre_ready_acks":
- from binary921 import FrameType, decode_stream
- raw = (root / "combined-rx.raw").read_bytes()
- frames, remainder = decode_stream(raw)
- self.assertEqual(remainder, b"")
- ready_len = len(frames[0].raw)
- ack_len = sum(len(frame.raw) for frame in frames[1:13])
- ready = raw[:ready_len]
- acks = raw[ready_len : ready_len + ack_len]
- tail = raw[ready_len + ack_len :]
- (root / "combined-rx.raw").write_bytes(acks + ready + tail)
- collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(acks + ready + tail).hexdigest()
- elif name == "bmc_provenance":
- receipt = json.loads(bmc.read_text(encoding="utf-8"))
- receipt["payload_hex"][0] = "20"
- bmc.write_text(json.dumps(receipt), encoding="utf-8")
- elif name == "stale_bmc_session":
- receipt = json.loads(bmc.read_text(encoding="utf-8"))
- receipt["last_reply_at"] = "2026-07-10T09:59:58Z"
- bmc.write_text(json.dumps(receipt), encoding="utf-8")
- elif name == "malformed_bmc_counts":
- receipt = json.loads(bmc.read_text(encoding="utf-8"))
- receipt["matched_poll_count"] = "not-a-number"
- receipt["reply_count"] = {"truncated": True}
- bmc.write_text(json.dumps(receipt), encoding="utf-8")
- else:
- collector["artifact_hashes"]["combined-rx.raw"] = "0" * 64
- evidence = validator.validate_evidence_directory(
- collector_dir=root,
- collector=collector,
- program=program_receipt(),
- source_manifest=source,
- programmer_receipt_path="programmer/program-sram-receipt.json",
- programmer_receipt_sha256="c" * 64,
- bmc_replay_receipt_path=bmc,
- )
- self.assertEqual(evidence["status"], "fail")
- self.assertTrue(evidence["blockers"])
- if __name__ == "__main__":
- unittest.main()
|