test_how_tor_works_lesson.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The how-Tor-works lesson: registered, honest about what was read, diagrammed, and safe to read.
  3. docs/wiki/How-Tor-Works-in-Depth-Circuits-Relays-Directory-Authorities-and-Onion-Services.md teaches the machinery
  4. under Tor with six diagrams. A banner that claims more than was run, a dead link, a missing registration, an onion
  5. address, a claim with no status or date, a diagram with no alt text, no source or no picture, or an unattributed
  6. statement of a number would each teach or reveal the wrong thing.
  7. """
  8. import json
  9. import re
  10. from pathlib import Path
  11. ROOT = Path(__file__).resolve().parent.parent
  12. WIKI = ROOT / "docs" / "wiki"
  13. NAME = "How-Tor-Works-in-Depth-Circuits-Relays-Directory-Authorities-and-Onion-Services"
  14. PAGE = WIKI / f"{NAME}.md"
  15. OVERVIEW = "Tor-I2P-and-the-Darknet-Without-the-Myths"
  16. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#[^)]*)?\)")
  17. ADDR = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
  18. ONION = re.compile(r"\b[a-z2-7]{16,56}\.(?:onion|b32\.i2p)\b")
  19. STATUS_WORDS = ("Read", "General knowledge", "**est.**")
  20. URL = re.compile(r"\]\(https://[^)\s]+\)")
  21. DIAGRAM = re.compile(
  22. r"!\[(?P<alt>[^\]\n]*)\]\((?P<path>images/[^)\n]+\.png)\)\n\n<details>\n<summary>Diagram source \(Mermaid\)</summary>"
  23. r"\n\n```mermaid\n(?P<src>.*?)\n```\n\n</details>",
  24. re.DOTALL,
  25. )
  26. IMAGE_ANY = re.compile(r"!\[[^\]\n]*\]\([^)\n]+\)")
  27. MAX_ALT = 150
  28. EXPECTED_DIAGRAMS = 6
  29. DATE_READ = "2026-11-01"
  30. # A long run of base32 or hex characters next to a key-like word is what the repository secret scan flags.
  31. LONG_RANDOM = re.compile(r"[A-Za-z0-9+/=_-]{32,}")
  32. def text() -> str:
  33. return PAGE.read_text(encoding="utf-8")
  34. def register_rows(body: str) -> list[list[str]]:
  35. reg = body.split("## Claims register")[1]
  36. rows = [line for line in reg.splitlines() if line.startswith("|") and not line.startswith("|---")]
  37. return [[c.strip() for c in r.strip("|").split("|")] for r in rows[1:]]
  38. def rows_missing_status(body: str) -> list[str]:
  39. return [r[0] for r in register_rows(body) if not any(w in r[-1] for w in STATUS_WORDS)]
  40. def diagram_problems(body: str, root: Path = ROOT, wiki: Path = WIKI) -> list[str]:
  41. """Every picture on the page is a wrapped diagram with alt text, a Mermaid source and a picture on disk."""
  42. problems = []
  43. wrapped = list(DIAGRAM.finditer(body))
  44. if len(wrapped) != len(IMAGE_ANY.findall(body)):
  45. problems.append("a picture on the page is not a wrapped diagram")
  46. for m in wrapped:
  47. alt = m["alt"].strip()
  48. if len(alt) < 20 or len(alt) > MAX_ALT:
  49. problems.append(f"alt text length {len(alt)}: {alt[:40]!r}")
  50. if not m["src"].strip():
  51. problems.append(f"empty source for {m['path']}")
  52. if not (wiki / m["path"]).is_file():
  53. problems.append(f"picture missing: {m['path']}")
  54. return problems
  55. def test_the_banner_says_it_was_written_from_reading_and_nothing_was_run():
  56. body = text()
  57. assert body.startswith("# How Tor works in depth")
  58. assert "Status: unverified draft, written from reading" in body
  59. assert "Nothing on this page was run" in body
  60. assert "**Not run:**" in body and DATE_READ in body
  61. assert "## Not verified, plainly" in body
  62. def test_every_linked_wiki_page_exists_and_the_overview_and_sibling_lessons_are_linked():
  63. body = text()
  64. links = set(LINK.findall(body))
  65. assert len(links) >= 6, "the guard collected too few links"
  66. missing = sorted(t for t in links if not (WIKI / f"{t}.md").exists())
  67. assert not missing, missing
  68. assert OVERVIEW in links
  69. assert "Privacy-vs-Security-Blinds-and-Locks-Physical-Security-and-Monero" in links
  70. assert "Cryptography-Fundamentals-Symmetric-Asymmetric-Hashing-Certificates-and-Keys" in links
  71. def test_the_other_series_pages_are_linked_now_that_they_exist():
  72. body = text()
  73. links = set(LINK.findall(body))
  74. for prefix in ("How-a-VPN-Works-", "How-I2P-Works-", "Privacy-Security-and-Anonymity-", "The-Browsing-Setups-Compared-",
  75. "OPSEC-for-Tor-and-I2P-", "Detecting-and-Managing-Tor-I2P-and-VPN-", "The-Darknet-Landscape-"):
  76. found = {t for t in links if t.startswith(prefix)}
  77. assert found, f"the page {prefix} exists and must be linked"
  78. assert all((WIKI / f"{t}.md").exists() for t in found), found
  79. # The stale statements that these pages are written separately and not linked are gone.
  80. assert "named here in plain text" not in body and "tracked separately" not in body and "Until they exist" not in body
  81. def test_the_lesson_is_registered_in_contents_reading_order_and_nav():
  82. nav = (WIKI / "_nav.yaml").read_text(encoding="utf-8")
  83. assert f"page: {NAME}," in nav
  84. for special in ("Contents.md", "Reading-Order.md"):
  85. assert f"{NAME}.md" in (WIKI / special).read_text(encoding="utf-8"), special
  86. line = next(l for l in nav.splitlines() if f"page: {NAME}," in l)
  87. assert 'status: "draft"' in line
  88. def test_glossary_rows_point_at_real_headings():
  89. heads = {re.sub(r"[^a-z0-9-]", "", re.sub(r"[^a-z0-9 -]", "", h.lower()).strip().replace(" ", "-"))
  90. for h in re.findall(r"^#+ (.+)$", text(), re.MULTILINE)}
  91. anchors = set()
  92. rows = 0
  93. for line in (WIKI / "Glossary.md").read_text(encoding="utf-8").splitlines():
  94. if f"{NAME}.md" in line:
  95. rows += 1
  96. anchors.update(re.findall(rf"{NAME}\.md#([a-z0-9-]+)", line))
  97. assert rows >= 8, "expected glossary rows for the new terms"
  98. assert anchors and anchors <= heads, sorted(anchors - heads)
  99. def test_no_addresses_onion_names_long_random_values_or_em_dashes():
  100. body = text()
  101. assert not ADDR.findall(body), set(ADDR.findall(body))
  102. assert not ONION.findall(body)
  103. assert "—" not in body
  104. # URLs and the register's identifiers are short; a long random-looking run would trip the secret scan.
  105. visible = re.sub(r"\]\([^)\s]+\)", "]()", body) # link and picture targets are paths, not values
  106. runs = [r for r in LONG_RANDOM.findall(visible) if re.search(r"[0-9]", r) and re.search(r"[A-Za-z]", r)]
  107. assert not runs, runs
  108. def test_the_address_guard_bites():
  109. assert ADDR.findall("host 192.0.2.7")
  110. assert ONION.findall("go to " + "a" * 56 + ".onion")
  111. assert LONG_RANDOM.findall("x" + "a1" * 20)
  112. def test_every_diagram_has_alt_text_a_source_block_and_a_picture_that_exists():
  113. body = text()
  114. wrapped = list(DIAGRAM.finditer(body))
  115. assert len(wrapped) == EXPECTED_DIAGRAMS, f"expected {EXPECTED_DIAGRAMS} diagrams, found {len(wrapped)}"
  116. assert not diagram_problems(body)
  117. manifest = json.loads((ROOT / "docs" / "diagrams.json").read_text())
  118. for m in wrapped:
  119. assert f"docs/wiki/{m['path']}" in manifest, m["path"]
  120. names = [m["path"] for m in wrapped]
  121. assert len(set(names)) == len(names)
  122. def test_the_diagram_guard_bites(tmp_path):
  123. wiki = tmp_path
  124. (wiki / "images").mkdir()
  125. good = "![Diagram, a circuit of three relays and what each knows](images/a.png)\n\n<details>\n<summary>Diagram source (Mermaid)</summary>\n\n```mermaid\nflowchart LR\n a --> b\n```\n\n</details>"
  126. assert diagram_problems(good, tmp_path, wiki) == ["picture missing: images/a.png"]
  127. (wiki / "images" / "a.png").write_bytes(b"x")
  128. assert not diagram_problems(good, tmp_path, wiki)
  129. assert diagram_problems(good.replace("Diagram, a circuit of three relays and what each knows", "x"), tmp_path, wiki)
  130. assert diagram_problems("![alt text long enough to pass](images/a.png)\n\n```mermaid\nflowchart LR\n```", tmp_path, wiki)
  131. def test_the_diagrams_cover_the_required_topics():
  132. body = text()
  133. sources = " ".join(m["src"] for m in DIAGRAM.finditer(body)).lower()
  134. for term in ("guard", "middle", "exit", "consensus", "directory authorities", "bridge", "pluggable transport",
  135. "introduction points", "rendezvous point", "hsdir"):
  136. assert term in sources, term
  137. assert "sequenceDiagram" in body, "the one-request timeline is a sequence diagram"
  138. def test_every_claims_register_row_has_a_status_a_source_and_the_read_date():
  139. rows = register_rows(text())
  140. assert len(rows) >= 28, "the guard collected too few rows"
  141. assert not rows_missing_status(text())
  142. sourced = [r for r in rows if URL.search(r[1])]
  143. assert len(sourced) >= 26
  144. for r in sourced:
  145. assert DATE_READ in r[2], r[0]
  146. sources = " ".join(r[1] for r in rows)
  147. for host in ("freehaven.net", "support.torproject.org", "spec.torproject.org", "community.torproject.org",
  148. "metrics.torproject.org", "blog.torproject.org", "arxiv.org"):
  149. assert host in sources, host
  150. def test_the_register_guard_bites():
  151. bad = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | y | maybe |\n"
  152. assert rows_missing_status(bad) == ["X"]
  153. def test_the_spec_pages_the_issue_names_are_cited():
  154. sources = " ".join(r[1] for r in register_rows(text()))
  155. for page in ("dir-spec", "path-spec", "guard-spec", "vanguards-spec", "rend-spec", "pt-spec", "tor-spec"):
  156. assert f"spec.torproject.org/{page}/" in sources, page
  157. def test_the_relay_count_is_dated_and_matches_the_register():
  158. body = text()
  159. assert "2026-10-29" in body and "9,220" in body and "2,476" in body
  160. rows = [r for r in register_rows(body) if "9,220" in r[0]]
  161. assert rows and "metrics.torproject.org" in rows[0][1]
  162. def test_research_claims_are_attributed_to_the_authors_and_dated():
  163. body = text()
  164. assert "2015-03-13" in body and "2018-08-22" in body and "2014-07-30" in body
  165. row = next(r for r in register_rows(body) if "DeepCorr" in r[0])
  166. assert "abstract" in row[2].lower()
  167. sentence = next(s for s in re.split(r"(?<=\.)\s+", body) if "96% accuracy" in s)
  168. assert "in its experiments" in sentence or "authors" in sentence
  169. def test_the_unverified_hop_count_and_guard_count_are_marked():
  170. body = text()
  171. assert "**unverified**" in body
  172. assert body.count("**unverified**") >= 2
  173. def test_the_page_makes_no_marketplace_how_to_or_evasion_content():
  174. body = text().lower()
  175. assert "no onion addresses on this page" in body
  176. for banned in ("buy drugs", "vendor shop", "how to buy", "escrow", "evade detection", "bypass the filter"):
  177. assert banned not in body
  178. assert "does not tell you how to hide wrongdoing" in body
  179. def test_the_law_note_tells_learners_to_check_their_jurisdiction():
  180. body = text()
  181. assert "Check the law where you live" in body
  182. assert "nothing here is legal advice" in body.lower()
  183. def test_the_threat_model_comes_before_the_machinery():
  184. body = text()
  185. order = ["## The short version and the threat model", "## Directory authorities and the consensus",
  186. "## One circuit, hop by hop", "## Why three hops", "## Why guards persist",
  187. "## Bridges and pluggable transports", "## Onion services", "## One request, start to finish",
  188. "## What is known to break Tor, with dates", "## What Tor Browser adds"]
  189. positions = [body.index(h) for h in order]
  190. assert positions == sorted(positions)
  191. assert "## What this means for the series' message" in body