test_backups_deep_dive_lesson.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The backups deep dive lesson: its drill runs, its citations exist, it is registered and honest about what was run.
  3. docs/wiki/Backups-Deep-Dive-3-2-1-1-0-Immutability-and-Restore-Testing.md extends the Backups page with 3-2-1-1-0,
  4. immutable copies, key custody and restore testing, and lists what this project would have to back up with the file
  5. for each (or None). A cited file that does not exist, a drill whose output differs from the page, a missing
  6. registration or a real address would each teach the wrong thing.
  7. """
  8. import os
  9. import re
  10. import shutil
  11. import subprocess
  12. import textwrap
  13. from pathlib import Path
  14. import pytest
  15. from wikitext import glossary_text, nav_text
  16. ROOT = Path(__file__).resolve().parent.parent
  17. WIKI = ROOT / "docs" / "wiki"
  18. NAME = "Backups-Deep-Dive-3-2-1-1-0-Immutability-and-Restore-Testing"
  19. PAGE = WIKI / f"{NAME}.md"
  20. FENCE = re.compile(r"^[ ]*```(\w*)\n(.*?)^[ ]*```$", re.MULTILINE | re.DOTALL)
  21. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#[^)]*)?\)")
  22. ADDR = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
  23. PATH_TOKEN = re.compile(r"`((?:modules|stacks|scripts|docs|\.github|\.spacelift|tests)/[A-Za-z0-9_./-]+|board\.yaml|\.gitignore)`")
  24. STATUS_WORDS = ("Read", "Observed", "Not run", "**est.**", "General knowledge")
  25. RAID_LESSON = "RAID-Levels-Parity-Rebuilds-and-Why-RAID-Is-Continuity-Not-a-Backup"
  26. BCP_LESSON = "Business-Continuity-and-Disaster-Recovery-BCP-and-DR"
  27. RAID_SECTION = "## RAID is business continuity, not a backup"
  28. TOPICS = (
  29. RAID_SECTION,
  30. "## From 3-2-1 to 3-2-1-1-0",
  31. "## Backup types: full, incremental, differential",
  32. "## Immutable and offline copies",
  33. "## Encryption and key custody",
  34. "## Backing up the backup system itself",
  35. "## Restore testing",
  36. "## Retention and legal holds",
  37. "## The ransomware angle",
  38. "## Cloud traps",
  39. "## Where this shows up in this project",
  40. "## Free path: a restore drill on your own computer",
  41. "## Claims register",
  42. )
  43. def text() -> str:
  44. return PAGE.read_text(encoding="utf-8")
  45. def section(body: str, start: str, end: str) -> str:
  46. return body.split(start)[1].split(end)[0]
  47. def table_rows(block: str) -> list[list[str]]:
  48. rows = [line for line in block.splitlines() if line.startswith("|") and not line.startswith("|---")]
  49. return [[c.strip() for c in r.strip("|").split("|")] for r in rows[1:]]
  50. def cited_paths(cell: str) -> list[str]:
  51. return PATH_TOKEN.findall(cell)
  52. def rows_missing_citation(rows: list[list[str]]) -> list[str]:
  53. """A project row must cite files that exist, or start with None in its file column and say None in its status."""
  54. bad = []
  55. for r in rows:
  56. files, status = r[2], r[3]
  57. paths = cited_paths(files)
  58. if any(not (ROOT / p).exists() for p in paths):
  59. bad.append(r[0])
  60. elif files.startswith("None"):
  61. if "None" not in status:
  62. bad.append(r[0])
  63. elif not paths:
  64. bad.append(r[0])
  65. return bad
  66. def project_rows(body: str) -> list[list[str]]:
  67. return table_rows(section(body, "## Where this shows up in this project", "Four honest notes"))
  68. def register_rows(body: str) -> list[list[str]]:
  69. return table_rows(body.split("## Claims register")[1])
  70. def rows_missing_status(rows: list[list[str]]) -> list[str]:
  71. return [r[0] for r in rows if not any(w in r[-1] for w in STATUS_WORDS)]
  72. def test_the_banner_says_what_was_and_was_not_run():
  73. body = text()
  74. assert body.startswith("# Backups deep dive")
  75. assert "Status: unverified draft" in body
  76. assert "**Not run:**" in body and "2026-10-31" in body
  77. def test_every_topic_the_issue_asked_for_has_a_section():
  78. body = text()
  79. missing = [t for t in TOPICS if f"\n{t}\n" not in body]
  80. assert not missing, missing
  81. def test_the_coiner_of_3_2_1_1_0_is_named_with_a_page_and_dates():
  82. body = text()
  83. assert "At Veeam, we extended the rule to 3-2-1-1-0" in body
  84. assert "February 5, 2024" in body and "July 3, 2026" in body
  85. assert "https://www.veeam.com/blog/321-backup-rule.html" in body
  86. for needle in ("SP 800-34", "StopRansomware"):
  87. assert needle in body, needle
  88. def test_every_linked_wiki_page_exists():
  89. links = set(LINK.findall(text()))
  90. assert len(links) >= 8, "the guard collected too few links"
  91. missing = sorted(t for t in links if not (WIKI / f"{t}.md").exists())
  92. assert not missing, missing
  93. def test_the_blast_radius_lesson_is_named_in_plain_text_and_the_continuity_lesson_is_linked():
  94. # tests/test_blast_radius_lesson.py caps how many pages may link the blast radius lesson, so it is not linked
  95. # from here. The continuity lesson is merged and is linked (issue 421).
  96. body = text()
  97. assert "Plan-for-Failure-Blast-Radius" not in body
  98. assert "business continuity and disaster recovery" in body
  99. assert f"]({BCP_LESSON}.md" in body
  100. assert f"]({RAID_LESSON}.md" in body
  101. def raid_section(body: str) -> str:
  102. return section(body, RAID_SECTION, "\n## From 3-2-1 to 3-2-1-1-0")
  103. def test_the_page_leads_with_raid_as_continuity_and_not_a_backup():
  104. body = text()
  105. opening = body.split("> Unfamiliar word or acronym?")[0]
  106. assert "RAID" in opening and "not a backup" in opening, "the opening paragraph carries the framing"
  107. assert body.index(RAID_SECTION) < body.index("## From 3-2-1 to 3-2-1-1-0"), "the RAID section comes first"
  108. assert body.index(RAID_SECTION) < body.index("## Backup types"), "the RAID section comes before the backup types"
  109. sec = raid_section(body)
  110. for needed in (
  111. "business continuity",
  112. "availability",
  113. "not a backup",
  114. "at most one copy",
  115. "deletion",
  116. "corruption",
  117. "ransomware",
  118. "site",
  119. "SP 800-34",
  120. "cannot be a replacement for a solid backup strategy",
  121. "Without a backup of the system separate from the system itself",
  122. "Linux Raid Wiki",
  123. "backup, backup, BACK UP",
  124. "RAID is not a panacea",
  125. "Patterson",
  126. "backup versions of all information every night",
  127. ):
  128. assert needed in sec, needed
  129. for link in (BCP_LESSON, RAID_LESSON, "The-CIA-Triad-Confidentiality-Integrity-Availability"):
  130. assert f"]({link}.md" in sec, link
  131. def test_the_raid_section_has_a_table_that_says_what_each_event_does_to_raid_and_to_a_backup():
  132. sec = raid_section(text())
  133. rows = table_rows(sec)
  134. assert len(rows) >= 7, "the guard collected too few rows"
  135. events = " ".join(r[0] for r in rows).lower()
  136. for needed in ("drive", "deleted", "ransomware", "corrupt", "controller", "fire"):
  137. assert needed in events, needed
  138. # a drive failure is the one row where RAID helps; every other row says RAID does not
  139. first = rows[0]
  140. assert "Yes" in first[1] and "drive" in first[0].lower()
  141. assert sum("**No**" in r[1] for r in rows) >= 5
  142. assert sum("**No**" in r[2] for r in rows) <= 2, "a backup is not a cure for everything either"
  143. def test_the_raid_section_guard_bites():
  144. assert raid_section(f"x\n{RAID_SECTION}\nbody\n\n## From 3-2-1 to 3-2-1-1-0\ny") == "\nbody\n"
  145. bad = ["a drive fails", "Yes", "Yes"], ["ransomware", "Yes", "Yes"]
  146. assert sum("**No**" in r[1] for r in bad) == 0
  147. def test_the_banner_and_summary_say_the_raid_section_was_added_on_2026_11_01_from_reading():
  148. body = text()
  149. banner = body.split("## What you will be able to do")[0]
  150. assert "2026-11-01" in banner and "issue 421" in banner
  151. low = body.split("## What you will be able to do")[1].split("## What the wiki already says")[0].lower()
  152. assert "raid" in low and "not a backup" in low
  153. def test_the_register_carries_the_raid_sources_read_on_2026_11_01():
  154. rows = register_rows(text())
  155. joined = " ".join(r[1] for r in rows)
  156. for host in (
  157. "nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-34r1.pdf",
  158. "raid.wiki.kernel.org/index.php/How_to_protect_your_data",
  159. "www2.eecs.berkeley.edu/Pubs/TechRpts/1987/CSD-87-391.pdf",
  160. ):
  161. assert host in joined, host
  162. assert sum("2026-11-01" in r[-1] for r in rows) >= 3
  163. assert not rows_missing_status(rows)
  164. def test_the_common_mistakes_table_names_the_raid_is_a_backup_mistake():
  165. block = section(text(), "## Common mistakes", "## Claims register")
  166. assert any("RAID" in r[0] and "backup" in r[0].lower() for r in table_rows(block))
  167. def test_the_lesson_is_registered_in_contents_and_reading_order_not_the_sidebar():
  168. nav = nav_text(WIKI)
  169. entry = nav.split(f"page: {NAME},")[1].split("\n")[0]
  170. assert 'status: "draft"' in entry
  171. assert "sidebar" not in entry, "new lessons are reached from Contents and Reading Order, not the sidebar"
  172. for special in ("Contents.md", "Reading-Order.md"):
  173. assert f"{NAME}.md" in (WIKI / special).read_text(encoding="utf-8"), special
  174. rows = [line for line in glossary_text(WIKI).splitlines() if f"{NAME}.md" in line]
  175. assert len(rows) >= 5, "expected glossary rows for the new terms"
  176. def test_glossary_rows_point_at_real_headings():
  177. heads = {re.sub(r"[^a-z0-9-]", "", h.lower().replace(" ", "-")) for h in re.findall(r"^#+ (.+)$", text(), re.MULTILINE)}
  178. anchors = set()
  179. for line in glossary_text(WIKI).splitlines():
  180. anchors.update(re.findall(rf"{NAME}\.md#([a-z0-9-]+)", line))
  181. assert anchors, "the guard collected nothing"
  182. assert anchors <= heads, sorted(anchors - heads)
  183. def test_the_backups_page_links_the_lesson():
  184. assert f"{NAME}.md" in (WIKI / "Backups-Recovery-and-Patching.md").read_text(encoding="utf-8")
  185. def test_no_addresses_and_no_em_dashes():
  186. body = text()
  187. assert not ADDR.findall(body)
  188. assert "—" not in body
  189. def test_the_address_guard_bites():
  190. assert ADDR.findall("ping 192.0.2.7")
  191. def test_every_project_row_cites_an_existing_file_or_says_none():
  192. rows = project_rows(text())
  193. assert len(rows) >= 10, "the guard collected too few rows"
  194. assert not rows_missing_citation(rows)
  195. assert sum(r[2].startswith("None") for r in rows) >= 4, "the table should say None where nothing exists"
  196. wanted = ("repository", "wiki", "Issues", "OpenTofu state", "secret store", "Twingate", "backup system itself", "timed restore")
  197. joined = " ".join(r[0] for r in rows)
  198. assert all(w in joined for w in wanted), [w for w in wanted if w not in joined]
  199. def test_the_citation_guard_bites():
  200. rows = [
  201. ["a", "x", "`scripts/does_not_exist.py`", "Built"],
  202. ["b", "x", "`scripts/secret_rule.py`", "Built"],
  203. ["c", "x", "None here", "Built"],
  204. ["d", "x", "None; the design is in `docs/does/not/exist.md`", "None"],
  205. ["e", "x", "no path at all", "Built"],
  206. ]
  207. assert rows_missing_citation(rows) == ["a", "c", "d", "e"]
  208. def test_every_repository_path_the_page_names_exists():
  209. paths = set(cited_paths(text()))
  210. assert len(paths) >= 10, "the guard collected too few paths"
  211. assert not [p for p in sorted(paths) if not (ROOT / p).exists()]
  212. def test_the_immutability_table_names_what_it_does_not_protect_against():
  213. block = section(text(), "### What immutability protects against, and what it does not", "Notice that **versioning is not immutability.**")
  214. rows = table_rows(block)
  215. assert len(rows) >= 6
  216. assert sum("**No**" in r[1] for r in rows) >= 3
  217. assert any("account" in r[0] for r in rows)
  218. def test_the_key_custody_table_has_a_circular_and_a_single_holder_case():
  219. block = section(text(), "## Encryption and key custody", "## Backing up the backup system itself")
  220. assert "single point of failure" in block and "A circle" in block
  221. assert "irrecoverably lost" in block
  222. def test_every_claims_register_row_has_a_status():
  223. rows = register_rows(text())
  224. assert len(rows) >= 20, "the guard collected too few rows"
  225. assert not rows_missing_status(rows)
  226. assert any("nvlpubs.nist.gov" in r[1] for r in rows) and any("cisa.gov/stopransomware" in r[1] for r in rows)
  227. assert sum("2026-10-31" in r[-1] for r in rows) >= 10
  228. def test_the_register_guard_bites():
  229. assert rows_missing_status([["X", "y", "maybe"]]) == ["X"]
  230. def script() -> str:
  231. found = [textwrap.dedent(b) for t, b in FENCE.findall(text()) if t == "bash" and "# backup_drill.sh - " in b]
  232. assert len(found) == 1, f"expected one backup_drill.sh block, found {len(found)}"
  233. return found[0]
  234. @pytest.mark.skipif(any(shutil.which(t) is None for t in ("sha256sum", "tar", "openssl", "dd")), reason="GNU coreutils, tar and openssl are needed")
  235. def test_the_drill_runs_and_its_output_matches_the_page(tmp_path):
  236. path = tmp_path / "backup_drill.sh"
  237. path.write_text(script())
  238. done = subprocess.run(["bash", str(path)], capture_output=True, text=True, timeout=120, check=False, env={**os.environ, "TMPDIR": str(tmp_path)})
  239. assert done.returncode == 0, done.stderr
  240. shown = next(b for t, b in FENCE.findall(text()) if t == "text" and b.startswith("== Backup types"))
  241. norm = re.compile(r"took \d+ ms")
  242. got = [line.rstrip() for line in norm.sub("took N ms", done.stdout).strip().splitlines()]
  243. want = [line.rstrip() for line in norm.sub("took N ms", shown).strip().splitlines()]
  244. assert got == want
  245. assert not any(tmp_path.glob("tmp*")), "the script must delete its own lab folder"
  246. def test_the_drill_never_touches_anything_outside_its_own_folder():
  247. body = script()
  248. assert "mktemp -d" in body
  249. for line in body.splitlines():
  250. if line.startswith(("rm ", "chmod ", "tar ", "cp ")):
  251. assert not re.search(r"\s/(?!$)", line), line
  252. assert not re.search(r"\bsudo\b|\bcurl\b|\bwget\b|\bchattr\b", body)
  253. assert "of=copy-a/backup.tgz" in body, "the only deliberate damage is to the drill's own copy"