test_patch_management_lesson.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The patch management lesson keeps the promises it makes (issue #325).
  3. docs/wiki/Patch-Management-and-Automatic-Security-Updates.md is partly run and partly written
  4. from reading. These tests hold what a machine can hold: the honest status banner, a dated
  5. claims-register row for every vendor page it cites, no real address or credential shape, the
  6. triage script on the page runs and raises exactly the four alerts the page says it raises, and
  7. the registrations. Each guard has a case proving it bites.
  8. """
  9. import ipaddress
  10. import os
  11. import re
  12. import subprocess
  13. from pathlib import Path
  14. import pytest
  15. from wikitext import nav_text
  16. ROOT = Path(__file__).resolve().parent.parent
  17. WIKI = ROOT / "docs" / "wiki"
  18. PAGE = WIKI / "Patch-Management-and-Automatic-Security-Updates.md"
  19. FENCE = re.compile(r"^```(\w*)\n(.*?)^```$", re.MULTILINE | re.DOTALL)
  20. IPV4 = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
  21. DOC_NETS = [ipaddress.ip_network(n) for n in ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24")]
  22. SECRET_SHAPE = re.compile(r"(?i)(password|passwd|token|secret)\s*[:=]\s*(?!\$|<|\{|\.\.\.|')[^\s`]{4,}")
  23. VENDOR = re.compile(r"https://(?:documentation\.ubuntu\.com|manpages\.debian\.org|wiki\.debian\.org|dnf\.readthedocs\.io)/[^\s)|]+")
  24. PATCH_GREMLIN = "https://github.com/ChiefGyk3D/Patch-Gremlin"
  25. def text() -> str:
  26. return PAGE.read_text(encoding="utf-8")
  27. def real_addresses(body: str) -> list[str]:
  28. bad = []
  29. for m in IPV4.findall(body):
  30. try:
  31. ip = ipaddress.ip_address(m)
  32. except ValueError:
  33. continue
  34. if ip.is_loopback or ip.is_unspecified:
  35. continue
  36. if not any(ip in net for net in DOC_NETS):
  37. bad.append(m)
  38. return bad
  39. def register_rows(body: str) -> list[str]:
  40. section = body.split("## Claims register", 1)[1]
  41. return [line for line in section.splitlines() if line.startswith("|")]
  42. def script() -> str:
  43. found = [b for tag, b in FENCE.findall(text()) if tag == "bash" and "uu-triage.sh - read" in b]
  44. assert len(found) == 1, f"expected one uu-triage.sh block, found {len(found)}"
  45. return found[0]
  46. LOGS = {
  47. "ok": ["2026-10-29 06:19:10,100 INFO Starting unattended upgrades script"],
  48. "applied": [
  49. "2026-10-29 06:19:10,100 INFO Starting unattended upgrades script",
  50. "2026-10-29 06:19:12,000 INFO Packages that will be upgraded: libc6 python3-jinja2",
  51. "2026-10-29 06:19:30,000 INFO All upgrades installed",
  52. ],
  53. "reboot": [
  54. "2026-10-29 06:19:10,100 INFO Starting unattended upgrades script",
  55. "2026-10-29 06:19:31,000 WARNING Found /var/run/reboot-required, rebooting",
  56. ],
  57. "failed": [
  58. "2026-10-28 06:19:10,100 INFO Starting unattended upgrades script",
  59. "2026-10-28 06:19:30,000 ERROR an old failure from a previous run",
  60. "2026-10-29 06:19:10,100 INFO Starting unattended upgrades script",
  61. "2026-10-29 06:19:30,000 ERROR Installing the upgrades failed!",
  62. ],
  63. "oldfailure": [
  64. "2026-10-28 06:19:10,100 INFO Starting unattended upgrades script",
  65. "2026-10-28 06:19:30,000 ERROR an old failure from a previous run",
  66. "2026-10-29 06:19:10,100 INFO Starting unattended upgrades script",
  67. ],
  68. "dryrun": [
  69. "2026-10-29 06:19:10,100 INFO Starting unattended upgrades script",
  70. "2026-10-29 06:19:12,000 INFO Packages that will be upgraded: zlib1g",
  71. "2026-10-29 06:19:13,000 INFO Option --dry-run given, *not* performing real actions",
  72. ],
  73. "empty": ["2026-10-29 06:19:10,100 DEBUG nothing useful"],
  74. }
  75. @pytest.fixture()
  76. def triage(tmp_path):
  77. sh = tmp_path / "uu-triage.sh"
  78. sh.write_text(script())
  79. for name, lines in LOGS.items():
  80. (tmp_path / f"{name}.log").write_text("\n".join(lines) + "\n")
  81. def run(name, now="2026-10-29 12:00:00", flag=None, *extra):
  82. env = {
  83. "PATH": os.environ["PATH"],
  84. "TZ": "UTC",
  85. "REBOOT_FLAG": str(flag or tmp_path / "no-such-flag"),
  86. "TRIAGE_NOW": subprocess.run(["date", "-u", "-d", now, "+%s"], capture_output=True, text=True, check=True).stdout.strip(),
  87. }
  88. done = subprocess.run(["bash", str(sh), str(tmp_path / f"{name}.log"), *extra], capture_output=True, text=True, env=env, timeout=60, check=False)
  89. return done.returncode, done.stdout
  90. run.dir = tmp_path
  91. run.script = sh
  92. return run
  93. def test_page_exists_and_opens_with_an_honest_status_banner():
  94. banner = next(line for line in text().splitlines() if line.startswith("> **"))
  95. assert "partly run" in banner.lower()
  96. assert "written from reading" in banner.lower()
  97. def test_every_vendor_url_in_the_page_has_a_dated_register_row():
  98. body = text()
  99. rows = [r for r in register_rows(body) if VENDOR.search(r) or PATCH_GREMLIN in r]
  100. cited = set(VENDOR.findall(body))
  101. registered = set(VENDOR.findall("\n".join(rows)))
  102. assert len(registered) >= 4, "the register must cover Ubuntu, the man page, Debian and DNF"
  103. assert cited <= registered, cited - registered
  104. for r in rows:
  105. assert re.search(r"2026-10-30", r), r
  106. assert "Read" in r or "README read" in r, r
  107. def test_patch_gremlin_is_linked_by_its_real_url_and_described_as_readme_only():
  108. body = text()
  109. assert PATCH_GREMLIN in body
  110. assert "I did not read its code" in body
  111. assert any(PATCH_GREMLIN in r and "code not read" in r for r in register_rows(body))
  112. def test_no_real_address_and_no_credential_shape():
  113. body = text()
  114. assert real_addresses(body) == []
  115. assert SECRET_SHAPE.findall(body) == []
  116. def test_guards_bite():
  117. assert real_addresses("host 8.8.8.8 and 192.0.2.5") == ["8.8.8.8"]
  118. assert SECRET_SHAPE.findall("token: abcd1234") != []
  119. assert SECRET_SHAPE.findall("token: $TOKEN") == []
  120. assert VENDOR.findall("see https://wiki.debian.org/UnattendedUpgrades.") != []
  121. assert VENDOR.findall("see https://example.org/page") == []
  122. def test_the_four_alerts_are_raised_and_only_those(triage):
  123. code, out = triage("ok")
  124. assert (code, out.strip()) == (0, "OK nothing to report")
  125. code, out = triage("applied")
  126. assert code == 0 and "NOTICE applied: libc6 python3-jinja2" in out
  127. code, out = triage("reboot")
  128. assert code == 1 and "WARNING reboot" in out
  129. code, out = triage("failed")
  130. assert code == 2 and "CRITICAL failed: 1 ERROR" in out
  131. code, out = triage("empty")
  132. assert code == 2 and "stale: no run recorded" in out
  133. def test_the_stale_alert_fires_only_past_the_limit(triage):
  134. assert triage("ok", "2026-10-30 06:00:00")[0] == 0 # 24 hours, inside the 36-hour default
  135. code, out = triage("ok", "2026-11-02 12:00:00")
  136. assert code == 2 and "newest run began 101 hours ago" in out
  137. assert triage("ok", "2026-10-30 06:00:00", None, "12")[0] == 2 # a tighter limit bites
  138. def test_only_the_newest_run_counts(triage):
  139. code, out = triage("oldfailure")
  140. assert code == 0, out
  141. def test_a_reboot_flag_file_raises_the_warning(triage):
  142. flag = triage.dir / "flag"
  143. flag.write_text("")
  144. code, out = triage("ok", flag=flag)
  145. assert code == 1 and "WARNING reboot" in out
  146. def test_a_dry_run_is_not_reported_as_applied(triage):
  147. code, out = triage("dryrun")
  148. assert code == 0 and "dry run, nothing installed" in out and "applied:" not in out
  149. def test_usage_and_unreadable_log_have_their_own_exit_codes(triage):
  150. bare = subprocess.run(["bash", str(triage.script)], capture_output=True, text=True, check=False)
  151. assert bare.returncode == 64
  152. missing = subprocess.run(["bash", str(triage.script), str(triage.dir / "nope.log")], capture_output=True, text=True, check=False)
  153. assert missing.returncode == 2
  154. def test_the_script_is_read_only(triage):
  155. body = script()
  156. for word in ("rm ", "curl", "wget", "apt-get", "systemctl", "> /"):
  157. assert word not in body, word
  158. def test_registered_everywhere():
  159. name = "Patch-Management-and-Automatic-Security-Updates.md"
  160. for page in ("Contents.md", "Reading-Order.md", "Droplet-Hardening.md"):
  161. assert name in (WIKI / page).read_text(), page
  162. assert "Patch-Management-and-Automatic-Security-Updates" in nav_text(WIKI)
  163. glossary = (WIKI / "Glossary.md").read_text()
  164. for term in ("Allowed origins", "Needrestart", "Patch Gremlin", "Reboot-required flag", "Stale-host alert"):
  165. assert f"| **{term}** |" in glossary, term