test_ratelimit_split.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The rate limiting lesson is a short hub and parts, none of them long (issue #562).
  3. The lesson was one page of about 1,300 lines. It is now a hub that keeps the page name and URL, the intro and the
  4. banners, plus numbered part pages. The hub must list every part, each part must link back to the hub and stay under
  5. a line cap, the manifest must hold the pages as one series with the hub first, and every exercise the hub indexes must
  6. point at a part that really holds that heading. The parts are compared with a record of the pre-split page (a list of
  7. its headings with line counts, and a digest of every fenced line), not with themselves, so a part that loses or repeats
  8. a section, an exercise or a code block fails.
  9. """
  10. import re
  11. import sys
  12. from pathlib import Path
  13. sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
  14. import gen_wiki_nav as gwn
  15. from test_stale_sibling_statements import split_inventory
  16. from wikitext import page_text
  17. ROOT = Path(__file__).resolve().parent.parent
  18. WIKI = ROOT / "docs" / "wiki"
  19. STEM = "Rate-Limiting-at-Every-Layer"
  20. SERIES = "Rate limiting at every layer"
  21. MAX_PART_LINES = 450
  22. PARTS = (
  23. f"{STEM}-Part-1-Words-Algorithms-and-What-to-Count-By",
  24. f"{STEM}-Part-2-Each-Layer-and-the-Lab-Setup",
  25. f"{STEM}-Part-3-Lab-Exercises-3-to-7",
  26. f"{STEM}-Part-4-Quota-Threat-Model-and-Claims",
  27. )
  28. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#([^)]*))?\)")
  29. def part_names(wiki: Path) -> list[str]:
  30. return sorted(p.stem for p in wiki.glob(f"{STEM}-Part-*.md"))
  31. def split_problems(wiki: Path, cap: int = MAX_PART_LINES, expected: tuple[str, ...] = PARTS) -> list[str]:
  32. """Every way the split is broken: a part missing or extra, one the hub does not list, a long part, no way back."""
  33. parts = part_names(wiki)
  34. problems = []
  35. if tuple(parts) != tuple(sorted(expected)):
  36. problems.append(f"parts are {parts}, expected {sorted(expected)}")
  37. hub = page_text(wiki / f"{STEM}.md")
  38. linked = [name for name, _ in LINK.findall(hub)]
  39. for name in parts:
  40. if name not in linked:
  41. problems.append(f"the hub does not list {name}")
  42. text = page_text(wiki / f"{name}.md")
  43. lines = len(text.splitlines())
  44. if lines > cap:
  45. problems.append(f"{name} is {lines} lines, over {cap}")
  46. if f"]({STEM}.md)" not in text:
  47. problems.append(f"{name} does not link back to the hub")
  48. return problems
  49. def test_the_hub_lists_every_part_and_each_part_is_short():
  50. assert part_names(WIKI) == sorted(PARTS)
  51. assert split_problems(WIKI) == []
  52. def test_every_exercise_the_hub_indexes_is_a_heading_of_the_part_it_names():
  53. hub = page_text(WIKI / f"{STEM}.md")
  54. index = [(n, a) for n, a in LINK.findall(hub) if n.startswith(f"{STEM}-Part-") and a]
  55. assert len(index) >= 8, "the hub indexes fewer than the eight exercises"
  56. for name, anchor in index:
  57. text = page_text(WIKI / f"{name}.md")
  58. assert anchor in {gwn.slug(h) for h in re.findall(r"^#{2,3} (.+)$", text, re.MULTILINE)}, (name, anchor)
  59. def test_the_manifest_holds_hub_and_parts_as_one_series_hub_first():
  60. m = gwn.read_manifest(ROOT)
  61. group = next(g["id"] for g in gwn.groups_of(m) if any(e["page"] == STEM for e in gwn.entries(m, g["id"])))
  62. rows = [e for e in gwn.entries(m, group) if e.get("series") == SERIES]
  63. assert [e["page"] for e in rows] == [STEM, *PARTS]
  64. def test_the_split_check_bites(tmp_path):
  65. wiki = tmp_path
  66. for name in (STEM, *(f"{STEM}-Part-{i}-X" for i in (1, 2, 3))):
  67. body = "\n".join(["line"] * 10)
  68. (wiki / f"{name}.md").write_text(f"# t\n\n{body}\n[hub]({STEM}.md)\n", encoding="utf-8")
  69. hub = "\n".join(f"- [p]({STEM}-Part-{i}-X.md)" for i in (1, 2, 3))
  70. (wiki / f"{STEM}.md").write_text(f"# hub\n\n{hub}\n", encoding="utf-8")
  71. fake = tuple(f"{STEM}-Part-{i}-X" for i in (1, 2, 3))
  72. assert split_problems(wiki, expected=fake) == []
  73. assert any("expected" in p for p in split_problems(wiki, expected=(*fake, f"{STEM}-Part-4-X")))
  74. (wiki / f"{STEM}-Part-2-X.md").write_text("\n".join(["line"] * 500) + f"\n[hub]({STEM}.md)\n", encoding="utf-8")
  75. assert any("over" in p for p in split_problems(wiki, expected=fake))
  76. (wiki / f"{STEM}.md").write_text(f"# hub\n\n- [p]({STEM}-Part-1-X.md)\n", encoding="utf-8")
  77. assert any("does not list" in p for p in split_problems(wiki, expected=fake))
  78. (wiki / f"{STEM}-Part-3-X.md").write_text("# t\n", encoding="utf-8")
  79. assert any("does not link back" in p for p in split_problems(wiki, expected=fake))
  80. def anchor_problems(wiki: Path, stem: str = STEM) -> list[str]:
  81. """Every link into the hub or a part, from any wiki page, whose anchor is not a heading of the page it names."""
  82. names = {stem, *part_names(wiki)}
  83. link = re.compile(r"\]\(([A-Za-z0-9_-]*)\.md#([^)]*)\)|\]\(#([^)]*)\)")
  84. problems = []
  85. for path in sorted(wiki.glob("*.md")):
  86. for target, anchor, local in link.findall(page_text(path)):
  87. if local:
  88. target, anchor = path.stem, local
  89. if target not in names:
  90. continue
  91. headings = {gwn.slug(h) for h in re.findall(r"^#{1,6} (.+)$", page_text(wiki / f"{target}.md"), re.MULTILINE)}
  92. if anchor not in headings:
  93. problems.append(f"{path.name} links {target}#{anchor}, which is not a heading there")
  94. return problems
  95. def test_every_link_into_the_lesson_lands_on_a_heading_of_the_page_it_names():
  96. assert anchor_problems(WIKI) == []
  97. def test_the_banner_names_the_part_that_holds_the_claims_register_the_same_way_everywhere():
  98. link = f"[claims register]({PARTS[3]}.md#claims-register)"
  99. pages = [WIKI / f"{STEM}.md", *(WIKI / f"{n}.md" for n in PARTS)]
  100. for path in pages:
  101. text = page_text(path)
  102. assert link in text, path.name
  103. assert "](#claims-register)" not in text, f"{path.name} links the register without naming its part"
  104. assert "## Claims register" in page_text(WIKI / f"{PARTS[3]}.md")
  105. def test_the_anchor_check_bites(tmp_path):
  106. (tmp_path / f"{STEM}.md").write_text(f"# hub\n\n- [a]({STEM}-Part-1-X.md#real)\n", encoding="utf-8")
  107. (tmp_path / f"{STEM}-Part-1-X.md").write_text("# t\n\n## Real\n\n[x](#missing)\n", encoding="utf-8")
  108. for i in (2, 3):
  109. (tmp_path / f"{STEM}-Part-{i}-X.md").write_text("# t\n", encoding="utf-8")
  110. problems = anchor_problems(tmp_path)
  111. assert problems == [f"{STEM}-Part-1-X.md links {STEM}-Part-1-X#missing, which is not a heading there"]
  112. SPLIT_SECTIONS = (
  113. ('What you will be able to do', 10),
  114. ('What the wiki already says (and the gap)', 9),
  115. ('First, the words', 7),
  116. ('Why rate limit', 9),
  117. ('The algorithms', 12),
  118. ('Exercise 1: run all four and watch the burst', 99),
  119. ('What to count by', 10),
  120. ('The three ways an address lies', 3),
  121. ('Trusting `X-Forwarded-For`', 5),
  122. ('Exercise 2: count by the wrong key and see who gets hurt', 44),
  123. ('Think at each level', 14),
  124. ('The upstream network', 1),
  125. ('DNS', 17),
  126. ('The CDN or WAF edge', 4),
  127. ('The load balancer', 1),
  128. ('The reverse proxy: Nginx and HAProxy', 16),
  129. ('The application and the framework', 2),
  130. ('Login, password reset and one-time codes', 5),
  131. ('API per-token quotas', 3),
  132. ('Database and connection pools', 2),
  133. ('The host firewall and the kernel', 5),
  134. ('When one address is not one attacker', 6),
  135. ('Fail open or fail closed', 6),
  136. ('The honest cost to real people', 7),
  137. ('Observability: a limit nobody can see is an outage nobody can explain', 6),
  138. ('Layers must not hide each other', 6),
  139. ('Only your own lab', 1),
  140. ('Free path: a lab on your own computer', 1),
  141. ('Setup for the Nginx lab: files and a container', 103),
  142. ('Exercise 3: a client that sees 429 and Retry-After', 104),
  143. ('Exercise 4: connections, not requests', 10),
  144. ('Exercise 5: spoof `X-Forwarded-For`, then fix it', 61),
  145. ('Exercise 6: read the evidence, then try the limit safely', 25),
  146. ('Exercise 7: the firewall layer, in a private namespace', 125),
  147. ('Exercise 8: a token bucket per API key, with a quota', 84),
  148. ('Optional: your own accounts', 4),
  149. ('Build, break, detect, evade, defend', 28),
  150. ('Flip the board', 29),
  151. ('A threat model for a limiter', 17),
  152. ('Checkpoint', 9),
  153. ('Common mistakes', 12),
  154. ('Claims register', 36),
  155. )
  156. SPLIT_CODE_DIGEST = '5eaf5f92d26d12593ba5b29cefdae70a67ec8f960cb56fd72304769399f06cd0'
  157. HEADINGS_ADDED = "(from the free path of the original page)"
  158. def test_the_parts_hold_every_section_of_the_old_page_once():
  159. """Compared with the pre-split page (git show 100054e:docs/wiki/Rate-Limiting-at-Every-Layer.md, issue #562)."""
  160. texts = [page_text(WIKI / f"{name}.md") for name in PARTS]
  161. sections, digest = split_inventory(texts)
  162. sections = [s for s in sections if HEADINGS_ADDED not in s[0]] # the two headings the split added
  163. assert tuple(sections) == SPLIT_SECTIONS
  164. assert digest == SPLIT_CODE_DIGEST
  165. assert sum(h.startswith("Exercise ") for h, _ in sections) == 8
  166. def test_the_split_inventory_bites_when_a_section_is_lost_or_repeated():
  167. texts = [page_text(WIKI / f"{name}.md") for name in PARTS]
  168. lost = [texts[0], re.sub(r"## Layers must not hide each other.*?(?=## Only your own lab)", "", texts[1], flags=re.DOTALL), *texts[2:]]
  169. assert lost[1] != texts[1], "the section to delete was not found"
  170. assert split_inventory(lost) != split_inventory(texts)
  171. assert split_inventory([*texts, texts[0]]) != split_inventory(texts)