test_bcp_dr_lesson.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The business continuity and disaster recovery lesson: registered, honest about what was run, and checkable.
  3. docs/wiki/Business-Continuity-and-Disaster-Recovery-BCP-and-DR.md teaches BCP versus DR and plans recovery for this
  4. project's own pieces. A broken link, a missing registration, a recovery step cited from a file that does not exist, a
  5. sample output that no longer matches the script, a claim with no status, or a link that pushes another lesson over its
  6. link cap would each teach the wrong thing.
  7. """
  8. import re
  9. import subprocess
  10. import sys
  11. from pathlib import Path
  12. ROOT = Path(__file__).resolve().parent.parent
  13. WIKI = ROOT / "docs" / "wiki"
  14. NAME = "Business-Continuity-and-Disaster-Recovery-BCP-and-DR"
  15. PAGE = WIKI / f"{NAME}.md"
  16. FENCE = re.compile(r"^```(\w*)\n(.*?)^```$", re.MULTILINE | re.DOTALL)
  17. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#[^)]*)?\)")
  18. ADDR = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
  19. REPO_URL = "https://github.com/ChiefGyk3D/Clouds-Against-Humanity/blob/main/"
  20. STATUS_WORDS = ("Read", "Observed", "Not read", "General knowledge", "**est.**", "Common practice")
  21. BLAST = "Plan-for-Failure-Blast-Radius-and-Assuming-Breach"
  22. PIECES = ("1. The repository", "2. The secret store", "3. Spacelift state", "4. Twingate", "5. The connectors", "6. The wiki", "7. The home logging server")
  23. def text() -> str:
  24. return PAGE.read_text(encoding="utf-8")
  25. def blocks(tag: str) -> list[str]:
  26. return [b for t, b in FENCE.findall(text()) if t == tag]
  27. def csv_blocks() -> list[str]:
  28. return [b for b in blocks("text") if b.startswith("system,tier,")]
  29. def register_rows(body: str) -> list[list[str]]:
  30. reg = body.split("## Claims register")[1].split("## Where to next")[0]
  31. rows = [line for line in reg.splitlines() if line.startswith("|") and not line.startswith("|---")]
  32. return [[c.strip() for c in r.strip("|").split("|")] for r in rows[1:]]
  33. def rows_missing_status(body: str) -> list[str]:
  34. return [r[0] for r in register_rows(body) if not any(w in r[-1] for w in STATUS_WORDS)]
  35. def cited_repo_paths(body: str) -> set[str]:
  36. paths = set(re.findall(re.escape(REPO_URL) + r"([A-Za-z0-9_./-]+?)(?:#[^)]*)?\)", body))
  37. paths |= set(re.findall(r"`((?:tests|scripts|docs|\.github)/[A-Za-z0-9_./-]+)`", body))
  38. return paths
  39. def missing_paths(paths: set[str]) -> list[str]:
  40. return sorted(p for p in paths if not (ROOT / p).exists())
  41. def run_checker(tmp: Path, table: str, today: str = "2026-10-31") -> subprocess.CompletedProcess:
  42. script, data = tmp / "bia_check.py", tmp / "table.csv"
  43. script.write_text(blocks("python")[0], encoding="utf-8")
  44. data.write_text(table, encoding="utf-8")
  45. return subprocess.run([sys.executable, "-I", str(script), str(data), "--today", today], capture_output=True, text=True, timeout=60, check=False)
  46. def test_the_page_exists_and_says_what_was_and_was_not_run():
  47. body = text()
  48. assert body.startswith("# Business continuity and disaster recovery")
  49. assert "Status: unverified draft" in body
  50. assert "no recovery procedure on this page was run" in body
  51. assert "2026-10-31" in body
  52. assert "ever been timed" in body
  53. def test_every_linked_wiki_page_exists():
  54. links = set(LINK.findall(text()))
  55. assert len(links) >= 8, "the guard collected too few links"
  56. missing = sorted(t for t in links if not (WIKI / f"{t}.md").exists())
  57. assert not missing, missing
  58. def test_the_lesson_is_registered_everywhere():
  59. nav = (WIKI / "_nav.yaml").read_text(encoding="utf-8")
  60. assert f"page: {NAME}," in nav and 'status: "draft"' in nav.split(f"page: {NAME},")[1].split("\n")[0]
  61. for special in ("Contents.md", "Reading-Order.md"):
  62. assert f"{NAME}.md" in (WIKI / special).read_text(encoding="utf-8"), special
  63. rows = [line for line in (WIKI / "Glossary.md").read_text(encoding="utf-8").splitlines() if f"{NAME}.md" in line]
  64. assert len(rows) >= 7, "expected glossary rows for the new terms"
  65. def test_glossary_rows_point_at_real_headings():
  66. heads = {re.sub(r"[^a-z0-9-]", "", h.lower().replace(" ", "-")) for h in re.findall(r"^#+ (.+)$", text(), re.MULTILINE)}
  67. anchors: set[str] = set()
  68. for line in (WIKI / "Glossary.md").read_text(encoding="utf-8").splitlines():
  69. anchors.update(re.findall(rf"{NAME}\.md#([a-z0-9-]+)", line))
  70. assert anchors, "the guard collected nothing"
  71. assert anchors <= heads, sorted(anchors - heads)
  72. def test_related_lessons_link_the_new_one():
  73. skip = {"Glossary.md", "_Sidebar.md", "Reading-Order.md", "Contents.md", PAGE.name}
  74. inbound = [p.name for p in WIKI.glob("*.md") if p.name not in skip and f"{NAME}.md" in p.read_text(encoding="utf-8")]
  75. assert len(inbound) >= 4, inbound
  76. def test_the_blast_radius_lesson_is_named_in_plain_text_so_its_link_cap_holds():
  77. # tests/test_blast_radius_lesson.py caps the pages that link that lesson at 9, and it is already at 9.
  78. assert f"{BLAST}.md" not in text()
  79. assert "blast radius and assuming breach" in text()
  80. def test_the_cap_guard_bites():
  81. assert f"{BLAST}.md" in "see [x](Plan-for-Failure-Blast-Radius-and-Assuming-Breach.md)"
  82. def test_no_addresses_and_no_em_dashes():
  83. body = text()
  84. assert not ADDR.findall(body), set(ADDR.findall(body))
  85. assert "—" not in body
  86. assert "Python" in body, "the guard collected nothing"
  87. def test_the_address_guard_bites():
  88. assert ADDR.findall("ping 192.0.2.7")
  89. def test_every_claims_register_row_has_a_status():
  90. rows = register_rows(text())
  91. assert len(rows) >= 20, "the guard collected too few rows"
  92. assert not rows_missing_status(text())
  93. def test_the_register_guard_bites():
  94. bad = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | y | maybe |\n\n## Where to next\n"
  95. assert rows_missing_status(bad) == ["X"]
  96. def test_the_sources_are_dated_and_the_unread_one_is_not_cited():
  97. body = text()
  98. reg = body.split("## Claims register")[1]
  99. for needle in ("NIST SP 800-34", "Ready.gov", "AWS Well-Architected", "CISA #StopRansomware", "GitLab", "Atlassian", "CrowdStrike"):
  100. row = next((line for line in reg.splitlines() if needle in line), "")
  101. assert "Read 2026-10-31" in row, needle
  102. assert "returned \"404 - Page not found\"" in body
  103. assert "Not read: the page returned" in reg
  104. def test_the_four_postmortems_carry_their_dates():
  105. section = text().split("## Lessons from public postmortems")[1].split("## A worked plan for this project")[0]
  106. for date in ("10 February 2017", "29 April 2022", "19 to 20 October 2025", "August 2024"):
  107. assert date in section, date
  108. def test_the_project_plan_covers_all_seven_pieces_with_steps_and_coverage():
  109. plan = text().split("## A worked plan for this project")[1].split("## Free exercises")[0]
  110. for piece in PIECES:
  111. assert f"### {piece}" in plan, piece
  112. assert plan.count("**Recovery steps**") == 7 and plan.count("**Covered by**") == 7
  113. assert plan.count("**Proposed RTO / RPO**") == 7
  114. assert "**None.**" in plan or "**None**" in plan, "the plan must say None where nothing exists"
  115. assert "proposals" in plan and "never timed" in plan
  116. def test_every_repository_file_the_page_cites_exists():
  117. paths = cited_repo_paths(text())
  118. assert len(paths) >= 8, "the guard collected too few paths"
  119. assert not missing_paths(paths)
  120. def test_the_path_guard_bites():
  121. assert missing_paths({"docs/stages/99-not-a-stage.md"}) == ["docs/stages/99-not-a-stage.md"]
  122. def test_the_checker_output_on_the_page_matches_a_real_run(tmp_path):
  123. body = text()
  124. tables = csv_blocks()
  125. assert len(tables) == 2, "expected the project table and the broken table"
  126. done = run_checker(tmp_path, tables[0])
  127. assert done.returncode == 0, done.stdout + done.stderr
  128. for line in done.stdout.strip().splitlines():
  129. assert line in body, line
  130. assert "7 systems, 0 fail, 2 warn" in done.stdout
  131. def test_the_broken_table_fails_in_the_ways_the_page_says(tmp_path):
  132. done = run_checker(tmp_path, csv_blocks()[1])
  133. assert done.returncode == 1
  134. assert done.stdout.count("FAIL") == 4
  135. for needle in ("cannot meet an RPO of 4 h", "shop: RTO 2 h is shorter than database's 8 h", "cache: RTO 1 h is shorter", "'queue', which is not in the table"):
  136. assert needle in done.stdout, needle
  137. assert "WARN shop: the last restore test (2024-01-05) is more than a year old" in done.stdout
  138. def test_the_checker_passes_a_sound_table(tmp_path):
  139. sound = "system,tier,rto_hours,rpo_hours,copy_every_hours,last_restore_test,depends_on\ndb,0,8,4,4,2026-09-01,\napp,1,12,4,4,2026-09-01,db\n"
  140. done = run_checker(tmp_path, sound)
  141. assert done.returncode == 0 and "0 fail, 0 warn" in done.stdout, done.stdout
  142. def test_the_tabletop_has_its_ground_rules_and_five_injects():
  143. section = text().split("### Exercise 4: a free tabletop on a scenario from this project")[1].split("## Checkpoint")[0]
  144. assert "Only what is written down counts" in section
  145. assert "at most three findings" in section
  146. injects = re.findall(r"^\d\. \*\*", section, re.MULTILINE)
  147. assert len(injects) == 5, injects
  148. assert "could not read DIGITALOCEAN_TOKEN from Doppler" in section
  149. assert "nothing is run, restored or changed" in section
  150. def test_the_bcp_and_dr_definitions_are_attributed_to_nist():
  151. section = text().split("## BCP and DR: two plans, not one")[1].split("## Business impact analysis")[0]
  152. assert "NIST SP 800-34 Rev. 1" in section
  153. assert "sustaining an organization's mission/business processes" in section
  154. assert "information system-focused plan" in section