check_svg_safety.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. #!/usr/bin/env python3
  2. """Fail-closed safety and provenance checks for board-viewer SVG assets.
  3. These SVGs are derived analysis evidence from the Allegro BRD via KiCad export.
  4. They are not RTL, TD, ADC, or bitstream source closure.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import hashlib
  9. import json
  10. import re
  11. import sys
  12. from dataclasses import asdict, dataclass, field
  13. from datetime import datetime, timezone
  14. from pathlib import Path
  15. from typing import Any
  16. ROOT = Path(__file__).resolve().parents[2]
  17. DEFAULT_GENERATED = ROOT / "tools" / "board-viewer" / "generated"
  18. DEFAULT_BRD = (
  19. ROOT
  20. / "reference/original/board/FCB_FPGA_MCU_V1.2_20260717"
  21. / "FCB_FPGA+MCU_V1.2_20260717.brd"
  22. )
  23. EXPECTED_BRD_SHA256 = "269b5bab2f2e1215b9392079a003badc34238ae3cbe8e5094c9a11bba8b84ebb"
  24. SVG_NAMES = (
  25. "board-copper.svg",
  26. "board-silkscreen.svg",
  27. "board-mask-edge.svg",
  28. "board-copper-back.svg",
  29. "board-silkscreen-back.svg",
  30. "board-mask-edge-back.svg",
  31. )
  32. VIEWBOX_TOLERANCE_MM = 0.1
  33. _SCRIPT_RE = re.compile(r"<\s*script\b", re.I)
  34. _EXTERNAL_HTTP_RE = re.compile(r"https?://(?!www\.w3\.org/)", re.I)
  35. _FILE_URL_RE = re.compile(r"file://", re.I)
  36. _ABS_WIN_RE = re.compile(r"[A-Za-z]:\\")
  37. _ABS_UNIX_RE = re.compile(r"/(?:home|Users|tmp|var/tmp)/")
  38. _HREF_EXT_RE = re.compile(r"(?:xlink:)?href\s*=\s*[\"'](?!#)", re.I)
  39. _URL_FUNC_RE = re.compile(r"url\(\s*[\"']?(?!#)", re.I)
  40. _RANDOM_RE = re.compile(
  41. r"Math\.random|Date\.now|uuid|randomUUID|crypto\.getRandomValues",
  42. re.I,
  43. )
  44. _VIEWBOX_RE = re.compile(r'viewBox\s*=\s*"([^"]+)"')
  45. _WIDTH_RE = re.compile(r'\bwidth\s*=\s*"([^"]+)"')
  46. _HEIGHT_RE = re.compile(r'\bheight\s*=\s*"([^"]+)"')
  47. @dataclass
  48. class Finding:
  49. check: str
  50. status: str
  51. detail: str
  52. @dataclass
  53. class Report:
  54. schema: str = "board-viewer-svg-safety-report-v1"
  55. generated_at_utc: str = ""
  56. repository_root: str = ""
  57. evidence_class: str = (
  58. "derived_analysis_from_brd_not_rtl_td_source_closure"
  59. )
  60. brd: dict[str, Any] = field(default_factory=dict)
  61. provenance: dict[str, Any] = field(default_factory=dict)
  62. svgs: dict[str, Any] = field(default_factory=dict)
  63. findings: list[Finding] = field(default_factory=list)
  64. summary: dict[str, int] = field(default_factory=dict)
  65. def add(self, check: str, status: str, detail: str) -> None:
  66. self.findings.append(Finding(check=check, status=status, detail=detail))
  67. def sha256_file(path: Path) -> str:
  68. digest = hashlib.sha256()
  69. with path.open("rb") as stream:
  70. while chunk := stream.read(1024 * 1024):
  71. digest.update(chunk)
  72. return digest.hexdigest()
  73. def _parse_viewbox(text: str) -> tuple[float, float, float, float] | None:
  74. match = _VIEWBOX_RE.search(text)
  75. if not match:
  76. return None
  77. parts = match.group(1).replace(",", " ").split()
  78. if len(parts) != 4:
  79. return None
  80. try:
  81. return float(parts[0]), float(parts[1]), float(parts[2]), float(parts[3])
  82. except ValueError:
  83. return None
  84. def _scan_svg_text(name: str, text: str, report: Report) -> dict[str, Any]:
  85. issues: list[str] = []
  86. for label, pattern in (
  87. ("script", _SCRIPT_RE),
  88. ("external_http", _EXTERNAL_HTTP_RE),
  89. ("file_url", _FILE_URL_RE),
  90. ("absolute_windows_path", _ABS_WIN_RE),
  91. ("absolute_local_unix_path", _ABS_UNIX_RE),
  92. ("external_href", _HREF_EXT_RE),
  93. ("external_url_func", _URL_FUNC_RE),
  94. ("non_reproducible_randomness", _RANDOM_RE),
  95. ):
  96. hits = pattern.findall(text)
  97. if hits:
  98. issues.append(f"{label}:{len(hits)}")
  99. report.add(
  100. f"svg_safety.{name}.{label}",
  101. "fail",
  102. f"{len(hits)} hit(s)",
  103. )
  104. else:
  105. report.add(f"svg_safety.{name}.{label}", "pass", "clean")
  106. viewbox = _parse_viewbox(text)
  107. width = _WIDTH_RE.search(text)
  108. height = _HEIGHT_RE.search(text)
  109. return {
  110. "viewBox": None if viewbox is None else list(viewbox),
  111. "width": None if width is None else width.group(1),
  112. "height": None if height is None else height.group(1),
  113. "safety_issues": issues,
  114. "xmlns_w3_only_external": bool(
  115. re.search(r'xmlns(?::\w+)?="https?://www\.w3\.org/', text)
  116. )
  117. and not _EXTERNAL_HTTP_RE.search(text),
  118. }
  119. def check_svg_safety(
  120. *,
  121. generated_dir: Path = DEFAULT_GENERATED,
  122. brd_path: Path = DEFAULT_BRD,
  123. expected_brd_sha256: str = EXPECTED_BRD_SHA256,
  124. repository_root: Path = ROOT,
  125. mode: str = "local",
  126. ) -> Report:
  127. """Check SVG safety and provenance.
  128. mode:
  129. - local: require BRD bytes on disk (developer / regeneration lane)
  130. - detached: BRD may be absent; use build-info recorded hashes only and
  131. never claim regeneration (compact / remote replay)
  132. """
  133. if mode not in {"local", "detached"}:
  134. raise ValueError(f"unsupported mode: {mode}")
  135. report = Report(
  136. generated_at_utc=datetime.now(timezone.utc).isoformat(),
  137. repository_root=str(repository_root.resolve()),
  138. )
  139. if mode == "detached":
  140. report.evidence_class = (
  141. "derived_evidence_detached_no_brd_regeneration_claim"
  142. )
  143. generated = generated_dir.resolve()
  144. brd = brd_path.resolve()
  145. if not brd.is_file():
  146. if mode == "detached":
  147. report.add(
  148. "brd.exists",
  149. "pass",
  150. "missing (detached/compact expected; regeneration=not_packaged_by_policy)",
  151. )
  152. report.brd = {
  153. "path": str(brd_path),
  154. "exists": False,
  155. "mode": "detached",
  156. "reference_regeneration_replay": "not_packaged_by_policy",
  157. }
  158. else:
  159. report.add("brd.exists", "fail", f"missing {brd}")
  160. report.brd = {"path": str(brd_path), "exists": False}
  161. else:
  162. actual = sha256_file(brd)
  163. match = actual == expected_brd_sha256
  164. root_resolved = repository_root.resolve()
  165. logical = brd_path if not brd_path.is_absolute() else brd
  166. try:
  167. display_path = str(logical.resolve().relative_to(root_resolved))
  168. except ValueError:
  169. try:
  170. display_path = str(brd_path.relative_to(repository_root))
  171. except ValueError:
  172. display_path = str(brd_path)
  173. report.brd = {
  174. "path": display_path,
  175. "exists": True,
  176. "bytes": brd.stat().st_size,
  177. "sha256": actual,
  178. "expected_sha256": expected_brd_sha256,
  179. "hash_match": match,
  180. }
  181. report.add(
  182. "brd.sha256",
  183. "pass" if match else "fail",
  184. actual if match else f"actual={actual} expected={expected_brd_sha256}",
  185. )
  186. build_info_path = generated / "build-info.json"
  187. import_report_path = generated / "import-report.json"
  188. board_data_path = generated / "board-data.json"
  189. provenance: dict[str, Any] = {
  190. "chain": (
  191. "BRD bytes -> build-info.sources.brd.sha256; "
  192. "import-report.source_file names the BRD; "
  193. "board-data.json carries geometry/touchpoints only (no embedded BRD digest); "
  194. "SVG asset digests recorded in build-info.assets"
  195. ),
  196. "evidence_class": report.evidence_class,
  197. }
  198. build_info: dict[str, Any] | None = None
  199. if build_info_path.is_file():
  200. build_info = json.loads(build_info_path.read_text(encoding="utf-8"))
  201. brd_meta = (build_info.get("sources") or {}).get("brd") or {}
  202. provenance["build_info_brd"] = brd_meta
  203. bi_sha = str(brd_meta.get("sha256") or "")
  204. report.add(
  205. "provenance.build_info.brd_sha256",
  206. "pass" if bi_sha == expected_brd_sha256 else "fail",
  207. bi_sha or "missing",
  208. )
  209. assets = build_info.get("assets") or {}
  210. for name in SVG_NAMES:
  211. meta = assets.get(name) or {}
  212. provenance.setdefault("build_info_svg_assets", {})[name] = meta
  213. else:
  214. report.add("provenance.build_info", "fail", "missing build-info.json")
  215. if import_report_path.is_file():
  216. import_report = json.loads(import_report_path.read_text(encoding="utf-8"))
  217. source_file = str(import_report.get("source_file") or "")
  218. provenance["import_report"] = {
  219. "source_file": source_file,
  220. "source_format": import_report.get("source_format"),
  221. "output_file": import_report.get("output_file"),
  222. "errors": import_report.get("errors") or [],
  223. }
  224. expected_name = brd.name if brd.is_file() else "FCB_FPGA+MCU_V1.2_20260717.brd"
  225. report.add(
  226. "provenance.import_report.source_file",
  227. "pass" if source_file == expected_name else "fail",
  228. source_file or "missing",
  229. )
  230. report.add(
  231. "provenance.import_report.errors",
  232. "pass" if not import_report.get("errors") else "fail",
  233. "none" if not import_report.get("errors") else str(import_report.get("errors")),
  234. )
  235. else:
  236. report.add("provenance.import_report", "fail", "missing import-report.json")
  237. board_view_box: dict[str, float] | None = None
  238. if board_data_path.is_file():
  239. board_data = json.loads(board_data_path.read_text(encoding="utf-8"))
  240. board = board_data.get("board") or {}
  241. view_box = board.get("view_box") or {}
  242. board_view_box = {
  243. "x": float(view_box.get("x", 0.0)),
  244. "y": float(view_box.get("y", 0.0)),
  245. "width": float(view_box.get("width", 0.0)),
  246. "height": float(view_box.get("height", 0.0)),
  247. }
  248. provenance["board_data"] = {
  249. "schema": board_data.get("schema"),
  250. "board_id": board.get("id"),
  251. "view_box": board_view_box,
  252. "embeds_brd_sha256": EXPECTED_BRD_SHA256
  253. in board_data_path.read_text(encoding="utf-8"),
  254. "note": (
  255. "board-data.json does not embed the BRD digest; "
  256. "trust chain is via sibling build-info.json"
  257. ),
  258. }
  259. report.add(
  260. "provenance.board_data.view_box",
  261. "pass" if board_view_box["width"] > 0 and board_view_box["height"] > 0 else "fail",
  262. json.dumps(board_view_box),
  263. )
  264. else:
  265. report.add("provenance.board_data", "fail", "missing board-data.json")
  266. report.provenance = provenance
  267. svg_payload: dict[str, Any] = {}
  268. viewboxes: list[tuple[float, float, float, float]] = []
  269. for name in SVG_NAMES:
  270. path = generated / name
  271. entry: dict[str, Any] = {"path": str(path), "exists": path.is_file()}
  272. if not path.is_file():
  273. report.add(f"svg.exists.{name}", "fail", "missing")
  274. svg_payload[name] = entry
  275. continue
  276. text = path.read_text(encoding="utf-8", errors="replace")
  277. digest = sha256_file(path)
  278. entry.update(
  279. {
  280. "bytes": path.stat().st_size,
  281. "sha256": digest,
  282. **_scan_svg_text(name, text, report),
  283. }
  284. )
  285. if build_info is not None:
  286. expected = ((build_info.get("assets") or {}).get(name) or {}).get("sha256")
  287. entry["build_info_sha256"] = expected
  288. entry["matches_build_info"] = digest == expected
  289. report.add(
  290. f"svg.hash.{name}",
  291. "pass" if digest == expected else "fail",
  292. digest if digest == expected else f"actual={digest} build-info={expected}",
  293. )
  294. viewbox = entry.get("viewBox")
  295. if isinstance(viewbox, list) and len(viewbox) == 4:
  296. viewboxes.append(tuple(float(v) for v in viewbox)) # type: ignore[arg-type]
  297. if board_view_box is not None:
  298. dw = abs(viewbox[2] - board_view_box["width"])
  299. dh = abs(viewbox[3] - board_view_box["height"])
  300. dx = abs(viewbox[0] - board_view_box["x"])
  301. dy = abs(viewbox[1] - board_view_box["y"])
  302. ok = max(dw, dh, dx, dy) <= VIEWBOX_TOLERANCE_MM
  303. entry["coord_delta_vs_board_data_mm"] = {
  304. "dx": dx,
  305. "dy": dy,
  306. "dw": dw,
  307. "dh": dh,
  308. }
  309. report.add(
  310. f"svg.coords.{name}",
  311. "pass" if ok else "fail",
  312. f"delta_mm dx={dx:.6f} dy={dy:.6f} dw={dw:.6f} dh={dh:.6f}",
  313. )
  314. else:
  315. report.add(f"svg.coords.{name}", "fail", "missing/invalid viewBox")
  316. svg_payload[name] = entry
  317. if len(viewboxes) == len(SVG_NAMES) and len(set(viewboxes)) == 1:
  318. report.add("svg.coords.consistent_across_layers", "pass", str(viewboxes[0]))
  319. elif viewboxes:
  320. report.add(
  321. "svg.coords.consistent_across_layers",
  322. "fail",
  323. f"divergent viewBoxes: {viewboxes}",
  324. )
  325. report.svgs = svg_payload
  326. summary = {"pass": 0, "fail": 0, "other": 0}
  327. for finding in report.findings:
  328. if finding.status in summary:
  329. summary[finding.status] += 1
  330. else:
  331. summary["other"] += 1
  332. report.summary = summary
  333. return report
  334. def report_to_dict(report: Report) -> dict[str, Any]:
  335. payload = asdict(report)
  336. return payload
  337. def render_markdown(report: Report) -> str:
  338. lines = [
  339. "# Board-viewer SVG safety / provenance report",
  340. "",
  341. f"Generated: `{report.generated_at_utc}`",
  342. "",
  343. f"Evidence class: **{report.evidence_class}**",
  344. "",
  345. "SVGs under `tools/board-viewer/generated/` are derived analysis artifacts "
  346. "produced from the Allegro BRD through KiCad import/export. They support "
  347. "physical pin/network review only. They are **not** RTL, TD, ADC, constraint, "
  348. "or bitstream source closure.",
  349. "",
  350. "## BRD",
  351. "",
  352. "```json",
  353. json.dumps(report.brd, indent=2, ensure_ascii=False),
  354. "```",
  355. "",
  356. "## Provenance",
  357. "",
  358. "```json",
  359. json.dumps(report.provenance, indent=2, ensure_ascii=False),
  360. "```",
  361. "",
  362. "## SVG summary",
  363. "",
  364. "| SVG | Exists | SHA-256 | Safety issues | Matches build-info |",
  365. "|-----|--------|---------|---------------|--------------------|",
  366. ]
  367. for name in SVG_NAMES:
  368. entry = report.svgs.get(name) or {}
  369. lines.append(
  370. "| `{name}` | {exists} | `{sha}` | {issues} | {match} |".format(
  371. name=name,
  372. exists=entry.get("exists"),
  373. sha=(entry.get("sha256") or "")[:16] + ("..." if entry.get("sha256") else ""),
  374. issues=",".join(entry.get("safety_issues") or []) or "none",
  375. match=entry.get("matches_build_info"),
  376. )
  377. )
  378. lines.extend(
  379. [
  380. "",
  381. "## Findings",
  382. "",
  383. f"- pass: {report.summary.get('pass', 0)}",
  384. f"- fail: {report.summary.get('fail', 0)}",
  385. "",
  386. ]
  387. )
  388. for finding in report.findings:
  389. if finding.status == "fail":
  390. lines.append(f"- FAIL `{finding.check}`: {finding.detail}")
  391. if report.summary.get("fail", 0) == 0:
  392. lines.append("- All checks passed.")
  393. lines.append("")
  394. return "\n".join(lines)
  395. def main(argv: list[str] | None = None) -> int:
  396. parser = argparse.ArgumentParser(description=__doc__)
  397. parser.add_argument("--generated", type=Path, default=DEFAULT_GENERATED)
  398. parser.add_argument("--brd", type=Path, default=DEFAULT_BRD)
  399. parser.add_argument("--expected-brd-sha256", default=EXPECTED_BRD_SHA256)
  400. parser.add_argument("--repository-root", type=Path, default=ROOT)
  401. parser.add_argument(
  402. "--mode",
  403. choices=("local", "detached"),
  404. default="local",
  405. help="local requires BRD on disk; detached accepts missing BRD without regeneration claim",
  406. )
  407. parser.add_argument("--json-out", type=Path)
  408. parser.add_argument("--md-out", type=Path)
  409. parser.add_argument("--json", action="store_true", help="Print JSON report to stdout")
  410. args = parser.parse_args(argv)
  411. report = check_svg_safety(
  412. generated_dir=args.generated,
  413. brd_path=args.brd,
  414. expected_brd_sha256=args.expected_brd_sha256,
  415. repository_root=args.repository_root,
  416. mode=args.mode,
  417. )
  418. payload = report_to_dict(report)
  419. markdown = render_markdown(report)
  420. if args.json_out:
  421. args.json_out.parent.mkdir(parents=True, exist_ok=True)
  422. args.json_out.write_text(
  423. json.dumps(payload, indent=2, ensure_ascii=False) + "\n",
  424. encoding="utf-8",
  425. )
  426. if args.md_out:
  427. args.md_out.parent.mkdir(parents=True, exist_ok=True)
  428. args.md_out.write_text(markdown, encoding="utf-8")
  429. if args.json:
  430. print(json.dumps(payload, indent=2, ensure_ascii=False))
  431. else:
  432. print(markdown)
  433. return 1 if report.summary.get("fail", 0) else 0
  434. if __name__ == "__main__":
  435. sys.exit(main())