| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241 |
- from __future__ import annotations
- import hashlib
- import json
- from pathlib import Path
- import zipfile
- import pytest
- from tools import package_target
- ROOT = Path(__file__).resolve().parents[2]
- TEST_COMMIT = "a" * 40
- TEST_SOURCE_COMMIT = "b" * 40
- def _receipt(
- tmp_path: Path, profile_name: str, commit: str = TEST_SOURCE_COMMIT
- ) -> Path:
- profile = package_target.HARDWARE_PROFILES[profile_name]
- inputs = package_target.td_input_manifest(profile_name)
- bitstream = tmp_path / f"{profile['artifact_basename']}.bit"
- bitstream.write_bytes(b"TD-BIT-TEST")
- payload = {
- "schema": "prod2u-6400-td-receipt-v1",
- "status": "PASS",
- "profile": profile_name,
- "project": str(profile["project"]),
- "source_closure": str(profile["closure"]),
- "commit": commit,
- "production": bool(profile["production"]),
- "stimulus": bool(profile["stimulus"]),
- "simulation_only": False,
- "artifact_basename": str(profile["artifact_basename"]),
- "timing_pass_25mhz": True,
- "project_sha256": package_target._sha256(ROOT / str(profile["project"])),
- "source_closure_sha256": package_target._sha256(
- ROOT / str(profile["closure"])
- ),
- "source_manifest_sha256": hashlib.sha256(
- json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()
- ).hexdigest(),
- "inputs": inputs,
- "known_unbound_ports": [],
- "deployment_status": package_target._expected_deployment_status(profile_name),
- "warning_audit": {
- "status": "PASS",
- "expected_unbound_ports": [],
- "observed_unbound_ports": [],
- "unexpected_unbound_ports": [],
- "missing_expected_unbound_ports": [],
- },
- "bitstream": str(bitstream),
- "bitstream_sha256": package_target._sha256(bitstream),
- }
- path = tmp_path / "td-receipt.json"
- path.write_text(json.dumps(payload), encoding="utf-8")
- return path
- def test_firmware_requires_explicit_profile_and_td_receipt(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- monkeypatch.setattr(package_target, "_git", lambda *_args: TEST_COMMIT)
- with pytest.raises(SystemExit, match="explicitly select --profile"):
- package_target.build_target_package("6400", "firmware", tmp_path)
- with pytest.raises(SystemExit, match="explicit --td-receipt is required"):
- package_target.build_target_package(
- "6400", "firmware", tmp_path, profile_name="6400-control"
- )
- with pytest.raises(SystemExit, match="Sim-Debug"):
- package_target.build_target_package(
- "6400", "firmware", tmp_path, profile_name="6400-sim-debug"
- )
- @pytest.mark.parametrize("profile_name", ["6400-control", "6400-identification"])
- def test_td_receipt_is_profile_commit_closure_and_bit_bound(
- tmp_path: Path, profile_name: str
- ) -> None:
- receipt_path = _receipt(tmp_path, profile_name)
- commit = TEST_COMMIT
- bitstream, receipt = package_target._validated_td_bitstream(
- profile_name, receipt_path, commit
- )
- assert bitstream.name == f"{package_target.HARDWARE_PROFILES[profile_name]['artifact_basename']}.bit"
- assert receipt["profile"] == profile_name
- assert receipt["commit"] == TEST_SOURCE_COMMIT
- assert receipt["commit"] != commit
- payload = json.loads(receipt_path.read_text(encoding="utf-8"))
- payload["source_closure_sha256"] = "0" * 64
- receipt_path.write_text(json.dumps(payload), encoding="utf-8")
- with pytest.raises(SystemExit, match="TD receipt mismatch"):
- package_target._validated_td_bitstream(profile_name, receipt_path, commit)
- @pytest.mark.parametrize(
- "tamper",
- [
- "input_digest",
- "input_missing",
- "ports_missing",
- "ports_duplicate",
- "deployment_status",
- "warning_observed",
- ],
- )
- def test_td_receipt_rejects_missing_duplicate_and_tampered_provenance(
- tmp_path: Path, tamper: str
- ) -> None:
- receipt_path = _receipt(tmp_path, "6400-identification")
- payload = json.loads(receipt_path.read_text(encoding="utf-8"))
- if tamper == "input_digest":
- first = next(iter(payload["inputs"]))
- payload["inputs"][first] = "0" * 64
- elif tamper == "input_missing":
- payload["inputs"].pop(next(iter(payload["inputs"])))
- elif tamper == "ports_missing":
- payload.pop("known_unbound_ports")
- elif tamper == "ports_duplicate":
- payload["known_unbound_ports"].append("host_ttl_rx")
- elif tamper == "deployment_status":
- payload["deployment_status"] = package_target.CONTROL_DEPLOYMENT_STATUS
- else:
- payload["warning_audit"]["observed_unbound_ports"].append("unexpected")
- receipt_path.write_text(json.dumps(payload), encoding="utf-8")
- with pytest.raises(SystemExit, match="TD receipt mismatch|warning audit mismatch"):
- package_target._validated_td_bitstream(
- "6400-identification", receipt_path, TEST_COMMIT
- )
- def test_control_source_package_contains_only_active_grouped_closure(tmp_path: Path) -> None:
- archive = package_target.build_target_package(
- "6400", "source", tmp_path, profile_name="6400-control"
- )
- with zipfile.ZipFile(archive) as zipf:
- names = set(zipf.namelist())
- manifest = json.loads(zipf.read("manifest.json"))
- closure = json.loads(zipf.read("source-closure-expanded.json"))
- host_contract = json.loads(zipf.read("generated/6400/host-contract.json"))
- assert manifest["profile"] == "6400-control"
- assert manifest["top"] == "prod2u_6400_rs232_only_top"
- assert "src/actuator/fan_board_output_adapter.v" in closure["sources"]
- assert host_contract["wire"]["host_uart"]["baud"] == 921600
- assert host_contract["wire"]["responses"]["SET_TARGET_ACK"]["type"] == 0x81
- assert host_contract["wire"]["responses"]["GET_SNAPSHOT_ACK"]["type"] == 0x82
- assert host_contract["wire"]["responses"]["SNAPSHOT_DATA"]["type"] == 0x42
- assert host_contract["canonical_profiles"]["6400-control"]["stimulus"] is False
- assert not any(name.startswith("src/generated/6400/") for name in names)
- assert not any("prod2u_6400_front_back_top" in name for name in names)
- @pytest.mark.parametrize(
- ("profile_name", "expected_bit", "role", "production", "stimulus", "contract_text"),
- [
- (
- "6400-control",
- "prod2u_6400_front_back.bit",
- "production",
- True,
- False,
- "stimulus=false",
- ),
- (
- "6400-identification",
- "prod2u_6400_identification.bit",
- "identification",
- False,
- True,
- "不得作为 Production",
- ),
- ],
- )
- def test_firmware_package_is_fail_closed_and_profile_bound(
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
- profile_name: str,
- expected_bit: str,
- role: str,
- production: bool,
- stimulus: bool,
- contract_text: str,
- ) -> None:
- monkeypatch.setattr(package_target, "_git", lambda *_args: TEST_COMMIT)
- receipt = _receipt(tmp_path, profile_name)
- archive = package_target.build_target_package(
- profile_name, "firmware", tmp_path / "out", td_receipt=receipt
- )
- with zipfile.ZipFile(archive) as zipf:
- names = set(zipf.namelist())
- manifest = json.loads(zipf.read("manifest.json"))
- instructions = zipf.read("FLASH-INSTRUCTIONS.zh-CN.txt").decode("utf-8")
- assert manifest["profile"] == profile_name
- assert manifest["firmware_role"] == role
- assert manifest["production"] is production
- assert manifest["stimulus"] is stimulus
- assert manifest["source_commit"] == TEST_SOURCE_COMMIT
- assert manifest["package_commit"] == TEST_COMMIT
- assert manifest["contract_sha256"] == package_target._contract_sha256()
- assert manifest["source_closure_sha256"] == package_target._sha256(
- ROOT / str(package_target.HARDWARE_PROFILES[profile_name]["closure"])
- )
- assert expected_bit in names
- assert "source-manifest.json" in names
- assert "921600 8N1" in instructions
- assert "独立 ACK" in instructions
- assert contract_text in instructions
- expected_header = (
- package_target.PRODUCTION_PROGRAM_LINE
- if production
- else package_target.IDENTIFICATION_PROGRAM_LINE
- )
- assert instructions.startswith(expected_header)
- assert manifest["release_blocked"] is False
- assert manifest["td_programmable"] is True
- assert manifest["candidate_only"] is True
- assert manifest["hardware_validated"] is False
- assert manifest["deployable"] is False
- assert manifest["production_deployable"] is False
- assert manifest["identification_programmable"] is (not production)
- assert manifest["known_unbound_ports"] == []
- assert "CANDIDATE-NOTICE.zh-CN.txt" not in names
- def test_blocked_firmware_selftest_rejects_programming_instructions(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- monkeypatch.setattr(package_target, "_git", lambda *_args: TEST_COMMIT)
- monkeypatch.setattr(
- package_target,
- "PRODUCTION_PROGRAM_LINE",
- "RS-232-ONLY PRODUCTION TD PASS\n3. 先执行 Erase/Program",
- )
- receipt = _receipt(tmp_path, "6400-control")
- with pytest.raises(SystemExit, match="Host UART/ACK contract missing"):
- package_target.build_target_package(
- "6400-control", "firmware", tmp_path / "out", td_receipt=receipt
- )
|