test_telemetry_lessons.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. """Checks for the five telemetry lesson pages in docs/wiki/.
  2. The pages are unverified drafts (four describe merged but unapplied code), so these tests keep three things
  3. honest: each page says it is a draft and links its neighbors, nothing on them
  4. looks like a real address, and every figure in the mini SOC cost tables is
  5. recomputed here from docs/cost-prices.json rather than trusted.
  6. """
  7. import ipaddress
  8. import itertools
  9. import json
  10. import re
  11. from pathlib import Path
  12. import pytest
  13. ROOT = Path(__file__).resolve().parent.parent
  14. WIKI = ROOT / "docs" / "wiki"
  15. # Dependency order: each page assumes the ones before it.
  16. LESSONS = [
  17. "Cloud-Telemetry-What-and-Why",
  18. "Multiple-Sites-and-Identity",
  19. "Telemetry-Crosses-the-Trust-Boundary",
  20. "Reading-a-Dashboard-as-an-Operator",
  21. "Build-Your-Own-Mini-SOC",
  22. ]
  23. DESIGN_BANNER = "Unverified draft: written from the design, none of stage 2 has been built or applied"
  24. # Stage 2 telemetry is merged but nothing has been applied or run, so the four
  25. # pages that describe it say exactly that. The draft label stays.
  26. MERGED_BANNER = (
  27. "Unverified draft: the stage 2 telemetry pieces this page describes are built and merged "
  28. "(opt-in node exporter, Wazuh agent with auditd, metrics firewall rules, Grafana dashboards), "
  29. "but none of it has been applied or run against real infrastructure, and nothing has been measured"
  30. )
  31. # The operator page also points at the synthetic lab, where the inventory, the
  32. # two alert rules and the promtool fixtures are committed. Still a draft.
  33. LAB_BANNER = (
  34. "Unverified draft: the inventory, alert rules and promtool fixtures this page describes are built "
  35. "and merged in a synthetic monitoring lab, but nothing here has been applied or run against real "
  36. "infrastructure, and nothing has been measured"
  37. )
  38. BANNERS = {name: DESIGN_BANNER for name in LESSONS}
  39. BANNERS["Reading-a-Dashboard-as-an-Operator"] = LAB_BANNER
  40. BANNERS["Cloud-Telemetry-What-and-Why"] = MERGED_BANNER
  41. BANNERS["Multiple-Sites-and-Identity"] = MERGED_BANNER
  42. BANNERS["Telemetry-Crosses-the-Trust-Boundary"] = MERGED_BANNER
  43. BANNERS["Build-Your-Own-Mini-SOC"] = MERGED_BANNER
  44. def banner_is_honest(banner: str) -> bool:
  45. """Only an approved banner passes: the draft label stays and no extra claim may trail it."""
  46. return banner.startswith("Unverified draft") and banner.rstrip(".") in {DESIGN_BANNER, MERGED_BANNER, LAB_BANNER}
  47. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#([^)]*))?\)")
  48. def text(name: str) -> str:
  49. return (WIKI / f"{name}.md").read_text()
  50. def slug(heading: str) -> str:
  51. """GitHub's anchor for a heading: lower case, punctuation dropped."""
  52. heading = heading.strip().lower()
  53. heading = re.sub(r"[^\w\- ]", "", heading)
  54. return heading.replace(" ", "-")
  55. def anchors(name: str) -> set[str]:
  56. found = set()
  57. for line in text(name).splitlines():
  58. m = re.match(r"#{1,6}\s+(.*)", line)
  59. if m:
  60. found.add(slug(m.group(1)))
  61. return found
  62. @pytest.mark.parametrize("name", LESSONS)
  63. def test_page_has_status_banner_prerequisites_and_next(name):
  64. body = text(name)
  65. head = "\n".join(body.splitlines()[:4])
  66. assert f"**{BANNERS[name]}.**" in head, f"{name}: status banner missing from the top"
  67. assert re.search(r"^\*\*Prerequisites:\*\* .*\]\(", body, re.MULTILINE), f"{name}: no Prerequisites line"
  68. assert re.search(r"^Next: .*\]\(", body, re.MULTILINE), f"{name}: no Next line"
  69. def page_banner(name: str) -> str:
  70. """The first bold banner in a page's first lines, as written on the page."""
  71. head = "\n".join(text(name).splitlines()[:4])
  72. m = re.search(r"^> \*\*(Unverified draft.*?)\*\*", head, re.MULTILINE)
  73. assert m, f"{name}: no bold Unverified draft banner at the top"
  74. return m.group(1)
  75. @pytest.mark.parametrize("name", LESSONS)
  76. def test_every_page_banner_keeps_the_draft_label_and_claims_no_run(name):
  77. banner = page_banner(name)
  78. assert banner_is_honest(banner), f"{name}: {banner}"
  79. assert banner == BANNERS[name] + ".", f"{name}: banner differs from the pinned text"
  80. def test_pinned_banners_cover_every_lesson():
  81. assert set(BANNERS) == set(LESSONS)
  82. def test_banner_guard_rejects_a_verified_looking_banner():
  83. for bad in (
  84. "Verified: stage 2 telemetry is built and applied",
  85. "Unverified draft: the stage 2 telemetry is built and merged",
  86. "Draft: built and merged, none of it has been applied and nothing has been measured",
  87. MERGED_BANNER + " and applied",
  88. MERGED_BANNER + ", and verified.",
  89. DESIGN_BANNER + " and verified",
  90. LAB_BANNER + " and verified",
  91. ):
  92. assert not banner_is_honest(bad), bad
  93. @pytest.mark.parametrize("name", LESSONS)
  94. def test_page_has_a_predict_exercise_with_reference_answers(name):
  95. body = text(name)
  96. assert "Predict, then check" in body, f"{name}: no predict-then-check section"
  97. assert "Reference answers" in body, f"{name}: no reference answers"
  98. assert "Try it yourself" in body, f"{name}: no try-it-yourself list"
  99. @pytest.mark.parametrize("name", LESSONS)
  100. def test_every_wiki_link_and_anchor_resolves(name):
  101. problems = []
  102. for target, anchor in LINK.findall(text(name)):
  103. if not (WIKI / f"{target}.md").exists():
  104. problems.append(f"{target} (missing page)")
  105. elif anchor and anchor not in anchors(target):
  106. problems.append(f"{target}#{anchor} (missing anchor)")
  107. assert not problems, f"{name}: {problems}"
  108. def test_next_lines_follow_the_dependency_order():
  109. for earlier, later in itertools.pairwise(LESSONS):
  110. next_line = re.search(r"^Next: .*$", text(earlier), re.MULTILINE).group(0)
  111. assert f"({later}.md)" in next_line, f"{earlier}: Next should name {later}"
  112. def test_lessons_are_in_contents_and_reading_order_in_order():
  113. for page in ("Contents", "Reading-Order"):
  114. links = [t for t, _ in LINK.findall(text(page))]
  115. positions = [links.index(n) for n in LESSONS] # raises if missing
  116. assert positions == sorted(positions), f"{page}: lessons out of order"
  117. @pytest.mark.parametrize("name", LESSONS)
  118. def test_only_documentation_or_private_example_addresses(name):
  119. ok_nets = [
  120. ipaddress.ip_network(n)
  121. for n in ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24", "10.0.0.0/8")
  122. ]
  123. bad = []
  124. for ip in re.findall(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", text(name)):
  125. try:
  126. addr = ipaddress.ip_address(ip)
  127. except ValueError:
  128. continue
  129. if not any(addr in net for net in ok_nets):
  130. bad.append("address outside the documentation and example ranges")
  131. assert not bad, f"{name}: {len(bad)} finding(s)"
  132. # --- the cost tables -------------------------------------------------------
  133. PRICES = json.loads((ROOT / "docs" / "cost-prices.json").read_text())["droplets"]
  134. _APPROVED = json.loads((ROOT / "docs" / "stages" / "approved.json").read_text())
  135. CEILING = _APPROVED["phases"][_APPROVED["current_phase"]]["ceiling"]
  136. SITE_CONNECTORS = sum(
  137. PRICES[m["size"]]
  138. for m in json.loads((ROOT / "stacks" / "10-access" / "cost.json").read_text())["resources"]
  139. )
  140. # docs/cost.md, "Stage 3 estimate": option A is a s-1vcpu-2gb droplet, a flat
  141. # $5 bucket and the stage 1 connectors, $29 running.
  142. STAGE3_A = SITE_CONNECTORS + PRICES["s-1vcpu-2gb"] + 5
  143. MONEY = re.compile(r"\$(\d+(?:\.\d+)?)")
  144. def cost_tables():
  145. body = text("Build-Your-Own-Mini-SOC")
  146. tables = []
  147. for marker in re.finditer(r"<!-- cost-table ceiling=(\d+) -->\n\n((?:\|.*\n)+)", body):
  148. ceiling = float(marker.group(1))
  149. rows = [
  150. [c.strip() for c in line.strip().strip("|").split("|")]
  151. for line in marker.group(2).splitlines()[2:]
  152. ]
  153. tables.append((ceiling, rows))
  154. return tables
  155. def droplet_cost(cell: str) -> int:
  156. if cell == "none":
  157. return 0
  158. return sum(PRICES[slug_] for slug_ in re.findall(r"`([^`]+)`", cell))
  159. def test_site_connector_and_stage3_constants_match_the_repo():
  160. assert SITE_CONNECTORS == 12
  161. assert STAGE3_A == 29
  162. cost_doc = (ROOT / "docs" / "cost.md").read_text()
  163. assert "$29" in cost_doc and "$5 flat" in cost_doc
  164. def test_there_are_two_cost_tables_and_the_first_uses_the_real_ceiling():
  165. tables = cost_tables()
  166. assert len(tables) == 2
  167. assert tables[0][0] == CEILING
  168. def test_every_cost_figure_is_recomputed_from_the_price_file():
  169. for ceiling, rows in cost_tables():
  170. assert len(rows) == 7
  171. for option, droplets, one, two, with3, fits in rows:
  172. d = droplet_cost(droplets)
  173. expected = [
  174. (one, SITE_CONNECTORS, d),
  175. (two, 2 * SITE_CONNECTORS, d),
  176. (with3, STAGE3_A, d),
  177. ]
  178. for cell, base, add in expected:
  179. a, b, total = (float(x) for x in MONEY.findall(cell))
  180. assert (a, b, total) == (base, add, base + add), f"{option}: {cell}"
  181. fits_cells = [w.strip() for w in fits.split("/")]
  182. totals = [base + add for _, base, add in expected]
  183. want = ["Yes" if t <= ceiling else "No" for t in totals]
  184. assert fits_cells == want, f"{option} at ${ceiling:.0f}: {fits_cells} != {want}"
  185. def test_ceiling_36_reference_answer_matches_the_arithmetic():
  186. """The page's worked answer for a $36 ceiling, recomputed."""
  187. rows = cost_tables()[0][1]
  188. totals = []
  189. for _, droplets, *_ in rows:
  190. d = droplet_cost(droplets)
  191. totals.append((SITE_CONNECTORS + d, 2 * SITE_CONNECTORS + d, STAGE3_A + d))
  192. one = [t[0] for t in totals if t[0] <= 36]
  193. two = [t[1] for t in totals if t[1] <= 36]
  194. three = [t[2] for t in totals if t[2] <= 36]
  195. assert (len(one), len(two), len(three)) == (6, 3, 2)
  196. def _covered(checklist, cid):
  197. """True if cid is named alone or inside a numeric range like 'M1 to M3'."""
  198. letter, num = cid[0], int(cid[1:])
  199. if re.search(rf"\b{cid}\b", checklist):
  200. return True
  201. for lo, hi in re.findall(rf"\b{letter}(\d+) to {letter}(\d+)\b", checklist):
  202. if int(lo) <= num <= int(hi):
  203. return True
  204. return False
  205. def test_stage2_checklist_covers_every_verification_id():
  206. """The 7.0 checklist must mention every M/L/X check, and none may claim a result."""
  207. guide = (ROOT / "docs" / "stages" / "02-telemetry.md").read_text()
  208. _, _, rest = guide.partition("### 7.0 The checklist at a glance")
  209. assert rest, "section 7.0 is missing"
  210. checklist, _, detail = rest.partition("### 7.1 Metrics")
  211. ids = set(re.findall(r"^\| ([MLX]\d) \|", detail, re.MULTILINE))
  212. assert len(ids) >= 10, "collected too few check ids"
  213. for cid in sorted(ids):
  214. assert _covered(checklist, cid), cid
  215. assert "not run yet" in checklist
  216. assert not re.search(r"\bpassed on 20\d\d", checklist)
  217. def test_stage2_checklist_guard_bites():
  218. """Negative case: ranges are read numerically, so M1 to M2 does not cover M3."""
  219. assert not _covered("M1 to M2, X1, X2", "M3")
  220. assert not _covered("M1 to M3, X1, X2", "X3")
  221. assert _covered("M1 to M3", "M2")