check_svg_safety.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. ) -> Report:
  119. report = Report(
  120. generated_at_utc=datetime.now(timezone.utc).isoformat(),
  121. repository_root=str(repository_root.resolve()),
  122. )
  123. generated = generated_dir.resolve()
  124. brd = brd_path.resolve()
  125. if not brd.is_file():
  126. report.add("brd.exists", "fail", f"missing {brd}")
  127. report.brd = {"path": str(brd_path), "exists": False}
  128. else:
  129. actual = sha256_file(brd)
  130. match = actual == expected_brd_sha256
  131. root_resolved = repository_root.resolve()
  132. logical = brd_path if not brd_path.is_absolute() else brd
  133. try:
  134. display_path = str(logical.resolve().relative_to(root_resolved))
  135. except ValueError:
  136. try:
  137. display_path = str(brd_path.relative_to(repository_root))
  138. except ValueError:
  139. display_path = str(brd_path)
  140. report.brd = {
  141. "path": display_path,
  142. "exists": True,
  143. "bytes": brd.stat().st_size,
  144. "sha256": actual,
  145. "expected_sha256": expected_brd_sha256,
  146. "hash_match": match,
  147. }
  148. report.add(
  149. "brd.sha256",
  150. "pass" if match else "fail",
  151. actual if match else f"actual={actual} expected={expected_brd_sha256}",
  152. )
  153. build_info_path = generated / "build-info.json"
  154. import_report_path = generated / "import-report.json"
  155. board_data_path = generated / "board-data.json"
  156. provenance: dict[str, Any] = {
  157. "chain": (
  158. "BRD bytes -> build-info.sources.brd.sha256; "
  159. "import-report.source_file names the BRD; "
  160. "board-data.json carries geometry/touchpoints only (no embedded BRD digest); "
  161. "SVG asset digests recorded in build-info.assets"
  162. ),
  163. "evidence_class": report.evidence_class,
  164. }
  165. build_info: dict[str, Any] | None = None
  166. if build_info_path.is_file():
  167. build_info = json.loads(build_info_path.read_text(encoding="utf-8"))
  168. brd_meta = (build_info.get("sources") or {}).get("brd") or {}
  169. provenance["build_info_brd"] = brd_meta
  170. bi_sha = str(brd_meta.get("sha256") or "")
  171. report.add(
  172. "provenance.build_info.brd_sha256",
  173. "pass" if bi_sha == expected_brd_sha256 else "fail",
  174. bi_sha or "missing",
  175. )
  176. assets = build_info.get("assets") or {}
  177. for name in SVG_NAMES:
  178. meta = assets.get(name) or {}
  179. provenance.setdefault("build_info_svg_assets", {})[name] = meta
  180. else:
  181. report.add("provenance.build_info", "fail", "missing build-info.json")
  182. if import_report_path.is_file():
  183. import_report = json.loads(import_report_path.read_text(encoding="utf-8"))
  184. source_file = str(import_report.get("source_file") or "")
  185. provenance["import_report"] = {
  186. "source_file": source_file,
  187. "source_format": import_report.get("source_format"),
  188. "output_file": import_report.get("output_file"),
  189. "errors": import_report.get("errors") or [],
  190. }
  191. expected_name = brd.name if brd.is_file() else "FCB_FPGA+MCU_V1.2_20260717.brd"
  192. report.add(
  193. "provenance.import_report.source_file",
  194. "pass" if source_file == expected_name else "fail",
  195. source_file or "missing",
  196. )
  197. report.add(
  198. "provenance.import_report.errors",
  199. "pass" if not import_report.get("errors") else "fail",
  200. "none" if not import_report.get("errors") else str(import_report.get("errors")),
  201. )
  202. else:
  203. report.add("provenance.import_report", "fail", "missing import-report.json")
  204. board_view_box: dict[str, float] | None = None
  205. if board_data_path.is_file():
  206. board_data = json.loads(board_data_path.read_text(encoding="utf-8"))
  207. board = board_data.get("board") or {}
  208. view_box = board.get("view_box") or {}
  209. board_view_box = {
  210. "x": float(view_box.get("x", 0.0)),
  211. "y": float(view_box.get("y", 0.0)),
  212. "width": float(view_box.get("width", 0.0)),
  213. "height": float(view_box.get("height", 0.0)),
  214. }
  215. provenance["board_data"] = {
  216. "schema": board_data.get("schema"),
  217. "board_id": board.get("id"),
  218. "view_box": board_view_box,
  219. "embeds_brd_sha256": EXPECTED_BRD_SHA256
  220. in board_data_path.read_text(encoding="utf-8"),
  221. "note": (
  222. "board-data.json does not embed the BRD digest; "
  223. "trust chain is via sibling build-info.json"
  224. ),
  225. }
  226. report.add(
  227. "provenance.board_data.view_box",
  228. "pass" if board_view_box["width"] > 0 and board_view_box["height"] > 0 else "fail",
  229. json.dumps(board_view_box),
  230. )
  231. else:
  232. report.add("provenance.board_data", "fail", "missing board-data.json")
  233. report.provenance = provenance
  234. svg_payload: dict[str, Any] = {}
  235. viewboxes: list[tuple[float, float, float, float]] = []
  236. for name in SVG_NAMES:
  237. path = generated / name
  238. entry: dict[str, Any] = {"path": str(path), "exists": path.is_file()}
  239. if not path.is_file():
  240. report.add(f"svg.exists.{name}", "fail", "missing")
  241. svg_payload[name] = entry
  242. continue
  243. text = path.read_text(encoding="utf-8", errors="replace")
  244. digest = sha256_file(path)
  245. entry.update(
  246. {
  247. "bytes": path.stat().st_size,
  248. "sha256": digest,
  249. **_scan_svg_text(name, text, report),
  250. }
  251. )
  252. if build_info is not None:
  253. expected = ((build_info.get("assets") or {}).get(name) or {}).get("sha256")
  254. entry["build_info_sha256"] = expected
  255. entry["matches_build_info"] = digest == expected
  256. report.add(
  257. f"svg.hash.{name}",
  258. "pass" if digest == expected else "fail",
  259. digest if digest == expected else f"actual={digest} build-info={expected}",
  260. )
  261. viewbox = entry.get("viewBox")
  262. if isinstance(viewbox, list) and len(viewbox) == 4:
  263. viewboxes.append(tuple(float(v) for v in viewbox)) # type: ignore[arg-type]
  264. if board_view_box is not None:
  265. dw = abs(viewbox[2] - board_view_box["width"])
  266. dh = abs(viewbox[3] - board_view_box["height"])
  267. dx = abs(viewbox[0] - board_view_box["x"])
  268. dy = abs(viewbox[1] - board_view_box["y"])
  269. ok = max(dw, dh, dx, dy) <= VIEWBOX_TOLERANCE_MM
  270. entry["coord_delta_vs_board_data_mm"] = {
  271. "dx": dx,
  272. "dy": dy,
  273. "dw": dw,
  274. "dh": dh,
  275. }
  276. report.add(
  277. f"svg.coords.{name}",
  278. "pass" if ok else "fail",
  279. f"delta_mm dx={dx:.6f} dy={dy:.6f} dw={dw:.6f} dh={dh:.6f}",
  280. )
  281. else:
  282. report.add(f"svg.coords.{name}", "fail", "missing/invalid viewBox")
  283. svg_payload[name] = entry
  284. if len(viewboxes) == len(SVG_NAMES) and len(set(viewboxes)) == 1:
  285. report.add("svg.coords.consistent_across_layers", "pass", str(viewboxes[0]))
  286. elif viewboxes:
  287. report.add(
  288. "svg.coords.consistent_across_layers",
  289. "fail",
  290. f"divergent viewBoxes: {viewboxes}",
  291. )
  292. report.svgs = svg_payload
  293. summary = {"pass": 0, "fail": 0, "other": 0}
  294. for finding in report.findings:
  295. if finding.status in summary:
  296. summary[finding.status] += 1
  297. else:
  298. summary["other"] += 1
  299. report.summary = summary
  300. return report
  301. def report_to_dict(report: Report) -> dict[str, Any]:
  302. payload = asdict(report)
  303. return payload
  304. def render_markdown(report: Report) -> str:
  305. lines = [
  306. "# Board-viewer SVG safety / provenance report",
  307. "",
  308. f"Generated: `{report.generated_at_utc}`",
  309. "",
  310. f"Evidence class: **{report.evidence_class}**",
  311. "",
  312. "SVGs under `tools/board-viewer/generated/` are derived analysis artifacts "
  313. "produced from the Allegro BRD through KiCad import/export. They support "
  314. "physical pin/network review only. They are **not** RTL, TD, ADC, constraint, "
  315. "or bitstream source closure.",
  316. "",
  317. "## BRD",
  318. "",
  319. "```json",
  320. json.dumps(report.brd, indent=2, ensure_ascii=False),
  321. "```",
  322. "",
  323. "## Provenance",
  324. "",
  325. "```json",
  326. json.dumps(report.provenance, indent=2, ensure_ascii=False),
  327. "```",
  328. "",
  329. "## SVG summary",
  330. "",
  331. "| SVG | Exists | SHA-256 | Safety issues | Matches build-info |",
  332. "|-----|--------|---------|---------------|--------------------|",
  333. ]
  334. for name in SVG_NAMES:
  335. entry = report.svgs.get(name) or {}
  336. lines.append(
  337. "| `{name}` | {exists} | `{sha}` | {issues} | {match} |".format(
  338. name=name,
  339. exists=entry.get("exists"),
  340. sha=(entry.get("sha256") or "")[:16] + ("..." if entry.get("sha256") else ""),
  341. issues=",".join(entry.get("safety_issues") or []) or "none",
  342. match=entry.get("matches_build_info"),
  343. )
  344. )
  345. lines.extend(
  346. [
  347. "",
  348. "## Findings",
  349. "",
  350. f"- pass: {report.summary.get('pass', 0)}",
  351. f"- fail: {report.summary.get('fail', 0)}",
  352. "",
  353. ]
  354. )
  355. for finding in report.findings:
  356. if finding.status == "fail":
  357. lines.append(f"- FAIL `{finding.check}`: {finding.detail}")
  358. if report.summary.get("fail", 0) == 0:
  359. lines.append("- All checks passed.")
  360. lines.append("")
  361. return "\n".join(lines)
  362. def main(argv: list[str] | None = None) -> int:
  363. parser = argparse.ArgumentParser(description=__doc__)
  364. parser.add_argument("--generated", type=Path, default=DEFAULT_GENERATED)
  365. parser.add_argument("--brd", type=Path, default=DEFAULT_BRD)
  366. parser.add_argument("--expected-brd-sha256", default=EXPECTED_BRD_SHA256)
  367. parser.add_argument("--repository-root", type=Path, default=ROOT)
  368. parser.add_argument("--json-out", type=Path)
  369. parser.add_argument("--md-out", type=Path)
  370. parser.add_argument("--json", action="store_true", help="Print JSON report to stdout")
  371. args = parser.parse_args(argv)
  372. report = check_svg_safety(
  373. generated_dir=args.generated,
  374. brd_path=args.brd,
  375. expected_brd_sha256=args.expected_brd_sha256,
  376. repository_root=args.repository_root,
  377. )
  378. payload = report_to_dict(report)
  379. markdown = render_markdown(report)
  380. if args.json_out:
  381. args.json_out.parent.mkdir(parents=True, exist_ok=True)
  382. args.json_out.write_text(
  383. json.dumps(payload, indent=2, ensure_ascii=False) + "\n",
  384. encoding="utf-8",
  385. )
  386. if args.md_out:
  387. args.md_out.parent.mkdir(parents=True, exist_ok=True)
  388. args.md_out.write_text(markdown, encoding="utf-8")
  389. if args.json:
  390. print(json.dumps(payload, indent=2, ensure_ascii=False))
  391. else:
  392. print(markdown)
  393. return 1 if report.summary.get("fail", 0) else 0
  394. if __name__ == "__main__":
  395. sys.exit(main())