check_svg_safety.py 17 KB

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