test_patch_management_lesson.py 8.2 KB

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