test_threat_dragon_layout.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. """Tests for scripts/threat_dragon_layout.py and the layout of the three models.
  2. The committed models are generated from the layout script, so a position is a
  3. number in that script and not a hand-drawn guess. These tests check the
  4. geometry rules on the committed files themselves (no node overlaps another, the
  5. gaps hold, every node sits inside the boundary box that claims it, labels are
  6. short and sit on nothing) and that the files are exactly what the script writes.
  7. """
  8. import importlib.util
  9. import itertools
  10. import json
  11. import subprocess
  12. import sys
  13. from pathlib import Path
  14. import pytest
  15. ROOT = Path(__file__).resolve().parent.parent
  16. SCRIPT = ROOT / "scripts" / "threat_dragon_layout.py"
  17. MODEL_DIR = ROOT / "docs" / "threat-model"
  18. spec = importlib.util.spec_from_file_location("threat_dragon_layout", SCRIPT)
  19. layout_mod = importlib.util.module_from_spec(spec)
  20. sys.modules["threat_dragon_layout"] = layout_mod
  21. spec.loader.exec_module(layout_mod)
  22. NAMES = sorted(layout_mod.LAYOUTS)
  23. def load(name: str) -> dict:
  24. return json.loads((MODEL_DIR / name).read_text(encoding="utf-8"))
  25. def parts(model):
  26. cs = layout_mod.cells(model)
  27. nodes = [c for c in cs if layout_mod.is_node(c)]
  28. boxes = [c for c in cs if layout_mod.is_box(c)]
  29. flows = [c for c in cs if c["shape"] == "flow"]
  30. return cs, nodes, boxes, flows
  31. def test_every_model_in_the_directory_has_a_layout():
  32. on_disk = {p.name for p in MODEL_DIR.glob("*.threat-dragon.json")}
  33. assert on_disk == set(NAMES)
  34. @pytest.mark.parametrize("name", NAMES)
  35. class TestLayout:
  36. def test_committed_file_is_what_the_script_writes(self, name):
  37. model = load(name)
  38. regenerated = layout_mod.apply_layout(model, layout_mod.LAYOUTS[name])
  39. assert layout_mod.render(regenerated) == (MODEL_DIR / name).read_text(
  40. encoding="utf-8"
  41. )
  42. def test_no_geometry_violations(self, name):
  43. model = load(name)
  44. assert layout_mod.violations(model, layout_mod.LAYOUTS[name]) == []
  45. def test_no_two_nodes_overlap_and_gaps_hold(self, name):
  46. _, nodes, _, _ = parts(load(name))
  47. for i, a in enumerate(nodes):
  48. for b in nodes[i + 1 :]:
  49. ra, rb = layout_mod.node_rect(a), layout_mod.node_rect(b)
  50. assert not layout_mod.rects_overlap(ra, rb), (a["id"], b["id"])
  51. hgap = max(rb[0] - ra[2], ra[0] - rb[2])
  52. vgap = max(rb[1] - ra[3], ra[1] - rb[3])
  53. # two nodes are either a column apart or a row apart
  54. assert (
  55. hgap >= layout_mod.MIN_COL_GAP or vgap >= layout_mod.MIN_ROW_GAP
  56. ), (
  57. a["id"],
  58. b["id"],
  59. hgap,
  60. vgap,
  61. )
  62. def test_columns_are_at_least_the_minimum_apart(self, name):
  63. _, nodes, _, _ = parts(load(name))
  64. centres = sorted({round(layout_mod.centre(n)[0]) for n in nodes})
  65. for left, right in itertools.pairwise(centres):
  66. assert right - left >= 300 + 300, (left, right)
  67. def test_every_node_lies_inside_its_declared_boundary_box(self, name):
  68. model = load(name)
  69. cs, nodes, boxes, _ = parts(model)
  70. by_id = {c["id"]: c for c in cs}
  71. declared = layout_mod.LAYOUTS[name]["boxes"]
  72. assert set(declared) == {b["id"] for b in boxes}
  73. for box_id, members in declared.items():
  74. assert members
  75. for m in members:
  76. assert layout_mod.inside(
  77. layout_mod.node_rect(by_id[m]), layout_mod.node_rect(by_id[box_id])
  78. ), (m, box_id)
  79. # a node is in at most one box and no box swallows a stranger
  80. owner = {}
  81. for box_id, members in declared.items():
  82. for m in members:
  83. assert m not in owner, m
  84. owner[m] = box_id
  85. for box in boxes:
  86. for n in nodes:
  87. if owner.get(n["id"]) != box["id"]:
  88. assert not layout_mod.rects_overlap(
  89. layout_mod.node_rect(n), layout_mod.node_rect(box)
  90. ), (n["id"], box["id"])
  91. def test_boundaries_are_boxes_not_curves(self, name):
  92. cs, _, boxes, _ = parts(load(name))
  93. assert boxes
  94. assert not [c for c in cs if c["shape"] == "trust-boundary-curve"]
  95. for box in boxes:
  96. assert box["data"]["isTrustBoundary"] is True
  97. assert box["data"]["type"] == "tm.BoundaryBox"
  98. assert box["attrs"]["label"]["text"] == box["data"]["name"]
  99. assert not box["data"].get("threats")
  100. def test_flow_labels_are_short_and_keep_the_long_wording(self, name):
  101. _, _, _, flows = parts(load(name))
  102. assert flows
  103. for flow in flows:
  104. label = flow["labels"][0]["attrs"]["label"]["text"]
  105. assert label == flow["data"]["name"]
  106. assert 1 <= len(label.split()) <= 4, (flow["id"], label)
  107. assert len(label) <= 28, (flow["id"], label)
  108. assert 0 < flow["labels"][0]["position"] < 1
  109. # the original wording moved into the description
  110. assert any("Full label:" in f["data"]["description"] for f in flows)
  111. def test_node_names_fit_their_shapes(self, name):
  112. # Threat Dragon v2.6.2 does not wrap a node's name, so a long one runs
  113. # past the shape; the wording lives in the description instead.
  114. _, nodes, _, _ = parts(load(name))
  115. for node in nodes:
  116. label = node["attrs"]["text"]["text"]
  117. assert label == node["data"]["name"]
  118. assert len(label) <= layout_mod.NODE_NAME_MAX, label
  119. def test_flows_avoid_nodes_labels_and_each_other(self, name):
  120. model = load(name)
  121. cs, nodes, _boxes, flows = parts(model)
  122. by_id = {c["id"]: c for c in cs}
  123. rects = {f["id"]: layout_mod.label_rect(f, by_id) for f in flows}
  124. for f in flows:
  125. pts = layout_mod.polyline(f, by_id)
  126. ends = {f["source"]["cell"], f["target"]["cell"]}
  127. for n in nodes:
  128. assert not layout_mod.rects_overlap(
  129. rects[f["id"]], layout_mod.node_rect(n)
  130. ), (
  131. f["id"],
  132. n["id"],
  133. )
  134. if n["id"] not in ends:
  135. for p, q in itertools.pairwise(pts):
  136. assert not layout_mod.seg_hits_rect(
  137. p, q, layout_mod.node_rect(n), layout_mod.NODE_MARGIN
  138. ), (f["id"], n["id"])
  139. ids = sorted(rects)
  140. for i, a in enumerate(ids):
  141. for b in ids[i + 1 :]:
  142. assert not layout_mod.rects_overlap(rects[a], rects[b]), (a, b)
  143. def test_flows_that_share_two_nodes_are_fanned_out(self, name):
  144. _, _, _, flows = parts(load(name))
  145. seen: dict = {}
  146. for f in flows:
  147. key = tuple(sorted((f["source"]["cell"], f["target"]["cell"])))
  148. seen.setdefault(key, []).append(f)
  149. pairs = [group for group in seen.values() if len(group) > 1]
  150. for group in pairs:
  151. assert all(f["vertices"] for f in group), [f["id"] for f in group]
  152. starts = {json.dumps(f["vertices"]) for f in group}
  153. assert len(starts) == len(group)
  154. def test_zones_run_left_to_right_in_the_pipeline_models():
  155. for name in (
  156. "clouds-against-humanity.threat-dragon.json",
  157. "clouds-against-humanity.attack.threat-dragon.json",
  158. ):
  159. nodes = {n["id"]: n for n in parts(load(name))[1]}
  160. x = {k: layout_mod.centre(v)[0] for k, v in nodes.items()}
  161. assert (
  162. x["node-contributor"]
  163. < x["node-gh_repo"]
  164. < x["node-sl_track"]
  165. < x["node-doppler"]
  166. < x["node-droplets"]
  167. )
  168. assert x["node-doppler"] == x["node-cloud_api"]
  169. assert x["node-twingate"] == x["node-droplets"]
  170. def test_layout_script_check_passes_from_the_command_line():
  171. result = subprocess.run(
  172. [sys.executable, "-I", str(SCRIPT), "--check"],
  173. check=False,
  174. capture_output=True,
  175. text=True,
  176. timeout=60,
  177. )
  178. assert result.returncode == 0, result.stderr
  179. def test_layout_check_fails_when_a_position_is_changed(tmp_path):
  180. for name in NAMES:
  181. (tmp_path / name).write_text(
  182. (MODEL_DIR / name).read_text(encoding="utf-8"), encoding="utf-8"
  183. )
  184. victim = tmp_path / NAMES[0]
  185. model = json.loads(victim.read_text(encoding="utf-8"))
  186. for cell in layout_mod.cells(model):
  187. if layout_mod.is_node(cell):
  188. cell["position"]["x"] += 7
  189. break
  190. victim.write_text(json.dumps(model, indent=2) + "\n", encoding="utf-8")
  191. result = subprocess.run(
  192. [sys.executable, "-I", str(SCRIPT), "--check", "--root", str(tmp_path)],
  193. check=False,
  194. capture_output=True,
  195. text=True,
  196. timeout=60,
  197. )
  198. assert result.returncode == 1
  199. assert "out of date" in result.stderr
  200. def test_a_label_over_four_words_is_rejected():
  201. layout = json.loads(
  202. json.dumps(
  203. layout_mod.LAYOUTS["clouds-against-humanity.threat-dragon.json"],
  204. default=list,
  205. )
  206. )
  207. layout["nodes"] = {k: tuple(v) for k, v in layout["nodes"].items()}
  208. layout["vertices"] = {
  209. k: [tuple(p) for p in v] for k, v in layout["vertices"].items()
  210. }
  211. layout["labels"]["flow-f-tok"] = "one two three four five"
  212. with pytest.raises(AssertionError):
  213. layout_mod.apply_layout(
  214. load("clouds-against-humanity.threat-dragon.json"), layout
  215. )