test_6400_profile_package.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. from __future__ import annotations
  2. import hashlib
  3. import json
  4. from pathlib import Path
  5. import zipfile
  6. import pytest
  7. from tools import package_target
  8. ROOT = Path(__file__).resolve().parents[2]
  9. TEST_COMMIT = "a" * 40
  10. TEST_SOURCE_COMMIT = "b" * 40
  11. def _receipt(
  12. tmp_path: Path, profile_name: str, commit: str = TEST_SOURCE_COMMIT
  13. ) -> Path:
  14. profile = package_target.HARDWARE_PROFILES[profile_name]
  15. inputs = package_target.td_input_manifest(profile_name)
  16. bitstream = tmp_path / f"{profile['artifact_basename']}.bit"
  17. bitstream.write_bytes(b"TD-BIT-TEST")
  18. payload = {
  19. "schema": "prod2u-6400-td-receipt-v1",
  20. "status": "PASS",
  21. "profile": profile_name,
  22. "project": str(profile["project"]),
  23. "source_closure": str(profile["closure"]),
  24. "commit": commit,
  25. "production": bool(profile["production"]),
  26. "stimulus": bool(profile["stimulus"]),
  27. "simulation_only": False,
  28. "artifact_basename": str(profile["artifact_basename"]),
  29. "timing_pass_25mhz": True,
  30. "project_sha256": package_target._sha256(ROOT / str(profile["project"])),
  31. "source_closure_sha256": package_target._sha256(
  32. ROOT / str(profile["closure"])
  33. ),
  34. "source_manifest_sha256": hashlib.sha256(
  35. json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()
  36. ).hexdigest(),
  37. "inputs": inputs,
  38. "known_unbound_ports": ["host_ttl_rx", "host_ttl_tx"],
  39. "deployment_status": package_target._expected_deployment_status(profile_name),
  40. "warning_audit": {
  41. "status": "PASS",
  42. "expected_unbound_ports": ["host_ttl_rx", "host_ttl_tx"],
  43. "observed_unbound_ports": ["host_ttl_rx", "host_ttl_tx"],
  44. "unexpected_unbound_ports": [],
  45. "missing_expected_unbound_ports": [],
  46. },
  47. "bitstream": str(bitstream),
  48. "bitstream_sha256": package_target._sha256(bitstream),
  49. }
  50. path = tmp_path / "td-receipt.json"
  51. path.write_text(json.dumps(payload), encoding="utf-8")
  52. return path
  53. def test_firmware_requires_explicit_profile_and_td_receipt(
  54. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  55. ) -> None:
  56. monkeypatch.setattr(package_target, "_git", lambda *_args: TEST_COMMIT)
  57. with pytest.raises(SystemExit, match="explicitly select --profile"):
  58. package_target.build_target_package("6400", "firmware", tmp_path)
  59. with pytest.raises(SystemExit, match="explicit --td-receipt is required"):
  60. package_target.build_target_package(
  61. "6400", "firmware", tmp_path, profile_name="6400-control"
  62. )
  63. with pytest.raises(SystemExit, match="Sim-Debug"):
  64. package_target.build_target_package(
  65. "6400", "firmware", tmp_path, profile_name="6400-sim-debug"
  66. )
  67. @pytest.mark.parametrize("profile_name", ["6400-control", "6400-identification"])
  68. def test_td_receipt_is_profile_commit_closure_and_bit_bound(
  69. tmp_path: Path, profile_name: str
  70. ) -> None:
  71. receipt_path = _receipt(tmp_path, profile_name)
  72. commit = TEST_COMMIT
  73. bitstream, receipt = package_target._validated_td_bitstream(
  74. profile_name, receipt_path, commit
  75. )
  76. assert bitstream.name == f"{package_target.HARDWARE_PROFILES[profile_name]['artifact_basename']}.bit"
  77. assert receipt["profile"] == profile_name
  78. assert receipt["commit"] == TEST_SOURCE_COMMIT
  79. assert receipt["commit"] != commit
  80. payload = json.loads(receipt_path.read_text(encoding="utf-8"))
  81. payload["source_closure_sha256"] = "0" * 64
  82. receipt_path.write_text(json.dumps(payload), encoding="utf-8")
  83. with pytest.raises(SystemExit, match="TD receipt mismatch"):
  84. package_target._validated_td_bitstream(profile_name, receipt_path, commit)
  85. @pytest.mark.parametrize(
  86. "tamper",
  87. [
  88. "input_digest",
  89. "input_missing",
  90. "ports_missing",
  91. "ports_duplicate",
  92. "deployment_status",
  93. "warning_observed",
  94. ],
  95. )
  96. def test_td_receipt_rejects_missing_duplicate_and_tampered_provenance(
  97. tmp_path: Path, tamper: str
  98. ) -> None:
  99. receipt_path = _receipt(tmp_path, "6400-identification")
  100. payload = json.loads(receipt_path.read_text(encoding="utf-8"))
  101. if tamper == "input_digest":
  102. first = next(iter(payload["inputs"]))
  103. payload["inputs"][first] = "0" * 64
  104. elif tamper == "input_missing":
  105. payload["inputs"].pop(next(iter(payload["inputs"])))
  106. elif tamper == "ports_missing":
  107. payload.pop("known_unbound_ports")
  108. elif tamper == "ports_duplicate":
  109. payload["known_unbound_ports"].append("host_ttl_rx")
  110. elif tamper == "deployment_status":
  111. payload["deployment_status"] = package_target.CONTROL_DEPLOYMENT_STATUS
  112. else:
  113. payload["warning_audit"]["observed_unbound_ports"].append("unexpected")
  114. receipt_path.write_text(json.dumps(payload), encoding="utf-8")
  115. with pytest.raises(SystemExit, match="TD receipt mismatch|warning audit mismatch"):
  116. package_target._validated_td_bitstream(
  117. "6400-identification", receipt_path, TEST_COMMIT
  118. )
  119. def test_control_source_package_contains_only_active_grouped_closure(tmp_path: Path) -> None:
  120. archive = package_target.build_target_package(
  121. "6400", "source", tmp_path, profile_name="6400-control"
  122. )
  123. with zipfile.ZipFile(archive) as zipf:
  124. names = set(zipf.namelist())
  125. manifest = json.loads(zipf.read("manifest.json"))
  126. closure = json.loads(zipf.read("source-closure-expanded.json"))
  127. host_contract = json.loads(zipf.read("generated/6400/host-contract.json"))
  128. assert manifest["profile"] == "6400-control"
  129. assert manifest["top"] == "prod2u_6400_v1_top"
  130. assert "src/actuator/fan_board_output_adapter.v" in closure["sources"]
  131. assert host_contract["wire"]["host_uart"]["baud"] == 921600
  132. assert host_contract["wire"]["responses"]["SET_TARGET_ACK"]["type"] == 0x81
  133. assert host_contract["wire"]["responses"]["GET_SNAPSHOT_ACK"]["type"] == 0x82
  134. assert host_contract["wire"]["responses"]["SNAPSHOT_DATA"]["type"] == 0x42
  135. assert host_contract["canonical_profiles"]["6400-control"]["stimulus"] is False
  136. assert not any(name.startswith("src/generated/6400/") for name in names)
  137. assert not any("prod2u_6400_front_back_top" in name for name in names)
  138. @pytest.mark.parametrize(
  139. ("profile_name", "expected_bit", "role", "production", "stimulus", "contract_text"),
  140. [
  141. (
  142. "6400-control",
  143. "prod2u_6400_front_back.bit",
  144. "production",
  145. True,
  146. False,
  147. "stimulus=false",
  148. ),
  149. (
  150. "6400-identification",
  151. "prod2u_6400_identification.bit",
  152. "identification",
  153. False,
  154. True,
  155. "不得作为 Production",
  156. ),
  157. ],
  158. )
  159. def test_firmware_package_is_fail_closed_and_profile_bound(
  160. tmp_path: Path,
  161. monkeypatch: pytest.MonkeyPatch,
  162. profile_name: str,
  163. expected_bit: str,
  164. role: str,
  165. production: bool,
  166. stimulus: bool,
  167. contract_text: str,
  168. ) -> None:
  169. monkeypatch.setattr(package_target, "_git", lambda *_args: TEST_COMMIT)
  170. receipt = _receipt(tmp_path, profile_name)
  171. archive = package_target.build_target_package(
  172. profile_name, "firmware", tmp_path / "out", td_receipt=receipt
  173. )
  174. with zipfile.ZipFile(archive) as zipf:
  175. names = set(zipf.namelist())
  176. manifest = json.loads(zipf.read("manifest.json"))
  177. instructions = zipf.read("FLASH-INSTRUCTIONS.zh-CN.txt").decode("utf-8")
  178. assert manifest["profile"] == profile_name
  179. assert manifest["firmware_role"] == role
  180. assert manifest["production"] is production
  181. assert manifest["stimulus"] is stimulus
  182. assert manifest["source_commit"] == TEST_SOURCE_COMMIT
  183. assert manifest["package_commit"] == TEST_COMMIT
  184. assert manifest["contract_sha256"] == package_target._contract_sha256()
  185. assert expected_bit in names
  186. assert "921600 8N1" in instructions
  187. assert "独立 ACK" in instructions
  188. assert contract_text in instructions
  189. assert instructions.startswith(package_target.DO_NOT_PROGRAM_LINE)
  190. assert manifest["release_blocked"] is True
  191. assert manifest["deployable"] is False
  192. assert manifest["known_unbound_ports"] == ["host_ttl_rx", "host_ttl_tx"]
  193. assert "CANDIDATE-NOTICE.zh-CN.txt" in names
  194. def test_blocked_firmware_selftest_rejects_programming_instructions(
  195. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  196. ) -> None:
  197. monkeypatch.setattr(package_target, "_git", lambda *_args: TEST_COMMIT)
  198. monkeypatch.setattr(
  199. package_target,
  200. "DO_NOT_PROGRAM_LINE",
  201. "DO NOT PROGRAM / 不要烧录\n3. 先执行 Erase/Program",
  202. )
  203. receipt = _receipt(tmp_path, "6400-control")
  204. with pytest.raises(SystemExit, match="Host UART/ACK contract missing"):
  205. package_target.build_target_package(
  206. "6400-control", "firmware", tmp_path / "out", td_receipt=receipt
  207. )