threat_dragon_layout.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. #!/usr/bin/env python3
  2. """Deterministic layout for the Threat Dragon models in docs/threat-model/.
  3. Threat Dragon stores a position and a size for every cell, and a list of
  4. vertices for every flow. Hand-placed values drift as people edit, and a model
  5. that renders as a pile of overlapping labels teaches nothing. This script owns
  6. the geometry: nodes sit in columns by trust zone, each trust boundary is a box
  7. around the nodes it protects, every flow label is at most four words (the full
  8. wording lives in the flow's description), and flows that would cross a node are
  9. routed around it with vertices.
  10. python3 scripts/threat_dragon_layout.py # rewrite the models
  11. python3 scripts/threat_dragon_layout.py --check # fail if a file differs
  12. A layout is data (LAYOUTS below), so a change of position is a diff of numbers,
  13. not of a drawing. The geometry rules (no overlapping nodes, minimum gaps, nodes
  14. inside their boundary box, no label on a node) are checked by `violations`,
  15. which the tests call as well. The script never reads the network.
  16. Threat Dragon draws a trust boundary box as shape `trust-boundary-box`, a
  17. dashed rectangle whose caption sits at the top (verified in the v2.6.2 source,
  18. td.vue/src/service/x6/shapes/trust-boundary-box.js).
  19. """
  20. from __future__ import annotations
  21. import argparse
  22. import copy
  23. import itertools
  24. import json
  25. import sys
  26. from pathlib import Path
  27. ROOT = Path(__file__).resolve().parent.parent
  28. MODEL_DIR = ROOT / "docs" / "threat-model"
  29. COL_PITCH = 600
  30. ROW_PITCH = 340
  31. X0 = 170
  32. VERTEX_X_SHIFT = X0 - 140 # vertices below were authored for X0 = 140
  33. Y0 = 200
  34. SIZES = {"actor": (300, 80), "store": (260, 80), "process": (180, 110)}
  35. BOX_PAD_X = 50
  36. BOX_PAD_TOP = 75
  37. BOX_PAD_BOTTOM = 45
  38. BOX_MIN_W = 440
  39. LABEL_MAX_WORDS = 4
  40. CHAR_W = 6.6
  41. LABEL_H = 20
  42. MIN_COL_GAP = 300
  43. MIN_ROW_GAP = 160
  44. NODE_MARGIN = 8
  45. BOX_STROKE = "#b45309"
  46. # Threat Dragon v2.6.2 draws a node's name on one line and does not wrap it, so
  47. # a long name runs past its shape. Node names stay at about 24 characters; the
  48. # full wording moves to the node's description.
  49. NODE_NAMES = {
  50. "node-contributor": "Contributor (A2)",
  51. "node-upstream": "Upstream publishers",
  52. "node-reviewer": "Hosted AI reviewer",
  53. "node-local": "Local LLM",
  54. "store-a-repo": "Repository content",
  55. "store-a-agentcfg": "Agent config",
  56. "store-a-secrets": "Secrets (Doppler)",
  57. "node-maintainer": "Maintainer (A3/A4)",
  58. "node-gh_repo": "Source repo",
  59. "node-sl_prop": "Spacelift proposed run",
  60. "node-sl_track": "Spacelift tracked run",
  61. "node-state": "OpenTofu state",
  62. "node-twingate": "Twingate",
  63. "node-droplets": "Connector droplets",
  64. "node-resources": "Protected resources",
  65. "node-s2-upstream": "Wazuh apt repository",
  66. "store-s2-hostboot": "Doppler hostboot config",
  67. }
  68. NODE_NAME_MAX = 24
  69. def at(col: float, row: float) -> tuple[float, float]:
  70. """Center of a grid cell."""
  71. return (X0 + COL_PITCH * col, Y0 + ROW_PITCH * row)
  72. # --- the layouts -------------------------------------------------------------
  73. PIPELINE = {
  74. # node id -> (column, row). Columns run left to right by trust zone:
  75. # outside parties, GitHub, Spacelift, secrets and the cloud API, the cloud.
  76. "nodes": {
  77. "node-contributor": (0, 1),
  78. "node-upstream": (0, 2),
  79. "node-maintainer": (0, 3),
  80. "node-scanner": (0, 4),
  81. "node-ci": (1, 0),
  82. "node-gh_repo": (1, 1),
  83. "node-sl_prop": (2, 0),
  84. "node-sl_track": (2, 2),
  85. "node-state": (2, 3),
  86. "node-doppler": (3, 1),
  87. "node-cloud_api": (3, 3),
  88. "node-twingate": (4, 1),
  89. "node-droplets": (4, 3),
  90. "node-resources": (4, 4),
  91. },
  92. # boundary id -> the nodes the box encloses
  93. "boxes": {
  94. "boundary-B1": ["node-droplets", "node-resources"],
  95. "boundary-B2": ["node-ci"],
  96. "boundary-B3": ["node-sl_prop"],
  97. "boundary-B4": ["node-gh_repo"],
  98. "boundary-B5": ["node-sl_track", "node-state"],
  99. "boundary-B6": ["node-doppler"],
  100. "boundary-B7": ["node-cloud_api"],
  101. "boundary-B8": ["node-twingate"],
  102. },
  103. # flow id -> short label (at most four words)
  104. "labels": {
  105. "flow-f-scan": "Blocked inbound traffic",
  106. "flow-f-pr": "Fork pull request",
  107. "flow-f-ci": "PR code checkout",
  108. "flow-f-ci-status": "CI status check",
  109. "flow-f-up-ci": "Action refs by SHA",
  110. "flow-f-merge": "Review and merge",
  111. "flow-f-push-prop": "PR push event",
  112. "flow-f-push-track": "Merged commit",
  113. "flow-f-up-doppler-cli": "Doppler CLI download",
  114. "flow-f-tok": "Service token read",
  115. "flow-f-sec": "Secrets returned",
  116. "flow-f-state": "State and tokens",
  117. "flow-f-plan": "Plan for review",
  118. "flow-f-confirm": "Human confirms apply",
  119. "flow-f-apply": "Apply with cloud token",
  120. "flow-f-userdata": "Create droplet",
  121. "flow-f-tg-api": "Twingate API call",
  122. "flow-f-login": "IdP sign-in",
  123. "flow-f-connector-link": "Outbound connector link",
  124. "flow-f-session": "Relayed session",
  125. "flow-f-ssh": "SSH to resource",
  126. "flow-f-up-apt": "Signed apt packages",
  127. },
  128. # flow id -> vertices in canvas pixels. A flow with none is drawn straight,
  129. # or fanned out when it shares its two nodes with another flow.
  130. "vertices": {
  131. "flow-f-up-ci": [(400, 880), (400, 200)],
  132. "flow-f-login": [(140, 1420), (2240, 1420), (2240, 540)],
  133. "flow-f-scan": [(2100, 1560)],
  134. "flow-f-up-apt": [(330, 880), (330, 1480), (2160, 1480)],
  135. },
  136. # flow id -> position of its label along the path (default 0.5)
  137. "label_at": {
  138. "flow-f-up-ci": 0.35,
  139. "flow-f-login": 0.35,
  140. "flow-f-scan": 0.4,
  141. "flow-f-connector-link": 0.3,
  142. "flow-f-session": 0.3,
  143. },
  144. }
  145. ATLAS = {
  146. "nodes": {
  147. "node-contributor": (0, 0),
  148. "node-upstream": (0, 2),
  149. "node-maintainer": (0, 3),
  150. "node-ci": (1, 0),
  151. "store-a-repo": (1, 1),
  152. "node-local": (2, 1),
  153. "node-agent": (2, 2),
  154. "store-a-agentcfg": (2, 3),
  155. "node-reviewer": (3, 0),
  156. "node-hosted": (3, 2),
  157. "store-a-secrets": (4, 3),
  158. },
  159. "boxes": {
  160. "boundary-AB1": ["node-ci", "store-a-repo"],
  161. "boundary-AB2": ["store-a-agentcfg", "node-agent"],
  162. "boundary-AB3": ["node-hosted", "node-reviewer"],
  163. "boundary-AB4": ["store-a-secrets"],
  164. "boundary-AB5": ["node-maintainer"],
  165. },
  166. "labels": {
  167. "flow-a-text": "Untrusted text",
  168. "flow-a-ctx": "Files into context",
  169. "flow-a-task": "Task and approvals",
  170. "flow-a-cfg": "Tool allow-list",
  171. "flow-a-prompt": "Prompt and context",
  172. "flow-a-out": "Output and tool calls",
  173. "flow-a-push": "Agent opens PR",
  174. "flow-a-secrets": "Visible secrets",
  175. "flow-a-web": "Fetched web content",
  176. "flow-a-dep": "Dependency added",
  177. "flow-a-diff": "Diff for review",
  178. "flow-a-review": "Advisory review",
  179. "flow-a-local": "Text for summary",
  180. "flow-a-summary": "Summary text",
  181. "flow-a-ci": "PR code checkout",
  182. "flow-a-merge": "Review and merge",
  183. },
  184. "vertices": {
  185. "flow-a-review": [(1560, 680), (500, 680)],
  186. "flow-a-secrets": [(1970, 1100)],
  187. },
  188. "label_at": {"flow-a-web": 0.7, "flow-a-summary": 0.3},
  189. }
  190. STAGE2 = {
  191. "nodes": {
  192. "node-s2-maintainer": (0, 1),
  193. "node-s2-run": (1, 0),
  194. "store-s2-state": (1, 2),
  195. "node-s2-twingate": (2, 0),
  196. "store-s2-hostboot": (2, 3),
  197. "node-s2-droplet": (3, 1),
  198. "node-s2-upstream": (3, 3),
  199. "node-s2-manager": (4, 0),
  200. "node-s2-scraper": (4, 2),
  201. },
  202. "boxes": {
  203. "boundary-SB1": ["node-s2-droplet"],
  204. "boundary-SB2": ["node-s2-twingate"],
  205. "boundary-SB3": ["store-s2-hostboot"],
  206. "boundary-SB4": ["node-s2-manager", "node-s2-scraper"],
  207. "boundary-SB5": ["node-s2-run", "store-s2-state"],
  208. },
  209. "labels": {
  210. "flow-s2-api": "Twingate API call",
  211. "flow-s2-state": "State and tokens",
  212. "flow-s2-userdata": "User-data with token",
  213. "flow-s2-keys": "Out-of-band service key",
  214. "flow-s2-boot": "Hostboot config pull",
  215. "flow-s2-logs": "Logs and enrollment",
  216. "flow-s2-scrape": "Metrics scrape",
  217. "flow-s2-apt": "Signed apt packages",
  218. },
  219. "vertices": {"flow-s2-keys": [(140, 20), (1940, 20)]},
  220. "label_at": {"flow-s2-keys": 0.5},
  221. }
  222. LAYOUTS = {
  223. "clouds-against-humanity.threat-dragon.json": PIPELINE,
  224. "clouds-against-humanity.attack.threat-dragon.json": PIPELINE,
  225. "clouds-against-humanity.atlas.threat-dragon.json": ATLAS,
  226. "clouds-against-humanity.stage2.threat-dragon.json": STAGE2,
  227. }
  228. # --- applying a layout -------------------------------------------------------
  229. def cells(model: dict) -> list:
  230. return model["detail"]["diagrams"][0]["cells"]
  231. def node_rect(cell: dict) -> tuple[float, float, float, float]:
  232. p, s = cell["position"], cell["size"]
  233. return (p["x"], p["y"], p["x"] + s["width"], p["y"] + s["height"])
  234. def is_node(cell: dict) -> bool:
  235. return cell["shape"] in SIZES
  236. def is_box(cell: dict) -> bool:
  237. return cell["shape"] == "trust-boundary-box"
  238. def box_cell(old: dict, rect: tuple[float, float, float, float], z: int) -> dict:
  239. name = old["data"]["name"]
  240. return {
  241. "position": {"x": rect[0], "y": rect[1]},
  242. "size": {"width": rect[2] - rect[0], "height": rect[3] - rect[1]},
  243. "attrs": {
  244. "body": {
  245. "stroke": BOX_STROKE,
  246. "strokeWidth": 3,
  247. "strokeDasharray": "10 5",
  248. "fill": "transparent",
  249. "fillOpacity": 0,
  250. },
  251. "label": {"text": name, "refX": 20, "refY": 14, "fontSize": 14},
  252. },
  253. "shape": "trust-boundary-box",
  254. "zIndex": z,
  255. "id": old["id"],
  256. "data": {
  257. "type": "tm.BoundaryBox",
  258. "name": name,
  259. "description": old["data"]["description"],
  260. "isTrustBoundary": True,
  261. "hasOpenThreats": False,
  262. },
  263. }
  264. def apply_layout(model: dict, layout: dict) -> dict:
  265. model = copy.deepcopy(model)
  266. all_cells = cells(model)
  267. by_id = {c["id"]: c for c in all_cells}
  268. for ident, (col, row) in layout["nodes"].items():
  269. c = by_id[ident]
  270. w, h = SIZES[c["shape"]]
  271. cx, cy = at(col, row)
  272. c["position"] = {"x": cx - w / 2, "y": cy - h / 2}
  273. c["size"] = {"width": w, "height": h}
  274. # The v2.6.2 schema allows no text wrapping attribute, so a long name
  275. # runs past its shape; keep the label equal to the name.
  276. data = c["data"]
  277. short = NODE_NAMES.get(ident)
  278. if short is not None and data["name"] != short:
  279. data["description"] = f"Full name: {data['name']}. {data['description']}"
  280. data["name"] = short
  281. assert len(data["name"]) <= NODE_NAME_MAX, data["name"]
  282. text = c["attrs"].setdefault("text", {})
  283. text.pop("textWrap", None)
  284. text["text"] = data["name"]
  285. nodes = {c["id"]: c for c in all_cells if is_node(c)}
  286. assert set(nodes) == set(layout["nodes"]), set(nodes) ^ set(layout["nodes"])
  287. out = []
  288. for c in all_cells:
  289. if c["shape"] in ("trust-boundary-curve", "trust-boundary-box"):
  290. members = [node_rect(by_id[m]) for m in layout["boxes"][c["id"]]]
  291. left = min(m[0] for m in members) - BOX_PAD_X
  292. right = max(m[2] for m in members) + BOX_PAD_X
  293. if right - left < BOX_MIN_W:
  294. mid = (left + right) / 2
  295. left, right = mid - BOX_MIN_W / 2, mid + BOX_MIN_W / 2
  296. top = min(m[1] for m in members) - BOX_PAD_TOP
  297. bottom = max(m[3] for m in members) + BOX_PAD_BOTTOM
  298. c = box_cell(c, (left, top, right, bottom), -50)
  299. out.append(c)
  300. assert set(layout["boxes"]) == {c["id"] for c in out if is_box(c)}
  301. by_id = {c["id"]: c for c in out}
  302. pairs: dict = {}
  303. for c in out:
  304. if c["shape"] == "flow":
  305. key = tuple(sorted((c["source"]["cell"], c["target"]["cell"])))
  306. pairs.setdefault(key, []).append(c["id"])
  307. for c in out:
  308. if c["shape"] != "flow":
  309. continue
  310. short = layout["labels"][c["id"]]
  311. assert len(short.split()) <= LABEL_MAX_WORDS, short
  312. data = c["data"]
  313. if data["name"] != short:
  314. data["description"] = f"Full label: {data['name']}. {data['description']}"
  315. data["name"] = short
  316. c["labels"] = [
  317. {
  318. "position": layout["label_at"].get(c["id"], 0.5),
  319. "attrs": {"label": {"text": short}},
  320. }
  321. ]
  322. c["connector"] = "normal"
  323. verts = layout["vertices"].get(c["id"])
  324. if verts is None:
  325. verts = auto_vertices(c, by_id, pairs)
  326. else:
  327. verts = [(x + VERTEX_X_SHIFT, y) for x, y in verts]
  328. c["vertices"] = [{"x": round(x), "y": round(y)} for x, y in verts]
  329. place_labels(out, layout)
  330. model["detail"]["diagrams"][0]["cells"] = out
  331. return model
  332. LABEL_TRIES = (0.5, 0.4, 0.6, 0.3, 0.7, 0.25, 0.75, 0.2, 0.8, 0.15, 0.85)
  333. def label_clear(rect, flow, by_id, placed) -> bool:
  334. """True when a label rectangle sits on no node, caption, other label or other flow."""
  335. for c in by_id.values():
  336. if is_node(c) and rects_overlap(rect, node_rect(c), 4):
  337. return False
  338. if is_box(c) and rects_overlap(rect, caption_rect(c), 4):
  339. return False
  340. if c["shape"] == "flow" and c["id"] != flow["id"]:
  341. pts = polyline(c, by_id)
  342. if any(seg_hits_rect(p, q, rect, 2) for p, q in itertools.pairwise(pts)):
  343. return False
  344. return not any(rects_overlap(rect, other, 4) for other in placed)
  345. def place_labels(out: list, layout: dict) -> None:
  346. """Slide each label along its flow to the first spot that overlaps nothing."""
  347. by_id = {c["id"]: c for c in out}
  348. placed: list = []
  349. for c in out:
  350. if c["shape"] != "flow":
  351. continue
  352. tries = LABEL_TRIES
  353. if c["id"] in layout["label_at"]:
  354. tries = (layout["label_at"][c["id"]],) + LABEL_TRIES
  355. chosen = tries[0]
  356. for t in tries:
  357. c["labels"][0]["position"] = t
  358. if label_clear(label_rect(c, by_id), c, by_id, placed):
  359. chosen = t
  360. break
  361. c["labels"][0]["position"] = chosen
  362. placed.append(label_rect(c, by_id))
  363. def centre(cell: dict) -> tuple[float, float]:
  364. x0, y0, x1, y1 = node_rect(cell)
  365. return ((x0 + x1) / 2, (y0 + y1) / 2)
  366. def auto_vertices(flow: dict, by_id: dict, pairs: dict) -> list:
  367. """Spread flows that share a pair of nodes so they do not lie on one line."""
  368. a, b = by_id[flow["source"]["cell"]], by_id[flow["target"]["cell"]]
  369. key = tuple(sorted((a["id"], b["id"])))
  370. group = pairs[key]
  371. if len(group) < 2:
  372. return []
  373. first, second = by_id[key[0]], by_id[key[1]]
  374. (ax, ay), (bx, by) = centre(first), centre(second)
  375. dx, dy = bx - ax, by - ay
  376. length = (dx * dx + dy * dy) ** 0.5 or 1.0
  377. nx, ny = -dy / length, dx / length
  378. # opposite directions get opposite sides, so a request and its reply part
  379. side = 1 if flow["source"]["cell"] == key[0] else -1
  380. slot = group.index(flow["id"])
  381. off = 70 * side * (1 + (slot // 2) * 0.5)
  382. return [((ax + bx) / 2 + nx * off, (ay + by) / 2 + ny * off)]
  383. # --- geometry rules ----------------------------------------------------------
  384. def polyline(flow: dict, by_id: dict) -> list:
  385. pts = [centre(by_id[flow["source"]["cell"]])]
  386. pts += [(v["x"], v["y"]) for v in flow.get("vertices", [])]
  387. pts.append(centre(by_id[flow["target"]["cell"]]))
  388. return pts
  389. def seg_hits_rect(p, q, rect, margin=0.0) -> bool:
  390. x0, y0, x1, y1 = (
  391. rect[0] - margin,
  392. rect[1] - margin,
  393. rect[2] + margin,
  394. rect[3] + margin,
  395. )
  396. (px, py), (qx, qy) = p, q
  397. t0, t1 = 0.0, 1.0
  398. dx, dy = qx - px, qy - py
  399. for pp, dd, lo, hi in ((px, dx, x0, x1), (py, dy, y0, y1)):
  400. if abs(dd) < 1e-9:
  401. if pp < lo or pp > hi:
  402. return False
  403. else:
  404. ta, tb = (lo - pp) / dd, (hi - pp) / dd
  405. if ta > tb:
  406. ta, tb = tb, ta
  407. t0, t1 = max(t0, ta), min(t1, tb)
  408. if t0 > t1:
  409. return False
  410. return True
  411. def point_at(pts: list, t: float) -> tuple[float, float]:
  412. segs = [(pts[i], pts[i + 1]) for i in range(len(pts) - 1)]
  413. lengths = [((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) ** 0.5 for a, b in segs]
  414. target = sum(lengths) * t
  415. for (a, b), ln in zip(segs, lengths):
  416. if target <= ln or ln == 0:
  417. f = target / ln if ln else 0
  418. return (a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f)
  419. target -= ln
  420. return pts[-1]
  421. def label_rect(flow: dict, by_id: dict) -> tuple[float, float, float, float]:
  422. text = flow["labels"][0]["attrs"]["label"]["text"]
  423. cx, cy = point_at(polyline(flow, by_id), flow["labels"][0]["position"])
  424. w = CHAR_W * len(text) + 12
  425. return (cx - w / 2, cy - LABEL_H / 2, cx + w / 2, cy + LABEL_H / 2)
  426. def caption_rect(box: dict) -> tuple[float, float, float, float]:
  427. text = box["attrs"]["label"]["text"]
  428. x0, y0 = box["position"]["x"], box["position"]["y"]
  429. lab = box["attrs"]["label"]
  430. x = x0 + lab["refX"]
  431. y = y0 + lab["refY"]
  432. return (x, y, x + 7.2 * len(text), y + 20)
  433. def rects_overlap(a, b, margin=0.0) -> bool:
  434. return not (
  435. a[2] + margin <= b[0]
  436. or b[2] + margin <= a[0]
  437. or a[3] + margin <= b[1]
  438. or b[3] + margin <= a[1]
  439. )
  440. def inside(inner, outer) -> bool:
  441. return (
  442. outer[0] <= inner[0]
  443. and outer[1] <= inner[1]
  444. and inner[2] <= outer[2]
  445. and inner[3] <= outer[3]
  446. )
  447. def violations(model: dict, layout: dict) -> list[str]:
  448. """Human-readable list of broken geometry rules; empty when the layout is fine."""
  449. cs = cells(model)
  450. by_id = {c["id"]: c for c in cs}
  451. nodes = [c for c in cs if is_node(c)]
  452. boxes = [c for c in cs if is_box(c)]
  453. flows = [c for c in cs if c["shape"] == "flow"]
  454. bad: list[str] = []
  455. for i, a in enumerate(nodes):
  456. for b in nodes[i + 1 :]:
  457. ra, rb = node_rect(a), node_rect(b)
  458. if rects_overlap(ra, rb):
  459. bad.append(f"nodes overlap: {a['id']} {b['id']}")
  460. continue
  461. hgap = max(rb[0] - ra[2], ra[0] - rb[2])
  462. vgap = max(rb[1] - ra[3], ra[1] - rb[3])
  463. if hgap < MIN_COL_GAP and vgap < MIN_ROW_GAP:
  464. bad.append(
  465. f"nodes too close: {a['id']} {b['id']} ({hgap:.0f}, {vgap:.0f})"
  466. )
  467. members = {b["id"]: layout["boxes"][b["id"]] for b in boxes}
  468. inside_ids = {m for ms in members.values() for m in ms}
  469. for b in boxes:
  470. rb = node_rect(b)
  471. for m in members[b["id"]]:
  472. if not inside(node_rect(by_id[m]), rb):
  473. bad.append(f"{m} not inside {b['id']}")
  474. for n in nodes:
  475. if n["id"] not in members[b["id"]] and rects_overlap(node_rect(n), rb):
  476. bad.append(f"{n['id']} overlaps {b['id']}")
  477. for other in boxes:
  478. if other["id"] > b["id"] and rects_overlap(rb, node_rect(other), 20):
  479. bad.append(f"boxes overlap: {b['id']} {other['id']}")
  480. for n in nodes:
  481. if n["id"] not in inside_ids:
  482. continue
  483. labels = {f["id"]: label_rect(f, by_id) for f in flows}
  484. for f in flows:
  485. short = f["labels"][0]["attrs"]["label"]["text"]
  486. if len(short.split()) > LABEL_MAX_WORDS:
  487. bad.append(f"label too long: {f['id']}")
  488. pts = polyline(f, by_id)
  489. ends = {f["source"]["cell"], f["target"]["cell"]}
  490. for n in nodes:
  491. if n["id"] in ends:
  492. continue
  493. for p, q in itertools.pairwise(pts):
  494. if seg_hits_rect(p, q, node_rect(n), NODE_MARGIN):
  495. bad.append(f"flow {f['id']} crosses node {n['id']}")
  496. break
  497. for b in boxes:
  498. if ends & set(members[b["id"]]):
  499. continue
  500. if any(
  501. seg_hits_rect(p, q, node_rect(b)) for p, q in itertools.pairwise(pts)
  502. ):
  503. bad.append(f"flow {f['id']} passes through unrelated {b['id']}")
  504. for n in nodes:
  505. if rects_overlap(labels[f["id"]], node_rect(n), 4):
  506. bad.append(f"label of {f['id']} on node {n['id']}")
  507. for other in flows:
  508. if other["id"] != f["id"] and any(
  509. seg_hits_rect(p, q, labels[f["id"]], 2)
  510. for p, q in itertools.pairwise(polyline(other, by_id))
  511. ):
  512. bad.append(f"label of {f['id']} on the line of {other['id']}")
  513. for b in boxes:
  514. if rects_overlap(labels[f["id"]], caption_rect(b), 4):
  515. bad.append(f"label of {f['id']} on caption of {b['id']}")
  516. ids = sorted(labels)
  517. for i, a in enumerate(ids):
  518. for b in ids[i + 1 :]:
  519. if rects_overlap(labels[a], labels[b], 4):
  520. bad.append(f"labels overlap: {a} {b}")
  521. for b in boxes:
  522. cap = caption_rect(b)
  523. if cap[2] > b["position"]["x"] + b["size"]["width"]:
  524. bad.append(f"caption wider than its box: {b['id']}")
  525. return bad
  526. # --- command line ------------------------------------------------------------
  527. def render(model: dict) -> str:
  528. return json.dumps(model, indent=2) + "\n"
  529. def main(argv: list[str] | None = None) -> int:
  530. ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
  531. ap.add_argument("--check", action="store_true", help="fail if a file would change")
  532. ap.add_argument("--root", default=str(MODEL_DIR), help="directory of models")
  533. args = ap.parse_args(argv)
  534. root = Path(args.root)
  535. status = 0
  536. for name, layout in LAYOUTS.items():
  537. path = root / name
  538. model = json.loads(path.read_text(encoding="utf-8"))
  539. new = apply_layout(model, layout)
  540. for problem in violations(new, layout):
  541. print(f"{name}: {problem}", file=sys.stderr)
  542. status = 1
  543. text = render(new)
  544. if args.check:
  545. if path.read_text(encoding="utf-8") != text:
  546. print(
  547. f"{name}: layout is out of date; run scripts/threat_dragon_layout.py",
  548. file=sys.stderr,
  549. )
  550. status = 1
  551. else:
  552. path.write_text(text, encoding="utf-8")
  553. return status
  554. if __name__ == "__main__":
  555. sys.exit(main())