test_attack_surface_map.py 4.4 KB

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