test_dmz_lesson.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. """The DMZ lesson: its exercise output is real, the tests and files it cites exist, and it is registered.
  2. docs/wiki/The-DMZ-and-Hardening-a-Host-That-Faces-the-Internet.md teaches from the unbuilt edge design and
  3. cites tests as the check for each hardening item. A cited test that does not exist, or an exercise whose
  4. shown output is not what the commands print, teaches the wrong thing.
  5. """
  6. import re
  7. import shlex
  8. import subprocess
  9. from pathlib import Path
  10. ROOT = Path(__file__).resolve().parent.parent
  11. WIKI = ROOT / "docs" / "wiki"
  12. NAME = "The-DMZ-and-Hardening-a-Host-That-Faces-the-Internet.md"
  13. PAGE = WIKI / NAME
  14. FENCE = re.compile(r"^```(\w*)\n(.*?)^```$", re.MULTILINE | re.DOTALL)
  15. PATH = re.compile(r"`((?:stacks|modules|scripts|tests|\.spacelift|docs/stages|docs/superpowers)/[A-Za-z0-9_./-]+)`")
  16. PYTEST_ID = re.compile(r"`(tests/[A-Za-z0-9_]+\.py)::([A-Za-z0-9_]+)`")
  17. TFTEST = re.compile(r"`([a-z0-9_]+)`")
  18. def text() -> str:
  19. return PAGE.read_text(encoding="utf-8")
  20. def blocks() -> list[str]:
  21. return [b for t, b in FENCE.findall(text()) if t == "text"]
  22. def commands() -> list[str]:
  23. found = [b for b in blocks() if b.startswith("grep ")]
  24. assert len(found) == 1, "expected one command block"
  25. return [ln for ln in found[0].splitlines() if ln.strip()]
  26. def shown() -> str:
  27. found = [b for b in blocks() if b.startswith("93:")]
  28. assert len(found) == 1, "expected one output block"
  29. return found[0].strip()
  30. def run_all(cmds: list[str]) -> str:
  31. out = []
  32. for cmd in cmds:
  33. argv = shlex.split(cmd) # no shell: a pipe or a semicolon would be a plain argument
  34. assert argv[0] == "grep"
  35. done = subprocess.run(argv, cwd=ROOT, capture_output=True, text=True, timeout=30, check=False)
  36. out.append(done.stdout.rstrip("\n"))
  37. return "\n".join(out).strip()
  38. def test_the_exercise_prints_what_the_page_shows():
  39. assert run_all(commands()) == shown()
  40. def test_the_guard_bites_on_a_wrong_output():
  41. assert run_all(commands()) != shown().replace("policy drop", "policy accept")
  42. def test_every_repository_path_the_page_cites_exists():
  43. cited = sorted(set(PATH.findall(text())))
  44. assert len(cited) >= 8, "the guard collected too little"
  45. missing = [c for c in cited if not (ROOT / c.rstrip("/")).exists()]
  46. assert not missing, missing
  47. def test_every_pytest_the_page_names_exists():
  48. ids = PYTEST_ID.findall(text())
  49. assert len(ids) >= 5, "the guard collected too little"
  50. for file, name in ids:
  51. assert re.search(rf"(?m)^def {name}\(", (ROOT / file).read_text(encoding="utf-8")), (file, name)
  52. def test_every_tofu_test_the_page_names_exists():
  53. tests = (ROOT / "modules/edge-host/tests/edge-host.tftest.hcl").read_text() + (ROOT / "stacks/50-edge/tests/edge.tftest.hcl").read_text()
  54. named = [n for n in TFTEST.findall(text()) if "_" in n and not n.startswith("test_") and n.islower() and "." not in n]
  55. wanted = [n for n in named if n in {
  56. "no_ports_means_no_accept_rules_and_a_default_drop_table",
  57. "public_and_restricted_ports_render_into_the_host_firewall",
  58. "the_user_data_has_no_ssh_path",
  59. "the_droplet_has_no_admin_path_and_no_public_v6",
  60. "the_reboot_time_defaults_to_the_services_slot_in_eastern",
  61. "no_service_is_installed",
  62. "every_public_inbound_rule_is_ipv4_only",
  63. "enabled_opens_reticulum_and_mqtt_only_so_i2pd_and_iperf3_stay_closed",
  64. }]
  65. assert len(set(wanted)) == 8, wanted
  66. for n in set(wanted):
  67. assert f'run "{n}"' in tests, n
  68. def test_the_page_says_the_edge_is_design_only():
  69. t = text()
  70. assert "design only" in t.lower()
  71. assert "not approved" in t
  72. assert "written from reading" in t
  73. assert "issue #325" in t and "(issue #325" in t
  74. def test_the_page_links_the_patch_lesson_now_that_it_exists():
  75. t = text()
  76. target = "Patch-Management-and-Automatic-Security-Updates"
  77. assert f"]({target}.md)" in t, "the patch management lesson exists, so it must be linked"
  78. assert (WIKI / f"{target}.md").is_file()
  79. # The stale statements that the lesson is not written are gone; the issue number stays.
  80. assert "which is not written yet" not in t and "Named only; not written" not in t
  81. assert "issue #325" in t
  82. def test_the_page_uses_no_real_address():
  83. for ip in re.findall(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", text()):
  84. assert ip in {"169.254.169.254"}, ip
  85. def test_the_page_is_registered_everywhere_pages_are():
  86. for name in ("_Sidebar.md", "Contents.md", "Reading-Order.md", "Glossary.md", "_nav.yaml"):
  87. assert NAME[:-3] in (WIKI / name).read_text(encoding="utf-8") or NAME in (WIKI / name).read_text(encoding="utf-8"), name
  88. CHECKLIST = WIKI / "DMZ-Hardening-Checklist.md"
  89. def checklist() -> str:
  90. return CHECKLIST.read_text(encoding="utf-8")
  91. def test_the_checklist_cites_only_tests_and_paths_that_exist():
  92. t = checklist()
  93. paths = sorted(set(PATH.findall(t)))
  94. assert len(paths) >= 5, "the guard collected too little"
  95. assert not [c for c in paths if not (ROOT / c.rstrip("/")).exists()]
  96. ids = PYTEST_ID.findall(t)
  97. assert len(ids) >= 5, "the guard collected too little"
  98. for file, name in ids:
  99. assert re.search(rf"(?m)^def {name}\(", (ROOT / file).read_text(encoding="utf-8")), (file, name)
  100. tofu = (ROOT / "modules/edge-host/tests/edge-host.tftest.hcl").read_text() + (ROOT / "stacks/50-edge/tests/edge.tftest.hcl").read_text()
  101. named = {n for n in TFTEST.findall(t) if n.islower() and n.count("_") >= 3 and not n.startswith("test_")}
  102. assert len(named) >= 6, named
  103. assert not [n for n in named if f'run "{n}"' not in tofu]
  104. def test_every_checklist_row_names_a_check_or_says_none():
  105. rows = [ln for ln in checklist().split("## What to log")[0].splitlines() if ln.startswith("| [ ]")]
  106. assert len(rows) >= 12, "the guard collected too little"
  107. for ln in rows:
  108. last = ln.rstrip().rstrip("|").rsplit("|", 1)[-1]
  109. assert "`" in last or "**None" in last, ln
  110. def test_the_checklist_guard_bites_on_a_row_with_neither():
  111. bad = "| [ ] | Something | Design | we thought about it |"
  112. last = bad.rstrip().rstrip("|").rsplit("|", 1)[-1]
  113. assert not ("`" in last or "**None" in last)
  114. def test_the_checklist_is_honest_about_the_edge_and_leaks_nothing():
  115. t = checklist()
  116. assert "design only" in t.lower() and "not approved" in t and "written from reading" in t
  117. assert not re.search(r"\]\([^)]*(?:325|[Pp]atch-[Mm]anagement)[^)]*\)", t)
  118. for ip in re.findall(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", t):
  119. assert ip in {"169.254.169.254"}, ip
  120. def test_the_checklist_is_registered_and_the_lesson_still_names_its_rows():
  121. for name in ("Contents.md", "Reading-Order.md", "_nav.yaml"):
  122. assert "DMZ-Hardening-Checklist" in (WIKI / name).read_text(encoding="utf-8"), name