#!/usr/bin/env python3 """Unit tests for tools/build_firmware_package.py.""" from __future__ import annotations import hashlib import json import shutil import subprocess import sys import tempfile import unittest import zipfile from pathlib import Path from unittest import mock TOOLS = Path(__file__).resolve().parents[2] / "tools" if str(TOOLS) not in sys.path: sys.path.insert(0, str(TOOLS)) import build_firmware_package as builder import package_provenance as pkg_prov ROOT = Path(__file__).resolve().parents[2] FAKE_BITS = b"FAKEBITS" FAKE_BIT_SHA = hashlib.sha256(FAKE_BITS).hexdigest() FAKE_TD_RUN_ID = "td-run-123" def _current_project_sha() -> str: return builder._sha256_file(ROOT / "projects" / "prod2u-door-temp" / "project.json") def _patch_canonical_td_for_fake(*, bits: bytes = FAKE_BITS, run_id: str = FAKE_TD_RUN_ID): """Unit fixtures use fake bits; align shared identity to those bytes.""" sha = hashlib.sha256(bits).hexdigest() fields = { "artifact_source_commit": "fe1a0a2a19622b6f290905ec14795bb6cce6899d", "td_bound_commit": "fe1a0a2a19622b6f290905ec14795bb6cce6899d", "bitstream_sha256": sha, "td_artifact_run_id": run_id, "td_verification_run_id": "88888888888888888888888888888888", "td_receipt_path": "receipts/mse-r4-td-a1-ff44128.json", "td_receipt_sha256": "c" * 64, "td_binding_status": "pass", "production_binding": "37/37/0/0", "lut": 1113, "mslice": 570, "dsp": 0, "status": "pass", } return mock.patch.object(pkg_prov, "load_canonical_td_a1_fields", return_value=fields) def _write_report(path: Path, *, bitstream_sha256: str | None = None, project_sha: str | None = None) -> None: project_sha = project_sha or _current_project_sha() if bitstream_sha256 is None: bitstream_sha256 = FAKE_BIT_SHA report = { "run_id": FAKE_TD_RUN_ID, "verification_run_id": "88888888888888888888888888888888", "status": "pass", "commit_full": "fe1a0a2a19622b6f290905ec14795bb6cce6899d", "commit": "fe1a0a2a19622b6f290905ec14795bb6cce6899d", "project_config_sha256": project_sha, "td_source_manifest_sha256": "8e0da456e865f3c3afa613d2660c1ed0ebf0e422ef51ec7acef223c2017a14bd", "bitstream_sha256": bitstream_sha256, "synthesis_input_manifest": { "schema": "prod2u-simple-synthesis-inputs-v2", "sha256": "aa9f59236f8ffb89df318eaa5ed5037523d7f46e8b838d45c1e3ab44b60bc423", "inputs": { "src/generated/prod2u_door_temp_params.vh": "ffcb0ffbaef92ef63f96ba7ed6a048cb85d3e9d8a1a5b553e458252446fc6950", "projects/prod2u-door-temp/project.json": project_sha, "src/generated/td-source-manifest.json": "8e0da456e865f3c3afa613d2660c1ed0ebf0e422ef51ec7acef223c2017a14bd", }, }, "timing": { "fmax_mhz": 90.49, "worst_setup_slack_ns": 28.949, "worst_hold_slack_ns": 0.046, }, "resources": { "utilization": { "lut": {"used": 1113}, "reg": {"used": 677}, "bram": {"used": 0}, "dsp": {"used": 0}, }, "packing": {"mslice": 570, "lslice": 570, "total_slices": 1140}, }, } path.write_text(json.dumps(report), encoding="utf-8") class BuildFirmwarePackageTests(unittest.TestCase): def _make_td_root(self, tmp_path: Path, *, bitstream_sha256: str | None = None, project_sha: str | None = None) -> tuple[Path, Path, Path]: td_root = tmp_path / "td_root" bitstream = td_root / "td" / "prod2u_p4_normal_v3" / "bitgen" / "prod2u_p4_normal_v3.bit" bitstream.parent.mkdir(parents=True, exist_ok=True) bitstream.write_bytes(FAKE_BITS) report = td_root / "report.json" _write_report(report, bitstream_sha256=bitstream_sha256, project_sha=project_sha) # Add a fake stage log to verify allowlist (td_root / "td" / "prod2u_p4_normal_v3" / "syn").mkdir(parents=True, exist_ok=True) (td_root / "td" / "prod2u_p4_normal_v3" / "syn" / "gate.qor").write_text("fake qor", encoding="utf-8") return td_root, bitstream, report def _commits(self) -> tuple[str, str, str]: # Use the artifact commit for all three in tests so git comparison succeeds. artifact = "fe1a0a2a19622b6f290905ec14795bb6cce6899d" return (artifact, artifact, artifact) def test_build_with_fake_bitstream_and_report(self) -> None: with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) td_root, bitstream, report = self._make_td_root(tmp_path) output_dir = tmp_path / "dist" artifact, matrix, final_dev = self._commits() with _patch_canonical_td_for_fake(): package, sidecar = builder.build_firmware_package( output_dir=output_dir, package_name="test-firmware-package", td_root=td_root, bitstream_path=bitstream, td_report_path=report, artifact_commit=artifact, matrix_commit=matrix, final_dev_commit=final_dev, source_closure_unchanged=True, ) self.assertTrue(package.is_file()) with zipfile.ZipFile(package, "r") as zipf: names = set(zipf.namelist()) self.assertIn("fw.bit", names) self.assertIn("BITSTREAM-SHA256.txt", names) self.assertIn("PACKAGE-MANIFEST.json", names) self.assertIn("SHA256SUMS.txt", names) self.assertIn("td/original-final_td_report.json", names) self.assertIn("td/TD-PROVENANCE.json", names) self.assertIn("evidence/SOURCE-CLOSURE-COMPARISON.json", names) self.assertIn("td/syn/gate.qor", names) manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json")) self.assertEqual(manifest["hardware_validation"], "not_run") self.assertEqual(manifest["verification_scope"], "offline") self.assertTrue(manifest["source_closure_unchanged"]) self.assertEqual(manifest["schema"], "prod2u-door-temp-final-package-manifest-v2") polarity = manifest["motor_polarity_config"] self.assertEqual(polarity["masks"]["limit_active_high_mask"], "3'b111") self.assertEqual(polarity["masks"]["dir_close_level_mask"], "3'b111") self.assertEqual(polarity["masks"]["close_limit_is_ls_mask"], "3'b111") self.assertEqual(len(polarity["sha256"]), 64) polarity_id = builder.motor_polarity_config_identity(ROOT) self.assertEqual(polarity["sha256"], polarity_id["sha256"]) identity = json.loads(zipf.read("meta/release-set-identity.json")) self.assertEqual(identity["bitstream_sha256"], FAKE_BIT_SHA) self.assertNotEqual( identity["bitstream_sha256"], pkg_prov.CANONICAL_TD_A1_BITSTREAM, ) self.assertEqual(identity["td_artifact_run_id"], FAKE_TD_RUN_ID) self.assertEqual(identity["lut"], 1113) self.assertEqual(identity["mslice"], 570) resources = manifest["resources"] self.assertEqual(resources["lut"], 1113) self.assertEqual(resources["register"], 677) self.assertEqual(resources["mslice"], 570) self.assertEqual(resources["lslice"], 570) self.assertEqual(resources["total_slices"], 1140) self.assertEqual(resources["dsp"], 0) self.assertEqual(resources["bram"], 0) self.assertEqual(resources["packed_slice"], 1140) self.assertNotEqual(resources["packed_slice"], resources["mslice"]) self.assertEqual(identity["td_policy"], "fresh_td") self.assertEqual(identity["td_binding_status"], "pass") sums = zipf.read("SHA256SUMS.txt").decode("utf-8") self.assertIn("fw.bit", sums) def test_bitstream_report_mismatch_blocks(self) -> None: with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) td_root, bitstream, report = self._make_td_root(tmp_path, bitstream_sha256="0" * 64) artifact, matrix, final_dev = self._commits() with self.assertRaises(builder.PackagingError): builder.build_firmware_package( output_dir=tmp_path / "dist", package_name="mismatch", td_root=td_root, bitstream_path=bitstream, td_report_path=report, artifact_commit=artifact, matrix_commit=matrix, final_dev_commit=final_dev, source_closure_unchanged=True, ) def test_report_outside_td_root_blocks(self) -> None: with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) td_root, bitstream, _ = self._make_td_root(tmp_path) other_report = tmp_path / "other_report.json" _write_report(other_report) artifact, matrix, final_dev = self._commits() with self.assertRaises(builder.PackagingError): builder.build_firmware_package( output_dir=tmp_path / "dist", package_name="bad-root", td_root=td_root, bitstream_path=bitstream, td_report_path=other_report, artifact_commit=artifact, matrix_commit=matrix, final_dev_commit=final_dev, source_closure_unchanged=True, ) def test_stale_td_logs_not_in_package(self) -> None: with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) td_root, bitstream, report = self._make_td_root(tmp_path) # Place an old log in repo td/ that should not be included (ROOT / "td" / "td_20260630_134648.log").write_text("stale", encoding="utf-8") try: artifact, matrix, final_dev = self._commits() with _patch_canonical_td_for_fake(): package, _ = builder.build_firmware_package( output_dir=tmp_path / "dist", package_name="no-stale", td_root=td_root, bitstream_path=bitstream, td_report_path=report, artifact_commit=artifact, matrix_commit=matrix, final_dev_commit=final_dev, source_closure_unchanged=True, ) with zipfile.ZipFile(package, "r") as zipf: self.assertNotIn("td/td_20260630_134648.log", set(zipf.namelist())) finally: (ROOT / "td" / "td_20260630_134648.log").unlink(missing_ok=True) def test_missing_bitstream_blocks(self) -> None: with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) td_root = tmp_path / "td_root" td_root.mkdir(parents=True, exist_ok=True) report = td_root / "report.json" _write_report(report) artifact, matrix, final_dev = self._commits() with self.assertRaises(FileNotFoundError): builder.build_firmware_package( output_dir=tmp_path / "dist", package_name="missing", td_root=td_root, artifact_commit=artifact, matrix_commit=matrix, final_dev_commit=final_dev, source_closure_unchanged=True, ) def test_source_closure_unavailable_without_git_is_not_fake_diff(self) -> None: td_report = { "synthesis_input_manifest": { "inputs": { "projects/prod2u-door-temp/project.json": "a" * 64, "src/generated/td-source-manifest.json": "b" * 64, } } } comparison = builder.generate_source_closure_comparison( td_report=td_report, artifact_commit="0" * 40, matrix_commit="1" * 40, final_dev_commit="2" * 40, repo_root=ROOT, ) self.assertEqual(comparison["mode"], "comparison_unavailable_without_git") self.assertIsNone(comparison["source_closure_equal"]) self.assertEqual(comparison["production_changed_paths"], []) self.assertTrue(all(entry["status"] == "unavailable" for entry in comparison["inputs"])) def test_source_closure_snapshot_hash_mode(self) -> None: project_sha = _current_project_sha() td_report = { "synthesis_input_manifest": { "inputs": { "projects/prod2u-door-temp/project.json": project_sha, } } } snapshot = { "artifact": {"projects/prod2u-door-temp/project.json": project_sha}, "matrix": {"projects/prod2u-door-temp/project.json": project_sha}, "final_dev": {"projects/prod2u-door-temp/project.json": project_sha}, } comparison = builder.generate_source_closure_comparison( td_report=td_report, artifact_commit="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", matrix_commit="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", final_dev_commit="cccccccccccccccccccccccccccccccccccccccc", snapshot_hashes=snapshot, ) self.assertEqual(comparison["mode"], "snapshot_hash") self.assertTrue(comparison["source_closure_equal"]) self.assertEqual(comparison["production_changed_paths"], []) def test_source_closure_live_commit_compare(self) -> None: # live_git remains strict; compact/detached hosts skip instead of hard-failing. sys.path.insert(0, str(ROOT / "tools")) from git_worktree_mode import require_live_git # noqa: WPS433 require_live_git(ROOT, self) head = subprocess.check_output( ["git", "-C", str(ROOT), "rev-parse", "HEAD"], text=True, ).strip() td_report = { "synthesis_input_manifest": { "inputs": { "projects/prod2u-door-temp/project.json": _current_project_sha(), } } } comparison = builder.generate_source_closure_comparison( td_report=td_report, artifact_commit=head, matrix_commit=head, final_dev_commit=head, repo_root=ROOT, ) self.assertEqual(comparison["mode"], "commit_compare") self.assertTrue(comparison["source_closure_equal"]) self.assertEqual(comparison["inputs"][0]["status"], "same") def _build_fake_fw(self, tmp_path: Path) -> Path: td_root, bitstream, report = self._make_td_root(tmp_path) artifact, matrix, final_dev = self._commits() with _patch_canonical_td_for_fake(): package, _sidecar = builder.build_firmware_package( output_dir=tmp_path / "dist", package_name="tamper-firmware", td_root=td_root, bitstream_path=bitstream, td_report_path=report, artifact_commit=artifact, matrix_commit=matrix, final_dev_commit=final_dev, source_closure_unchanged=True, ) return package def test_firmware_selftest_tamper_bitstream_byte(self) -> None: with tempfile.TemporaryDirectory() as tmp: package = self._build_fake_fw(Path(tmp)) mutated = Path(tmp) / "mut-bit.zip" with zipfile.ZipFile(package, "r") as src, zipfile.ZipFile(mutated, "w") as dst: for info in src.infolist(): data = src.read(info.filename) if info.filename == "fw.bit": data = data[:-1] + bytes([data[-1] ^ 0x01]) dst.writestr(info, data) result = builder.run_firmware_zip_selftest(mutated) self.assertEqual(result["status"], "fail") joined = " ".join(result["failures"]) self.assertTrue( "bitstream" in joined or "sha256sums_mismatch:fw.bit" in joined, result["failures"], ) def test_firmware_selftest_tamper_sha256sums_entry(self) -> None: with tempfile.TemporaryDirectory() as tmp: package = self._build_fake_fw(Path(tmp)) mutated = Path(tmp) / "mut-sum.zip" with zipfile.ZipFile(package, "r") as src, zipfile.ZipFile(mutated, "w") as dst: for info in src.infolist(): data = src.read(info.filename) if info.filename == "SHA256SUMS.txt": text = data.decode("ascii") text = text.replace("fw.bit", "fw.bit", 1) # Flip first hex nibble of the fw.bit line. lines = [] for line in text.splitlines(): if line.endswith(" fw.bit"): line = ("0" if line[0] != "0" else "1") + line[1:] lines.append(line) data = ("\n".join(lines) + "\n").encode("ascii") dst.writestr(info, data) result = builder.run_firmware_zip_selftest(mutated) self.assertEqual(result["status"], "fail") self.assertTrue( any("sha256sums_mismatch:fw.bit" in item for item in result["failures"]), result["failures"], ) def test_firmware_selftest_duplicate_sha_entry(self) -> None: with tempfile.TemporaryDirectory() as tmp: package = self._build_fake_fw(Path(tmp)) mutated = Path(tmp) / "mut-dup.zip" with zipfile.ZipFile(package, "r") as src, zipfile.ZipFile(mutated, "w") as dst: for info in src.infolist(): data = src.read(info.filename) if info.filename == "SHA256SUMS.txt": text = data.decode("ascii") fw_line = next( line for line in text.splitlines() if line.endswith(" fw.bit") ) data = (text + fw_line + "\n").encode("ascii") dst.writestr(info, data) result = builder.run_firmware_zip_selftest(mutated) self.assertEqual(result["status"], "fail") self.assertTrue( any("sha256sums_duplicate:fw.bit" in item for item in result["failures"]), result["failures"], ) def test_firmware_selftest_delete_td_receipt(self) -> None: with tempfile.TemporaryDirectory() as tmp: package = self._build_fake_fw(Path(tmp)) mutated = Path(tmp) / "mut-del.zip" with zipfile.ZipFile(package, "r") as src, zipfile.ZipFile(mutated, "w") as dst: for info in src.infolist(): if info.filename == "td/original-final_td_report.json": continue dst.writestr(info, src.read(info.filename)) result = builder.run_firmware_zip_selftest(mutated) self.assertEqual(result["status"], "fail") joined = " ".join(result["failures"]) self.assertTrue( "missing_required_files" in joined or "sha256sums_missing_file" in joined, result["failures"], ) def test_firmware_selftest_wrong_delivery(self) -> None: with tempfile.TemporaryDirectory() as tmp: package = self._build_fake_fw(Path(tmp)) mutated = Path(tmp) / "mut-deliv.zip" with zipfile.ZipFile(package, "r") as src, zipfile.ZipFile(mutated, "w") as dst: for info in src.infolist(): data = src.read(info.filename) if info.filename == "meta/release-set-identity.json": ident = json.loads(data) ident["delivery_commit"] = "0" * 40 data = (json.dumps(ident) + "\n").encode("utf-8") dst.writestr(info, data) result = builder.run_firmware_zip_selftest(mutated) self.assertEqual(result["status"], "fail") self.assertTrue( any("identity_delivery_mismatch_txt" in item for item in result["failures"]), result["failures"], ) def test_firmware_selftest_stale_sibling(self) -> None: with tempfile.TemporaryDirectory() as tmp: package = self._build_fake_fw(Path(tmp)) mutated = Path(tmp) / "mut-sib.zip" with zipfile.ZipFile(package, "r") as src, zipfile.ZipFile(mutated, "w") as dst: for info in src.infolist(): data = src.read(info.filename) if info.filename == "meta/release-set-sibling.json": sib = json.loads(data) sib["sibling_expected_filename"] = ( "prod2u-review-compact-door-percent-deadbeef.zip" ) data = (json.dumps(sib) + "\n").encode("utf-8") dst.writestr(info, data) result = builder.run_firmware_zip_selftest(mutated) self.assertEqual(result["status"], "fail") joined = " ".join(result["failures"]) self.assertTrue( "sibling_stale_door_percent" in joined or "sibling_topic_not_mse_a1" in joined, result["failures"], ) if __name__ == "__main__": unittest.main()