#!/usr/bin/env python3 """Fail-closed safety and provenance checks for board-viewer SVG assets. These SVGs are derived analysis evidence from the Allegro BRD via KiCad export. They are not RTL, TD, ADC, or bitstream source closure. """ from __future__ import annotations import argparse import hashlib import json import re import sys from dataclasses import asdict, dataclass, field from datetime import datetime, timezone from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parents[2] DEFAULT_GENERATED = ROOT / "tools" / "board-viewer" / "generated" DEFAULT_BRD = ( ROOT / "reference/original/board/FCB_FPGA_MCU_V1.2_20260717" / "FCB_FPGA+MCU_V1.2_20260717.brd" ) EXPECTED_BRD_SHA256 = "269b5bab2f2e1215b9392079a003badc34238ae3cbe8e5094c9a11bba8b84ebb" SVG_NAMES = ( "board-copper.svg", "board-silkscreen.svg", "board-mask-edge.svg", "board-copper-back.svg", "board-silkscreen-back.svg", "board-mask-edge-back.svg", ) VIEWBOX_TOLERANCE_MM = 0.1 _SCRIPT_RE = re.compile(r"<\s*script\b", re.I) _EXTERNAL_HTTP_RE = re.compile(r"https?://(?!www\.w3\.org/)", re.I) _FILE_URL_RE = re.compile(r"file://", re.I) _ABS_WIN_RE = re.compile(r"[A-Za-z]:\\") _ABS_UNIX_RE = re.compile(r"/(?:home|Users|tmp|var/tmp)/") _HREF_EXT_RE = re.compile(r"(?:xlink:)?href\s*=\s*[\"'](?!#)", re.I) _URL_FUNC_RE = re.compile(r"url\(\s*[\"']?(?!#)", re.I) _RANDOM_RE = re.compile( r"Math\.random|Date\.now|uuid|randomUUID|crypto\.getRandomValues", re.I, ) _VIEWBOX_RE = re.compile(r'viewBox\s*=\s*"([^"]+)"') _WIDTH_RE = re.compile(r'\bwidth\s*=\s*"([^"]+)"') _HEIGHT_RE = re.compile(r'\bheight\s*=\s*"([^"]+)"') @dataclass class Finding: check: str status: str detail: str @dataclass class Report: schema: str = "board-viewer-svg-safety-report-v1" generated_at_utc: str = "" repository_root: str = "" evidence_class: str = ( "derived_analysis_from_brd_not_rtl_td_source_closure" ) brd: dict[str, Any] = field(default_factory=dict) provenance: dict[str, Any] = field(default_factory=dict) svgs: dict[str, Any] = field(default_factory=dict) findings: list[Finding] = field(default_factory=list) summary: dict[str, int] = field(default_factory=dict) def add(self, check: str, status: str, detail: str) -> None: self.findings.append(Finding(check=check, status=status, detail=detail)) def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: while chunk := stream.read(1024 * 1024): digest.update(chunk) return digest.hexdigest() def _parse_viewbox(text: str) -> tuple[float, float, float, float] | None: match = _VIEWBOX_RE.search(text) if not match: return None parts = match.group(1).replace(",", " ").split() if len(parts) != 4: return None try: return float(parts[0]), float(parts[1]), float(parts[2]), float(parts[3]) except ValueError: return None def _scan_svg_text(name: str, text: str, report: Report) -> dict[str, Any]: issues: list[str] = [] for label, pattern in ( ("script", _SCRIPT_RE), ("external_http", _EXTERNAL_HTTP_RE), ("file_url", _FILE_URL_RE), ("absolute_windows_path", _ABS_WIN_RE), ("absolute_local_unix_path", _ABS_UNIX_RE), ("external_href", _HREF_EXT_RE), ("external_url_func", _URL_FUNC_RE), ("non_reproducible_randomness", _RANDOM_RE), ): hits = pattern.findall(text) if hits: issues.append(f"{label}:{len(hits)}") report.add( f"svg_safety.{name}.{label}", "fail", f"{len(hits)} hit(s)", ) else: report.add(f"svg_safety.{name}.{label}", "pass", "clean") viewbox = _parse_viewbox(text) width = _WIDTH_RE.search(text) height = _HEIGHT_RE.search(text) return { "viewBox": None if viewbox is None else list(viewbox), "width": None if width is None else width.group(1), "height": None if height is None else height.group(1), "safety_issues": issues, "xmlns_w3_only_external": bool( re.search(r'xmlns(?::\w+)?="https?://www\.w3\.org/', text) ) and not _EXTERNAL_HTTP_RE.search(text), } def check_svg_safety( *, generated_dir: Path = DEFAULT_GENERATED, brd_path: Path = DEFAULT_BRD, expected_brd_sha256: str = EXPECTED_BRD_SHA256, repository_root: Path = ROOT, mode: str = "local", ) -> Report: """Check SVG safety and provenance. mode: - local: require BRD bytes on disk (developer / regeneration lane) - detached: BRD may be absent; use build-info recorded hashes only and never claim regeneration (compact / remote replay) """ if mode not in {"local", "detached"}: raise ValueError(f"unsupported mode: {mode}") report = Report( generated_at_utc=datetime.now(timezone.utc).isoformat(), repository_root=str(repository_root.resolve()), ) if mode == "detached": report.evidence_class = ( "derived_evidence_detached_no_brd_regeneration_claim" ) generated = generated_dir.resolve() brd = brd_path.resolve() if not brd.is_file(): if mode == "detached": report.add( "brd.exists", "pass", "missing (detached/compact expected; regeneration=not_packaged_by_policy)", ) report.brd = { "path": str(brd_path), "exists": False, "mode": "detached", "reference_regeneration_replay": "not_packaged_by_policy", } else: report.add("brd.exists", "fail", f"missing {brd}") report.brd = {"path": str(brd_path), "exists": False} else: actual = sha256_file(brd) match = actual == expected_brd_sha256 root_resolved = repository_root.resolve() logical = brd_path if not brd_path.is_absolute() else brd try: display_path = str(logical.resolve().relative_to(root_resolved)) except ValueError: try: display_path = str(brd_path.relative_to(repository_root)) except ValueError: display_path = str(brd_path) report.brd = { "path": display_path, "exists": True, "bytes": brd.stat().st_size, "sha256": actual, "expected_sha256": expected_brd_sha256, "hash_match": match, } report.add( "brd.sha256", "pass" if match else "fail", actual if match else f"actual={actual} expected={expected_brd_sha256}", ) build_info_path = generated / "build-info.json" import_report_path = generated / "import-report.json" board_data_path = generated / "board-data.json" provenance: dict[str, Any] = { "chain": ( "BRD bytes -> build-info.sources.brd.sha256; " "import-report.source_file names the BRD; " "board-data.json carries geometry/touchpoints only (no embedded BRD digest); " "SVG asset digests recorded in build-info.assets" ), "evidence_class": report.evidence_class, } build_info: dict[str, Any] | None = None if build_info_path.is_file(): build_info = json.loads(build_info_path.read_text(encoding="utf-8")) brd_meta = (build_info.get("sources") or {}).get("brd") or {} provenance["build_info_brd"] = brd_meta bi_sha = str(brd_meta.get("sha256") or "") report.add( "provenance.build_info.brd_sha256", "pass" if bi_sha == expected_brd_sha256 else "fail", bi_sha or "missing", ) assets = build_info.get("assets") or {} for name in SVG_NAMES: meta = assets.get(name) or {} provenance.setdefault("build_info_svg_assets", {})[name] = meta else: report.add("provenance.build_info", "fail", "missing build-info.json") if import_report_path.is_file(): import_report = json.loads(import_report_path.read_text(encoding="utf-8")) source_file = str(import_report.get("source_file") or "") provenance["import_report"] = { "source_file": source_file, "source_format": import_report.get("source_format"), "output_file": import_report.get("output_file"), "errors": import_report.get("errors") or [], } expected_name = brd.name if brd.is_file() else "FCB_FPGA+MCU_V1.2_20260717.brd" report.add( "provenance.import_report.source_file", "pass" if source_file == expected_name else "fail", source_file or "missing", ) report.add( "provenance.import_report.errors", "pass" if not import_report.get("errors") else "fail", "none" if not import_report.get("errors") else str(import_report.get("errors")), ) else: report.add("provenance.import_report", "fail", "missing import-report.json") board_view_box: dict[str, float] | None = None if board_data_path.is_file(): board_data = json.loads(board_data_path.read_text(encoding="utf-8")) board = board_data.get("board") or {} view_box = board.get("view_box") or {} board_view_box = { "x": float(view_box.get("x", 0.0)), "y": float(view_box.get("y", 0.0)), "width": float(view_box.get("width", 0.0)), "height": float(view_box.get("height", 0.0)), } provenance["board_data"] = { "schema": board_data.get("schema"), "board_id": board.get("id"), "view_box": board_view_box, "embeds_brd_sha256": EXPECTED_BRD_SHA256 in board_data_path.read_text(encoding="utf-8"), "note": ( "board-data.json does not embed the BRD digest; " "trust chain is via sibling build-info.json" ), } report.add( "provenance.board_data.view_box", "pass" if board_view_box["width"] > 0 and board_view_box["height"] > 0 else "fail", json.dumps(board_view_box), ) else: report.add("provenance.board_data", "fail", "missing board-data.json") report.provenance = provenance svg_payload: dict[str, Any] = {} viewboxes: list[tuple[float, float, float, float]] = [] for name in SVG_NAMES: path = generated / name entry: dict[str, Any] = {"path": str(path), "exists": path.is_file()} if not path.is_file(): report.add(f"svg.exists.{name}", "fail", "missing") svg_payload[name] = entry continue text = path.read_text(encoding="utf-8", errors="replace") digest = sha256_file(path) entry.update( { "bytes": path.stat().st_size, "sha256": digest, **_scan_svg_text(name, text, report), } ) if build_info is not None: expected = ((build_info.get("assets") or {}).get(name) or {}).get("sha256") entry["build_info_sha256"] = expected entry["matches_build_info"] = digest == expected report.add( f"svg.hash.{name}", "pass" if digest == expected else "fail", digest if digest == expected else f"actual={digest} build-info={expected}", ) viewbox = entry.get("viewBox") if isinstance(viewbox, list) and len(viewbox) == 4: viewboxes.append(tuple(float(v) for v in viewbox)) # type: ignore[arg-type] if board_view_box is not None: dw = abs(viewbox[2] - board_view_box["width"]) dh = abs(viewbox[3] - board_view_box["height"]) dx = abs(viewbox[0] - board_view_box["x"]) dy = abs(viewbox[1] - board_view_box["y"]) ok = max(dw, dh, dx, dy) <= VIEWBOX_TOLERANCE_MM entry["coord_delta_vs_board_data_mm"] = { "dx": dx, "dy": dy, "dw": dw, "dh": dh, } report.add( f"svg.coords.{name}", "pass" if ok else "fail", f"delta_mm dx={dx:.6f} dy={dy:.6f} dw={dw:.6f} dh={dh:.6f}", ) else: report.add(f"svg.coords.{name}", "fail", "missing/invalid viewBox") svg_payload[name] = entry if len(viewboxes) == len(SVG_NAMES) and len(set(viewboxes)) == 1: report.add("svg.coords.consistent_across_layers", "pass", str(viewboxes[0])) elif viewboxes: report.add( "svg.coords.consistent_across_layers", "fail", f"divergent viewBoxes: {viewboxes}", ) report.svgs = svg_payload summary = {"pass": 0, "fail": 0, "other": 0} for finding in report.findings: if finding.status in summary: summary[finding.status] += 1 else: summary["other"] += 1 report.summary = summary return report def report_to_dict(report: Report) -> dict[str, Any]: payload = asdict(report) return payload def render_markdown(report: Report) -> str: lines = [ "# Board-viewer SVG safety / provenance report", "", f"Generated: `{report.generated_at_utc}`", "", f"Evidence class: **{report.evidence_class}**", "", "SVGs under `tools/board-viewer/generated/` are derived analysis artifacts " "produced from the Allegro BRD through KiCad import/export. They support " "physical pin/network review only. They are **not** RTL, TD, ADC, constraint, " "or bitstream source closure.", "", "## BRD", "", "```json", json.dumps(report.brd, indent=2, ensure_ascii=False), "```", "", "## Provenance", "", "```json", json.dumps(report.provenance, indent=2, ensure_ascii=False), "```", "", "## SVG summary", "", "| SVG | Exists | SHA-256 | Safety issues | Matches build-info |", "|-----|--------|---------|---------------|--------------------|", ] for name in SVG_NAMES: entry = report.svgs.get(name) or {} lines.append( "| `{name}` | {exists} | `{sha}` | {issues} | {match} |".format( name=name, exists=entry.get("exists"), sha=(entry.get("sha256") or "")[:16] + ("..." if entry.get("sha256") else ""), issues=",".join(entry.get("safety_issues") or []) or "none", match=entry.get("matches_build_info"), ) ) lines.extend( [ "", "## Findings", "", f"- pass: {report.summary.get('pass', 0)}", f"- fail: {report.summary.get('fail', 0)}", "", ] ) for finding in report.findings: if finding.status == "fail": lines.append(f"- FAIL `{finding.check}`: {finding.detail}") if report.summary.get("fail", 0) == 0: lines.append("- All checks passed.") lines.append("") return "\n".join(lines) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--generated", type=Path, default=DEFAULT_GENERATED) parser.add_argument("--brd", type=Path, default=DEFAULT_BRD) parser.add_argument("--expected-brd-sha256", default=EXPECTED_BRD_SHA256) parser.add_argument("--repository-root", type=Path, default=ROOT) parser.add_argument( "--mode", choices=("local", "detached"), default="local", help="local requires BRD on disk; detached accepts missing BRD without regeneration claim", ) parser.add_argument("--json-out", type=Path) parser.add_argument("--md-out", type=Path) parser.add_argument("--json", action="store_true", help="Print JSON report to stdout") args = parser.parse_args(argv) report = check_svg_safety( generated_dir=args.generated, brd_path=args.brd, expected_brd_sha256=args.expected_brd_sha256, repository_root=args.repository_root, mode=args.mode, ) payload = report_to_dict(report) markdown = render_markdown(report) if args.json_out: args.json_out.parent.mkdir(parents=True, exist_ok=True) args.json_out.write_text( json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", ) if args.md_out: args.md_out.parent.mkdir(parents=True, exist_ok=True) args.md_out.write_text(markdown, encoding="utf-8") if args.json: print(json.dumps(payload, indent=2, ensure_ascii=False)) else: print(markdown) return 1 if report.summary.get("fail", 0) else 0 if __name__ == "__main__": sys.exit(main())