test_threat_dragon_model.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. """Tests for the OWASP Threat Dragon model that goes with the wiki exercise.
  2. The model is a teaching artifact: it records the data flow diagram of this
  3. repository, with the trust boundaries B1 to B8 from Threat-Model-Exercise.md
  4. and the T-numbers from Threat-Model.md. These checks keep the three in step.
  5. They cannot show that the model is true of the running system.
  6. """
  7. import json
  8. import re
  9. from pathlib import Path
  10. import pytest
  11. ROOT = Path(__file__).resolve().parent.parent
  12. MODEL = ROOT / "docs" / "threat-model" / "clouds-against-humanity.threat-dragon.json"
  13. WIKI = ROOT / "docs" / "wiki"
  14. STRIDE = {
  15. "Spoofing",
  16. "Tampering",
  17. "Repudiation",
  18. "Information disclosure",
  19. "Denial of service",
  20. "Elevation of privilege",
  21. }
  22. # Threat Dragon v2.6.2 (ThreatEditDialog.vue) offers only these three statuses.
  23. STATUSES = {"Open", "Mitigated", "NotApplicable"}
  24. SEVERITIES = {"High", "Medium", "Low"}
  25. @pytest.fixture(scope="module")
  26. def model() -> dict:
  27. return json.loads(MODEL.read_text(encoding="utf-8"))
  28. @pytest.fixture(scope="module")
  29. def cells(model) -> list:
  30. return model["detail"]["diagrams"][0]["cells"]
  31. def threats_of(cells):
  32. for cell in cells:
  33. for threat in cell["data"].get("threats", []):
  34. yield cell, threat
  35. def test_top_level_keys(model):
  36. assert {"version", "summary", "detail"} <= model.keys()
  37. assert model["version"].startswith("2.")
  38. assert model["summary"]["title"]
  39. detail = model["detail"]
  40. assert {"contributors", "diagrams", "diagramTop", "reviewer", "threatTop"} <= (
  41. detail.keys()
  42. )
  43. assert detail["diagrams"], "no diagram"
  44. diagram = detail["diagrams"][0]
  45. assert {"diagramType", "id", "thumbnail", "title", "version", "cells"} <= (
  46. diagram.keys()
  47. )
  48. assert diagram["diagramType"] == "STRIDE"
  49. def test_cell_ids_are_unique(cells):
  50. ids = [c["id"] for c in cells]
  51. assert len(ids) == len(set(ids))
  52. def test_threat_ids_and_numbers_are_unique(model, cells):
  53. found = [t for _, t in threats_of(cells)]
  54. ids = [t["id"] for t in found]
  55. numbers = [t["number"] for t in found]
  56. assert len(ids) == len(set(ids))
  57. assert len(numbers) == len(set(numbers))
  58. assert model["detail"]["threatTop"] == max(numbers)
  59. def test_flow_endpoints_exist(cells):
  60. ids = {c["id"] for c in cells}
  61. flows = [c for c in cells if c["shape"] == "flow"]
  62. assert flows
  63. for flow in flows:
  64. for end in ("source", "target"):
  65. assert flow[end]["cell"] in ids, f"{flow['data']['name']}: {end}"
  66. assert flow["source"]["cell"] != flow["target"]["cell"]
  67. assert flow["data"]["name"].strip(), "unlabelled flow"
  68. def test_flows_connect_elements_not_boundaries(cells):
  69. kinds = {c["id"]: c["shape"] for c in cells}
  70. for flow in (c for c in cells if c["shape"] == "flow"):
  71. assert kinds[flow["source"]["cell"]] not in {
  72. "flow",
  73. "trust-boundary-curve",
  74. "trust-boundary-box",
  75. }
  76. assert kinds[flow["target"]["cell"]] not in {
  77. "flow",
  78. "trust-boundary-curve",
  79. "trust-boundary-box",
  80. }
  81. def test_threats_sit_on_elements_that_exist_and_can_hold_them(cells):
  82. # Threat Dragon stores a threat inside the element it is about, and its
  83. # documentation says trust boundaries cannot have threats.
  84. for cell in cells:
  85. if cell["data"].get("isTrustBoundary"):
  86. assert not cell["data"].get("threats"), cell["data"]["name"]
  87. elif cell["shape"] != "flow":
  88. assert "threats" in cell["data"]
  89. assert list(threats_of(cells))
  90. def test_threat_fields_are_valid(cells):
  91. for cell, t in threats_of(cells):
  92. where = cell["data"]["name"]
  93. assert t["modelType"] == "STRIDE", where
  94. assert t["type"] in STRIDE, where
  95. assert t["status"] in STATUSES, where
  96. assert t["severity"] in SEVERITIES, where
  97. for field in ("title", "description", "mitigation"):
  98. assert t[field].strip(), (where, field)
  99. def test_has_open_threats_flag_matches(cells):
  100. for cell in cells:
  101. if "threats" not in cell["data"]:
  102. continue
  103. expected = any(t["status"] == "Open" for t in cell["data"]["threats"])
  104. assert cell["data"]["hasOpenThreats"] is expected, cell["data"]["name"]
  105. def test_every_stride_letter_is_used(cells):
  106. used = {t["type"] for _, t in threats_of(cells)}
  107. assert used == STRIDE
  108. def exercise_boundaries() -> dict:
  109. text = (WIKI / "Threat-Model-Exercise.md").read_text(encoding="utf-8")
  110. text = text.replace("<br/>", " ")
  111. found = dict(re.findall(r'"(B\d+): ([^"]+)"', text))
  112. assert found, "no boundaries parsed from the exercise page"
  113. return found
  114. def test_boundaries_in_exercise_page_exist_in_model(cells):
  115. names = [
  116. c["data"]["name"] for c in cells if c["data"].get("isTrustBoundary") is True
  117. ]
  118. for ident in exercise_boundaries():
  119. assert any(n.startswith(f"{ident}:") for n in names), ident
  120. assert len(names) == len(set(names))
  121. assert len(names) == len(exercise_boundaries())
  122. for c in cells:
  123. if c["data"].get("isTrustBoundary") is True:
  124. assert c["shape"].startswith("trust-boundary")
  125. def test_boundary_wording_matches_exercise_page(cells):
  126. names = {
  127. n.split(":")[0]: n
  128. for n in (
  129. c["data"]["name"] for c in cells if c["data"].get("isTrustBoundary") is True
  130. )
  131. }
  132. for ident, text in exercise_boundaries().items():
  133. first = " ".join(text.lower().split()[:2]).rstrip(",;")
  134. assert first in names[ident].lower(), (ident, text, names[ident])
  135. def model_text(model) -> str:
  136. return json.dumps(model)
  137. def test_t_numbers_in_model_exist_in_threat_model_page(model):
  138. page = (WIKI / "Threat-Model.md").read_text(encoding="utf-8")
  139. defined = set(re.findall(r"^\| (T\d+) \|", page, flags=re.MULTILINE))
  140. assert defined
  141. used = set(re.findall(r"\bT\d+\b", model_text(model)))
  142. assert used, "model cites no T-numbers"
  143. assert used <= defined, sorted(used - defined)
  144. def test_every_documented_threat_is_modelled(model):
  145. page = (WIKI / "Threat-Model.md").read_text(encoding="utf-8")
  146. defined = set(re.findall(r"^\| (T\d+) \|", page, flags=re.MULTILINE))
  147. used = set(re.findall(r"\bT\d+\b", model_text(model)))
  148. assert defined <= used, sorted(defined - used)
  149. def test_no_addresses_or_private_identifiers(model):
  150. text = model_text(model)
  151. assert not re.search(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", text), "IPv4 address"
  152. assert not re.search(
  153. r"\b[0-9a-f]{1,4}(?::[0-9a-f]{0,4}){3,}\b", text, re.IGNORECASE
  154. )
  155. assert not re.search(r"https?://", text), "URL in model"
  156. assert not re.search(r"\b[\w.+-]+@[\w-]+\.\w+", text), "email address"
  157. def test_exercise_page_points_at_the_model():
  158. page = (WIKI / "Threat-Dragon-Exercise.md").read_text(encoding="utf-8")
  159. assert "docs/threat-model/clouds-against-humanity.threat-dragon.json" in page
  160. for ident in exercise_boundaries():
  161. assert ident in page
  162. def test_wiki_pages_link_the_exercise():
  163. for name in ("Contents.md", "Home.md"):
  164. text = (WIKI / name).read_text(encoding="utf-8")
  165. assert "(Threat-Dragon-Exercise.md)" in text, name
  166. def test_flow_count_matches_exercise_page(cells):
  167. page = (WIKI / "Threat-Dragon-Exercise.md").read_text(encoding="utf-8")
  168. flows = [c for c in cells if c["shape"] == "flow"]
  169. assert f"{len(flows)} labeled flows" in page
  170. def test_flows_are_unidirectional_and_connector_link_is_split(cells):
  171. # A flow in the model runs one way; a link that carries a token out and
  172. # a session back is two flows.
  173. by_id = {c["id"]: c for c in cells}
  174. for flow in (c for c in cells if c["shape"] == "flow"):
  175. if flow["data"].get("isBidirectional"):
  176. assert flow["id"] == "flow-f-state", flow["data"]["name"]
  177. link, session = by_id["flow-f-connector-link"], by_id["flow-f-session"]
  178. assert (link["source"]["cell"], link["target"]["cell"]) == (
  179. "node-droplets",
  180. "node-twingate",
  181. )
  182. assert (session["source"]["cell"], session["target"]["cell"]) == (
  183. "node-twingate",
  184. "node-droplets",
  185. )
  186. assert "flow-f-relay" not in by_id
  187. def test_accepted_risks_stay_open_and_say_so(cells):
  188. # The app has no Accepted status, so an accepted risk is Open and its
  189. # mitigation text says "Accepted".
  190. accepted = [t for _, t in threats_of(cells) if "Accepted" in t["mitigation"]]
  191. assert accepted
  192. for t in accepted:
  193. assert t["status"] == "Open", t["id"]
  194. def test_proposed_run_is_not_described_as_credential_free(cells):
  195. node = next(c for c in cells if c["id"] == "node-sl_prop")
  196. text = node["data"]["description"]
  197. assert "no credentials" not in text.lower()
  198. assert "DOPPLER_TOKEN" in text
  199. def test_exercise_reference_answer_matches_read_request_flow(cells):
  200. flow = next(c for c in cells if c["id"] == "flow-f-tok")
  201. types = {t["type"] for t in flow["data"]["threats"]}
  202. assert {"Spoofing", "Information disclosure"} <= types