test_lesson_guards.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. # SPDX-License-Identifier: Apache-2.0
  2. """One data-driven guard suite for every lesson page (issue #525).
  3. It replaces the copy-pasted per-lesson guard files. Two layers:
  4. 1. GENERIC checks, run on every lesson page the discovery rule finds (see `lesson_pages`): no em dash, no address
  5. outside the page's allowlist, no identifier or private key (scripts/identifier_check.py), a status banner that
  6. says what was and was not run, a claims register whose rows all carry a known status, link targets and in-page
  7. anchors that exist, glossary anchors that resolve, registration in the navigation files, sibling lessons linked
  8. rather than named in plain text, and the UNTESTED or **est.** marks where the page says something was not run.
  9. 2. PER-LESSON rows in tests/lesson_guard_data.py (`PAGES`): the thresholds and the unique requirements the old
  10. per-lesson files held, as data. A row is a dict; `check_row` below is the only code that reads them.
  11. Every failure names the page and the rule. Each guard has a negative case (`test_guard_bites_*`) proving it fires.
  12. American English is guarded by tests/test_american_english.py and is not repeated here.
  13. """
  14. from __future__ import annotations
  15. import functools
  16. import importlib.util
  17. import re
  18. import shutil
  19. import subprocess
  20. import sys
  21. import textwrap
  22. from pathlib import Path
  23. import pytest
  24. from lesson_guard_data import DEFAULTS, NO_REGISTER, PAGES
  25. from wikitext import GLOSSARY_FILES, gen_wiki_nav, glossary_text, nav_text, page_text
  26. ROOT = Path(__file__).resolve().parent.parent
  27. WIKI = ROOT / "docs" / "wiki"
  28. _spec = importlib.util.spec_from_file_location("identifier_check", ROOT / "scripts" / "identifier_check.py")
  29. ic = importlib.util.module_from_spec(_spec)
  30. sys.modules.setdefault("identifier_check", ic)
  31. _spec.loader.exec_module(ic)
  32. FENCE = re.compile(r"^[ ]*```(\w*)\n(.*?)^[ ]*```$", re.MULTILINE | re.DOTALL)
  33. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#[^)]*)?\)")
  34. OWN_ANCHOR = re.compile(r"\]\(#([^)\s]+)\)")
  35. ADDR = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
  36. PRIVATE_KEY = re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")
  37. BANNER = re.compile(r"^> \*\*Status:.*?(?=\n\n)", re.MULTILINE | re.DOTALL)
  38. HONEST = re.compile(
  39. r"not run|nothing run|nothing was run|no command|was run|were run|run once|did not|not built|not applied|has not been|have not been|not seen to work|not verified|no \w+ was|not installed|not tested|written from reading",
  40. re.IGNORECASE,
  41. )
  42. NOT_RUN = re.compile(r"\*\*Not run:\*\*|nothing run|not run|did not run|no command on this page was run|has not been run|have not been run|not built", re.IGNORECASE)
  43. MARKS = ("**est.**", "UNTESTED", "**Untested", "**not verified**", "Not verified, plainly")
  44. # "unverified draft" is the banner label every draft page carries, not a statement that something was not run
  45. UNRUN_SAYS = re.compile(
  46. r"did not run|was not run|were not run|not run\b|never run|I did not|could not run|untested|not tested|not verified|unverified(?! draft)",
  47. re.IGNORECASE,
  48. )
  49. DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
  50. SIBLING_WORDING = ("plain text until", "They are not linked here")
  51. NAV_PLACES = ("Contents.md", "_Sidebar.md", "Reading-Order.md")
  52. # -- discovery ---------------------------------------------------------------------------------------------
  53. @functools.cache
  54. def read(path: Path) -> str:
  55. return path.read_text(encoding="utf-8")
  56. @functools.cache
  57. def nav_entries() -> dict[str, str]:
  58. """page name -> its docs/wiki/_nav/ line, for every entry that carries a `status`."""
  59. found = {}
  60. for line in nav_text(WIKI).splitlines():
  61. m = re.search(r"\bpage: ([^,]+),", line)
  62. if m and re.search(r'\bstatus: "', line):
  63. found[m.group(1)] = line
  64. return found
  65. @functools.cache
  66. def series_sidebar_entries() -> dict[str, str]:
  67. """page name -> the sidebar link text its series is shown as ("[Series name](First-Page.md)"), for every page
  68. that carries a `series` in the manifest."""
  69. manifest = gen_wiki_nav.read_manifest(ROOT)
  70. found = {}
  71. for entries in manifest["pages"].values():
  72. first: dict[str, str] = {}
  73. for e in entries:
  74. if e.get("series"):
  75. first.setdefault(e["series"], e["page"])
  76. found[e["page"]] = f"[{e['series']}]({first[e['series']]}.md)"
  77. return found
  78. def lesson_pages() -> list[str]:
  79. """The discovery rule: a page is a lesson when its docs/wiki/_nav/ entry carries a `status` AND the page has a
  80. `## Claims register` section. Those two together are what every old per-lesson file guarded; the status-only
  81. pages without a register (the cloud-provider and telemetry pages) are not lessons of this form."""
  82. names = []
  83. for name in nav_entries():
  84. page = WIKI / f"{name}.md"
  85. if page.exists() and "## Claims register" in read(page):
  86. names.append(name)
  87. return sorted(names)
  88. LESSONS = lesson_pages()
  89. def cfg(name: str) -> dict:
  90. return {**DEFAULTS, **PAGES.get(name, {}).get("config", {})}
  91. @functools.cache
  92. def text(name: str) -> str:
  93. return page_text(WIKI / f"{name}.md")
  94. # -- helpers (each one has a negative case below) ------------------------------------------------------------
  95. def register_rows(body: str) -> list[list[str]]:
  96. reg = body.split("## Claims register")[1]
  97. nxt = re.search(r"^## ", reg, re.MULTILINE)
  98. reg = reg[: nxt.start()] if nxt else reg
  99. rows = [line for line in reg.splitlines() if line.startswith("|") and not re.match(r"^\|[\s:|-]+\|?$", line)]
  100. return [[c.strip() for c in r.strip().strip("|").split("|")] for r in rows[1:]]
  101. def rows_with_bad_status(body: str, words: tuple[str, ...]) -> list[str]:
  102. bad = []
  103. for r in register_rows(body):
  104. status = r[-1] if len(r) >= 3 else ""
  105. if not status or not any(w in status for w in words):
  106. bad.append(r[0][:60])
  107. return bad
  108. def addresses_outside(body: str, allow: tuple[str, ...]) -> list[str]:
  109. return sorted({a for a in ADDR.findall(body) if not any(re.fullmatch(p, a) for p in allow)})
  110. def dead_links(body: str) -> list[str]:
  111. return sorted({t for t in LINK.findall(body) if not (WIKI / f"{t}.md").exists()})
  112. def dead_own_anchors(body: str) -> list[str]:
  113. heads = {a for _, _, a in gen_wiki_nav.page_headings(body)}
  114. return sorted({a for a in OWN_ANCHOR.findall(body) if a not in heads})
  115. def glossary_anchors(name: str) -> set[str]:
  116. found: set[str] = set()
  117. for line in glossary_text(WIKI).splitlines():
  118. found.update(re.findall(rf"{re.escape(name)}\.md#([a-z0-9_-]+)", line))
  119. return found
  120. def glossary_rows(name: str) -> int:
  121. return sum(1 for line in glossary_text(WIKI).splitlines() if f"{name}.md" in line)
  122. # The repository gate `identifier_check.py --root .` scans every tracked file with every pattern. This suite applies
  123. # the gate's own scan_line (all pattern kinds: AWS, Azure, GCP; its placeholder allowlist; its ignore marker) to each
  124. # lesson page, so a page cannot publish a real-looking account, tenant, project or key id, and adds private keys.
  125. def identifier_findings(body: str) -> list[str]:
  126. kinds = [kind for line in body.splitlines() for kind in ic.scan_line(line)]
  127. if PRIVATE_KEY.search(body):
  128. kinds.append("private key block")
  129. return kinds
  130. def identifier_problem(name: str, body: str) -> str | None:
  131. kinds = identifier_findings(body)
  132. return fail(name, "no cloud account, tenant, project or key id and no private key (patterns of scripts/identifier_check.py)", kinds) if kinds else None
  133. def banner_problem(name: str, body: str, nav_status: str) -> str | None:
  134. banner = banner_of(body)
  135. if not banner:
  136. return fail(name, "status banner", "no '> **Status:' blockquote")
  137. if not DATE.search(banner): # the banner itself, never the introduction
  138. return fail(name, "status banner is dated", "no date inside the banner text")
  139. if not HONEST.search(banner):
  140. return fail(name, "status banner says what was or was not run", banner[:120])
  141. if nav_status == "draft" and "unverified draft" not in banner:
  142. return fail(name, "draft banner", "nav says draft but the banner does not say 'unverified draft'")
  143. return None
  144. def unrun_problem(name: str, body: str, extra_marks: tuple[str, ...] = ()) -> str | None:
  145. """Anywhere in the page, a statement that something was not run needs an unrun mark somewhere on the page."""
  146. hit = UNRUN_SAYS.search(body)
  147. if hit and not any(m in body for m in MARKS + tuple(extra_marks)):
  148. return fail(name, "an UNTESTED / **est.** / not-verified mark", f"the page says {hit.group(0)!r} but carries no mark")
  149. return None
  150. def banner_of(body: str) -> str:
  151. m = BANNER.search(body)
  152. return m.group(0) if m else ""
  153. def strip_generated_comment_blocks(body: str) -> str:
  154. return re.sub(r"<!-- BEGIN GENERATED .*?<!-- END GENERATED [^>]*-->", "", body, flags=re.DOTALL)
  155. def blocks(body: str, tag: str) -> list[str]:
  156. return [textwrap.dedent(b) for t, b in FENCE.findall(body) if t == tag]
  157. def fail(name: str, rule: str, detail: object) -> str:
  158. return f"[{name}] rule '{rule}' failed: {detail}"
  159. # -- the generic checks ----------------------------------------------------------------------------------------
  160. def test_discovery_finds_every_page_the_old_files_guarded():
  161. # the pages the deleted per-lesson files named; a lesson that stops being discovered must fail loudly
  162. assert len(LESSONS) >= 50, f"discovery collected only {len(LESSONS)} lesson pages"
  163. missing = sorted(set(PAGES) - set(LESSONS))
  164. assert not missing, f"pages with guard rows that discovery no longer finds (status or claims register gone?): {missing}"
  165. def test_every_status_page_is_a_lesson_or_listed_as_having_no_register():
  166. for name in nav_entries():
  167. if name in LESSONS:
  168. assert name not in NO_REGISTER, f"[{name}] rule 'discovery': now has a claims register; remove it from NO_REGISTER in tests/lesson_guard_data.py"
  169. else:
  170. assert name in NO_REGISTER, (
  171. f"[{name}] rule 'discovery': carries a status in docs/wiki/_nav/ but has no '## Claims register'. "
  172. "A lesson that lost its register must get it back; a new page without one goes in NO_REGISTER in tests/lesson_guard_data.py"
  173. )
  174. assert not [n for n in NO_REGISTER if n not in nav_entries()], "NO_REGISTER names a page that no longer carries a status"
  175. @pytest.mark.parametrize("name", LESSONS)
  176. def test_page_title_and_no_em_dash(name):
  177. body = text(name)
  178. assert body.startswith("# "), fail(name, "title", "the page does not start with a level-1 heading")
  179. assert "—" not in body, fail(name, "no em dash", f"em dash at line {body[: body.index('—')].count(chr(10)) + 1}")
  180. @pytest.mark.parametrize("name", LESSONS)
  181. def test_page_addresses_are_documented_placeholders_only(name):
  182. body = text(name)
  183. c = cfg(name)
  184. exact = "addresses_allow" in PAGES.get(name, {}).get("config", {}) # an exact list replaces the shared defaults
  185. allow = tuple(c["addresses_allow"]) if exact else tuple(c["addresses_default"]) + tuple(c.get("addresses_extra", ()))
  186. found = addresses_outside(body, allow)
  187. assert not found, fail(name, "no addresses beyond the page's allowlist", found)
  188. for needed in c.get("addresses_require", ()):
  189. assert needed in ADDR.findall(body), fail(name, "address guard collected nothing", needed)
  190. @pytest.mark.parametrize("name", LESSONS)
  191. def test_page_has_no_identifier_or_private_key(name):
  192. problem = identifier_problem(name, text(name))
  193. assert problem is None, problem
  194. @pytest.mark.parametrize("name", LESSONS)
  195. def test_page_status_banner_says_what_was_and_was_not_run(name):
  196. body = text(name)
  197. nav_status = re.search(r'\bstatus: "([^"]*)"', nav_entries()[name]).group(1)
  198. problem = banner_problem(name, body, nav_status)
  199. assert problem is None, problem
  200. assert NOT_RUN.search(body[:6000]) or "run" in banner_of(body).lower(), fail(name, "says what was not run", "no 'Not run' statement near the top")
  201. @pytest.mark.parametrize("name", LESSONS)
  202. def test_page_marks_what_was_not_run(name):
  203. problem = unrun_problem(name, text(name), cfg(name).get("unrun_marks_extra", ()))
  204. assert problem is None, problem
  205. @pytest.mark.parametrize("name", LESSONS)
  206. def test_page_claims_register_rows_all_have_a_known_status(name):
  207. body = text(name)
  208. c = cfg(name)
  209. rows = register_rows(body)
  210. assert len(rows) >= c["min_register_rows"], fail(name, "claims register size", f"{len(rows)} rows, expected at least {c['min_register_rows']}")
  211. exact = "status_words" in PAGES.get(name, {}).get("config", {}) # an exact list replaces the shared vocabulary
  212. words = tuple(c["status_words"]) if exact else tuple(c["status_words"]) + tuple(c.get("status_extra", ()))
  213. bad = rows_with_bad_status(body, words)
  214. assert not bad, fail(name, f"claims register status in {words}", bad)
  215. @pytest.mark.parametrize("name", LESSONS)
  216. def test_page_links_and_anchors_resolve(name):
  217. body = text(name)
  218. c = cfg(name)
  219. links = set(LINK.findall(body))
  220. assert len(links) >= c["min_links"], fail(name, "link guard collected too few links", f"{len(links)} < {c['min_links']}")
  221. assert not dead_links(body), fail(name, "every linked wiki page exists", dead_links(body))
  222. assert not dead_own_anchors(body), fail(name, "every in-page anchor points at a heading", dead_own_anchors(body))
  223. for needed in c.get("must_link", ()):
  224. assert needed in links, fail(name, "required link present", needed)
  225. for prefix in c.get("must_link_prefix", ()):
  226. hits = [t for t in set(LINK.findall(strip_generated_comment_blocks(body))) if t.startswith(prefix)]
  227. assert hits, fail(name, "sibling lesson is linked, not named in plain text", prefix)
  228. assert all((WIKI / f"{t}.md").exists() for t in hits), fail(name, "sibling link target exists", prefix)
  229. @pytest.mark.parametrize("name", LESSONS)
  230. def test_page_does_not_say_siblings_are_plain_text(name):
  231. body = strip_generated_comment_blocks(text(name))
  232. found = [w for w in SIBLING_WORDING if w in body]
  233. assert not found, fail(name, "no 'plain text until' sibling wording", found)
  234. @pytest.mark.parametrize("name", LESSONS)
  235. def test_page_is_registered_and_glossary_anchors_resolve(name):
  236. c = cfg(name)
  237. line = nav_entries()[name]
  238. for extra in c.get("nav_contains", ()):
  239. assert extra in line, fail(name, "nav entry carries", extra)
  240. for special in NAV_PLACES:
  241. if special in c.get("nav_places_skip", ()):
  242. continue
  243. if special == "_Sidebar.md" and name in series_sidebar_entries():
  244. # A page folded into a series (issue #559) shows in the sidebar as its series line, a link to the
  245. # first page of the series; Contents still lists it by file name.
  246. shown = series_sidebar_entries()[name]
  247. assert shown in read(WIKI / special), fail(name, "registered in the sidebar as its series entry", shown)
  248. continue
  249. assert f"{name}.md" in read(WIKI / special), fail(name, "registered in navigation file", special)
  250. assert glossary_rows(name) >= c["min_glossary_rows"], fail(name, "glossary rows for the new terms", f"{glossary_rows(name)} < {c['min_glossary_rows']}")
  251. anchors = glossary_anchors(name)
  252. if c["min_glossary_rows"] > 0:
  253. assert anchors, fail(name, "glossary guard collected nothing", "no Glossary.md row links an anchor of this page")
  254. heads = {a for _, _, a in gen_wiki_nav.page_headings(text(name))}
  255. assert anchors <= heads, fail(name, "glossary anchors resolve", sorted(anchors - heads))
  256. # -- the generic guards bite (negative cases) -------------------------------------------------------------------
  257. REGISTER_BAD = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | y | maybe |\n| Z | y | |\n"
  258. def test_guard_bites_register_status():
  259. assert rows_with_bad_status(REGISTER_BAD, ("Read",)) == ["X", "Z"]
  260. assert rows_with_bad_status("## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | y | Read |\n", ("Read",)) == []
  261. def test_guard_finds_series_pages_by_their_series_entry():
  262. entries = series_sidebar_entries()
  263. assert len(entries) >= 11, "the series guard collected too few pages"
  264. assert entries["Deception-and-Honeypots-Cloud-Cowrie-Weekend"] == "[Deception and honeypots](Deception-and-Honeypots-Start-Here.md)"
  265. assert entries["Deception-and-Honeypots-Cloud-Cowrie-Weekend"] in read(WIKI / "_Sidebar.md")
  266. assert "[Not the series](Deception-and-Honeypots-Start-Here.md)" not in read(WIKI / "_Sidebar.md")
  267. assert "Deception-and-Honeypots-Cloud-Cowrie-Weekend.md" in read(WIKI / "Contents.md")
  268. def test_guard_bites_addresses():
  269. assert addresses_outside("ping 192.0.2.7", ()) == ["192.0.2.7"]
  270. assert addresses_outside("ping 127.0.0.1", (r"127\.0\.0\.1",)) == []
  271. assert addresses_outside("ping 127.0.0.2", (r"127\.0\.0\.1",)) == ["127.0.0.2"]
  272. def test_guard_bites_links_and_anchors():
  273. assert dead_links("see [x](No-Such-Page-Anywhere.md)") == ["No-Such-Page-Anywhere"]
  274. assert dead_links(f"see [x]({LESSONS[0]}.md#a)") == []
  275. assert dead_own_anchors("# Title\n\n[x](#no-such-heading)") == ["no-such-heading"]
  276. assert dead_own_anchors("# Title\n\n[x](#title)") == []
  277. UUID_REAL = "3f2a9c1e-7b44-4d0a-9e51-8c6d2b7a1f03" # shaped like a real id, made up for this test
  278. def test_guard_bites_identifiers():
  279. assert identifier_findings("-----BEGIN RSA PRIVATE KEY-----")
  280. assert identifier_findings("key " + "AKIA" + "ABCDEFGHIJKLMNOP") == ["AWS access key id"]
  281. assert not identifier_findings("nothing secret here")
  282. # every kind in the gate's pattern list, not just the first Azure form
  283. assert identifier_findings(f"az group list --id /subscriptions/{UUID_REAL}/resourceGroups/x") == ["Azure subscription id in a resource path"]
  284. assert identifier_findings(f"https://login.microsoftonline.com/{UUID_REAL}/oauth2/v2.0/token") == ["Azure tenant id in a sign-in URL"]
  285. assert identifier_findings("arn:aws:iam::" + "210987654321" + ":role/x") == ["AWS ARN account id"]
  286. assert "GCP project id" in identifier_findings("project_id = \"real-looking-proj-4821\"")
  287. # the documented placeholder forms stay allowed
  288. assert not identifier_findings("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/x")
  289. assert not identifier_findings("https://login.microsoftonline.com/11111111-1111-1111-1111-111111111111/oauth2")
  290. assert not identifier_findings("arn:aws:iam::123456789012:role/x")
  291. name = LESSONS[0]
  292. assert "rule" in identifier_problem(name, f"/subscriptions/{UUID_REAL}/x") and name in identifier_problem(name, f"/subscriptions/{UUID_REAL}/x")
  293. assert identifier_problem(name, "clean") is None
  294. UNDATED = "# T\n\n> **Status: unverified draft. Nothing was run.** No date here.\n\nIntro written on 2026-11-07.\n"
  295. def test_guard_bites_banner_date_and_unrun_marker():
  296. # the date must be in the banner itself: a date in the introduction does not count
  297. problem = banner_problem("P", UNDATED, "draft")
  298. assert problem and "P" in problem and "dated" in problem
  299. assert banner_problem("P", UNDATED.replace("No date here.", "Read on 2026-11-07."), "draft") is None
  300. # an unrun statement anywhere in the page needs a mark
  301. middle = "# T\n\n> **Status: unverified draft, 2026-11-07. Nothing was run.**\n\n## Body\n\nI did not run X.\n"
  302. problem = unrun_problem("P", middle)
  303. assert problem and "P" in problem and "mark" in problem
  304. assert unrun_problem("P", middle + "\nThe step is **est.**\n") is None
  305. def test_guard_bites_banner():
  306. assert banner_of("# T\n\n> **Status: unverified draft. Nothing was run.**\n\ntext") != ""
  307. assert banner_of("# T\n\nno banner here") == ""
  308. assert not HONEST.search("> **Status: fine.**")
  309. # -- per-lesson rows ---------------------------------------------------------------------------------------------
  310. def section(body: str, start: str, end: str | None = None) -> str:
  311. assert start in body, f"section start {start!r} not found"
  312. rest = body.split(start, 1)[1]
  313. if end is not None:
  314. assert end in rest, f"section end {end!r} not found after {start!r}"
  315. rest = rest.split(end, 1)[0]
  316. return rest
  317. def check_row(name: str, row: dict) -> None:
  318. """Evaluate one data row against its page. Every assertion message names the page, the row and the rule."""
  319. body = text(name)
  320. rid = f"[{name}] row '{row['id']}'"
  321. scope = section(body, row["start"], row.get("end")) if "start" in row else body
  322. for needle in row.get("contains", ()):
  323. assert needle in scope, f"{rid}: missing {needle!r}"
  324. for needle in row.get("contains_ci", ()):
  325. assert needle.lower() in scope.lower(), f"{rid}: missing (any case) {needle!r}"
  326. if "contains_any" in row:
  327. assert any(n in scope for n in row["contains_any"]), f"{rid}: none of {row['contains_any']} is present"
  328. for needle in row.get("absent", ()):
  329. assert needle not in scope, f"{rid}: must not contain {needle!r}"
  330. for needle, allowed in row.get("absent_except", ()): # the needle may appear only inside the allowed phrase
  331. assert needle not in scope.replace(allowed, ""), f"{rid}: {needle!r} appears outside {allowed!r}"
  332. for needle, n in row.get("count_at_least", {}).items():
  333. assert scope.count(needle) >= n, f"{rid}: {needle!r} appears {scope.count(needle)} times, expected at least {n}"
  334. for pattern, n in row.get("regex_count_at_least", {}).items():
  335. got = len(re.findall(pattern, scope, re.MULTILINE))
  336. assert got >= n, f"{rid}: /{pattern}/ matched {got} times, expected at least {n}"
  337. for pattern in row.get("regex_absent", ()):
  338. assert not re.search(pattern, scope), f"{rid}: /{pattern}/ must not match"
  339. for pattern in row.get("regex_present", ()):
  340. assert re.search(pattern, scope), f"{rid}: /{pattern}/ must match"
  341. for first, second in row.get("order", ()):
  342. assert first in scope and second in scope, f"{rid}: order needles missing ({first!r}, {second!r})"
  343. assert scope.index(first) < scope.index(second), f"{rid}: {first!r} must come before {second!r}"
  344. for first, second in row.get("order_before_last", ()): # first occurrence of `first` before the LAST `second`
  345. assert first in scope and second in scope, f"{rid}: order needles missing ({first!r}, {second!r})"
  346. assert scope.index(first) < scope.rindex(second), f"{rid}: {first!r} must come before the last {second!r}"
  347. if "startswith" in row:
  348. assert body.startswith(row["startswith"]), f"{rid}: page must start with {row['startswith']!r}"
  349. for target in row.get("links_in_scope", ()):
  350. assert f"]({target}.md)" in scope, f"{rid}: no link to {target}"
  351. assert (WIKI / f"{target}.md").exists(), f"{rid}: {target} does not exist"
  352. if "register_row" in row: # the first register row whose first cell has all `select` words must also have the rest
  353. want = row["register_row"]
  354. picked = [r for r in register_rows(body) if all(w in r[0] for w in want["select"])]
  355. assert picked, f"{rid}: no claims register row selected by {want['select']}"
  356. assert all(w in picked[0][0] for w in want.get("first_has", ())), f"{rid}: register row {picked[0][0][:60]!r} lacks {want.get('first_has')}"
  357. assert all(w in picked[0][1] for w in want.get("second_has", ())), f"{rid}: register row source cell lacks {want.get('second_has')}"
  358. if "inbound_min" in row:
  359. skip = {*GLOSSARY_FILES, "_Sidebar.md", "Reading-Order.md", "Contents.md", f"{name}.md"}
  360. inbound = [p.name for p in WIKI.glob("*.md") if p.name not in skip and f"{name}.md" in p.read_text(encoding="utf-8")]
  361. assert len(inbound) >= row["inbound_min"], f"{rid}: only {len(inbound)} inbound lessons link here: {inbound}"
  362. for lesson in row.get("inbound_all", ()):
  363. assert f"{name}.md" in page_text(WIKI / f"{lesson}.md"), f"{rid}: {lesson} does not link this lesson"
  364. urls = re.findall(r"\]\((https?://[^)]+)\)", body)
  365. if "urls_min" in row:
  366. assert len(urls) >= row["urls_min"], f"{rid}: the url guard collected {len(urls)} urls"
  367. if "url_forbid" in row:
  368. bad = urls_matching(urls, row["url_forbid"])
  369. assert not bad, f"{rid}: forbidden url form {bad}"
  370. if "code" in row:
  371. check_code(rid, body, row["code"])
  372. if "numbered_items_min" in row:
  373. got = len(re.findall(r"^\d+\. ", scope, re.MULTILINE))
  374. assert got >= row["numbered_items_min"], f"{rid}: {got} numbered items, expected at least {row['numbered_items_min']}"
  375. for vendor, must in row.get("vendor_sections", {}).items():
  376. sec = vendor_section(body, vendor)
  377. for needle in must:
  378. assert needle in sec, f"{rid}: section '### {vendor}' lacks {needle!r}"
  379. def vendor_section(body: str, heading: str) -> str:
  380. start = body.index(f"### {heading}")
  381. first_line_end = body.index("\n", start) + 1
  382. rest = body[first_line_end:]
  383. nxt = re.search(r"^#{2,3} ", rest, re.MULTILINE)
  384. return body[start : first_line_end + (nxt.start() if nxt else len(rest))]
  385. def urls_matching(urls: list[str], pattern: str) -> list[str]:
  386. return [u for u in urls if re.search(pattern, u, re.IGNORECASE)]
  387. def matches_in(commands: str, pattern: str, flags: int = 0) -> list[str]:
  388. """Every match of `pattern` in the commands, as the line it starts on (the pattern may span a line break)."""
  389. found = []
  390. for m in re.finditer(pattern, commands, flags):
  391. start = commands.rfind("\n", 0, m.start()) + 1
  392. end = commands.find("\n", m.end())
  393. found.append(commands[start : end if end != -1 else len(commands)].strip())
  394. return found
  395. def check_code(rid: str, body: str, code: dict) -> None:
  396. """A code-block guard: collect loosely (the blocks must contain `require`), assert strictly (nothing matches
  397. `forbid`; `count_at_least` maps a regex to a minimum), and prove the guard fires on every `bite_bad` sample
  398. and stays quiet on every `bite_good` sample."""
  399. flags = re.IGNORECASE if code.get("ignorecase") else 0
  400. tags = tuple(code.get("tags", ()))
  401. chunks = [b for t, b in FENCE.findall(body) if not tags or t in tags]
  402. cmds = "\n".join(textwrap.dedent(c) for c in chunks)
  403. for needle in code.get("require", ()):
  404. assert needle in cmds, f"{rid}: the code guard collected nothing ({needle!r} not in the {tags or 'all'} blocks)"
  405. for pattern, n in code.get("count_at_least", {}).items():
  406. got = len(re.findall(pattern, cmds, flags))
  407. assert got >= n, f"{rid}: the code guard collected {got} matches of /{pattern}/, expected at least {n}"
  408. bad = matches_in(cmds, code["forbid"], flags)
  409. assert not bad, f"{rid}: forbidden command in a code block: {bad}"
  410. for sample in code.get("bite_bad", ()):
  411. assert matches_in(sample, code["forbid"], flags), f"{rid}: the guard does not bite on {sample!r}"
  412. for sample in code.get("bite_good", ()):
  413. assert not matches_in(sample, code["forbid"], flags), f"{rid}: the guard fires on the allowed {sample!r}"
  414. def _rows():
  415. for name, spec in sorted(PAGES.items()):
  416. for row in spec.get("rows", ()):
  417. yield pytest.param(name, row, id=f"{name[:40]}::{row['id']}")
  418. @pytest.mark.parametrize(("name", "row"), list(_rows()))
  419. def test_lesson_specific_row(name, row):
  420. check_row(name, row)
  421. def test_every_row_has_an_id_and_something_to_assert():
  422. keys = {"contains", "absent", "count_at_least", "regex_count_at_least", "regex_absent", "regex_present", "order", "order_before_last", "contains_ci", "contains_any", "absent_except", "startswith", "links_in_scope", "register_row", "inbound_min", "inbound_all", "urls_min", "url_forbid", "code", "numbered_items_min", "vendor_sections"}
  423. ids = set()
  424. for name, spec in PAGES.items():
  425. for row in spec.get("rows", ()):
  426. assert row.get("id"), f"{name}: a row without an id"
  427. assert (name, row["id"]) not in ids, f"{name}: duplicate row id {row['id']}"
  428. ids.add((name, row["id"]))
  429. assert keys & set(row), f"{name}: row {row['id']} asserts nothing"
  430. def test_row_engine_bites():
  431. page = LESSONS[0]
  432. with pytest.raises(AssertionError, match="missing"):
  433. check_row(page, {"id": "x", "contains": ["zzz-not-in-any-page-zzz"]})
  434. with pytest.raises(AssertionError, match="must not contain"):
  435. check_row(page, {"id": "x", "absent": ["# "]})
  436. with pytest.raises(AssertionError, match="must come before"):
  437. t = text(page)
  438. check_row(page, {"id": "x", "order": [(t[-30:].strip().splitlines()[-1][:20], t[:20])]})
  439. with pytest.raises(AssertionError, match="does not bite"):
  440. check_row(page, {"id": "x", "code": {"forbid": "zzz-never", "bite_bad": ["nothing"]}})
  441. assert matches_in("sudo flashrom -w x", r"\bsudo\b|\bflashrom\b")
  442. assert not matches_in("cat /sys/x", r"\bsudo\b|\bflashrom\b")
  443. assert urls_matching(["https://example.com/p?ref=abc"], r"[?&]ref=")
  444. assert not urls_matching(["https://example.com/p"], r"[?&]ref=")
  445. sample = "### A\nFirmware ME\n### B\nother\n"
  446. assert "Firmware ME" in vendor_section(sample, "A")
  447. assert "other" not in vendor_section(sample, "A")
  448. # -- tests that run external tools: kept as code, listed in the PR body -------------------------------------------
  449. def _first(body: str, tag: str, needle: str) -> str:
  450. return next(b for b in blocks(body, tag) if needle in b)
  451. @pytest.mark.skipif(shutil.which("qemu-img") is None, reason="qemu-img is not installed")
  452. def test_vm_exercise_3_runs_and_the_snapshot_round_trips(tmp_path):
  453. body = text("Virtual-Machines-Hypervisors-Desktop-and-Datacenter-Options")
  454. script = _first(body, "bash", "qemu-img create").replace("cd ~/vmlab", f"cd {tmp_path}")
  455. result = subprocess.run(["bash", "-eu", "-c", script], capture_output=True, text=True, timeout=60, check=False)
  456. assert result.returncode == 0, result.stderr
  457. assert "virtual size: 4 GiB" in result.stdout
  458. assert "clean-start" in result.stdout
  459. # the last listing, after the delete, shows no snapshot line after the final info block
  460. assert result.stdout.count("clean-start") == 1
  461. @pytest.mark.skipif(shutil.which("openssl") is None, reason="openssl is not installed")
  462. def test_hsm_part_a_signs_verifies_and_fails_on_a_changed_message(tmp_path):
  463. body = text("Hardware-Security-Modules-What-They-Are-and-Building-Your-Own-with-pico2hsm")
  464. block = _first(body, "bash", "ecparam")
  465. steps = block.replace("mkdir -p ~/hsmlab && cd ~/hsmlab", f"cd {tmp_path}").split("# 4.")[0] # up to the first verify
  466. ok = subprocess.run(["bash", "-eu", "-c", steps], capture_output=True, text=True, timeout=60, check=False)
  467. assert ok.returncode == 0, ok.stderr
  468. assert "Verified OK" in ok.stdout + ok.stderr
  469. bad = subprocess.run(
  470. ["bash", "-c", f"cd {tmp_path} && echo tamper >> msg.txt && openssl dgst -sha256 -verify pub.der -keyform DER -signature sig.bin msg.txt"],
  471. capture_output=True,
  472. text=True,
  473. timeout=60,
  474. check=False,
  475. )
  476. assert bad.returncode != 0
  477. @pytest.mark.skipif(shutil.which("ansible-playbook") is None, reason="ansible-playbook is not installed")
  478. def test_ansible_playbook_is_idempotent_and_the_bad_task_is_not(tmp_path):
  479. body = text("Ansible-Configuration-Management-Versus-Provisioning")
  480. recap = re.compile(r"ok=(\d+)\s+changed=(\d+)")
  481. inventory = next(b for b in blocks(body, "ini") if "[lab]" in b)
  482. playbook = next(b for b in blocks(body, "yaml") if "Make a small config directory" in b)
  483. bad = next(b for b in re.findall(r"cat > bad\.yml <<'EOF'\n(.*?)\nEOF", "\n".join(blocks(body, "bash")), re.DOTALL))
  484. (tmp_path / "inventory.ini").write_text(inventory, encoding="utf-8")
  485. (tmp_path / "site.yml").write_text(playbook, encoding="utf-8")
  486. (tmp_path / "bad.yml").write_text(bad, encoding="utf-8")
  487. def run(play: str) -> tuple[int, int]:
  488. out = subprocess.run(["ansible-playbook", "-i", "inventory.ini", play], cwd=tmp_path, capture_output=True, text=True, timeout=120, check=False)
  489. assert out.returncode == 0, out.stdout + out.stderr
  490. m = recap.search(out.stdout)
  491. assert m, out.stdout
  492. return int(m.group(1)), int(m.group(2))
  493. assert run("site.yml") == (3, 3)
  494. assert run("site.yml") == (3, 0)
  495. assert run("bad.yml")[1] == 1 and run("bad.yml")[1] == 1
  496. assert (tmp_path / "sandbox" / "bad.conf").read_text(encoding="utf-8").count("retries = 3") == 2