| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203 |
- # SPDX-License-Identifier: Apache-2.0
- """The rate limiting lesson is a short hub and parts, none of them long (issue #562).
- 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
- banners, plus numbered part pages. The hub must list every part, each part must link back to the hub and stay under
- a line cap, the manifest must hold the pages as one series with the hub first, and every exercise the hub indexes must
- point at a part that really holds that heading. The parts are compared with a record of the pre-split page (a list of
- its headings with line counts, and a digest of every fenced line), not with themselves, so a part that loses or repeats
- a section, an exercise or a code block fails.
- """
- import re
- import sys
- from pathlib import Path
- sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
- import gen_wiki_nav as gwn
- from test_stale_sibling_statements import split_inventory
- from wikitext import page_text
- ROOT = Path(__file__).resolve().parent.parent
- WIKI = ROOT / "docs" / "wiki"
- STEM = "Rate-Limiting-at-Every-Layer"
- SERIES = "Rate limiting at every layer"
- MAX_PART_LINES = 450
- PARTS = (
- f"{STEM}-Part-1-Words-Algorithms-and-What-to-Count-By",
- f"{STEM}-Part-2-Each-Layer-and-the-Lab-Setup",
- f"{STEM}-Part-3-Lab-Exercises-3-to-7",
- f"{STEM}-Part-4-Quota-Threat-Model-and-Claims",
- )
- LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#([^)]*))?\)")
- def part_names(wiki: Path) -> list[str]:
- return sorted(p.stem for p in wiki.glob(f"{STEM}-Part-*.md"))
- def split_problems(wiki: Path, cap: int = MAX_PART_LINES, expected: tuple[str, ...] = PARTS) -> list[str]:
- """Every way the split is broken: a part missing or extra, one the hub does not list, a long part, no way back."""
- parts = part_names(wiki)
- problems = []
- if tuple(parts) != tuple(sorted(expected)):
- problems.append(f"parts are {parts}, expected {sorted(expected)}")
- hub = page_text(wiki / f"{STEM}.md")
- linked = [name for name, _ in LINK.findall(hub)]
- for name in parts:
- if name not in linked:
- problems.append(f"the hub does not list {name}")
- text = page_text(wiki / f"{name}.md")
- lines = len(text.splitlines())
- if lines > cap:
- problems.append(f"{name} is {lines} lines, over {cap}")
- if f"]({STEM}.md)" not in text:
- problems.append(f"{name} does not link back to the hub")
- return problems
- def test_the_hub_lists_every_part_and_each_part_is_short():
- assert part_names(WIKI) == sorted(PARTS)
- assert split_problems(WIKI) == []
- def test_every_exercise_the_hub_indexes_is_a_heading_of_the_part_it_names():
- hub = page_text(WIKI / f"{STEM}.md")
- index = [(n, a) for n, a in LINK.findall(hub) if n.startswith(f"{STEM}-Part-") and a]
- assert len(index) >= 8, "the hub indexes fewer than the eight exercises"
- for name, anchor in index:
- text = page_text(WIKI / f"{name}.md")
- assert anchor in {gwn.slug(h) for h in re.findall(r"^#{2,3} (.+)$", text, re.MULTILINE)}, (name, anchor)
- def test_the_manifest_holds_hub_and_parts_as_one_series_hub_first():
- m = gwn.read_manifest(ROOT)
- group = next(g["id"] for g in gwn.groups_of(m) if any(e["page"] == STEM for e in gwn.entries(m, g["id"])))
- rows = [e for e in gwn.entries(m, group) if e.get("series") == SERIES]
- assert [e["page"] for e in rows] == [STEM, *PARTS]
- def test_the_split_check_bites(tmp_path):
- wiki = tmp_path
- for name in (STEM, *(f"{STEM}-Part-{i}-X" for i in (1, 2, 3))):
- body = "\n".join(["line"] * 10)
- (wiki / f"{name}.md").write_text(f"# t\n\n{body}\n[hub]({STEM}.md)\n", encoding="utf-8")
- hub = "\n".join(f"- [p]({STEM}-Part-{i}-X.md)" for i in (1, 2, 3))
- (wiki / f"{STEM}.md").write_text(f"# hub\n\n{hub}\n", encoding="utf-8")
- fake = tuple(f"{STEM}-Part-{i}-X" for i in (1, 2, 3))
- assert split_problems(wiki, expected=fake) == []
- assert any("expected" in p for p in split_problems(wiki, expected=(*fake, f"{STEM}-Part-4-X")))
- (wiki / f"{STEM}-Part-2-X.md").write_text("\n".join(["line"] * 500) + f"\n[hub]({STEM}.md)\n", encoding="utf-8")
- assert any("over" in p for p in split_problems(wiki, expected=fake))
- (wiki / f"{STEM}.md").write_text(f"# hub\n\n- [p]({STEM}-Part-1-X.md)\n", encoding="utf-8")
- assert any("does not list" in p for p in split_problems(wiki, expected=fake))
- (wiki / f"{STEM}-Part-3-X.md").write_text("# t\n", encoding="utf-8")
- assert any("does not link back" in p for p in split_problems(wiki, expected=fake))
- def anchor_problems(wiki: Path, stem: str = STEM) -> list[str]:
- """Every link into the hub or a part, from any wiki page, whose anchor is not a heading of the page it names."""
- names = {stem, *part_names(wiki)}
- link = re.compile(r"\]\(([A-Za-z0-9_-]*)\.md#([^)]*)\)|\]\(#([^)]*)\)")
- problems = []
- for path in sorted(wiki.glob("*.md")):
- for target, anchor, local in link.findall(page_text(path)):
- if local:
- target, anchor = path.stem, local
- if target not in names:
- continue
- headings = {gwn.slug(h) for h in re.findall(r"^#{1,6} (.+)$", page_text(wiki / f"{target}.md"), re.MULTILINE)}
- if anchor not in headings:
- problems.append(f"{path.name} links {target}#{anchor}, which is not a heading there")
- return problems
- def test_every_link_into_the_lesson_lands_on_a_heading_of_the_page_it_names():
- assert anchor_problems(WIKI) == []
- def test_the_banner_names_the_part_that_holds_the_claims_register_the_same_way_everywhere():
- link = f"[claims register]({PARTS[3]}.md#claims-register)"
- pages = [WIKI / f"{STEM}.md", *(WIKI / f"{n}.md" for n in PARTS)]
- for path in pages:
- text = page_text(path)
- assert link in text, path.name
- assert "](#claims-register)" not in text, f"{path.name} links the register without naming its part"
- assert "## Claims register" in page_text(WIKI / f"{PARTS[3]}.md")
- def test_the_anchor_check_bites(tmp_path):
- (tmp_path / f"{STEM}.md").write_text(f"# hub\n\n- [a]({STEM}-Part-1-X.md#real)\n", encoding="utf-8")
- (tmp_path / f"{STEM}-Part-1-X.md").write_text("# t\n\n## Real\n\n[x](#missing)\n", encoding="utf-8")
- for i in (2, 3):
- (tmp_path / f"{STEM}-Part-{i}-X.md").write_text("# t\n", encoding="utf-8")
- problems = anchor_problems(tmp_path)
- assert problems == [f"{STEM}-Part-1-X.md links {STEM}-Part-1-X#missing, which is not a heading there"]
- SPLIT_SECTIONS = (
- ('What you will be able to do', 10),
- ('What the wiki already says (and the gap)', 9),
- ('First, the words', 7),
- ('Why rate limit', 9),
- ('The algorithms', 12),
- ('Exercise 1: run all four and watch the burst', 99),
- ('What to count by', 10),
- ('The three ways an address lies', 3),
- ('Trusting `X-Forwarded-For`', 5),
- ('Exercise 2: count by the wrong key and see who gets hurt', 44),
- ('Think at each level', 14),
- ('The upstream network', 1),
- ('DNS', 17),
- ('The CDN or WAF edge', 4),
- ('The load balancer', 1),
- ('The reverse proxy: Nginx and HAProxy', 16),
- ('The application and the framework', 2),
- ('Login, password reset and one-time codes', 5),
- ('API per-token quotas', 3),
- ('Database and connection pools', 2),
- ('The host firewall and the kernel', 5),
- ('When one address is not one attacker', 6),
- ('Fail open or fail closed', 6),
- ('The honest cost to real people', 7),
- ('Observability: a limit nobody can see is an outage nobody can explain', 6),
- ('Layers must not hide each other', 6),
- ('Only your own lab', 1),
- ('Free path: a lab on your own computer', 1),
- ('Setup for the Nginx lab: files and a container', 103),
- ('Exercise 3: a client that sees 429 and Retry-After', 104),
- ('Exercise 4: connections, not requests', 10),
- ('Exercise 5: spoof `X-Forwarded-For`, then fix it', 61),
- ('Exercise 6: read the evidence, then try the limit safely', 25),
- ('Exercise 7: the firewall layer, in a private namespace', 125),
- ('Exercise 8: a token bucket per API key, with a quota', 84),
- ('Optional: your own accounts', 4),
- ('Build, break, detect, evade, defend', 28),
- ('Flip the board', 29),
- ('A threat model for a limiter', 17),
- ('Checkpoint', 9),
- ('Common mistakes', 12),
- ('Claims register', 36),
- )
- SPLIT_CODE_DIGEST = '5eaf5f92d26d12593ba5b29cefdae70a67ec8f960cb56fd72304769399f06cd0'
- HEADINGS_ADDED = "(from the free path of the original page)"
- def test_the_parts_hold_every_section_of_the_old_page_once():
- """Compared with the pre-split page (git show 100054e:docs/wiki/Rate-Limiting-at-Every-Layer.md, issue #562)."""
- texts = [page_text(WIKI / f"{name}.md") for name in PARTS]
- sections, digest = split_inventory(texts)
- sections = [s for s in sections if HEADINGS_ADDED not in s[0]] # the two headings the split added
- assert tuple(sections) == SPLIT_SECTIONS
- assert digest == SPLIT_CODE_DIGEST
- assert sum(h.startswith("Exercise ") for h, _ in sections) == 8
- def test_the_split_inventory_bites_when_a_section_is_lost_or_repeated():
- texts = [page_text(WIKI / f"{name}.md") for name in PARTS]
- lost = [texts[0], re.sub(r"## Layers must not hide each other.*?(?=## Only your own lab)", "", texts[1], flags=re.DOTALL), *texts[2:]]
- assert lost[1] != texts[1], "the section to delete was not found"
- assert split_inventory(lost) != split_inventory(texts)
- assert split_inventory([*texts, texts[0]]) != split_inventory(texts)
|