test_threat_frameworks.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. """Tests for the framework-mapped Threat Dragon models and their reference data.
  2. docs/threat-model/ holds three importable models of this repository: the STRIDE
  3. model (tested in test_threat_dragon_model.py), a STRIDE model whose threats
  4. cite MITRE ATT&CK techniques, and one for the AI tools that touch the repository
  5. that cites MITRE ATLAS techniques. Threat Dragon has no ATT&CK or ATLAS threat
  6. type, so the technique sits in the threat title and description.
  7. These checks keep three things in step: the model files, the wiki pages that
  8. teach them, and docs/threat-model/framework-reference.json, a small curated
  9. copy of the technique and tactic IDs and names this repository cites. Nothing
  10. here touches the network. They cannot show that a mapping is the best fit, only
  11. that every ID cited exists in the reference and is spelled the way the data
  12. spells it.
  13. """
  14. import json
  15. import re
  16. from pathlib import Path
  17. import pytest
  18. ROOT = Path(__file__).resolve().parent.parent
  19. MODEL_DIR = ROOT / "docs" / "threat-model"
  20. WIKI = ROOT / "docs" / "wiki"
  21. REFERENCE = MODEL_DIR / "framework-reference.json"
  22. STRIDE_MODEL = MODEL_DIR / "clouds-against-humanity.threat-dragon.json"
  23. ATTACK_MODEL = MODEL_DIR / "clouds-against-humanity.attack.threat-dragon.json"
  24. ATLAS_MODEL = MODEL_DIR / "clouds-against-humanity.atlas.threat-dragon.json"
  25. PAGE = WIKI / "Threat-Frameworks-STRIDE-ATTACK-ATLAS.md"
  26. MODELS = sorted(MODEL_DIR.glob("*.threat-dragon.json"))
  27. STRIDE = {
  28. "Spoofing",
  29. "Tampering",
  30. "Repudiation",
  31. "Information disclosure",
  32. "Denial of service",
  33. "Elevation of privilege",
  34. }
  35. STATUSES = {"Open", "Mitigated", "NotApplicable"}
  36. SEVERITIES = {"High", "Medium", "Low"}
  37. # The lookbehind keeps a URL path such as /techniques/T1078/004 and a file name
  38. # out of the match. ATLAS IDs always carry the AML. prefix.
  39. ATT_TECH = re.compile(r"(?<![\w./])T1\d{3}(?:\.\d{3})?\b")
  40. ATT_TAC = re.compile(r"(?<![\w./])TA\d{4}\b")
  41. ATL_TECH = re.compile(r"AML\.T\d{4}(?:\.\d{3})?\b")
  42. ATL_TAC = re.compile(r"AML\.TA\d{4}\b")
  43. UUID = re.compile(
  44. r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", re.IGNORECASE
  45. )
  46. @pytest.fixture(scope="module")
  47. def ref() -> dict:
  48. return json.loads(REFERENCE.read_text(encoding="utf-8"))
  49. def load(path: Path) -> dict:
  50. return json.loads(path.read_text(encoding="utf-8"))
  51. def cells_of(model: dict) -> list:
  52. return model["detail"]["diagrams"][0]["cells"]
  53. def threats_of(cells):
  54. for cell in cells:
  55. for threat in cell["data"].get("threats", []):
  56. yield cell, threat
  57. def known_names(ref: dict, kind: str) -> dict:
  58. """ID -> acceptable names (the current one, and a historic one if any)."""
  59. out: dict = {}
  60. if kind == "attack_tech":
  61. block = ref["attack"]
  62. for i, e in block["techniques"].items():
  63. out.setdefault(i, set()).add(e["name"])
  64. for i, e in block["historic_techniques"].items():
  65. out.setdefault(i, set()).add(e["name"])
  66. elif kind == "attack_tac":
  67. block = ref["attack"]
  68. for i, e in block["tactics"].items():
  69. out.setdefault(i, set()).add(e["name"])
  70. for i, e in block["historic_tactics"].items():
  71. out.setdefault(i, set()).add(e["name"])
  72. elif kind == "atlas_tech":
  73. for i, e in ref["atlas"]["techniques"].items():
  74. out.setdefault(i, set()).add(e["name"])
  75. else:
  76. for i, e in ref["atlas"]["tactics"].items():
  77. out.setdefault(i, set()).add(e["name"])
  78. return out
  79. KINDS = {
  80. "attack_tech": ATT_TECH,
  81. "attack_tac": ATT_TAC,
  82. "atlas_tech": ATL_TECH,
  83. "atlas_tac": ATL_TAC,
  84. }
  85. def all_ids(text: str) -> dict:
  86. return {k: set(rx.findall(text)) for k, rx in KINDS.items()}
  87. def check_text(ref: dict, text: str, where: str) -> None:
  88. """Every cited ID exists and is immediately followed by its name."""
  89. for kind, rx in KINDS.items():
  90. names = known_names(ref, kind)
  91. for m in rx.finditer(text):
  92. ident = m.group(0)
  93. assert ident in names, f"{where}: {ident} is not in the reference file"
  94. tail = text[m.end() :]
  95. # The exact name, then a non-name character (or the end): a name
  96. # that merely extends a valid one ("Cloud Logs" for "Cloud Log")
  97. # is a misspelling, not a match.
  98. assert any(
  99. re.match(rf" {re.escape(n)}(?![\w-])", tail) for n in names[ident]
  100. ), (
  101. f"{where}: {ident} is not followed by its name ({sorted(names[ident])})"
  102. )
  103. def tactic_sets_ok(ref: dict, text: str, where: str) -> None:
  104. """A technique cited with a tactic list has the tactics the data gives it."""
  105. pat = re.compile(
  106. r"((?:AML\.)?T\d{4}(?:\.\d{3})?) ([^\[\]().,;:]+?) [\[(]"
  107. r"((?:AML\.)?TA\d{4} [^\[\]()]*)[\])]"
  108. )
  109. for m in pat.finditer(text):
  110. ident, _name, listed = m.groups()
  111. if ident.startswith("AML."):
  112. entry = ref["atlas"]["techniques"].get(ident)
  113. else:
  114. entry = ref["attack"]["techniques"].get(ident)
  115. if entry is None:
  116. continue
  117. got = {item.strip().split(" ")[0] for item in listed.split(",")}
  118. assert got == set(entry["tactics"]), f"{where}: {ident} tactics {sorted(got)}"
  119. # --- structure, for every model in the directory --------------------------
  120. def test_the_expected_models_exist():
  121. assert STRIDE_MODEL in MODELS
  122. assert ATTACK_MODEL in MODELS
  123. assert ATLAS_MODEL in MODELS
  124. @pytest.mark.parametrize("path", MODELS, ids=lambda p: p.name)
  125. class TestEveryModel:
  126. def test_top_level_keys(self, path):
  127. model = load(path)
  128. assert {"version", "summary", "detail"} <= model.keys()
  129. assert model["version"].startswith("2.")
  130. assert model["summary"]["title"]
  131. detail = model["detail"]
  132. assert {"contributors", "diagrams", "diagramTop", "reviewer", "threatTop"} <= (
  133. detail.keys()
  134. )
  135. diagram = detail["diagrams"][0]
  136. assert {"diagramType", "id", "thumbnail", "title", "version", "cells"} <= (
  137. diagram.keys()
  138. )
  139. assert diagram["diagramType"] == "STRIDE"
  140. def test_ids_are_unique_and_readable(self, path):
  141. model = load(path)
  142. cells = cells_of(model)
  143. ids = [c["id"] for c in cells]
  144. assert len(ids) == len(set(ids))
  145. tids = [t["id"] for _, t in threats_of(cells)]
  146. numbers = [t["number"] for _, t in threats_of(cells)]
  147. assert len(tids) == len(set(tids))
  148. assert len(numbers) == len(set(numbers))
  149. assert model["detail"]["threatTop"] == max(numbers)
  150. assert not UUID.search(path.read_text(encoding="utf-8")), "UUID-looking id"
  151. def test_flows_connect_existing_elements(self, path):
  152. cells = cells_of(load(path))
  153. kinds = {c["id"]: c["shape"] for c in cells}
  154. flows = [c for c in cells if c["shape"] == "flow"]
  155. assert flows
  156. for flow in flows:
  157. assert flow["data"]["name"].strip(), "unlabelled flow"
  158. for end in ("source", "target"):
  159. target = flow[end]["cell"]
  160. assert target in kinds, f"{flow['id']}: {end}"
  161. assert kinds[target] not in {
  162. "flow",
  163. "trust-boundary-curve",
  164. "trust-boundary-box",
  165. }
  166. assert flow["source"]["cell"] != flow["target"]["cell"]
  167. def test_boundaries_hold_no_threats(self, path):
  168. cells = cells_of(load(path))
  169. boundaries = [c for c in cells if c["data"].get("isTrustBoundary") is True]
  170. assert boundaries
  171. for c in boundaries:
  172. assert c["shape"].startswith("trust-boundary"), c["id"]
  173. assert not c["data"].get("threats"), c["id"]
  174. names = [c["data"]["name"] for c in boundaries]
  175. assert len(names) == len(set(names))
  176. for c in cells:
  177. if not c["data"].get("isTrustBoundary") and c["shape"] != "flow":
  178. assert "threats" in c["data"], c["id"]
  179. def test_threat_fields_are_valid(self, path):
  180. cells = cells_of(load(path))
  181. found = list(threats_of(cells))
  182. assert found
  183. for cell, t in found:
  184. where = f"{path.name}: {cell['data']['name']}"
  185. assert t["modelType"] == "STRIDE", where
  186. assert t["type"] in STRIDE, where
  187. assert t["status"] in STATUSES, where
  188. assert t["severity"] in SEVERITIES, where
  189. for field in ("title", "description", "mitigation"):
  190. assert t[field].strip(), (where, field)
  191. def test_has_open_threats_flag_matches(self, path):
  192. for cell in cells_of(load(path)):
  193. if "threats" not in cell["data"]:
  194. continue
  195. expected = any(t["status"] == "Open" for t in cell["data"]["threats"])
  196. assert cell["data"]["hasOpenThreats"] is expected, cell["data"]["name"]
  197. def test_no_addresses_urls_or_private_identifiers(self, path):
  198. text = path.read_text(encoding="utf-8")
  199. assert not re.search(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", text), "IPv4 address"
  200. assert not re.search(
  201. r"\b[0-9a-f]{1,4}(?::[0-9a-f]{0,4}){3,}\b", text, re.IGNORECASE
  202. )
  203. assert not re.search(r"https?://", text), "URL in model"
  204. assert not re.search(r"\b[\w.+-]+@[\w-]+\.\w+", text), "email address"
  205. def test_every_cited_id_exists_with_its_name(self, path, ref):
  206. text = path.read_text(encoding="utf-8")
  207. check_text(ref, text, path.name)
  208. tactic_sets_ok(ref, text, path.name)
  209. # --- the ATT&CK model ------------------------------------------------------
  210. def test_attack_model_is_the_same_diagram_as_the_stride_model():
  211. stride = {c["id"]: c for c in cells_of(load(STRIDE_MODEL))}
  212. attack = {c["id"]: c for c in cells_of(load(ATTACK_MODEL))}
  213. assert stride.keys() == attack.keys()
  214. for ident, cell in stride.items():
  215. other = attack[ident]
  216. assert other["shape"] == cell["shape"], ident
  217. assert other["data"]["name"] == cell["data"]["name"], ident
  218. for end in ("source", "target"):
  219. assert other.get(end) == cell.get(end), (ident, end)
  220. def test_attack_threats_cite_attack_ids_only_and_lead_with_one(ref):
  221. cells = cells_of(load(ATTACK_MODEL))
  222. for _, t in threats_of(cells):
  223. assert ATT_TECH.match(t["title"]), t["id"]
  224. body = t["title"] + " " + t["description"]
  225. assert ATT_TECH.search(t["description"]), t["id"]
  226. assert not ATL_TECH.search(body), t["id"]
  227. assert "ATT&CK v20.0" in t["description"], t["id"]
  228. assert "Detection:" in t["mitigation"], t["id"]
  229. def test_attack_model_keeps_the_stride_model_numbers_and_t_numbers():
  230. stride = {t["id"]: t for _, t in threats_of(cells_of(load(STRIDE_MODEL)))}
  231. attack = list(threats_of(cells_of(load(ATTACK_MODEL))))
  232. assert attack
  233. for _, t in attack:
  234. original = stride[t["id"]]
  235. for field in ("number", "type", "severity", "status"):
  236. assert t[field] == original[field], (t["id"], field)
  237. page = (WIKI / "Threat-Model.md").read_text(encoding="utf-8")
  238. defined = set(re.findall(r"^\| (T\d+) \|", page, flags=re.MULTILINE))
  239. used = set(re.findall(r"\bT\d{1,2}\b", json.dumps(load(ATTACK_MODEL))))
  240. assert defined <= used, sorted(defined - used)
  241. assert used <= defined, sorted(used - defined)
  242. def test_attack_model_cites_cloud_and_enterprise_techniques_with_iaas(ref):
  243. text = ATTACK_MODEL.read_text(encoding="utf-8")
  244. cited = set(ATT_TECH.findall(text))
  245. techniques = ref["attack"]["techniques"]
  246. assert cited <= techniques.keys()
  247. # The brief asks for the cloud/IaaS matrix: several cited techniques must
  248. # list IaaS among their platforms in the data.
  249. assert sum(1 for i in cited if techniques[i]["iaas"]) >= 10
  250. # --- the ATLAS model -------------------------------------------------------
  251. def test_atlas_threats_cite_atlas_ids_only_and_lead_with_one():
  252. cells = cells_of(load(ATLAS_MODEL))
  253. found = list(threats_of(cells))
  254. assert len(found) >= 10
  255. for _, t in found:
  256. assert t["title"].startswith("AML.T"), t["id"]
  257. assert ATL_TECH.search(t["description"]), t["id"]
  258. assert "ATLAS 2026.09" in t["description"], t["id"]
  259. assert not ATT_TECH.search(t["title"] + t["description"]), t["id"]
  260. def test_atlas_boundaries_use_their_own_numbering():
  261. names = [
  262. c["data"]["name"]
  263. for c in cells_of(load(ATLAS_MODEL))
  264. if c["data"].get("isTrustBoundary") is True
  265. ]
  266. assert [n.split(":")[0] for n in names] == [f"AB{i}" for i in range(1, 6)]
  267. def test_stride_model_cites_no_framework_ids():
  268. text = STRIDE_MODEL.read_text(encoding="utf-8")
  269. for kind, ids in all_ids(text).items():
  270. assert not ids, (kind, sorted(ids))
  271. # --- the reference file ----------------------------------------------------
  272. def test_reference_has_source_version_and_date_for_each_framework(ref):
  273. assert re.fullmatch(r"\d{4}-\d{2}-\d{2}", ref["retrieved"])
  274. for name in ("attack", "atlas"):
  275. block = ref[name]
  276. assert block["version"]
  277. assert block["source"].startswith("https://")
  278. assert block["release"].startswith("https://")
  279. assert re.fullmatch(r"\d{4}-\d{2}-\d{2}", block["retrieved"])
  280. assert block["techniques"] and block["tactics"]
  281. assert ref["attack"]["version"] == "20.0"
  282. assert ref["atlas"]["version"] == "2026.09"
  283. for entry in ref["attack"]["techniques"].values():
  284. assert entry["url"].startswith("https://attack.mitre.org/")
  285. assert entry["name"].strip() and entry["tactics"]
  286. for entry in ref["attack"]["historic_techniques"].values():
  287. assert entry["version"] and entry["source"].startswith("https://")
  288. def test_reference_tactics_resolve(ref):
  289. for block, prefix in ((ref["attack"], "TA"), (ref["atlas"], "AML.TA")):
  290. for ident, entry in block["techniques"].items():
  291. assert entry["name"].strip(), ident
  292. for tactic in entry["tactics"]:
  293. assert tactic in block["tactics"], (ident, tactic)
  294. for tactic in block["tactics"]:
  295. assert tactic.startswith(prefix)
  296. for ident, entry in ref["attack"]["historic_techniques"].items():
  297. assert entry["superseded_by"] in ref["attack"]["techniques"], ident
  298. def test_reference_lists_only_ids_this_repository_cites(ref):
  299. text = "\n".join(
  300. p.read_text(encoding="utf-8") for p in [*MODELS, *sorted(WIKI.glob("*.md"))]
  301. )
  302. cited = all_ids(text)
  303. listed = {
  304. "attack_tech": set(ref["attack"]["techniques"])
  305. | set(ref["attack"]["historic_techniques"]),
  306. "attack_tac": set(ref["attack"]["tactics"])
  307. | set(ref["attack"]["historic_tactics"]),
  308. "atlas_tech": set(ref["atlas"]["techniques"]),
  309. "atlas_tac": set(ref["atlas"]["tactics"]),
  310. }
  311. for kind in KINDS:
  312. # Tactics are listed for the techniques that carry them even where no
  313. # text names the tactic, so only techniques must all be cited.
  314. if kind.endswith("tech"):
  315. assert listed[kind] == cited[kind], (kind, listed[kind] ^ cited[kind])
  316. else:
  317. assert cited[kind] <= listed[kind], (kind, cited[kind] - listed[kind])
  318. # --- the wiki pages --------------------------------------------------------
  319. @pytest.mark.parametrize("path", sorted(WIKI.glob("*.md")), ids=lambda p: p.name)
  320. def test_wiki_pages_cite_only_verified_ids_with_their_names(path, ref):
  321. text = path.read_text(encoding="utf-8")
  322. check_text(ref, text, path.name)
  323. tactic_sets_ok(ref, text, path.name)
  324. def test_wiki_page_counts_match_the_models():
  325. page = PAGE.read_text(encoding="utf-8")
  326. attack_cells = cells_of(load(ATTACK_MODEL))
  327. atlas_cells = cells_of(load(ATLAS_MODEL))
  328. attack_threats = len(list(threats_of(attack_cells)))
  329. atlas_threats = len(list(threats_of(atlas_cells)))
  330. attack_ids = set(ATT_TECH.findall(ATTACK_MODEL.read_text(encoding="utf-8")))
  331. atlas_ids = set(ATL_TECH.findall(ATLAS_MODEL.read_text(encoding="utf-8")))
  332. assert f"{attack_threats} threats" in page
  333. assert f"{len(attack_ids)} distinct techniques" in page
  334. assert (
  335. f"{atlas_threats} threats, {len(atlas_ids)} distinct ATLAS techniques" in page
  336. )
  337. assert f"{len(attack_cells)} for the ATT&CK model" in page
  338. assert f"{len(atlas_cells)} for the ATLAS model" in page
  339. def test_wiki_mapping_table_covers_every_t_number():
  340. page = PAGE.read_text(encoding="utf-8")
  341. defined = re.findall(
  342. r"^\| (T\d+) \|",
  343. (WIKI / "Threat-Model.md").read_text(encoding="utf-8"),
  344. flags=re.MULTILINE,
  345. )
  346. rows = re.findall(r"^\| (T\d{1,2}) \|", page, flags=re.MULTILINE)
  347. assert rows == defined
  348. def test_wiki_pages_link_the_frameworks_page():
  349. target = "(Threat-Frameworks-STRIDE-ATTACK-ATLAS.md)"
  350. for name in (
  351. "_Sidebar.md",
  352. "Home.md",
  353. "Threat-Dragon-Exercise.md",
  354. "Threat-Model-Exercise.md",
  355. ):
  356. assert target in (WIKI / name).read_text(encoding="utf-8"), name
  357. def test_wiki_page_says_threat_dragon_has_no_attack_or_atlas_type():
  358. page = PAGE.read_text(encoding="utf-8")
  359. assert "There is no ATT&CK or ATLAS type" in page
  360. for model in ("STRIDE", "LINDDUN", "CIA", "PLOT4ai"):
  361. assert model in page
  362. for path in (ATTACK_MODEL, ATLAS_MODEL):
  363. assert "no" in load(path)["summary"]["description"].lower()
  364. assert "threat type" in load(path)["summary"]["description"]