test_ipv6_lesson.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The IPv6 lesson's code runs, says what the page says, and keeps the page's promises.
  3. docs/wiki/IPv6-Adoption-and-Handling-It-Safely.md has the learner paste scripts into files with
  4. `cat > name <<'LAB_EOF'`. The two pure-Python ones (subnets.py and allowlist.py) are pulled out of the
  5. page, run in a temporary folder and compared with the output the page prints; the others are checked
  6. for syntax only, because they need a Linux network namespace. The page also promises: documentation
  7. addresses only, no em dashes, the maintainer's words quoted, a retrieval date for every statistic.
  8. """
  9. import ipaddress
  10. import re
  11. import subprocess
  12. import sys
  13. from pathlib import Path
  14. WIKI = Path(__file__).resolve().parent.parent / "docs" / "wiki"
  15. PAGE = WIKI / "IPv6-Adoption-and-Handling-It-Safely.md"
  16. HEREDOC = re.compile(
  17. r"cat > (?P<name>[\w.-]+) <<'LAB_EOF'\n(?P<body>.*?)^LAB_EOF$",
  18. re.MULTILINE | re.DOTALL,
  19. )
  20. FILES = {"subnets.py", "ra.py", "lab-up.sh", "serve.py", "probe.py", "allowlist.py"}
  21. def page() -> str:
  22. return PAGE.read_text()
  23. def files() -> dict[str, str]:
  24. return {m["name"]: m["body"] for m in HEREDOC.finditer(page())}
  25. def run(tmp_path, name, *args):
  26. (tmp_path / name).write_text(files()[name])
  27. return subprocess.run(
  28. [sys.executable, "-I", name, *args],
  29. check=False,
  30. cwd=tmp_path,
  31. capture_output=True,
  32. text=True,
  33. timeout=30,
  34. )
  35. def test_all_lab_files_are_on_the_page():
  36. assert FILES <= set(files())
  37. def test_python_files_compile_and_the_shell_file_parses(tmp_path):
  38. for name, body in files().items():
  39. (tmp_path / name).write_text(body)
  40. if name.endswith(".py"):
  41. compile(body, name, "exec")
  42. else:
  43. done = subprocess.run(["bash", "-n", name], cwd=tmp_path, capture_output=True, text=True, check=False)
  44. assert done.returncode == 0, done.stderr
  45. def test_subnets_prints_what_the_page_shows(tmp_path):
  46. done = run(tmp_path, "subnets.py")
  47. assert done.returncode == 0, done.stderr
  48. out = done.stdout
  49. for line in (
  50. "a /48 holds 65536 separate /64 networks",
  51. "a /56 holds 256 separate /64 networks",
  52. " 2001:db8:abcd:1::/64 first host 2001:db8:abcd:1::1",
  53. " fd12:3456:789a::1 unique local (ULA, private, not routed on the internet)",
  54. " ::ffff:192.0.2.5 IPv4-mapped (an IPv4 client seen through an IPv6 socket)",
  55. "on 2001:db8:abcd:1::/64 that is 2001:db8:abcd:1:200:5eff:fe00:5301",
  56. ):
  57. assert line in out, line
  58. assert line in page(), f"the page no longer shows: {line}"
  59. ula = re.search(r"different every run\): (\S+)", out).group(1)
  60. net = ipaddress.ip_network(ula)
  61. assert net.prefixlen == 64 and net.subnet_of(ipaddress.ip_network("fd00::/8"))
  62. def test_allowlist_matches_the_page_and_unwraps_mapped_addresses(tmp_path):
  63. done = run(tmp_path, "allowlist.py", "192.0.2.0/24,198.51.100.7", "192.0.2.9", "2001:db8::9", "::ffff:192.0.2.9", "::ffff:203.0.113.5")
  64. assert done.returncode == 0, done.stderr
  65. rows = {line.split()[0]: line.split()[1:] for line in done.stdout.splitlines()[1:5]}
  66. assert rows["192.0.2.9"] == ["allow", "allow"]
  67. assert rows["2001:db8::9"] == ["deny", "deny"]
  68. assert rows["::ffff:192.0.2.9"] == ["deny", "allow"] # the naive check denies its own client
  69. assert rows["::ffff:203.0.113.5"] == ["deny", "deny"]
  70. assert "WARNING: IPv4 only." in done.stdout
  71. both = run(tmp_path, "allowlist.py", "192.0.2.0/24,2001:db8:1:1::/64", "2001:db8:1:1::5", "2001:db8:1:2::5")
  72. assert "WARNING" not in both.stdout
  73. assert "WARNING: a /0 entry" in run(tmp_path, "allowlist.py", "0.0.0.0/0", "192.0.2.1").stdout
  74. def test_ra_refuses_anything_but_a_slash_64(tmp_path):
  75. done = run(tmp_path, "ra.py", "e0", "2001:db8:1::/48")
  76. assert done.returncode != 0
  77. assert "/64" in done.stderr
  78. def test_the_maintainers_words_are_quoted_exactly_and_nothing_waits_for_him():
  79. text = page()
  80. for quote in (
  81. "While IPv6 has been a thing for years, many companies are hesitant to adopt it, and even I haven't, for a myriad of reasons.",
  82. "IPv6 probably doesn't work, as I have it disabled on pfSense.",
  83. "While v6 fixes IP exhaustion, the format is hard to remember, and it was designed around the idea that every single device can have its own IP address directly, and it becomes harder to secure traffic.",
  84. ):
  85. assert quote in text
  86. assert "## Why the author has not adopted IPv6" in text
  87. low = text.lower()
  88. for waiting in ("to be supplied", "waiting for him", "placeholder", "tbd", "todo"):
  89. assert waiting not in low, waiting
  90. def test_no_em_dash_and_no_forbidden_word():
  91. text = page()
  92. assert "—" not in text
  93. assert not re.search(r"\bpaid\b", text, re.IGNORECASE)
  94. # Intended prefixes only. Nothing here may contain "any" address: ::/0 and 2000::/3 are NOT in this list,
  95. # because every global address is a subnet of them and the check would accept a real one.
  96. ALLOWED_V6 = [ipaddress.ip_network(n) for n in ("2001:db8::/32", "fc00::/7", "fe80::/10", "ff00::/8", "::/128", "::1/128")]
  97. # Route literals the page may show, matched as exact text and never by containment.
  98. ALLOWED_LITERALS = {"::/0", "2000::/3"}
  99. DOC_V4 = [ipaddress.ip_network(n) for n in ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24")]
  100. V6_TOKEN = re.compile(r"(?<![\w:.])([0-9A-Fa-f]{0,4}(?::[0-9A-Fa-f]{0,4}){2,7}(?:\.\d{1,3}){0,3}(?:/\d{1,3})?)(?![\w:])")
  101. def unapproved_v6(text: str) -> list[str]:
  102. """IPv6 addresses outside the documentation, ULA, link-local and scope prefixes (fenced code is skipped)."""
  103. bad = []
  104. for part in re.split(r"(?m)^```.*?^```", text, flags=re.DOTALL | re.MULTILINE):
  105. for m in V6_TOKEN.finditer(part):
  106. raw = m.group(1)
  107. if raw.count(":") < 2 or raw.strip(":") == "" or raw in ALLOWED_LITERALS:
  108. continue
  109. try:
  110. net = ipaddress.ip_network(raw, strict=False)
  111. except ValueError:
  112. continue # a time such as 22:09:47, or a MAC address
  113. mapped = net.network_address.ipv4_mapped
  114. if mapped is not None: # ::ffff:a.b.c.d is fine only when a.b.c.d is an RFC 5737 address
  115. if not any(mapped in n for n in DOC_V4):
  116. bad.append(raw)
  117. elif not any(net.subnet_of(a) for a in ALLOWED_V6):
  118. bad.append(raw)
  119. return bad
  120. def test_every_ipv6_address_in_the_page_is_a_documentation_ula_or_scope_address():
  121. assert not unapproved_v6(page())
  122. def test_the_address_check_flags_real_looking_and_mistyped_addresses():
  123. flagged = unapproved_v6(
  124. "Real looking 2606:4700::1111 and 2a00:1450:4001::2004, mistyped 2001:db9::1, "
  125. "a mapped one ::ffff:8.8.8.8, a /48 of 2001:db80::/32, and a loose 2000::/4 route."
  126. )
  127. assert flagged == ["2606:4700::1111", "2a00:1450:4001::2004", "2001:db9::1", "::ffff:8.8.8.8", "2001:db80::/32", "2000::/4"]
  128. assert not unapproved_v6("Fine: 2001:db8::10, fd12:3456:789a::1, fe80::1, ff02::1, ::1, ::ffff:192.0.2.5, the route ::/0 and 2000::/3.")
  129. def test_the_page_never_shows_a_real_looking_ipv4_address():
  130. # Every dotted quad in prose must be documentation (RFC 5737), private, loopback or a /0 literal.
  131. quad = re.compile(r"(?<![\w.])(\d{1,3}(?:\.\d{1,3}){3})(?![\w.])")
  132. ok = [ipaddress.ip_network(n) for n in ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24", "127.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")]
  133. bad = []
  134. prose = re.sub(r"[Ss]ections? (?:\d+(?:\.\d+)*(?:, and |, | and )?)+", "section N", page()) # RFC section numbers look like dotted quads
  135. for part in re.split(r"(?m)^```.*?^```", prose, flags=re.DOTALL | re.MULTILINE):
  136. for m in quad.finditer(part):
  137. addr = ipaddress.ip_address(m.group(1)) if all(int(x) < 256 for x in m.group(1).split(".")) else None
  138. if addr is not None and str(addr) != "0.0.0.0" and not any(addr in n for n in ok):
  139. bad.append(m.group(1))
  140. assert not bad, bad
  141. def test_every_statistic_carries_a_retrieval_date_and_the_register_says_numbers_drift():
  142. text = page()
  143. register = text[text.index("## Claims register") :]
  144. assert "2026-10-22" in register
  145. assert "drift" in register
  146. for needle in ("45.589127", "43.64", "0.005", "M-21-07", "Cloudflare Radar"):
  147. assert needle in register, needle
  148. assert "HTTP 403" in register # the Cloudflare figure is not quoted because it was not read
  149. def test_required_sections_exist():
  150. text = page()
  151. for heading in (
  152. "## What you will be able to do",
  153. "## Why adoption is slow",
  154. "## Why the author has not adopted IPv6",
  155. "## What this project does, and why",
  156. "## Turning it on deliberately: everything that must change together",
  157. "## If IPv6 is disabled on your router (as the maintainer's pfSense has it)",
  158. "## A threat model of a dual-stack host",
  159. "## Build, break, detect, evade, defend (the dual-stack loop)",
  160. "### Flip the board",
  161. "## Claims register",
  162. ):
  163. assert heading in text, heading
  164. assert "**Cost box. Read this before you create anything.**" in text