test_vm_hypervisors_lesson.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The virtual machines and hypervisors lesson: it is registered, honest about what was run, and safe to follow.
  3. docs/wiki/Virtual-Machines-Hypervisors-Desktop-and-Datacenter-Options.md teaches a first VM, network modes and a
  4. dated account of the VMware licensing changes. A broken link, a missing registration, a bridged-network command in a
  5. lab page, a real address, or a vendor claim with no status would each teach the wrong thing.
  6. """
  7. import re
  8. import shutil
  9. import subprocess
  10. import textwrap
  11. from pathlib import Path
  12. import pytest
  13. ROOT = Path(__file__).resolve().parent.parent
  14. WIKI = ROOT / "docs" / "wiki"
  15. NAME = "Virtual-Machines-Hypervisors-Desktop-and-Datacenter-Options"
  16. PAGE = WIKI / f"{NAME}.md"
  17. FENCE = re.compile(r"^[ ]*```(\w*)\n(.*?)^[ ]*```$", re.MULTILINE | re.DOTALL)
  18. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#[^)]*)?\)")
  19. ADDR = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
  20. STATUS_WORDS = ("Read", "Observed", "Page read", "General knowledge", "**est.**")
  21. def text() -> str:
  22. return PAGE.read_text(encoding="utf-8")
  23. def blocks(tag: str) -> list[str]:
  24. return [textwrap.dedent(b) for t, b in FENCE.findall(text()) if t == tag]
  25. def register_rows(body: str) -> list[list[str]]:
  26. reg = body.split("## Claims register")[1]
  27. rows = [line for line in reg.splitlines() if line.startswith("|") and not line.startswith("|---")]
  28. return [[c.strip() for c in r.strip("|").split("|")] for r in rows[1:]]
  29. def rows_missing_status(body: str) -> list[str]:
  30. return [r[0] for r in register_rows(body) if not any(r[-1].startswith(w) or w in r[-1] for w in STATUS_WORDS)]
  31. def unsafe_network_lines(commands: str) -> list[str]:
  32. return [l for l in commands.splitlines() if re.search(r"-(nic|netdev|net)\s+(bridge|tap)|\bbridge=|--network\s+bridged|nic\d?\s+bridged", l)]
  33. def test_the_page_exists_and_says_what_was_and_was_not_run():
  34. body = text()
  35. assert body.startswith("# Virtual machines for beginners")
  36. assert "Status: unverified draft" in body
  37. assert "no hypervisor was installed and no guest was booted" in body
  38. assert "**Not run:**" in body and "2026-10-31" in body
  39. assert "Not verified, plainly" in body
  40. def test_every_linked_wiki_page_exists():
  41. links = set(LINK.findall(text()))
  42. assert len(links) >= 8, "the guard collected too few links"
  43. missing = sorted(t for t in links if not (WIKI / f"{t}.md").exists())
  44. assert not missing, missing
  45. def test_the_lesson_is_registered_everywhere():
  46. nav = (WIKI / "_nav.yaml").read_text(encoding="utf-8")
  47. assert f"page: {NAME}," in nav and 'status: "draft"' in nav.split(f"page: {NAME},")[1].split("\n")[0]
  48. for special in ("Contents.md", "_Sidebar.md", "Reading-Order.md"):
  49. assert f"{NAME}.md" in (WIKI / special).read_text(encoding="utf-8"), special
  50. rows = [l for l in (WIKI / "Glossary.md").read_text(encoding="utf-8").splitlines() if f"{NAME}.md" in l]
  51. assert len(rows) >= 5, "expected glossary rows for the new terms"
  52. def test_glossary_rows_point_at_real_headings():
  53. heads = {re.sub(r"[^a-z0-9 -]", "", h.lower()).strip().replace(" ", "-") for h in re.findall(r"^#+ (.+)$", text(), re.MULTILINE)}
  54. heads = {re.sub(r"[^a-z0-9-]", "", h.replace(" ", "-")) for h in heads}
  55. anchors = set()
  56. for line in (WIKI / "Glossary.md").read_text(encoding="utf-8").splitlines():
  57. anchors.update(re.findall(rf"{NAME}\.md#([a-z0-9-]+)", line))
  58. assert anchors, "the guard collected nothing"
  59. assert anchors <= heads, sorted(anchors - heads)
  60. def test_existing_pages_that_assume_a_vm_or_linux_host_link_the_lesson():
  61. users = [p.name for p in WIKI.glob("*.md") if p.name != PAGE.name and f"{NAME}.md" in p.read_text(encoding="utf-8")]
  62. skip = {"Glossary.md", "_Sidebar.md", "Reading-Order.md", "Contents.md"}
  63. inbound = [u for u in users if u not in skip]
  64. assert len(inbound) >= 4, inbound
  65. def test_no_addresses_except_loopback_and_no_em_dashes():
  66. body = text()
  67. found = set(ADDR.findall(body))
  68. assert found <= {"127.0.0.1"}, found
  69. assert "127.0.0.1" in found, "the guard collected nothing"
  70. assert "—" not in body
  71. def test_the_address_guard_bites():
  72. assert set(ADDR.findall("ping 192.0.2.7")) != {"127.0.0.1"}
  73. def test_the_lab_commands_never_bridge_the_guest_onto_a_real_network():
  74. cmds = "\n".join(blocks("bash"))
  75. assert "qemu-system-x86_64" in cmds and "-nic user" in cmds, "the guard collected nothing"
  76. assert not unsafe_network_lines(cmds)
  77. def test_the_network_guard_bites():
  78. assert unsafe_network_lines("qemu-system-x86_64 -nic bridge,br=br0")
  79. assert unsafe_network_lines("qemu-system-x86_64 -netdev tap,id=n0")
  80. assert not unsafe_network_lines("qemu-system-x86_64 -nic user,model=virtio-net-pci")
  81. def test_the_safety_rule_names_the_three_core_steps():
  82. rule = text().split("## The safety rule for malware and recon labs")[1].split("## Free path")[0]
  83. assert "Isolate the network first" in rule
  84. assert "Snapshot a clean state first" in rule
  85. assert "Never bridge a hostile VM onto your home LAN" in rule
  86. def test_the_checksum_step_comes_before_the_first_boot():
  87. body = text()
  88. assert body.index("sha256sum -c") < body.index("qemu-system-x86_64 -accel kvm")
  89. assert "do not boot an image that fails its check" in body
  90. digest = re.search(r"`([0-9a-f]{64})`", body)
  91. assert digest, "the example checksum is missing"
  92. def test_every_claims_register_row_has_a_status():
  93. rows = register_rows(text())
  94. assert len(rows) >= 25, "the guard collected too few rows"
  95. assert not rows_missing_status(text())
  96. def test_the_register_guard_bites():
  97. bad = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | y | maybe |\n"
  98. assert rows_missing_status(bad) == ["X"]
  99. def test_the_vmware_account_is_dated_and_cites_vendor_and_news_sources():
  100. body = text()
  101. section = body.split("## VMware after Broadcom: a dated account")[1].split("## The bigger options")[0]
  102. for date in ("2023-11-22", "2023-12-11", "May 2024", "2024-11-11", "2025-03-10", "2025-04-10"):
  103. assert date in section, date
  104. for needle in ("BBC News", "Ars Technica", "release notes", "**est.**"):
  105. assert needle in section, needle
  106. assert "not verified" in section.lower()
  107. assert "Read" in section
  108. def test_the_page_names_the_apple_options_from_apples_own_pages():
  109. body = text()
  110. assert "Virtualization framework" in body and "macOS 11.0" in body
  111. assert "`container`" in body and "macOS 26" in body
  112. @pytest.mark.skipif(shutil.which("qemu-img") is None, reason="qemu-img is not installed")
  113. def test_exercise_3_runs_and_the_snapshot_round_trips(tmp_path):
  114. block = next(b for b in blocks("bash") if "qemu-img create" in b)
  115. script = block.replace("cd ~/vmlab", f"cd {tmp_path}")
  116. result = subprocess.run(["bash", "-eu", "-c", script], capture_output=True, text=True, timeout=60, check=False)
  117. assert result.returncode == 0, result.stderr
  118. assert "virtual size: 4 GiB" in result.stdout
  119. assert "clean-start" in result.stdout
  120. # the last listing, after the delete, shows no snapshot line after the final info block
  121. assert result.stdout.count("clean-start") == 1