test_prod2u_p4_cli_identity.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. #!/usr/bin/env python3
  2. """Identity and entrypoint contracts for the Prod2U Profile 4 CLI."""
  3. from __future__ import annotations
  4. import hashlib
  5. import importlib.util
  6. import json
  7. import subprocess
  8. import sys
  9. import tempfile
  10. import unittest
  11. from pathlib import Path
  12. from types import SimpleNamespace
  13. ROOT = Path(__file__).resolve().parents[2]
  14. TOOLS = ROOT / "tools"
  15. sys.path.insert(0, str(TOOLS))
  16. def load_cli():
  17. path = TOOLS / "prod2u_p4_cli.py"
  18. spec = importlib.util.spec_from_file_location("test_prod2u_p4_cli_identity_owned", path)
  19. if spec is None or spec.loader is None:
  20. raise AssertionError(f"unable to import {path}")
  21. module = importlib.util.module_from_spec(spec)
  22. sys.modules[spec.name] = module
  23. spec.loader.exec_module(module)
  24. return module
  25. def write_identity_fixture(root: Path, *, variant: str = "normal") -> SimpleNamespace:
  26. from prod2u_build_identity import source_manifest_sha256
  27. bitstream = root / f"{variant}.bit"
  28. bitstream.write_bytes(f"prod2u-p4-{variant}".encode("ascii"))
  29. bitstream_sha256 = hashlib.sha256(bitstream.read_bytes()).hexdigest()
  30. source = {
  31. "schema": "prod2u-source-manifest-v1",
  32. "profile": "prod2u-fan-tach-binary921-v2",
  33. "td_version": "6.2.2.198412",
  34. "files": [
  35. {
  36. "path": f"src/top/prod2u_fan_tach_binary921_v2_{variant}_top.v",
  37. "size": 1,
  38. "sha256": "a" * 64,
  39. }
  40. ],
  41. }
  42. source_hash = source_manifest_sha256(source)
  43. source.update(source_manifest_sha256=source_hash, build_id=source_hash[:8].upper())
  44. source_manifest = root / f"{variant}-source-manifest.json"
  45. source_manifest.write_text(json.dumps(source), encoding="utf-8")
  46. td_receipt = root / f"{variant}-td.json"
  47. td_receipt.write_text(
  48. json.dumps(
  49. {
  50. "schema": "prod2u-td-build-receipt-v1",
  51. "status": "pass",
  52. "top": f"prod2u_fan_tach_binary921_v2_{variant}",
  53. "top_module": f"prod2u_fan_tach_binary921_v2_{variant}_top",
  54. "pin_profile": "prod2u-fan-tach-binary921-v2",
  55. "build_id": source["build_id"],
  56. "source_manifest_sha256": source_hash,
  57. "build_identity": {
  58. "status": "pass",
  59. "build_id": source["build_id"],
  60. "source_manifest_sha256": source_hash,
  61. "staged_manifest_sha256": "b" * 64,
  62. },
  63. "por_initialization": {"status": "not_applicable", "failures": []},
  64. "bitstream": {
  65. "path": str(bitstream),
  66. "size": bitstream.stat().st_size,
  67. "sha256": bitstream_sha256,
  68. },
  69. "resources": {"utilization": {"lut": 1}},
  70. "timing": {"setup_wns_ns": 1.0, "hold_wns_ns": 0.1},
  71. "timing_gate": {"status": "pass", "failures": []},
  72. "syn": {"returncode": 0, "log_has_error": False},
  73. "phy": {"returncode": 0, "log_has_error": False},
  74. }
  75. ),
  76. encoding="utf-8",
  77. )
  78. td_root = root / "TD"
  79. (td_root / "bin").mkdir(parents=True)
  80. (td_root / "bin" / "bw_commands_prompt.exe").write_bytes(b"fixture")
  81. return SimpleNamespace(
  82. variant=variant,
  83. build_id=int(source["build_id"], 16),
  84. bitstream=bitstream,
  85. sha256=bitstream_sha256,
  86. td_receipt=td_receipt,
  87. source_manifest=source_manifest,
  88. td_root=td_root,
  89. output_dir=root / "evidence",
  90. run_id="identity-fixture",
  91. )
  92. class Prod2UP4CliIdentityTests(unittest.TestCase):
  93. def test_live_commands_require_td_receipt_and_source_manifest(self) -> None:
  94. cli = load_cli()
  95. parser = cli.build_parser()
  96. with self.assertRaises(SystemExit):
  97. parser.parse_args(
  98. [
  99. "program-only",
  100. "--variant",
  101. "normal",
  102. "--build-id",
  103. "1234ABCD",
  104. "--bitstream",
  105. "normal.bit",
  106. "--sha256",
  107. "a" * 64,
  108. "--td-root",
  109. "TD",
  110. "--output-dir",
  111. "evidence",
  112. ]
  113. )
  114. def test_preflight_hash_binds_bitstream_manifest_td_receipt_and_build(self) -> None:
  115. cli = load_cli()
  116. with tempfile.TemporaryDirectory() as temp:
  117. args = write_identity_fixture(Path(temp))
  118. passed = cli.run_preflight(args)
  119. receipt = json.loads(args.td_receipt.read_text(encoding="utf-8"))
  120. receipt["build_id"] = "DEADBEEF"
  121. args.td_receipt.write_text(json.dumps(receipt), encoding="utf-8")
  122. failed = cli.run_preflight(args)
  123. self.assertEqual(passed["status"], "pass", passed)
  124. self.assertEqual(passed["identity"]["build_id"], f"{args.build_id:08X}")
  125. self.assertEqual(passed["identity"]["source_manifest_status"], "pass")
  126. self.assertEqual(passed["identity"]["td_receipt_status"], "pass")
  127. self.assertEqual(failed["status"], "fail")
  128. self.assertIn("td_receipt_build_id_mismatch", failed["failures"])
  129. def test_default_powershell_selftest_routes_to_profile4(self) -> None:
  130. result = subprocess.run(
  131. [
  132. "powershell.exe",
  133. "-NoProfile",
  134. "-ExecutionPolicy",
  135. "Bypass",
  136. "-File",
  137. str(TOOLS / "prod2u.ps1"),
  138. "selftest",
  139. ],
  140. cwd=ROOT,
  141. capture_output=True,
  142. text=True,
  143. check=False,
  144. )
  145. payload = json.loads(result.stdout)
  146. self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
  147. self.assertEqual(payload["profile_id"], 4)
  148. self.assertEqual(payload["protocol_version"], 2)
  149. def test_powershell_profile_routing_preserves_profile3_read_only_commands(self) -> None:
  150. def run(*arguments: str) -> subprocess.CompletedProcess[str]:
  151. return subprocess.run(
  152. [
  153. "powershell.exe",
  154. "-NoProfile",
  155. "-ExecutionPolicy",
  156. "Bypass",
  157. "-File",
  158. str(TOOLS / "prod2u.ps1"),
  159. *arguments,
  160. ],
  161. cwd=ROOT,
  162. capture_output=True,
  163. text=True,
  164. check=False,
  165. )
  166. profile3_selftest = run("selftest", "-Profile", "profile3")
  167. self.assertEqual(profile3_selftest.returncode, 0, profile3_selftest.stdout + profile3_selftest.stderr)
  168. self.assertEqual(json.loads(profile3_selftest.stdout)["profile_id"], 3)
  169. with tempfile.TemporaryDirectory() as temp:
  170. receipt = Path(temp) / "td.json"
  171. receipt.write_text("{}", encoding="utf-8")
  172. profile3_legacy = run("validate-td-receipt", "-Profile", "profile3", "-TdReceipt", str(receipt))
  173. self.assertEqual(profile3_legacy.returncode, 1)
  174. self.assertEqual(json.loads(profile3_legacy.stdout)["schema"], "prod2u-td-receipt-schema-validation-v1")
  175. unsupported = run("validate-td-receipt", "-Profile", "profile4")
  176. self.assertNotEqual(unsupported.returncode, 0)
  177. self.assertIn("Profile 4 does not support command: validate-td-receipt", unsupported.stdout + unsupported.stderr)
  178. if __name__ == "__main__":
  179. unittest.main()