test_rate_limiting_lesson.py 4.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. """The simulations on the rate limiting lesson run, and print what the page says they print.
  2. docs/wiki/Rate-Limiting-at-Every-Layer.md teaches with Python scripts the learner saves from the page.
  3. Exercises 1 and 2 are simulations on a pretend clock, so their output is exact and is compared with the
  4. output block printed on the page. Exercise 8 starts a tiny API on 127.0.0.1 (a random free port) and uses
  5. the real clock, so only the shape of its output is checked. Nothing leaves the machine.
  6. """
  7. import re
  8. import subprocess
  9. import sys
  10. from pathlib import Path
  11. WIKI = Path(__file__).resolve().parent.parent / "docs" / "wiki"
  12. PAGE = WIKI / "Rate-Limiting-at-Every-Layer.md"
  13. # The lesson was split into a hub and parts (issue #562); the scripts and output blocks sit in the parts.
  14. PAGES = [PAGE, *sorted(WIKI.glob("Rate-Limiting-at-Every-Layer-Part-*.md"))]
  15. FENCE = re.compile(r"^```(\w*)\n(.*?)^```$", re.MULTILINE | re.DOTALL)
  16. def lesson_text() -> str:
  17. return "\n".join(path.read_text(encoding="utf-8") for path in PAGES)
  18. def blocks(tag: str) -> list[str]:
  19. text = lesson_text()
  20. return [b for t, b in FENCE.findall(text) if t == tag]
  21. def script(marker: str) -> str:
  22. found = [b for b in blocks("python") if b.startswith(marker)]
  23. assert len(found) == 1, f"expected one python block starting {marker!r}, found {len(found)}"
  24. return found[0]
  25. def run(code: str, tmp_path: Path, name: str) -> str:
  26. path = tmp_path / name
  27. path.write_text(code, encoding="utf-8")
  28. done = subprocess.run([sys.executable, "-I", str(path)], check=False, capture_output=True, text=True, timeout=60, cwd=tmp_path)
  29. assert done.returncode == 0, done.stderr
  30. return done.stdout.strip("\n")
  31. def printed(first_line: str) -> str:
  32. found = [b.strip("\n") for b in blocks("text") if b.strip("\n").startswith(first_line)]
  33. assert len(found) == 1, f"expected one text block starting {first_line!r}, found {len(found)}"
  34. return found[0]
  35. def test_algorithms_print_what_the_page_shows(tmp_path):
  36. out = run(script("# algos.py"), tmp_path, "algos.py")
  37. assert out == printed("Scenario 1: 12 requests at t=0")
  38. # The point of the lesson: only the fixed window lets ten through across a boundary.
  39. scenario2 = out.split("Scenario 2")[1].split("Scenario 3")[0]
  40. assert re.search(r"fixed window\s+allowed 10 of 10", scenario2)
  41. assert re.search(r"sliding window log\s+allowed 5 of 10", scenario2)
  42. assert re.search(r"token bucket \(cap 5\)\s+allowed 5 of 10", scenario2)
  43. def test_a_client_at_the_average_rate_is_never_refused(tmp_path):
  44. out = run(script("# algos.py"), tmp_path, "algos.py")
  45. scenario3 = out.split("Scenario 3")[1]
  46. assert len(re.findall(r"allowed 30 of 30", scenario3)) == 4
  47. def test_the_key_choice_decides_who_is_hurt(tmp_path):
  48. out = run(script("# keys.py"), tmp_path, "keys.py")
  49. assert out == printed("per address (each /128 alone)")
  50. rows = {line.split("legit")[0].strip(): line for line in out.splitlines()}
  51. assert "attacker blocked 0 of 600" in rows["per address (each /128 alone)"]
  52. assert "legit blocked 0 of 480" in rows["per account"]
  53. def test_per_key_quota_demo_shape(tmp_path):
  54. out = run(script("# apikeys.py"), tmp_path, "apikeys.py").splitlines()
  55. assert out[0].endswith("[200, 200, 200, 200, 200, 429, 429, 429]")
  56. assert "[200, 200, 200]" in out[1]
  57. assert "[200, 200, 429, 429]" in out[2]
  58. assert out[3].startswith("key A again : 429, Retry-After: ")
  59. assert out[4].endswith(": 200")
  60. assert "429, Retry-After: 86400" in out[5]
  61. def test_the_demo_prints_no_key_and_the_page_has_no_key_shaped_literal(tmp_path):
  62. code = script("# apikeys.py")
  63. assert "token_hex" in code # keys are made at run time
  64. out = run(code, tmp_path, "apikeys.py")
  65. assert not re.search(r"\b[0-9a-f]{16}\b", out)
  66. text = lesson_text()
  67. assert not re.search(r"Bearer [A-Za-z0-9_\-]{16,}", text)
  68. def test_the_lab_only_publishes_on_loopback():
  69. text = lesson_text()
  70. ports = re.findall(r"-p (\S+):\d+:\d+", text)
  71. assert ports and all(p == "127.0.0.1" for p in ports)
  72. assert "docker.sock" not in text and "--privileged" not in text