| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421 |
- #!/usr/bin/env python3
- """Raw-first validator for Prod2U PROGRAM_SRAM binary921 evidence."""
- from __future__ import annotations
- import hashlib
- import json
- import sys
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import Any, Mapping
- TOOLS = Path(__file__).resolve().parent
- if str(TOOLS) not in sys.path:
- sys.path.insert(0, str(TOOLS))
- from binary921 import MAGIC, CommandId, FrameType, decode_frame, decode_payload, frame_to_dict # noqa: E402
- from prod2u_collector import COMMAND_SEQUENCE # noqa: E402
- from prod2u_receipts import validate_evidence_manifest # noqa: E402
- PROFILE = "prod2u-bmc-replay-binary921"
- PROFILE_ID = 3
- def sha256_bytes(data: bytes) -> str:
- return hashlib.sha256(data).hexdigest()
- def _mapping(value: Any) -> Mapping[str, Any]:
- return value if isinstance(value, Mapping) else {}
- def _receipt_int(value: Any) -> int | None:
- if isinstance(value, bool) or not isinstance(value, int):
- return None
- return value
- def _parse_utc(value: Any) -> datetime | None:
- if not isinstance(value, str) or not value:
- return None
- normalized = value[:-1] + "+00:00" if value.endswith("Z") else value
- try:
- parsed = datetime.fromisoformat(normalized)
- except ValueError:
- return None
- if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=timezone.utc)
- return parsed.astimezone(timezone.utc)
- def strict_decode_stream(data: bytes) -> dict[str, Any]:
- failures: list[str] = []
- frames: list[dict[str, Any]] = []
- offset = 0
- if not data:
- failures.append("raw_empty")
- while offset < len(data):
- if data[offset : offset + 2] != MAGIC:
- failures.append(f"unexpected_bytes_at_offset:{offset}")
- break
- if len(data) - offset < 16:
- failures.append(f"incomplete_frame_header_at_offset:{offset}")
- break
- payload_len = data[offset + 13]
- end = offset + 14 + payload_len + 2
- if end > len(data):
- failures.append(f"incomplete_frame_at_offset:{offset}")
- break
- candidate = data[offset:end]
- try:
- frame = decode_frame(candidate)
- except Exception as exc:
- failures.append(f"corrupt_frame_at_offset:{offset}:{exc}")
- break
- row = frame_to_dict(frame)
- row["offset"] = offset
- row["end_offset"] = end
- frames.append(row)
- offset = end
- if offset != len(data) and not failures:
- failures.append(f"unconsumed_bytes_at_offset:{offset}")
- return {
- "status": "pass" if frames and not failures and offset == len(data) else "fail",
- "byte_count": len(data),
- "frame_count": len(frames),
- "consumed_bytes": offset,
- "failures": failures,
- "frames": frames,
- }
- def _validate_commands(frames: list[dict[str, Any]]) -> dict[str, Any]:
- failures: list[str] = []
- commands = [frame for frame in frames if frame.get("frame_type") == int(FrameType.HOST_CMD)]
- if len(commands) != len(COMMAND_SEQUENCE):
- failures.append(f"host_command_count_not_12:{len(commands)}")
- for index, expected in enumerate(COMMAND_SEQUENCE, start=1):
- if index > len(commands):
- break
- _, command, channel, percent = expected
- frame = commands[index - 1]
- decoded = _mapping(frame.get("decoded"))
- if frame.get("profile_id") != PROFILE_ID:
- failures.append(f"host_command_profile_mismatch:{index}")
- if frame.get("seq") != index:
- failures.append(f"host_command_seq_mismatch:{index}:{frame.get('seq')}")
- if decoded.get("cmd_id") != int(command):
- failures.append(f"host_command_id_mismatch:{index}")
- if channel is not None and decoded.get("channel") != channel:
- failures.append(f"host_command_channel_mismatch:{index}")
- if command == CommandId.SET_PID_REQUESTED:
- if decoded.get("enabled") is not bool(percent):
- failures.append(f"host_command_enabled_mismatch:{index}")
- elif percent is not None and decoded.get("percent") != percent:
- failures.append(f"host_command_percent_mismatch:{index}")
- return {"status": "pass" if not failures else "fail", "count": len(commands), "failures": failures}
- def _validate_acks(frames: list[dict[str, Any]]) -> dict[str, Any]:
- failures: list[str] = []
- acks = [frame for frame in frames if frame.get("frame_type") == int(FrameType.HOST_ACK)]
- matched = 0
- if len(acks) != len(COMMAND_SEQUENCE):
- failures.append(f"host_ack_count_not_12:{len(acks)}")
- for index, expected in enumerate(COMMAND_SEQUENCE, start=1):
- if index > len(acks):
- break
- _, command, _, _ = expected
- frame = acks[index - 1]
- decoded = _mapping(frame.get("decoded"))
- accepted = (
- frame.get("profile_id") == PROFILE_ID
- and frame.get("seq") == index
- and decoded.get("cmd_id") == int(command)
- and decoded.get("ok") is True
- and decoded.get("status_code") == 0
- )
- if accepted:
- matched += 1
- else:
- failures.append(f"host_ack_mismatch:{index}")
- return {
- "status": "pass" if not failures and matched == len(COMMAND_SEQUENCE) else "fail",
- "count": len(acks),
- "matched_count": matched,
- "failures": failures,
- }
- def _load_bmc_receipt(path: Path) -> dict[str, Any]:
- if not path.is_file():
- return {"status": "not_run", "bmc_source": "not_run", "payload_sha256": None}
- try:
- payload = json.loads(path.read_text(encoding="utf-8-sig"))
- except (OSError, json.JSONDecodeError) as exc:
- return {
- "status": "blocked_invalid_bmc_replay_receipt",
- "bmc_source": "not_run",
- "payload_sha256": None,
- "error": str(exc),
- "failures": ["bmc_receipt_unreadable"],
- }
- if not isinstance(payload, dict):
- return {
- "status": "blocked_invalid_bmc_replay_receipt",
- "bmc_source": "not_run",
- "payload_sha256": None,
- "failures": ["bmc_receipt_not_object"],
- }
- failures: list[str] = []
- reply_sha = str(payload.get("reply_sha256") or payload.get("payload_reply_sha256") or "").lower()
- values: bytes | None = None
- payload_hex = payload.get("payload_hex")
- if not isinstance(payload_hex, list) or len(payload_hex) != 48:
- failures.append("bmc_receipt_payload_hex_not_48")
- else:
- try:
- values = bytes(int(str(value), 16) for value in payload_hex)
- except (TypeError, ValueError, OverflowError):
- failures.append("bmc_receipt_payload_hex_invalid")
- else:
- canonical_reply = " ".join(f"{value:02x}" for value in values) + "\r\n"
- if sha256_bytes(canonical_reply.encode("ascii")) != reply_sha:
- failures.append("bmc_receipt_reply_sha256_mismatch")
- if payload.get("schema") != "prod2u-bmc-replay-session-v1":
- failures.append("bmc_receipt_schema_mismatch")
- if payload.get("status") != "pass":
- failures.append("bmc_receipt_status_not_pass")
- if payload.get("bmc_source") != "pc_replay_from_real_bmc_capture":
- failures.append("bmc_receipt_source_mismatch")
- matched_poll_count = _receipt_int(payload.get("matched_poll_count"))
- reply_count = _receipt_int(payload.get("reply_count"))
- if matched_poll_count is None or matched_poll_count <= 0 or reply_count is None or reply_count <= 0:
- failures.append("bmc_receipt_no_poll_response")
- byte_count = _receipt_int(payload.get("byte_count"))
- if byte_count != 48:
- failures.append("bmc_receipt_byte_count_not_48")
- valid_count = _receipt_int(payload.get("valid_count"))
- missing_count = _receipt_int(payload.get("missing_count"))
- if (
- valid_count is None
- or missing_count is None
- or valid_count < 0
- or missing_count < 0
- or valid_count + missing_count != 24
- ):
- failures.append("bmc_receipt_sensor_count_not_24")
- passed = not failures
- return {
- "status": "pass" if passed else "blocked_bmc_replay_not_run",
- "schema": payload.get("schema"),
- "bmc_source": payload.get("bmc_source", "not_run"),
- "payload_sha256": reply_sha or None,
- "byte_count": byte_count,
- "valid_count": valid_count,
- "missing_count": missing_count,
- "matched_poll_count": matched_poll_count,
- "reply_count": reply_count,
- "started_at": payload.get("started_at"),
- "last_reply_at": payload.get("last_reply_at"),
- "payload_hex": payload_hex if values is not None else None,
- "payload_first": None if values is None else values[0],
- "payload_last": None if values is None else values[-1],
- "payload_checksum": None if values is None else sum(values) & 0xFFFF,
- "failures": failures,
- }
- def validate_evidence_directory(
- *,
- collector_dir: Path,
- collector: Mapping[str, Any],
- program: Mapping[str, Any],
- source_manifest: Mapping[str, Any],
- programmer_receipt_path: str,
- programmer_receipt_sha256: str,
- bmc_replay_receipt_path: Path,
- ) -> dict[str, Any]:
- collector_dir = Path(collector_dir)
- combined_path = collector_dir / "combined-rx.raw"
- command_path = collector_dir / "host-command-wire.bin"
- combined = combined_path.read_bytes() if combined_path.is_file() else b""
- command_wire = command_path.read_bytes() if command_path.is_file() else b""
- combined_validation = strict_decode_stream(combined)
- command_validation = strict_decode_stream(command_wire)
- combined_frames = list(combined_validation["frames"])
- command_frames = list(command_validation["frames"])
- failures: list[str] = []
- failures.extend(f"combined:{failure}" for failure in combined_validation["failures"])
- failures.extend(f"host_wire:{failure}" for failure in command_validation["failures"])
- ready_frames = [frame for frame in combined_frames if frame.get("frame_type") == int(FrameType.READY)]
- expected_build_id = str(source_manifest.get("build_id", "")).upper()
- def ready_matches_identity(frame: Mapping[str, Any]) -> bool:
- decoded = _mapping(frame.get("decoded"))
- return (
- frame.get("profile_id") == PROFILE_ID
- and frame.get("seq") == 1
- and decoded.get("profile_id_payload") == PROFILE_ID
- and decoded.get("build_id") == expected_build_id
- and decoded.get("por_reason") == 1
- and isinstance(decoded.get("announcement_seq"), int)
- and 0 <= int(decoded["announcement_seq"]) <= 2
- )
- matching_ready_frames = [frame for frame in ready_frames if ready_matches_identity(frame)]
- if matching_ready_frames and int(matching_ready_frames[0].get("offset", -1)) != 0:
- failures.append("formal_epoch_does_not_start_at_matching_ready")
- ready = matching_ready_frames[-1] if matching_ready_frames else ready_frames[-1] if ready_frames else {}
- ready_decoded = _mapping(ready.get("decoded"))
- formal_frames = [
- frame
- for frame in combined_frames
- if ready and int(frame.get("offset", -1)) >= int(ready.get("end_offset", 0))
- ]
- command_result = _validate_commands(command_frames)
- ack_result = _validate_acks(formal_frames)
- failures.extend(command_result["failures"])
- failures.extend(ack_result["failures"])
- if not ready:
- failures.append("startup_ready_missing")
- elif not ready_matches_identity(ready):
- failures.append("startup_ready_identity_mismatch")
- bmc_replay = _load_bmc_receipt(Path(bmc_replay_receipt_path))
- bmc_replay_pass = bmc_replay["status"] == "pass"
- bmc_frames = [frame for frame in formal_frames if frame.get("frame_type") == int(FrameType.BMC_PAYLOAD)]
- sensor_frames = [frame for frame in formal_frames if frame.get("frame_type") == int(FrameType.SENSOR_CACHE)]
- snapshot_frames = [frame for frame in formal_frames if frame.get("frame_type") == int(FrameType.MODULE_SNAPSHOT)]
- if bmc_replay_pass and not bmc_frames:
- failures.append("bmc_payload_frame_missing")
- sensor = _mapping(sensor_frames[-1].get("decoded")) if sensor_frames else {}
- valid_count = sensor.get("valid_count")
- missing_count = sensor.get("missing_count")
- sensor_cache_valid = (
- isinstance(valid_count, int)
- and isinstance(missing_count, int)
- and valid_count + missing_count == 24
- )
- if bmc_replay_pass and not sensor_cache_valid:
- failures.append("sensor_cache_not_24_dimms")
- snapshot = _mapping(snapshot_frames[-1].get("decoded")) if snapshot_frames else {}
- if not snapshot_frames:
- failures.append("module_snapshot_missing")
- pid_status = "pass" if snapshot.get("pid_requested") is False else "fail"
- if pid_status != "pass":
- failures.append("pid_not_inactive")
- timeout_status = "pass" if (
- snapshot.get("timeout_active") is True
- and snapshot.get("ptc01_percent") == 0
- and snapshot.get("ptc24_percent") == 0
- and snapshot.get("fan01_percent") == 30
- and snapshot.get("fan04_percent") == 30
- ) else "fail"
- if timeout_status != "pass":
- failures.append("timeout_fallback_invalid")
- actual_hashes = {
- "combined-rx.raw": sha256_bytes(combined),
- "host-command-wire.bin": sha256_bytes(command_wire),
- }
- expected_hashes = _mapping(collector.get("artifact_hashes"))
- artifact_mismatches = [
- name for name, actual in actual_hashes.items() if expected_hashes.get(name) != actual
- ]
- failures.extend(f"collector_artifact_hash_mismatch:{name}" for name in artifact_mismatches)
- if not bmc_replay_pass:
- failures.extend(f"bmc_replay:{failure}" for failure in bmc_replay.get("failures", []))
- elif bmc_frames:
- observed_bmc = _mapping(bmc_frames[-1].get("decoded"))
- expected_bmc_fields = {
- "payload_len_reported": 48,
- "payload_count": 48,
- "first_byte": bmc_replay.get("payload_first"),
- "last_byte": bmc_replay.get("payload_last"),
- "checksum": bmc_replay.get("payload_checksum"),
- }
- for field, expected in expected_bmc_fields.items():
- if observed_bmc.get(field) != expected:
- failures.append(f"bmc_payload_provenance_mismatch:{field}")
- if valid_count != bmc_replay.get("valid_count") or missing_count != bmc_replay.get("missing_count"):
- failures.append("bmc_sensor_cache_provenance_mismatch")
- program_started_at = _parse_utc(_mapping(program.get("execution")).get("started_at"))
- bmc_last_reply_at = _parse_utc(bmc_replay.get("last_reply_at"))
- if program_started_at is None or bmc_last_reply_at is None:
- failures.append("bmc_session_time_evidence_missing")
- elif bmc_last_reply_at < program_started_at:
- failures.append("bmc_session_predates_program_invocation")
- evidence: dict[str, Any] = {
- "schema": "prod2u-evidence-manifest-v1",
- "status": "pass",
- "protocol": "binary921",
- "profile": PROFILE,
- "profile_id": PROFILE_ID,
- "build_identity": {
- "build_id": str(source_manifest.get("build_id", "")).upper(),
- "source_manifest_sha256": str(source_manifest.get("source_manifest_sha256", "")).lower(),
- },
- "programmer_receipt": {
- "path": programmer_receipt_path,
- "sha256": programmer_receipt_sha256,
- "status": program.get("status"),
- },
- "startup_ready": {
- "frame_type": ready.get("frame_type"),
- "seq": ready.get("seq"),
- "profile_id": ready.get("profile_id"),
- "build_id": ready_decoded.get("build_id"),
- "post_program_epoch": program.get("status") == "pass" and bool(ready),
- "timestamp_tick": ready.get("timestamp_tick"),
- "por_reason": ready_decoded.get("por_reason"),
- "announcement_seq": ready_decoded.get("announcement_seq"),
- "matching_ready_count": len(matching_ready_frames),
- "selection_policy": "last_matching_ready" if matching_ready_frames else None,
- "epoch_start_offset": _mapping(collector.get("startup_ready")).get("epoch_start_offset"),
- },
- "host_command_count": command_result["count"],
- "host_ack_count": ack_result["count"],
- "host_ack_matched_count": ack_result["matched_count"],
- "bmc_replay": bmc_replay,
- "artifact_hashes": actual_hashes,
- "real_fan_ptc_hardware_status": "not_run",
- "safety": {
- "flash_attempted": False,
- "programs_nonvolatile": False,
- "driver_install_attempted": False,
- "power_cycle_attempted": False,
- "toggles_dtr_rts": False,
- },
- "raw_validation": {
- "combined": {key: value for key, value in combined_validation.items() if key != "frames"},
- "host_command_wire": {key: value for key, value in command_validation.items() if key != "frames"},
- "host_commands": command_result,
- "host_acks": ack_result,
- "sensor_cache": {
- "status": "pass" if sensor_cache_valid else ("fail" if bmc_replay_pass else "not_run"),
- "valid_count": valid_count,
- "missing_count": missing_count,
- },
- "pid_inactive": {"status": pid_status},
- "timeout_fallback": {"status": timeout_status},
- "artifact_hash_mismatches": artifact_mismatches,
- },
- }
- contract = validate_evidence_manifest(evidence, program)
- blockers = list(dict.fromkeys(list(contract["failures"]) + failures))
- if failures:
- status = "fail"
- else:
- status = contract["status"]
- evidence["status"] = status
- evidence["blockers"] = blockers
- return evidence
|