test_attack_surface_map.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. """The attack surface map page: its layers are complete and every file it cites exists.
  2. docs/wiki/Attack-Surface-Map-Layer-by-Layer.md cites repository files, and tests or OpenTofu run blocks
  3. by name (path::name), as the evidence for each row. A cited file that does not exist, or a cited name that
  4. is not in it, teaches the wrong thing.
  5. """
  6. import re
  7. from pathlib import Path
  8. from wikitext import nav_text
  9. ROOT = Path(__file__).resolve().parent.parent
  10. WIKI = ROOT / "docs" / "wiki"
  11. NAME = "Attack-Surface-Map-Layer-by-Layer"
  12. PAGE = WIKI / f"{NAME}.md"
  13. LAYERS = [
  14. "Layer 1: the cloud account",
  15. "Layer 2: Spacelift and CI",
  16. "Layer 3: Doppler",
  17. "Layer 4: Twingate",
  18. "Layer 5: the droplets",
  19. "Layer 6: telemetry",
  20. "Layer 7: the edge",
  21. "Layer 8: the web tier",
  22. ]
  23. CITE = re.compile(r"`((?:stacks|modules|scripts|tests|labs|docs|\.spacelift|\.github)/[A-Za-z0-9_./-]+?)(?:::([A-Za-z0-9_]+))?`")
  24. HEADER = "| What an attacker could aim at |"
  25. def text() -> str:
  26. return PAGE.read_text(encoding="utf-8")
  27. def layer_rows(body: str) -> dict[str, list[list[str]]]:
  28. """Map each layer heading to its table rows, split into cells."""
  29. out: dict[str, list[list[str]]] = {}
  30. current = None
  31. for line in body.splitlines():
  32. if line.startswith("## "):
  33. current = line[3:].strip()
  34. out[current] = []
  35. elif current and line.startswith("|") and not line.startswith(HEADER) and not re.match(r"\|[-| ]+\|$", line):
  36. out[current].append([c.strip() for c in line.strip().strip("|").split("|")])
  37. return out
  38. def row_problems(cells: list[str], root: Path = ROOT) -> list[str]:
  39. """What is wrong with one row: not five cells, a blank cell, or a bad citation."""
  40. if len(cells) != 5:
  41. return [f"{len(cells)} cells, expected 5"]
  42. problems = [f"blank cell {i}" for i, c in enumerate(cells) if not c]
  43. cites = CITE.findall(cells[4])
  44. if not cites:
  45. problems.append("the Where cell cites no repository file")
  46. if not (cells[2].startswith("None") or CITE.search(cells[2])):
  47. problems.append("the test cell names no test and does not start with None")
  48. for cell in cells:
  49. for path, name in CITE.findall(cell):
  50. target = root / path
  51. if not target.exists():
  52. problems.append(f"missing: {path}")
  53. elif name and name not in target.read_text(encoding="utf-8", errors="replace"):
  54. problems.append(f"{path} has no {name}")
  55. return problems
  56. def test_all_eight_layers_are_present_in_order():
  57. headings = [h for h in layer_rows(text()) if h.startswith("Layer ")]
  58. assert headings == LAYERS
  59. def test_every_layer_has_rows_and_every_row_is_complete_and_cited():
  60. rows = layer_rows(text())
  61. total = 0
  62. for layer in LAYERS:
  63. assert rows[layer], f"{layer} has no rows"
  64. for cells in rows[layer]:
  65. total += 1
  66. assert not row_problems(cells), (layer, cells[0][:50], row_problems(cells))
  67. assert total >= 25, "the guard collected too few rows"
  68. def test_every_citation_anywhere_on_the_page_exists():
  69. cited = sorted(set(CITE.findall(text())))
  70. assert len(cited) >= 40, "the guard collected too little"
  71. bad = [(p, n) for p, n in cited if not (ROOT / p).exists() or (n and n not in (ROOT / p).read_text(encoding="utf-8", errors="replace"))]
  72. assert not bad, bad
  73. def test_the_guard_bites_on_a_bad_row():
  74. good = ["aim", "control", "`tests/test_attack_surface_map.py`", "log", "`tests/test_attack_surface_map.py`"]
  75. assert row_problems(good) == []
  76. assert row_problems(good[:4])
  77. assert row_problems(["aim", "", good[2], "log", good[4]])
  78. assert row_problems(good[:4] + ["`tests/no_such_file.py`"])
  79. assert row_problems(good[:4] + ["`tests/test_ipv6_closed.py::no_such_test_name_xyz`"])
  80. assert row_problems(good[:2] + ["it is tested somewhere"] + good[3:])
  81. assert row_problems(["aim", "control", "None. A setting.", "log", "no citation"])
  82. def test_the_page_states_its_limits():
  83. body = text()
  84. assert "built but off by default" in body
  85. assert "None" in body and "recommendation" in body.lower()
  86. assert "unverified" in body.lower()
  87. def test_the_page_uses_no_real_address():
  88. for ip in re.findall(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", text()):
  89. assert ip == "169.254.169.254", ip
  90. def test_the_page_is_registered_everywhere_pages_are():
  91. for name in ("Contents.md", "Reading-Order.md", "Glossary.md"):
  92. assert NAME in (WIKI / name).read_text(encoding="utf-8"), name
  93. assert NAME in nav_text(WIKI)