test_attack_surface_lesson.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """The attack surface lesson: its script runs and prints what the page shows, and its citations hold.
  2. docs/wiki/Attack-Surface-List-Shrink-Measure.md cites repository files as evidence and teaches with a
  3. loopback script. A script that does not run, or a cited file that does not exist, teaches the wrong thing.
  4. """
  5. import re
  6. import subprocess
  7. import sys
  8. from pathlib import Path
  9. ROOT = Path(__file__).resolve().parent.parent
  10. PAGE = ROOT / "docs" / "wiki" / "Attack-Surface-List-Shrink-Measure.md"
  11. FENCE = re.compile(r"^```(\w*)\n(.*?)^```$", re.MULTILINE | re.DOTALL)
  12. PATH = re.compile(r"`((?:stacks|modules|scripts|tests|\.spacelift)/[A-Za-z0-9_./-]+)`")
  13. def blocks(tag: str) -> list[str]:
  14. return [b for t, b in FENCE.findall(PAGE.read_text(encoding="utf-8")) if t == tag]
  15. def test_the_loopback_script_prints_what_the_page_shows(tmp_path):
  16. scripts = blocks("python")
  17. assert len(scripts) == 1
  18. path = tmp_path / "door.py"
  19. path.write_text(scripts[0], encoding="utf-8")
  20. done = subprocess.run([sys.executable, "-I", str(path)], capture_output=True, text=True, timeout=60, cwd=tmp_path, check=False)
  21. assert done.returncode == 0, done.stderr
  22. shown = [b for b in blocks("text") if b.startswith("ports tried:")]
  23. assert len(shown) == 1
  24. assert done.stdout.strip() == shown[0].strip()
  25. def test_the_script_only_ever_names_the_loopback_address():
  26. code = blocks("python")[0]
  27. addresses = re.findall(r"\"(\d+\.\d+\.\d+\.\d+)\"", code)
  28. assert addresses, "the guard collected nothing"
  29. assert set(addresses) == {"127.0.0.1"}
  30. def test_the_guard_bites_on_a_foreign_address():
  31. sample = 'probe.connect_ex(("192.0.2.1", port))'
  32. assert set(re.findall(r"\"(\d+\.\d+\.\d+\.\d+)\"", sample)) != {"127.0.0.1"}
  33. def test_every_repository_path_the_page_cites_exists():
  34. cited = sorted(set(PATH.findall(PAGE.read_text(encoding="utf-8"))))
  35. assert len(cited) >= 8, "the guard collected too little"
  36. missing = [c for c in cited if not (ROOT / c.rstrip("/")).exists()]
  37. assert not missing, missing
  38. def test_the_page_states_the_authorization_rule_and_the_port_move_rule():
  39. text = PAGE.read_text(encoding="utf-8")
  40. assert "written permission" in text
  41. assert "## The port-move rule" in text
  42. assert "not protection" in text