test_browsing_setups_lesson.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The browsing setups lesson: registered, honest about what was read, diagrammed, and safe to read.
  3. docs/wiki/The-Browsing-Setups-Compared-Tor-Browser-Brave-Whonix-Tails-and-Qubes-with-Whonix.md compares five ways to
  4. reach Tor (Tor Browser on a normal operating system, Brave's Tor window, Whonix, Tails, and Qubes running Whonix), says
  5. what each one's trust boundary and threat model are, and carries one clearly marked section of the maintainer's own
  6. opinion about running Tails or Kali as a daily system. A banner that claims more than was done, a dead link, a missing
  7. registration, an address outside the documentation ranges, a claim with no status or date, a diagram with no alt text,
  8. no source or no picture, a matrix that lost a setup or a threat, opinion words that leak out of the marked section, a
  9. section that criticizes a habit with no way out, a link to a page that has a link cap, or a line that states a security
  10. detail about this repository would each teach or reveal the wrong thing.
  11. """
  12. import json
  13. import re
  14. from pathlib import Path
  15. from wikitext import glossary_text, nav_text, page_text
  16. ROOT = Path(__file__).resolve().parent.parent
  17. WIKI = ROOT / "docs" / "wiki"
  18. NAME = "The-Browsing-Setups-Compared-Tor-Browser-Brave-Whonix-Tails-and-Qubes-with-Whonix"
  19. PAGE = WIKI / f"{NAME}.md"
  20. OVERVIEW = "Tor-I2P-and-the-Darknet-Without-the-Myths"
  21. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#[^)]*)?\)")
  22. ADDR = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
  23. ALLOWED_ADDR = re.compile(r"^(?:192\.0\.2\.\d{1,3}|198\.51\.100\.\d{1,3}|203\.0\.113\.\d{1,3})$")
  24. ONION = re.compile(r"\b[a-z2-7]{16,56}\.(?:onion|b32\.i2p)\b")
  25. STATUS_WORDS = ("Read", "General knowledge", "**est.**", "Observed", "Not read")
  26. URL = re.compile(r"\]\(https://[^)\s]+\)")
  27. DIAGRAM = re.compile(
  28. r"!\[(?P<alt>[^\]\n]*)\]\((?P<path>images/[^)\n]+\.png)\)\n\n<details>\n<summary>Diagram source \(Mermaid\)</summary>"
  29. r"\n\n```mermaid\n(?P<src>.*?)\n```\n\n</details>",
  30. re.DOTALL,
  31. )
  32. IMAGE_ANY = re.compile(r"!\[[^\]\n]*\]\([^)\n]+\)")
  33. MAX_ALT = 150
  34. EXPECTED_DIAGRAMS = 6
  35. DATE_READ = "2026-11-01"
  36. LONG_RANDOM = re.compile(r"[A-Za-z0-9+/=_-]{32,}")
  37. SETUPS = ("Tor Browser on a normal OS", "Brave's Tor window", "Whonix", "Tails", "Qubes with Whonix")
  38. THREATS = ("A site or tracker fingerprinting the browser", "An app that ignores Tor", "A browser bug that exposes the real address",
  39. "Malware on the computer or the host", "Traces left on the computer", "A watcher on the local network",
  40. "An observer of both ends", "Your own habits", "Altered hardware or firmware")
  41. MAINTAINER_HEADING = "## The maintainer's view: Tails and Kali as a daily system, and the badge"
  42. OPINION_WORDS = ("larp", "skid", "poser")
  43. def text() -> str:
  44. # The author's text without the generated navigation blocks (issue #417): the bottom block links the next page in
  45. # the track, which is now the OPSEC lesson (issue #389), and the series page is meant to be named in plain text.
  46. return page_text(PAGE)
  47. def register_rows(body: str) -> list[list[str]]:
  48. reg = body.split("## Claims register")[1]
  49. rows = [line for line in reg.splitlines() if line.startswith("|") and not line.startswith("|---")]
  50. return [[c.strip() for c in r.strip("|").split("|")] for r in rows[1:]]
  51. def rows_missing_status(body: str) -> list[str]:
  52. return [r[0] for r in register_rows(body) if not any(w in r[-1] for w in STATUS_WORDS)]
  53. def stray_addresses(body: str) -> list[str]:
  54. return [a for a in ADDR.findall(body) if not ALLOWED_ADDR.match(a)]
  55. def tables(body: str) -> list[list[str]]:
  56. """Every markdown table as its list of lines, found by a header line followed by a separator line."""
  57. lines = body.splitlines()
  58. found = []
  59. for i, line in enumerate(lines[:-1]):
  60. if line.startswith("|") and re.match(r"^\|(?:\s*:?-{3,}:?\s*\|)+\s*$", lines[i + 1]):
  61. block = [line]
  62. for later in lines[i + 2:]:
  63. if not later.startswith("|"):
  64. break
  65. block.append(later)
  66. found.append(block)
  67. return found
  68. def unnamed_first_cells(body: str) -> list[str]:
  69. return [t[0] for t in tables(body) if not t[0].strip("|").split("|")[0].strip()]
  70. def matrix_problems(body: str) -> list[str]:
  71. """The matrix has the five setups as columns and the nine threats as rows, every cell an answer."""
  72. start = body.index("## The matrix: five setups against nine threats")
  73. section = body[start:].split("\n## ")[0]
  74. block = next(iter(tables(section)), None)
  75. if block is None:
  76. return ["no table in the matrix section"]
  77. header = [c.strip() for c in block[0].strip("|").split("|")]
  78. problems = []
  79. if header != ["Threat", *SETUPS]:
  80. problems.append(f"header is {header}")
  81. rows = [[c.strip() for c in r.strip("|").split("|")] for r in block[1:]]
  82. if [r[0] for r in rows] != list(THREATS):
  83. problems.append(f"threats are {[r[0] for r in rows]}")
  84. for r in rows:
  85. if len(r) != 6 or any(len(c) < 20 for c in r[1:]):
  86. problems.append(f"thin row: {r[0]}")
  87. return problems
  88. def diagram_problems(body: str, root: Path = ROOT, wiki: Path = WIKI) -> list[str]:
  89. """Every picture on the page is a wrapped diagram with alt text, a Mermaid source and a picture on disk."""
  90. problems = []
  91. wrapped = list(DIAGRAM.finditer(body))
  92. if len(wrapped) != len(IMAGE_ANY.findall(body)):
  93. problems.append("a picture on the page is not a wrapped diagram")
  94. for m in wrapped:
  95. alt = m["alt"].strip()
  96. if len(alt) < 20 or len(alt) > MAX_ALT:
  97. problems.append(f"alt text length {len(alt)}: {alt[:40]!r}")
  98. if not m["src"].strip():
  99. problems.append(f"empty source for {m['path']}")
  100. if not (wiki / m["path"]).is_file():
  101. problems.append(f"picture missing: {m['path']}")
  102. return problems
  103. def section(body: str, heading: str) -> str:
  104. start = body.index(heading)
  105. return body[start:].split("\n## ", 1)[0] if body[start:].startswith(heading) else ""
  106. def opinion_outside(body: str, heading: str = MAINTAINER_HEADING, words: tuple[str, ...] = OPINION_WORDS) -> list[str]:
  107. """Opinion words that appear anywhere except inside the marked section."""
  108. inside = section(body, heading)
  109. outside = body.replace(inside, "", 1).lower()
  110. return [w for w in words if w in outside]
  111. def test_the_banner_says_it_was_written_from_reading_and_nothing_was_run():
  112. body = text()
  113. assert body.startswith("# The browsing setups compared")
  114. assert "Page 5 of a seven-page series" in body
  115. assert "Status: unverified draft, written from reading" in body
  116. assert "Nothing on this page was run" in body
  117. assert "**Not run:**" in body and DATE_READ in body
  118. assert "## Not verified, plainly" in body
  119. def test_every_linked_wiki_page_exists_and_the_finished_siblings_are_linked():
  120. body = text()
  121. links = set(LINK.findall(body))
  122. assert len(links) >= 14, "the guard collected too few links"
  123. missing = sorted(t for t in links if not (WIKI / f"{t}.md").exists())
  124. assert not missing, missing
  125. for needed in (
  126. OVERVIEW,
  127. "How-Tor-Works-in-Depth-Circuits-Relays-Directory-Authorities-and-Onion-Services",
  128. "How-I2P-Works-Tunnels-Garlic-Routing-and-the-Network-Database",
  129. "How-a-VPN-Works-Tunnels-What-It-Hides-What-It-Does-Not-and-What-an-Audit-Proves",
  130. "Privacy-Security-and-Anonymity-Three-Different-Things-and-Why-There-Is-No-Silver-Bullet",
  131. "The-Darknet-Landscape-Markets-OPSEC-Clearnet-and-Layering-Tor-I2P-and-VPN",
  132. "Privacy-vs-Security-Blinds-and-Locks-Physical-Security-and-Monero",
  133. "Cryptography-Fundamentals-Symmetric-Asymmetric-Hashing-Certificates-and-Keys",
  134. "Running-Monero-Properly-Hardware-Wallet-Qubes-and-Whonix-Offline-Wallet-and-PiNodeXMR",
  135. "How-Monero-Works-Compared-with-Bitcoin-and-Ethereum-DeFi-Mixers-Swaps-and-Ransomware",
  136. "Red-and-Blue-Yin-and-Yang-and-Your-Lab-OS",
  137. "Virtual-Machines-Hypervisors-Desktop-and-Datacenter-Options",
  138. "Threat-Model",
  139. ):
  140. assert needed in links, needed
  141. def test_the_later_series_pages_are_linked_now_that_they_exist():
  142. body = text()
  143. for named in ("operational security for Tor and I2P", "detecting and managing Tor, I2P and VPN traffic on a network"):
  144. assert named in body, named
  145. links = set(LINK.findall(body))
  146. for prefix in ("OPSEC-for-Tor-and-I2P-", "Detecting-and-Managing-Tor-I2P-and-VPN-"):
  147. found = {t for t in links if t.startswith(prefix)}
  148. assert found, f"the series page {prefix} exists and must be linked"
  149. assert all((WIKI / f"{t}.md").exists() for t in found), found
  150. # The stale statement that these pages are not written yet is gone.
  151. assert "The two pages not written yet" not in body
  152. EXERCISES = "Hands-On-Whonix-and-Qubes-OS-Gateway-Split-Compartments-Disposables-and-Policy-Prompts"
  153. def exercise_links(body: str) -> set[str]:
  154. return {t for t in LINK.findall(body) if t == EXERCISES}
  155. def test_the_whonix_and_qubes_exercises_are_linked_now_that_they_exist():
  156. body = text()
  157. assert "hands-on Whonix and Qubes exercises" in body
  158. assert exercise_links(body) == {EXERCISES}, "the exercises page (issue 372) exists and must be linked"
  159. assert (WIKI / f"{EXERCISES}.md").is_file()
  160. # The stale statement that the exercises are not written yet is gone.
  161. assert "are not written yet, so they are named in plain text" not in body
  162. def test_the_exercise_link_guard_bites():
  163. assert not exercise_links("the hands-on Whonix and Qubes exercises (issue 372) are not written yet")
  164. assert exercise_links(f"the [hands-on Whonix and Qubes exercises]({EXERCISES}.md)")
  165. def test_a_page_with_a_link_cap_is_not_linked():
  166. # tests/test_blast_radius_lesson.py caps how many pages may link that lesson, and the cap is full.
  167. assert "Plan-for-Failure-Blast-Radius" not in text()
  168. def test_the_lesson_is_registered_in_contents_reading_order_and_nav():
  169. nav = nav_text(WIKI)
  170. assert f"page: {NAME}," in nav
  171. for special in ("Contents.md", "Reading-Order.md"):
  172. assert f"{NAME}.md" in (WIKI / special).read_text(encoding="utf-8"), special
  173. line = next(row for row in nav.splitlines() if f"page: {NAME}," in row)
  174. assert 'status: "draft"' in line
  175. def test_glossary_rows_point_at_real_headings():
  176. heads = {re.sub(r"[^a-z0-9-]", "", re.sub(r"[^a-z0-9 -]", "", h.lower()).strip().replace(" ", "-"))
  177. for h in re.findall(r"^#+ (.+)$", text(), re.MULTILINE)}
  178. anchors = set()
  179. rows = 0
  180. terms = []
  181. for line in glossary_text(WIKI).splitlines():
  182. if f"{NAME}.md" in line:
  183. rows += 1
  184. terms.append(line.split("|")[1].strip().strip("*").lower())
  185. anchors.update(re.findall(rf"{NAME}\.md#([a-z0-9-]+)", line))
  186. assert rows >= 6, "expected glossary rows for the new terms"
  187. assert len(set(terms)) == len(terms), "a glossary term is defined twice"
  188. # A term this page adds must not already be defined by another row of the glossary.
  189. every = [ln.split("|")[1].strip().strip("*").lower() for ln in
  190. glossary_text(WIKI).splitlines() if ln.startswith("| **")]
  191. assert all(every.count(t) == 1 for t in terms), [t for t in terms if every.count(t) != 1]
  192. assert anchors and anchors <= heads, sorted(anchors - heads)
  193. def test_only_documentation_addresses_no_onion_names_long_random_values_or_em_dashes():
  194. body = text()
  195. assert not stray_addresses(body), set(stray_addresses(body))
  196. assert not ONION.findall(body)
  197. assert "—" not in body
  198. visible = re.sub(r"\]\([^)\s]+\)", "]()", body)
  199. runs = [r for r in LONG_RANDOM.findall(visible) if re.search(r"[0-9]", r) and re.search(r"[A-Za-z]", r)]
  200. assert not runs, runs
  201. def test_the_address_guard_bites():
  202. assert stray_addresses("host 8.8.8.8") == ["8.8.8.8"]
  203. assert stray_addresses("host 10.0.0.1 and 192.0.3.1") == ["10.0.0.1", "192.0.3.1"]
  204. assert not stray_addresses("Alice 192.0.2.10 and 203.0.113.50")
  205. assert ONION.findall("go to " + "a" * 56 + ".onion")
  206. assert LONG_RANDOM.findall("x" + "a1" * 20)
  207. def test_every_diagram_has_alt_text_a_source_block_and_a_picture_that_exists():
  208. body = text()
  209. wrapped = list(DIAGRAM.finditer(body))
  210. assert len(wrapped) == EXPECTED_DIAGRAMS, f"expected {EXPECTED_DIAGRAMS} diagrams, found {len(wrapped)}"
  211. assert not diagram_problems(body)
  212. manifest = json.loads((ROOT / "docs" / "diagrams.json").read_text())
  213. for m in wrapped:
  214. assert f"docs/wiki/{m['path']}" in manifest, m["path"]
  215. names = [m["path"] for m in wrapped]
  216. assert len(set(names)) == len(names)
  217. def test_the_diagram_guard_bites(tmp_path):
  218. wiki = tmp_path
  219. (wiki / "images").mkdir()
  220. good = ("![Diagram, five setups and where each draws its boundary around the browser and Tor](images/a.png)\n\n<details>\n"
  221. "<summary>Diagram source (Mermaid)</summary>\n\n```mermaid\nflowchart LR\n a --> b\n```\n\n</details>")
  222. assert diagram_problems(good, tmp_path, wiki) == ["picture missing: images/a.png"]
  223. (wiki / "images" / "a.png").write_bytes(b"x")
  224. assert not diagram_problems(good, tmp_path, wiki)
  225. assert diagram_problems(good.replace("Diagram, five setups and where each draws its boundary around the browser and Tor", "x"),
  226. tmp_path, wiki)
  227. too_long = "x" * (MAX_ALT + 1)
  228. assert diagram_problems(good.replace("Diagram, five setups and where each draws its boundary around the browser and Tor",
  229. too_long), tmp_path, wiki)
  230. assert diagram_problems("![alt text long enough to pass](images/a.png)\n\n```mermaid\nflowchart LR\n```", tmp_path, wiki)
  231. def test_the_diagrams_cover_the_required_topics():
  232. sources = " ".join(m["src"] for m in DIAGRAM.finditer(text())).lower()
  233. for term in ("tor browser", "brave", "whonix", "tails", "qubes", "gateway", "workstation", "host", "usb", "ram",
  234. "sys-whonix", "dom0", "disposable", "trust boundary", "other apps", "hypervisor", "persistent"):
  235. assert term in sources, term
  236. def test_every_table_has_a_named_first_header_cell_and_the_guard_bites():
  237. assert len(tables(text())) >= 7, "the guard collected too few tables"
  238. assert not unnamed_first_cells(text()), unnamed_first_cells(text())
  239. assert unnamed_first_cells("| | B |\n|---|---|\n| x | y |\n") == ["| | B |"]
  240. assert not unnamed_first_cells("| A | B |\n|---|---|\n| x | y |\n")
  241. def test_the_matrix_has_five_setups_against_nine_threats_each_cell_an_answer():
  242. body = text()
  243. assert not matrix_problems(body), matrix_problems(body)
  244. assert matrix_problems(body.replace("| Brave's Tor window | Whonix | Tails |", "| Brave's Tor window | Tails |", 1))
  245. assert matrix_problems(body.replace("| Your own habits |", "| Your habits |", 1))
  246. def test_every_claims_register_row_has_a_status_a_source_and_the_read_date():
  247. rows = register_rows(text())
  248. assert len(rows) >= 28, "the guard collected too few rows"
  249. assert not rows_missing_status(text())
  250. sourced = [r for r in rows if URL.search(r[1])]
  251. assert len(sourced) >= 20, "the page reads twenty outside sources"
  252. for r in sourced:
  253. assert DATE_READ in r[2], r[0]
  254. sources = " ".join(r[1] for r in rows)
  255. for host in ("support.torproject.org", "tb-manual.torproject.org", "support.brave.app", "whonix.org", "tails.net",
  256. "doc.qubes-os.org", "kali.org", "parrotsec.org"):
  257. assert host in sources, host
  258. def test_the_register_guard_bites():
  259. bad = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | y | maybe |\n"
  260. assert rows_missing_status(bad) == ["X"]
  261. def test_the_sources_the_issue_names_are_cited_with_their_own_dates_and_words():
  262. body = text()
  263. for item in ("Brave does NOT implement most of the privacy protections from Tor Browser", "2026-10-31",
  264. "NOT a recommended distribution", "2026-May-14", "Daily Use & Dev", "7.4",
  265. "Tails is safe but not magic", "Qubes OS 4.3.2", "silver bullet", "Kicksecure",
  266. "Warnings", "letterboxing", "reliant upon the security of the host"):
  267. assert item in body, item
  268. def test_the_sections_run_in_order_and_each_setup_has_a_threat_model_and_its_limits():
  269. body = text()
  270. order = ["## The idea in one paragraph", "## Threat models first", "## The five setups, one at a time",
  271. "## The matrix: five setups against nine threats", "## Why the browser-only model is weaker than Whonix",
  272. "## Tails: what it is for, and the daily-system question", "## Kali and ParrotOS: a tool kit and a daily system",
  273. MAINTAINER_HEADING, "## Choosing: six situations", "## Exercises", "## Checkpoint", "## Common mistakes",
  274. "## Not verified, plainly", "## Claims register"]
  275. positions = [body.index(h) for h in order]
  276. assert positions == sorted(positions)
  277. for needed in ("### Tor Browser on a normal operating system", "### Brave's Tor window", "### Whonix",
  278. "### Tails", "### Qubes with Whonix"):
  279. assert needed in body, needed
  280. assert body.count("**Threat model.**") == 5
  281. assert body.count("**What it does not protect against.**") == 5
  282. assert body.count("**Cost and fit.**") == 5
  283. def test_the_maintainers_section_is_marked_has_the_joke_and_a_way_out_and_does_not_leak():
  284. body = text()
  285. sec = section(body, MAINTAINER_HEADING)
  286. assert sec, "the maintainer's section is missing"
  287. assert "This section is the maintainer's opinion" in sec
  288. assert "not a source" in sec
  289. low = sec.lower()
  290. for word in OPINION_WORDS:
  291. assert word in low, word
  292. assert "ParrotOS for most of this project" in sec
  293. assert "What to run instead" in sec and "What to learn first" in sec
  294. assert "habit" in low
  295. assert "not a generation" in low, "the joke must say it is not aimed at a generation"
  296. assert not opinion_outside(body), opinion_outside(body)
  297. def test_the_opinion_guard_bites():
  298. body = text()
  299. assert opinion_outside(body + "\nYou are a poser.\n") == ["poser"]
  300. assert opinion_outside("## A\n\nskid here\n\n" + MAINTAINER_HEADING + "\n\nlarp\n") == ["skid"]
  301. assert not opinion_outside("## A\n\nplain\n\n" + MAINTAINER_HEADING + "\n\nlarp skid poser\n\n## B\n\nplain\n")
  302. def test_the_page_makes_no_coined_term_claim_and_aims_at_the_habit():
  303. low = section(text(), MAINTAINER_HEADING).lower()
  304. for banned in ("coined", "invented the term", "originated the term", "stupid", "idiot", "worthless", "kids these days"):
  305. assert banned not in low, banned
  306. def test_kali_and_parrot_are_cited_from_their_own_documentation():
  307. sec = section(text(), "## Kali and ParrotOS: a tool kit and a daily system")
  308. assert "kali.org/docs/introduction/should-i-use-kali-linux" in text()
  309. for word in ("virtual machine", "Home", "Security", "Daily Use & Dev", "professional penetration testers"):
  310. assert word in sec, word
  311. assert "parrotsec.org/download" in text() and "parrotsec.org/docs/introduction/download-parrot" in text()
  312. def test_the_page_states_nothing_about_this_repositorys_own_security_and_names_no_machine():
  313. lower = text().lower()
  314. for banned in ("this repository", "our droplet", "this project's lab", "twingate", "doppler", "spacelift", "hostname",
  315. "serial number of"):
  316. assert banned not in lower, banned
  317. def test_american_spelling_only():
  318. lower = text().lower()
  319. for british in ("behaviour", "colour", "defence", "anonymise", "organisation", "favour", "centre ", "licence",
  320. "recognise", "minimise", "analyse", "pseudonymise", "catalogue", "sceptic", "grey ", "whilst"):
  321. assert british not in lower, british
  322. def test_the_page_makes_no_evasion_how_to_or_illegal_content():
  323. body = text().lower()
  324. assert "no way around a block, a paywall or a rule" in body
  325. for banned in ("buy drugs", "vendor shop", "how to buy", "evade detection", "bypass the filter", "get around geo",
  326. "unblock netflix", "launder", "how to hide from", "step-by-step install", "sudo apt"):
  327. assert banned not in body
  328. assert "no onion or i2p service" in body or "no address of any onion or i2p service" in body
  329. def test_the_law_note_tells_learners_to_check_their_jurisdiction():
  330. body = text()
  331. assert "Check the law where you live" in body
  332. assert "nothing here is legal advice" in body.lower()
  333. assert "No country's law was checked" in body
  334. def test_no_product_is_ranked_best_or_sold():
  335. lower = text().lower()
  336. for banned in ("best vpn", "the best browser", "we recommend", "i recommend", "top pick", "buy now", "affiliate link"):
  337. assert banned not in lower, banned