# SPDX-License-Identifier: Apache-2.0 """The IDS and IPS lesson is a short hub and parts, none of them long (issue #562). The lesson was one page of about 1,060 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 text itself moved verbatim: the parts are compared with a record of the pre-split page (its headings with their line counts and a digest of every fenced code line), not with themselves. """ 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 = "IDS-and-IPS-Snort-and-Suricata" SERIES = "IDS and IPS" MAX_PART_LINES = 450 PARTS = ( f"{STEM}-Part-1-Concepts-Engines-Rules-and-Tuning", f"{STEM}-Part-2-The-Free-Lab-Setup-and-Exercises-1-to-3", f"{STEM}-Part-3-Exercises-4-to-8-Breaking-Tuning-and-Evading", f"{STEM}-Part-4-Live-Sensor-Threat-Model-the-Loop-and-Claims", ) LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#([^)]*))?\)") LOCAL_LINK = re.compile(r"\]\(#([^)]+)\)") def part_names(wiki: Path) -> list[str]: return sorted(p.stem for p in wiki.glob(f"{STEM}-Part-*.md")) def anchors_of(text: str) -> set[str]: return {gwn.slug(h) for h in re.findall(r"^#{2,3} (.+)$", text, re.MULTILINE)} 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: assert anchor in anchors_of(page_text(WIKI / f"{name}.md")), (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] assert len({e.get("subgroup") for e in rows}) == 1 assert all(len(e["title"]) <= 80 for e in rows) 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)) # --- promises that live in one part are links to it, and the pages read in order ------------------------------ def page_paths() -> list[Path]: return [WIKI / f"{STEM}.md", *(WIKI / f"{name}.md" for name in PARTS)] def banner_lines(text: str) -> list[str]: return [line for line in text.splitlines() if line.startswith(("> **Status:", "> **Prerequisites.**"))] def unlinked_promises(text: str) -> list[str]: """Banner lines that name the claims register, or say 'below', outside a link: the register is in one part.""" bad = [] for line in banner_lines(text): plain = re.sub(r"\[[^\]]*\]\([^)]*\)", "", line) if re.search(r"claims register|\bbelow\b", plain, re.IGNORECASE): bad.append(line[:80]) return bad def link_problems(text: str) -> list[str]: """A link to a lesson page whose file or anchor is missing, or a same-page anchor the page lacks.""" bad = [] for name, anchor in LINK.findall(text): if not name.startswith(STEM): continue target = WIKI / f"{name}.md" if not target.is_file(): bad.append(f"{name} is not a page") elif anchor and anchor not in anchors_of(page_text(target)): bad.append(f"{name}#{anchor} is not a heading") for anchor in LOCAL_LINK.findall(re.sub(r"```.*?```", "", text, flags=re.DOTALL)): if anchor not in anchors_of(text): bad.append(f"#{anchor} is not a heading of this page") return bad def test_every_page_repeats_the_same_banners_and_the_status_links_name_a_part(): banners = [banner_lines(page_text(p)) for p in page_paths()] assert all(len(b) == 2 for b in banners), "a page lacks its status or prerequisites banner" assert all(b == banners[0] for b in banners), "the banners differ between the hub and the parts" status = banners[0][0] assert f"]({PARTS[3]}.md#claims-register)" in status assert f"]({PARTS[1]}.md#" in status and f"]({PARTS[2]}.md#" in status for p in page_paths(): assert unlinked_promises(page_text(p)) == [], p.name def test_a_banner_that_promises_a_part_without_a_link_is_caught(): assert unlinked_promises("> **Status: x.** listed in the claims register, read 2026.") assert not unlinked_promises(f"> **Status: x.** listed in the [claims register]({PARTS[3]}.md#claims-register).") assert unlinked_promises("> **Status: x.** every command in Exercises 1 to 8 below") def test_every_link_inside_the_lesson_finds_its_page_and_heading(): checked = [link_problems(page_text(p)) for p in page_paths()] assert checked == [[]] * len(PARTS + (STEM,)), checked def test_the_link_check_bites(): assert link_problems("# a\n\n## Real\n\n[x](#real)\n") == [] assert link_problems("# a\n\n## Real\n\n[y](#gone)\n") == ["#gone is not a heading of this page"] assert link_problems(f"[z]({PARTS[0]}.md#no-such-heading)") == [f"{PARTS[0]}#no-such-heading is not a heading"] assert link_problems(f"[z]({STEM}-Part-9-Nothing.md)") == [f"{STEM}-Part-9-Nothing is not a page"] def test_each_part_starts_with_one_h1_then_an_h2_and_the_parts_chain_in_order(): for i, name in enumerate(PARTS): text = page_text(WIKI / f"{name}.md") levels = re.findall(r"^(#{1,3}) ", re.sub(r"```.*?```", "", text, flags=re.DOTALL), re.MULTILINE) assert levels[:2] == ["#", "##"] and levels.count("#") == 1, name nav = next(line for line in text.splitlines() if line.startswith(("Previous:", "Next:"))) assert (PARTS[i - 1] in nav) == (i > 0), name if i < len(PARTS) - 1: assert PARTS[i + 1] in nav, name else: assert "Next:" not in nav, name def test_no_page_links_the_old_single_page_with_an_anchor_that_moved(): hub_headings = anchors_of(page_text(WIKI / f"{STEM}.md")) seen = 0 for p in WIKI.glob("*.md"): if p.stem.startswith(STEM): continue for name, anchor in LINK.findall(p.read_text(encoding="utf-8")): if name == STEM: seen += 1 assert not anchor or anchor in hub_headings, f"{p.name} links {STEM}.md#{anchor}, which moved to a part" assert seen, "no page links the lesson" # Record of the old single page (before the split into parts, issue #562), taken from the commit before it # (git show 637c573:docs/wiki/IDS-and-IPS-Snort-and-Suricata.md): each `##`/`###` heading with its non-blank lines. SPLIT_SECTIONS = ( ('What you will be able to do', 12), ('The words, in plain language', 9), ('Passive and in line', 6), ('Network-based and host-based', 1), ('Signature and anomaly', 1), ('Where to put a sensor', 9), ('What encryption hides', 2), ('Snort 2, Snort 3 and Suricata', 14), ('What about "compatible rules"?', 1), ('Why this lesson uses Suricata', 1), ('Reading a rule', 33), ('Where rules come from', 11), ('Tuning', 7), ('False positives and false negatives', 3), ('Performance and sizing, at a concept level', 7), ('IDS and IPS on a firewall appliance: pfSense and OPNsense', 4), ('How alerts reach a SIEM', 7), ('Free path: a sensor on your own computer, offline', 1), ('Ground rules', 5), ('Where the Suricata comes from, and how far to trust it', 3), ('Setup', 166), ('Exercise 1: check your tools, pull the image, prove it is offline', 26), ('Exercise 2: build the capture, and read it before Suricata does', 20), ('Exercise 3: run the rules and read the alert', 50), ('Exercise 4: break the rule, and see which breaks are loud', 53), ('Exercise 5: tune the false positive', 48), ('Exercise 6: read the stats', 29), ('Exercise 7 (optional): capture your own loopback traffic', 43), ('Exercise 8: evade your own rule, then fix it', 38), ('Optional: a live sensor in a disposable virtual machine (shown, not run)', 7), ('Tamper and evade: how an attacker gets past a sensor (concept level)', 6), ('Threat model of the IDS itself', 11), ('Build, break, detect, evade, defend (the local loop)', 7), ('Flip the board', 21), ('Checkpoint', 11), ('Common mistakes', 11), ('What this page does not prove', 8), ('Where this shows up in this project', 6), ('Claims register', 37), ) SPLIT_CODE_DIGEST = 'dd7157914153d408f424a792b87b178f8067b5704587a699cadae44acfc236d6' def part_inventory(texts: list[str]) -> tuple[list[tuple[str, int]], str]: """The sections of the parts, with the heading the split added folded into the section it continues.""" sections, digest = split_inventory(texts) merged: list[list] = [] for heading, count in sections: if heading.startswith("Free path, continued") and merged: merged[-1][1] += count else: merged.append([heading, count]) return [(h, n) for h, n in merged], digest def part_texts() -> list[str]: return [page_text(WIKI / f"{name}.md") for name in PARTS] def test_the_parts_still_hold_every_section_of_the_old_page_once(): sections, digest = part_inventory(part_texts()) assert tuple(sections) == SPLIT_SECTIONS assert digest == SPLIT_CODE_DIGEST assert sum(h.startswith("Exercise ") for h, _ in sections) == 8 def test_the_inventory_bites_when_a_section_is_lost_repeated_or_a_code_line_changes(): texts = part_texts() base = part_inventory(texts) cut = re.sub(r"### Exercise 5:.*?(?=### Exercise 6:)", "", texts[2], flags=re.DOTALL) assert cut != texts[2] assert part_inventory([texts[0], texts[1], cut, texts[3]]) != base assert part_inventory([*texts, texts[0]]) != base changed = texts[2].replace("```bash", "```bash\n# extra", 1) assert changed != texts[2] assert part_inventory([texts[0], texts[1], changed, texts[3]])[1] != base[1]