verify_review_package.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. #!/usr/bin/env python3
  2. """Unzip-directory self-verify for an hth-platform review package.
  3. --mode offline: SHA, MANIFEST, permissions, L0 offline (buf missing = PARTIAL).
  4. --mode release: same plus buf lint+breaking required. Missing tools/logs FAIL.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import hashlib
  9. import json
  10. import os
  11. import subprocess
  12. import sys
  13. import tempfile
  14. from pathlib import Path
  15. LEGACY_REQUIRED_REVIEWS = (
  16. "01-scope-architecture.md",
  17. "02-watchdog-protocol-truth.md",
  18. "03-actor-action-lifecycle.md",
  19. "04-sdk-replay-deployment.md",
  20. "05-evidence-artifact-release.md",
  21. )
  22. def verify_6400_contract(root: Path, host: Path) -> list[str]:
  23. errors: list[str] = []
  24. paths = {
  25. "identity": root / "PACKAGE_IDENTITY.json",
  26. "contract": root / "evidence" / "6400" / "host-contract.json",
  27. "contract_sums": root / "evidence" / "6400" / "SHA256SUMS",
  28. "import_source": root / "evidence" / "6400" / "import-source.json",
  29. "control_profile": root / "evidence" / "6400" / "profiles" / "6400-control.json",
  30. "identification_profile": root / "evidence" / "6400" / "profiles" / "6400-identification.json",
  31. }
  32. missing = [name for name, path in paths.items() if not path.is_file()]
  33. if missing:
  34. return ["missing 6400 evidence: " + ", ".join(missing)]
  35. identity = json.loads(paths["identity"].read_text(encoding="utf-8"))
  36. contract = json.loads(paths["contract"].read_text(encoding="utf-8"))
  37. imported = json.loads(paths["import_source"].read_text(encoding="utf-8"))
  38. control = json.loads(paths["control_profile"].read_text(encoding="utf-8"))
  39. identification = json.loads(paths["identification_profile"].read_text(encoding="utf-8"))
  40. contract_id = contract.get("contract_sha256")
  41. contract_file_sha = hashlib.sha256(paths["contract"].read_bytes()).hexdigest()
  42. def expect(value: object, wanted: object, label: str) -> None:
  43. if value != wanted:
  44. errors.append(f"{label}: got {value!r}, expected {wanted!r}")
  45. expect(identity.get("product"), "6400-front-rear-v1", "identity product")
  46. expect(identity.get("profile_ids"), ["6400-control", "6400-identification"], "identity profiles")
  47. expect(identity.get("protocol_contract_sha256"), contract_id, "identity contract")
  48. expect(contract.get("schema"), "prod2u-6400-host-contract-v2", "contract schema")
  49. expect(imported.get("contract_sha256"), contract_id, "import contract")
  50. expect(imported.get("source_contract_file_sha256"), contract_file_sha, "import contract file")
  51. wire = contract.get("wire") or {}
  52. responses = wire.get("responses") or {}
  53. order = wire.get("host_response_order") or {}
  54. expected_responses = {
  55. "SET_TARGET_ACK": (0x81, 0),
  56. "GET_SNAPSHOT_ACK": (0x82, 0),
  57. "SET_STIMULUS_ACK": (0x83, 0),
  58. "SNAPSHOT_DATA": (0x42, None),
  59. }
  60. for name, (frame_type, payload_length) in expected_responses.items():
  61. response = responses.get(name) or {}
  62. expect(response.get("type"), frame_type, f"{name} type")
  63. if payload_length is not None:
  64. expect(response.get("payload_length"), payload_length, f"{name} payload length")
  65. expect(order.get("SET_TARGET"), ["SET_TARGET_ACK"], "SET_TARGET response order")
  66. expect(order.get("GET_SNAPSHOT"), ["GET_SNAPSHOT_ACK", "SNAPSHOT_DATA"], "GET_SNAPSHOT response order")
  67. expect(order.get("SET_STIMULUS"), ["SET_STIMULUS_ACK"], "SET_STIMULUS response order")
  68. expect((contract.get("snapshot") or {}).get("payload_length"), 193, "snapshot payload length")
  69. profile_expectations = (
  70. (
  71. control,
  72. "6400-control",
  73. ["SET_TARGET", "GET_SNAPSHOT"],
  74. True,
  75. False,
  76. ),
  77. (
  78. identification,
  79. "6400-identification",
  80. ["SET_TARGET", "GET_SNAPSHOT", "SET_STIMULUS"],
  81. False,
  82. True,
  83. ),
  84. )
  85. for profile, profile_id, commands, production, stimulus in profile_expectations:
  86. expect(profile.get("profile_id"), profile_id, f"{profile_id} id")
  87. expect(profile.get("contract_sha256"), contract_id, f"{profile_id} contract")
  88. expect(profile.get("source_contract_file_sha256"), contract_file_sha, f"{profile_id} contract file")
  89. expect(profile.get("allowed_commands"), commands, f"{profile_id} commands")
  90. expect(profile.get("production"), production, f"{profile_id} production")
  91. expect(profile.get("stimulus"), stimulus, f"{profile_id} stimulus")
  92. sums_fields = paths["contract_sums"].read_text(encoding="utf-8").split()
  93. if len(sums_fields) < 2 or sums_fields[0] != contract_file_sha or sums_fields[1] != "host-contract.json":
  94. errors.append("6400 contract SHA256SUMS does not bind host-contract.json")
  95. mirrors = {
  96. host / "contracts" / "6400" / "host-contract.json": paths["contract"],
  97. host / "profiles" / "6400-control" / "profile.json": paths["control_profile"],
  98. host / "profiles" / "6400-identification" / "profile.json": paths["identification_profile"],
  99. }
  100. for packaged, evidence_path in mirrors.items():
  101. if not packaged.is_file() or packaged.read_bytes() != evidence_path.read_bytes():
  102. errors.append(f"packaged source does not match 6400 evidence: {packaged.relative_to(root)}")
  103. forbidden = (
  104. host / "RELEASE.zh-CN.md",
  105. host / "REQUIREMENTS_TRACEABILITY.md",
  106. host / "contracts" / "evidence",
  107. host / "profiles" / "prod2u-door-temp",
  108. host / "profiles" / "6400-sim-debug",
  109. root / "reviews" / "02-watchdog-protocol-truth.md",
  110. )
  111. for path in forbidden:
  112. if path.exists():
  113. errors.append(f"legacy or non-release profile entered 6400 package: {path.relative_to(root)}")
  114. return errors
  115. def main() -> int:
  116. ap = argparse.ArgumentParser()
  117. ap.add_argument("root", nargs="?", default=".")
  118. ap.add_argument("--mode", choices=("offline", "release"), default="offline")
  119. ap.add_argument("--full", action="store_true", help="also go build and pip wheel --no-deps")
  120. args = ap.parse_args()
  121. root = Path(args.root).resolve()
  122. sums = root / "SHA256SUMS"
  123. manifest = root / "MANIFEST"
  124. if not sums.is_file() or not manifest.is_file():
  125. print("FAIL missing SHA256SUMS or MANIFEST", file=sys.stderr)
  126. return 1
  127. rc = 0
  128. man_set: set[str] = set()
  129. for line in manifest.read_text(encoding="utf-8").splitlines():
  130. if not line.strip():
  131. continue
  132. if line.startswith("/") or ".." in Path(line).parts:
  133. print("FAIL path", line, file=sys.stderr)
  134. rc = 1
  135. man_set.add(line.strip())
  136. sum_set: set[str] = set()
  137. for line in sums.read_text(encoding="utf-8").splitlines():
  138. if not line.strip():
  139. continue
  140. digest, name = line.split(None, 1)
  141. name = name.strip()
  142. sum_set.add(name)
  143. path = root / name
  144. if not path.is_file():
  145. print("FAIL missing", name, file=sys.stderr)
  146. rc = 1
  147. continue
  148. got = hashlib.sha256(path.read_bytes()).hexdigest()
  149. if got != digest:
  150. print("FAIL sha256", name, file=sys.stderr)
  151. rc = 1
  152. mode = path.stat().st_mode & 0o777
  153. if mode == 0o777:
  154. print("FAIL 0777", name, file=sys.stderr)
  155. rc = 1
  156. if path.suffix == ".sh" or (path.suffix == ".py" and path.read_bytes()[:2] == b"#!" and path.parent.name == "tools"):
  157. if mode != 0o755:
  158. print("FAIL expected 0755", name, oct(mode), file=sys.stderr)
  159. rc = 1
  160. if man_set != sum_set:
  161. print("FAIL MANIFEST and SHA256SUMS file sets differ", file=sys.stderr)
  162. print("only_manifest", sorted(man_set - sum_set)[:20], file=sys.stderr)
  163. print("only_sums", sorted(sum_set - man_set)[:20], file=sys.stderr)
  164. rc = 1
  165. identity_path = root / "PACKAGE_IDENTITY.json"
  166. identity = json.loads(identity_path.read_text(encoding="utf-8")) if identity_path.is_file() else {}
  167. is_6400 = identity.get("product") == "6400-front-rear-v1"
  168. golden = root / "evidence" / "golden-vectors.json"
  169. if not is_6400 and not golden.is_file():
  170. print("FAIL missing evidence/golden-vectors.json", file=sys.stderr)
  171. rc = 1
  172. host = root / "host"
  173. if not (host / "go.mod").is_file():
  174. print("FAIL host/go.mod missing", file=sys.stderr)
  175. return 1
  176. required_reviews = ("6400-migration.md",) if is_6400 else LEGACY_REQUIRED_REVIEWS
  177. for name in required_reviews:
  178. if (root / "reviews" / name).is_file():
  179. continue
  180. if (host / "reviews" / name).is_file():
  181. continue
  182. print("FAIL missing review", name, file=sys.stderr)
  183. rc = 1
  184. run_dir = root / "run"
  185. man_json = run_dir / "run-manifest.json"
  186. if man_json.is_file():
  187. payload = json.loads(man_json.read_text(encoding="utf-8"))
  188. commits = {payload.get("git_commit")}
  189. trees = {payload.get("git_tree")}
  190. dirties = {payload.get("git_dirty_state")}
  191. times: set[str] = set()
  192. for cmd in payload.get("commands") or []:
  193. log = cmd.get("log") or ""
  194. if log:
  195. lp = run_dir / Path(log).name
  196. if not lp.is_file():
  197. print("FAIL missing run log", log, file=sys.stderr)
  198. rc = 1
  199. elif cmd.get("log_sha256"):
  200. got = hashlib.sha256(lp.read_bytes()).hexdigest()
  201. if got != cmd["log_sha256"]:
  202. print("FAIL log sha", log, file=sys.stderr)
  203. rc = 1
  204. elif args.mode == "release":
  205. print("FAIL missing log_sha256", cmd.get("name"), file=sys.stderr)
  206. rc = 1
  207. st = (cmd.get("status") or "").upper()
  208. name = cmd.get("name") or ""
  209. if st in {"NOT RUN", "NOT_RUN"}:
  210. if not cmd.get("not_run_reason_sha256") and not cmd.get("command") and not cmd.get("not_run_reason"):
  211. print("FAIL NOT RUN missing reason", name, file=sys.stderr)
  212. rc = 1
  213. continue
  214. if st == "PASS" and (not log or not cmd.get("log_sha256")):
  215. print("FAIL PASS without raw log/sha", name, file=sys.stderr)
  216. rc = 1
  217. if "NOT RUN" in st and "PASS" in (cmd.get("matrix") or ""):
  218. print("FAIL NOT RUN marked PASS", name, file=sys.stderr)
  219. rc = 1
  220. times.add(cmd.get("start_utc") or "")
  221. times.add(cmd.get("end_utc") or "")
  222. if payload.get("git_dirty") and payload.get("git_dirty_state") == "clean":
  223. print("FAIL dirty flag vs dirty_state", file=sys.stderr)
  224. rc = 1
  225. if len([t for t in times if t]) == 1 and len(payload.get("commands") or []) > 3:
  226. print("FAIL all commands share one timestamp (forged window)", file=sys.stderr)
  227. rc = 1
  228. _ = commits, trees, dirties
  229. elif args.mode == "release":
  230. print("FAIL missing run/run-manifest.json", file=sys.stderr)
  231. rc = 1
  232. env = os.environ.copy()
  233. if is_6400:
  234. for error in verify_6400_contract(root, host):
  235. print("FAIL 6400 contract", error, file=sys.stderr)
  236. rc = 1
  237. if args.mode == "release":
  238. descriptor = host / "api" / "proto" / "hth.api.v1.desc.prev"
  239. try:
  240. buf_commands = [
  241. ["buf", "lint"],
  242. ["buf", "breaking", "--against", f"{descriptor}#format=binpb"],
  243. ]
  244. for command in buf_commands:
  245. check = subprocess.run(command, cwd=str(host), env=env)
  246. if check.returncode != 0:
  247. print("FAIL", " ".join(command), file=sys.stderr)
  248. rc = 1
  249. except FileNotFoundError:
  250. print("FAIL buf is required in release mode", file=sys.stderr)
  251. rc = 1
  252. else:
  253. l0 = subprocess.run(
  254. [
  255. sys.executable,
  256. str(host / "tools" / "l0_contract_check.py"),
  257. "--repo-root",
  258. str(root),
  259. "--evidence-root",
  260. str(root / "evidence"),
  261. "--mode",
  262. args.mode,
  263. ],
  264. cwd=str(host),
  265. env=env,
  266. )
  267. if l0.returncode != 0:
  268. print("FAIL l0", args.mode, file=sys.stderr)
  269. rc = 1
  270. oracle = host / "tools" / "protocol_oracle.py"
  271. if oracle.is_file() and golden.is_file():
  272. por = subprocess.run(
  273. [
  274. sys.executable,
  275. str(oracle),
  276. "--golden",
  277. str(golden),
  278. "--min-positive",
  279. "8",
  280. "--min-negative",
  281. "2",
  282. "--min-frames",
  283. "6",
  284. ],
  285. cwd=str(root),
  286. env=env,
  287. )
  288. if por.returncode != 0:
  289. print("FAIL protocol_oracle", file=sys.stderr)
  290. rc = 1
  291. if args.full:
  292. with tempfile.TemporaryDirectory(prefix="hth-verify-hthd-") as td:
  293. out_bin = Path(td) / "hthd"
  294. build = subprocess.run(["go", "build", "-o", str(out_bin), "./cmd/hthd"], cwd=str(host), env=env)
  295. if build.returncode != 0:
  296. print("FAIL go build", file=sys.stderr)
  297. rc = 1
  298. sdk = host / "sdk" / "python"
  299. if (sdk / "pyproject.toml").is_file():
  300. with tempfile.TemporaryDirectory(prefix="hth-verify-wheels-") as td:
  301. wheel_dir = Path(td)
  302. whl = subprocess.run(
  303. [sys.executable, "-m", "pip", "wheel", "--no-deps", "-q", "-w", str(wheel_dir), str(sdk)],
  304. env=env,
  305. )
  306. if whl.returncode != 0:
  307. print("FAIL python wheel --no-deps", file=sys.stderr)
  308. rc = 1
  309. else:
  310. print("python_wheel_ok", list(wheel_dir.glob("hth_sdk-*.whl")))
  311. if rc == 0:
  312. if args.mode == "release":
  313. print("RELEASE_CONTRACT_GATE_PASS")
  314. else:
  315. print("OFFLINE_EVIDENCE_CHECK_PASS")
  316. print("PACKAGE_SELF_VERIFY_PASS")
  317. return rc
  318. if __name__ == "__main__":
  319. raise SystemExit(main())