test_email_security_lesson.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. # SPDX-License-Identifier: Apache-2.0
  2. """Checks for the email security lesson and labs/email-security.
  3. The local lab is pure Python plus the `openssl` command, so the page's claims about it are tested
  4. directly: the evaluator's results on the synthetic messages, the SPF limit, a broken DKIM body,
  5. the DMARC report parser and its refusal of DOCTYPE, the triage hints, the position toy. The
  6. OpenTofu pieces are checked for flag-off defaults, and validated when `tofu` exists and can
  7. download its provider (skipped otherwise). Nothing here touches the network except that download.
  8. """
  9. import asyncio
  10. import importlib
  11. import json
  12. import re
  13. import shutil
  14. import subprocess
  15. import sys
  16. from pathlib import Path
  17. import pytest
  18. ROOT = Path(__file__).resolve().parent.parent
  19. LAB = ROOT / "labs" / "email-security"
  20. LOCAL = LAB / "local"
  21. PAGE = ROOT / "docs" / "wiki" / "Email-Security-DNS-Gateways-and-API-Driven-Protection.md"
  22. needs_openssl = pytest.mark.skipif(shutil.which("openssl") is None, reason="openssl is needed to build the lab keys")
  23. @pytest.fixture(scope="module")
  24. def mods():
  25. sys.path.insert(0, str(LOCAL))
  26. try:
  27. yield {n: importlib.import_module(n) for n in ("dkimlite", "mailauth", "mkmail", "triage", "dmarc_report", "positions")}
  28. finally:
  29. sys.path.remove(str(LOCAL))
  30. @pytest.fixture(scope="module")
  31. def built(tmp_path_factory, mods):
  32. if shutil.which("openssl") is None:
  33. pytest.skip("openssl is needed")
  34. out = tmp_path_factory.mktemp("emaillab")
  35. out.chmod(0o700)
  36. assert mods["mkmail"].main(str(out)) == 0
  37. return out
  38. def results(built, mods):
  39. res = mods["mailauth"].FileResolver(built / "zone.json")
  40. got = {}
  41. for m in json.loads((built / "manifest.json").read_text()):
  42. got[Path(m["file"]).stem] = mods["mailauth"].evaluate(res, (built / m["file"]).read_bytes(), m["client_ip"], m["mail_from"])
  43. return got
  44. @needs_openssl
  45. def test_dmarc_outcomes_match_the_page(built, mods):
  46. r = results(built, mods)
  47. assert (r["01-legit-internal-signed"]["dmarc"], r["01-legit-internal-signed"]["disposition"]) == ("pass", "deliver")
  48. # a hired mailer passes SPF and DKIM for ITS domain and still fails DMARC for ours
  49. u = r["02-newsletter-bulk-unaligned"]
  50. assert (u["spf"], u["dkim"][0]["result"], u["dmarc"], u["disposition"]) == ("pass", "pass", "fail", "quarantine")
  51. a = r["03-newsletter-bulk-aligned"]
  52. assert (a["dmarc"], a["spf_aligned"], a["dkim_aligned"]) == ("pass", False, True)
  53. f = r["04-forged-ceo"]
  54. assert (f["spf"], f["dmarc"], f["disposition"]) == ("fail", "fail", "quarantine")
  55. # a look-alike authenticates as itself
  56. assert r["05-lookalike-domain"]["dmarc"] == "pass"
  57. assert r["06-display-name-trick"]["dmarc"] == "none"
  58. # forwarding: SPF has nothing, DKIM carries it
  59. fw = r["07-forwarded-by-list"]
  60. assert (fw["dmarc"], fw["dkim_aligned"]) == ("pass", True)
  61. assert r["08-list-rewrote-body"]["dkim"][0]["reason"].startswith("body hash mismatch")
  62. assert r["09-spf-too-many-lookups"]["spf"] == "permerror"
  63. assert r["10-spf-two-records"]["spf"] == "permerror"
  64. # the subdomain policy is stricter than the domain's
  65. assert r["11-subdomain-spoof"]["disposition"] == "reject"
  66. @needs_openssl
  67. def test_spf_limit_is_exactly_ten(built, mods):
  68. res = mods["mailauth"].FileResolver(built / "zone.json")
  69. result, st = mods["mailauth"].spf(res, "203.0.113.201", "toomany.test")
  70. assert result == "permerror" and st.lookups == 11
  71. result, st = mods["mailauth"].spf(res, "203.0.113.200", "toomany.test")
  72. assert result == "pass" and st.lookups == 1 # matched by the first include, before the budget runs out
  73. @needs_openssl
  74. def test_dkim_detects_tampering_and_a_revoked_key(built, mods):
  75. ma, dk = mods["mailauth"], mods["dkimlite"]
  76. res = ma.FileResolver(built / "zone.json")
  77. raw = (built / "msgs" / "01-legit-internal-signed.eml").read_bytes()
  78. def lookup(name):
  79. _, vals = res.query(name, "TXT")
  80. return vals[0] if vals else None
  81. assert dk.verify(raw, lookup)[0]["result"] == "pass"
  82. assert dk.verify(raw.replace(b"Are we still on", b"Are we NOT on"), lookup)[0]["result"] == "fail"
  83. assert dk.verify(raw.replace(b"Subject: Lunch on Friday", b"Subject: Lunch on Saturday"), lookup)[0]["result"] == "fail"
  84. assert "revoked" in dk.verify(raw, lambda name: "v=DKIM1; k=rsa; p=")[0]["reason"]
  85. assert dk.verify(raw, lambda name: None)[0]["result"] == "neutral"
  86. @needs_openssl
  87. def test_udp_resolver_parses_a_real_dns_packet(mods):
  88. """The wire parser is exercised against a packet built by hand, with name compression."""
  89. ma = mods["mailauth"]
  90. name = b"\x04_spf\x04test\x00"
  91. txt = b"v=spf1 -all"
  92. pkt = (b"\x00\x01\x81\x80\x00\x01\x00\x01\x00\x00\x00\x00" + name + b"\x00\x10\x00\x01"
  93. + b"\xc0\x0c\x00\x10\x00\x01\x00\x00\x00\x1e" + (len(txt) + 1).to_bytes(2, "big") + bytes([len(txt)]) + txt)
  94. class Sock:
  95. def __init__(self, *a):
  96. pass
  97. def __enter__(self):
  98. return self
  99. def __exit__(self, *a):
  100. return False
  101. def settimeout(self, t):
  102. pass
  103. def sendto(self, data, addr):
  104. assert addr == ("127.0.0.1", 5300)
  105. def recvfrom(self, n):
  106. return pkt, ("127.0.0.1", 5300)
  107. real = ma.socket.socket
  108. ma.socket.socket = Sock
  109. try:
  110. assert ma.UdpResolver("127.0.0.1:5300").query("_spf.test", "TXT") == ("NOERROR", ["v=spf1 -all"])
  111. finally:
  112. ma.socket.socket = real
  113. @needs_openssl
  114. def test_dkim_signature_must_cover_from(built, mods):
  115. """Hostile fixture: sign only an unrelated header under the victim's own key. A verifier that
  116. accepts it would let any forged visible From pass DMARC through the DKIM side."""
  117. ma, dk = mods["mailauth"], mods["dkimlite"]
  118. res = ma.FileResolver(built / "zone.json")
  119. forged = (b"From: CEO <ceo@example.test>\r\nTo: bob@receiver.test\r\nSubject: Pay now\r\n"
  120. b"Date: Thu, 22 Oct 2026 14:00:00 +0000\r\nMessage-ID: <x@lab.test>\r\n\r\nWire it today.\r\n")
  121. signed = (dk.sign(forged, "example.test", "s2026a", built / "keys" / "org.pem", names=["subject"]) + "\r\n").encode() + forged
  122. r = ma.evaluate(res, signed, "203.0.113.66", "ceo@example.test")
  123. assert r["dkim"][0]["result"] == "fail" and "From is not in h=" in r["dkim"][0]["reason"]
  124. assert r["dmarc"] == "fail" and not r["dkim_aligned"]
  125. def test_smtpsink_cap_counts_the_current_line(tmp_path, mods):
  126. sink = importlib.import_module("smtpsink")
  127. async def talk(lines):
  128. out = tmp_path / "got.eml"
  129. done = asyncio.Event()
  130. server = await asyncio.start_server(lambda r, w: sink.handle(r, w, str(out), done), "127.0.0.1", 0)
  131. port = server.sockets[0].getsockname()[1]
  132. reader, writer = await asyncio.open_connection("127.0.0.1", port)
  133. await reader.readline()
  134. for line in lines:
  135. writer.write(line)
  136. await writer.drain()
  137. replies = []
  138. try:
  139. while True:
  140. got = await asyncio.wait_for(reader.readline(), timeout=3)
  141. if not got:
  142. break
  143. replies.append(got.decode())
  144. except TimeoutError:
  145. pass
  146. writer.close()
  147. server.close()
  148. return replies, out
  149. head = [b"EHLO a.test\r\n", b"MAIL FROM:<a@a.test>\r\n", b"RCPT TO:<b@b.test>\r\n", b"DATA\r\n"]
  150. # one single oversized line must be refused, and nothing written
  151. replies, out = asyncio.run(talk(head + [b"x" * (sink.MAX_BYTES + 10) + b"\r\n", b".\r\n"]))
  152. assert any(r.startswith("552") for r in replies) and not out.exists()
  153. # many small lines whose last one crosses the cap must be refused too
  154. line = b"y" * 998 + b"\r\n"
  155. n = sink.MAX_BYTES // 1000 + 2
  156. replies, out = asyncio.run(talk(head + [line] * n + [b".\r\n"]))
  157. assert any(r.startswith("552") for r in replies) and not out.exists()
  158. # a small message still goes through
  159. replies, out = asyncio.run(talk(head + [b"Subject: hi\r\n", b"\r\n", b"ok\r\n", b".\r\n"]))
  160. assert any(r.startswith("250 2.0.0") for r in replies) and out.exists()
  161. def test_triage_reads_single_quoted_and_unquoted_hrefs(tmp_path, mods):
  162. tr = mods["triage"]
  163. for href in ("'https://evil.invalid/login'", "https://evil.invalid/login", '"https://evil.invalid/login"'):
  164. eml = tmp_path / "q.eml"
  165. eml.write_bytes(b"From: A <a@random-host.test>\r\nTo: b@receiver.test\r\nSubject: s\r\nMIME-Version: 1.0\r\n"
  166. b"Content-Type: text/html; charset=utf-8\r\n\r\n<p>Go to <a class=x href=" + href.encode()
  167. + b">https://example.com/account</a></p>\r\n")
  168. a = tr.analyze(eml, ["example.test"])
  169. assert ("https://evil.invalid/login", "https://example.com/account") in a["links"], href
  170. assert any("shows example.com but goes to evil.invalid" in f for f in a["flags"]), href
  171. @needs_openssl
  172. def test_added_from_header_breaks_the_signature_and_dmarc(built, mods):
  173. """Parser differential: a second From added above the signed one. DKIM picks the bottom-most
  174. instance, a mail client may show the top one; the verifier and DMARC must not disagree."""
  175. ma, dk = mods["mailauth"], mods["dkimlite"]
  176. res = ma.FileResolver(built / "zone.json")
  177. def lookup(name):
  178. _, vals = res.query(name, "TXT")
  179. return vals[0] if vals else None
  180. original = (built / "msgs" / "01-legit-internal-signed.eml").read_bytes()
  181. body = original.split(b"DKIM-Signature:", 1)[1]
  182. signed = b"DKIM-Signature:" + body # drop the receiver's stamp lines above the signature
  183. assert dk.verify(signed, lookup)[0]["result"] == "pass"
  184. attacked = b"From: CEO <ceo@example.test>\r\n" + signed
  185. r = ma.evaluate(res, attacked, "203.0.113.66", "ceo@example.test")
  186. assert r["dkim"][0]["result"] == "fail" and "more From headers" in r["dkim"][0]["reason"]
  187. assert r["from_headers"] == 2 and r["dmarc"] == "fail" and not r["dkim_aligned"] and not r["spf_aligned"]
  188. # over-signing: h=from:from verifies with exactly one From, and refuses a From added on top
  189. plain = (b"From: Alice <alice@example.test>\r\nTo: bob@receiver.test\r\nSubject: Hi\r\n"
  190. b"Date: Thu, 22 Oct 2026 14:00:00 +0000\r\nMessage-ID: <o@lab.test>\r\n\r\nHello.\r\n")
  191. key = built / "keys" / "org.pem"
  192. over = (dk.sign(plain, "example.test", "s2026a", key, names=["from", "from", "subject", "date"]) + "\r\n").encode() + plain
  193. assert "h=from:from:subject:date" in over.decode()
  194. assert dk.verify(over, lookup)[0]["result"] == "pass"
  195. assert ma.evaluate(res, over, "192.0.2.25", "alice@example.test")["dmarc"] == "pass"
  196. assert dk.verify(b"From: CEO <ceo@example.test>\r\n" + over, lookup)[0]["result"] == "fail"
  197. # a message that really carries two From headers is never a DMARC pass, even if both are signed
  198. twice = b"From: Alice <alice@example.test>\r\n" + plain
  199. both = (dk.sign(twice, "example.test", "s2026a", key, names=["from", "from", "subject"]) + "\r\n").encode() + twice
  200. r2 = ma.evaluate(res, both, "192.0.2.25", "alice@example.test")
  201. assert r2["dkim"][0]["result"] == "pass" and r2["dmarc"] == "fail" and r2["from_headers"] == 2
  202. def _eml(html):
  203. return (b"From: A <a@random-host.test>\r\nTo: b@receiver.test\r\nSubject: s\r\nMIME-Version: 1.0\r\n"
  204. b"Content-Type: text/html; charset=utf-8\r\n\r\n" + html.encode() + b"\r\n")
  205. def test_triage_link_list_cannot_lose_a_link(tmp_path, mods):
  206. tr = mods["triage"]
  207. def run(html):
  208. eml = tmp_path / "t.eml"
  209. eml.write_bytes(_eml(html))
  210. a = tr.analyze(eml, ["example.test"])
  211. return {u for u, _ in a["links"]}, a["flags"]
  212. # duplicate href attributes: browsers use the first; the message is flagged
  213. links, flags = run('<a href="https://first.invalid/" href="https://second.invalid/">https://example.com/</a>')
  214. assert ("https://first.invalid/" in links) and any("more than one href" in f and "first.invalid" in f for f in flags)
  215. assert "https://second.invalid/" in links # not listed by the parser, so the raw scan reports it
  216. assert any("raw scan" in f and "second.invalid" in f for f in flags)
  217. # nested anchors: the open one is saved when the next starts
  218. links, _ = run('<a href="https://one.invalid/">one<a href="https://two.invalid/">two</a>')
  219. assert {"https://one.invalid/", "https://two.invalid/"} <= links
  220. # an anchor still open at the end of the document
  221. links, _ = run('<p>x</p><a href="https://open.invalid/">click')
  222. assert "https://open.invalid/" in links
  223. # uppercase tag and attribute
  224. links, _ = run('<A HREF="https://UPPER.invalid/path">go</A>')
  225. assert "https://UPPER.invalid/path" in links
  226. # a link only the raw scan can reach (not an anchor), and an entity-escaped one
  227. links, flags = run('<map><area href="https://hidden.invalid/x"></map><link href=https://bare.invalid/y>')
  228. assert {"https://hidden.invalid/x", "https://bare.invalid/y"} <= links
  229. assert any("hidden.invalid" in f and "raw scan" in f for f in flags)
  230. links, _ = run('<a href="https://amp.invalid/?a=1&amp;b=2">x</a>')
  231. assert "https://amp.invalid/?a=1&b=2" in links
  232. @needs_openssl
  233. def test_bare_cr_and_multi_address_from_cannot_hide_the_author(built, mods):
  234. """Parser differential: a lone CR can be a line break to one parser and nothing to another."""
  235. ma, dk = mods["mailauth"], mods["dkimlite"]
  236. res = ma.FileResolver(built / "zone.json")
  237. tail = b"To: bob@receiver.test\r\nSubject: Pay\r\nDate: Thu, 22 Oct 2026 14:00:00 +0000\r\n\r\nWire it.\r\n"
  238. # a second From hidden behind a bare CR inside another header's value
  239. hidden = b"X-Note: hello\rFrom: CEO <ceo@example.test>\r\nFrom: Eve <eve@random-host.test>\r\n" + tail
  240. headers, _ = dk.split_message(hidden)
  241. assert [n.lower() for n, _ in headers].count("from") == 2 # the strict reading sees both
  242. r = ma.evaluate(res, hidden, "203.0.113.60", "eve@random-host.test")
  243. assert r["from_headers"] == 2 and r["dmarc"] != "pass"
  244. # the same bytes with LF, CRLF and CR endings mixed must give one answer
  245. for eol in (b"\r\n", b"\n", b"\r"):
  246. two = b"From: Eve <eve@random-host.test>" + eol + b"From: CEO <ceo@example.test>" + eol + b"Subject: x" + eol + eol + b"body" + eol
  247. assert [n.lower() for n, _ in dk.split_message(two)[0]].count("from") == 2, eol
  248. mixed = b"From: a@example.test\r\nSubject: x\n\nbody\r\n"
  249. assert [n for n, _ in dk.split_message(mixed)[0]] == ["From", "Subject"]
  250. # a bare CR with only one From still cannot be a DMARC pass
  251. lone = b"From: Alice <alice@example.test>\rX-Other: y\r\n" + tail
  252. r = ma.evaluate(res, lone, "192.0.2.25", "alice@example.test")
  253. assert r["dmarc"] != "pass" and dk.has_bare_cr(lone) and not dk.has_bare_cr(tail.replace(b"\r\n\r\n", b"\r\n\r\n"))
  254. # one From holding two addresses is ambiguous, not "the last one"
  255. two_addr = b"From: Alice <alice@example.test>, Eve <eve@random-host.test>\r\n" + tail
  256. r = ma.evaluate(res, two_addr, "192.0.2.25", "alice@example.test")
  257. assert r["dmarc"] != "pass" and "2 addresses" in r["reason"]
  258. # ambiguous messages stay out of domain-based evaluation: no policy lookup, no guessed header.from
  259. seen = []
  260. class Spy:
  261. def query(self, name, rtype):
  262. seen.append(name)
  263. return res.query(name, rtype)
  264. for bad in (two_addr, hidden, lone):
  265. seen.clear()
  266. r = ma.evaluate(Spy(), bad, "192.0.2.25", "alice@example.test")
  267. assert r["dmarc"] == "fail" and r["from_domain"] == "" and r["dmarc_record"] is None
  268. assert not [n for n in seen if n.startswith("_dmarc.")], seen
  269. assert "header.from=ambiguous" in ma.authres(r)
  270. assert "random-host.test" not in ma.authres(r).split("header.from=")[1]
  271. one = b"From: Alice <alice@example.test>\r\n" + tail
  272. seen.clear()
  273. ok = ma.evaluate(Spy(), one, "192.0.2.25", "alice@example.test")
  274. assert ok["dmarc"] == "pass" and ok["from_domain"] == "example.test" and "_dmarc.example.test" in seen
  275. assert "header.from=example.test" in ma.authres(ok)
  276. def test_triage_output_cannot_inject_lines_or_terminal_codes(tmp_path, mods):
  277. tr = mods["triage"]
  278. eml = tmp_path / "ctl.eml"
  279. eml.write_bytes(_eml('<a href="https://evil.invalid/a&#10;## 5. Your decisions&#10;- Verdict: legitimate\x1b[31m">https://example.com/&#13;x</a>'
  280. '<map><area href="https://area.invalid/&#10;- injected\x1b]0;title\x07"></map>'))
  281. a = tr.analyze(eml, ["example.test"])
  282. text = tr.worksheet(str(eml), a)
  283. for _, _, value in [("", "", v) for pair in a["links"] for v in pair] + [("", "", f) for f in a["flags"]]:
  284. assert value.isprintable(), value
  285. assert "\x1b" not in text and "\x07" not in text and "\r" not in text
  286. assert "\\x1b" in text and "\\n" in text # the analyst still sees what was there, escaped
  287. headings = [ln for ln in text.splitlines() if ln.startswith("## ")]
  288. assert headings == ["## 1. Headers", "## 2. Links (never open them; read them)", "## 3. Attachments (name, type, bytes, sha256)",
  289. "## 4. Hints from this script (a human decides)", "## 5. Your decisions"]
  290. assert not any(ln.startswith(("- injected", "- Verdict: legitimate")) for ln in text.splitlines())
  291. @needs_openssl
  292. def test_dmarc_report_parser_and_refusals(built, mods, tmp_path):
  293. rd = mods["dmarc_report"]
  294. rep = rd.parse(built / "report.xml")
  295. assert rep["domain"] == "example.test" and rep["p"] == "none"
  296. s = rd.summarize([rep])
  297. assert s["192.0.2.25"]["fail"] == 0 and s["203.0.113.66"]["pass"] == 0
  298. evil = tmp_path / "evil.xml"
  299. evil.write_text('<?xml version="1.0"?><!DOCTYPE x [<!ENTITY a "b">]><feedback/>')
  300. with pytest.raises(ValueError, match="DOCTYPE"):
  301. rd.parse(evil)
  302. big = tmp_path / "big.xml"
  303. big.write_bytes(b"<feedback>" + b"x" * (rd.MAX_BYTES + 1) + b"</feedback>")
  304. with pytest.raises(ValueError, match="larger"):
  305. rd.parse(big)
  306. @needs_openssl
  307. def test_triage_hints(built, mods):
  308. tr = mods["triage"]
  309. hints = " ".join(tr.analyze(built / "msgs" / "05-lookalike-domain.eml", ["example.test"])["flags"])
  310. assert "looks like the protected domain" in hints and "link text shows example.com but goes to payroll-update.invalid" in hints
  311. assert "Reply-To" in hints
  312. assert "display name contains a different address" in " ".join(tr.analyze(built / "msgs" / "06-display-name-trick.eml", ["example.test"])["flags"])
  313. a = tr.analyze(built / "msgs" / "13-double-extension-attachment.eml", ["example.test"])
  314. assert a["attachments"][0][0] == "remittance.pdf.html" and any("double extension" in f for f in a["flags"])
  315. assert any("image" in f for f in tr.analyze(built / "msgs" / "12-qr-image-only.eml", ["example.test"])["flags"])
  316. forged = tr.analyze(built / "msgs" / "04-forged-ceo.eml", ["example.test"])
  317. assert len(forged["authres"]) == 2 and forged["authres"][0].startswith("mx.receiver.test")
  318. ws = tr.worksheet("x", forged)
  319. assert "## 5. Your decisions" in ws and "Verdict" in ws
  320. def test_positions_toy(mods, capsys):
  321. pos = mods["positions"]
  322. assert pos.main(["--lockdown", "yes"]) == 0
  323. out = capsys.readouterr().out
  324. gate = re.search(r"gateway\s+stopped=(\d+) late=(\d+) missed=(\d+)", out)
  325. assert gate and int(gate.group(3)) >= 3 # internal mail, chat and a later verdict are outside its view
  326. pos.main(["--lockdown", "no"])
  327. assert "MISSED" in next(ln for ln in capsys.readouterr().out.splitlines() if ln.startswith("M4 "))
  328. # a locked-down tenant refuses the direct-send message for every position
  329. pos.main(["--lockdown", "yes"])
  330. m4 = next(ln for ln in capsys.readouterr().out.splitlines() if ln.startswith("M4 "))
  331. assert "MISSED" not in m4
  332. def test_no_secret_shaped_literals_in_the_lab():
  333. for f in LAB.rglob("*"):
  334. if f.is_file() and f.suffix in {".py", ".tf", ".md", ".json"}:
  335. text = f.read_text()
  336. assert "PRIVATE KEY" not in text, f
  337. assert not re.search(r"[A-Za-z0-9+/]{100,}={0,2}", text), f"{f}: a long base64-looking run"
  338. def test_cloud_pieces_default_to_off():
  339. for tf in list((LAB / "cloud").rglob("*.tf")) + list((LAB / "compose").rglob("*.tf")):
  340. text = tf.read_text()
  341. for m in re.finditer(r'variable "(enabled|enable_\w+)" \{(.*?)\n\}', text, re.DOTALL):
  342. assert re.search(r"default\s*=\s*false", m.group(2)), f"{tf}: {m.group(1)} must default to false"
  343. assert not re.search(r'variable "\w*token\w*"', text), f"{tf}: a token must come from the environment, not a variable"
  344. comp = (LAB / "compose" / "main.tf").read_text()
  345. assert comp.count("default = false") >= 5
  346. def test_pieces_json_matches_the_price_table():
  347. pieces = json.loads((LAB / "pieces.json").read_text())["pieces"]
  348. prices = json.loads((ROOT / "docs" / "cost-prices.json").read_text())
  349. droplet = next(p for p in pieces if p["name"] == "droplet")
  350. assert droplet["monthly_usd"] == prices["droplets"][droplet["size"]]
  351. assert "$6 at list price" in PAGE.read_text() or "$6 a month" in PAGE.read_text()
  352. for p in pieces: # the destroy order is the reverse of the dependencies
  353. for dep in p["depends_on"]:
  354. other = next(q for q in pieces if q["name"] == dep)
  355. assert other["build"] <= p["build"] and other["destroy"] >= p["destroy"]
  356. @pytest.mark.slow
  357. @pytest.mark.skipif(shutil.which("tofu") is None, reason="tofu is not installed")
  358. def test_tofu_validate(tofu_lab):
  359. env, tree = tofu_lab # copied and initialized once per session (tests/conftest.py)
  360. for d in sorted((tree / "cloud").iterdir()) + [tree / "compose"]:
  361. val = subprocess.run(["tofu", "validate"], cwd=d, env=env, capture_output=True, text=True, check=False)
  362. assert val.returncode == 0, f"{d.name}: {val.stdout}{val.stderr}"
  363. fmt = subprocess.run(["tofu", "fmt", "-check"], cwd=d, env=env, capture_output=True, text=True, check=False)
  364. assert fmt.returncode == 0, f"{d.name}: tofu fmt would change {fmt.stdout}"
  365. def test_page_disclosure_and_links():
  366. text = PAGE.read_text()
  367. assert "—" not in text
  368. assert text.count("https://links.chiefgyk3d.com/productrecs") >= 1
  369. low = text.lower()
  370. assert "affiliate relationships with **both** proton and tuta" in low
  371. assert "not an affiliate" not in low and "no affiliation" not in low
  372. for bad in ("referral", "?ref=", "aff=", "affiliate="):
  373. assert bad not in low.replace("affiliate relationships", ""), bad
  374. why = (ROOT / "docs" / "wiki" / "Why-I-Picked-These-Tools.md").read_text()
  375. assert "affiliate relationships with Proton and with Tuta" in why
  376. # every repository path the page names exists
  377. for rel in re.findall(r"labs/email-security(?:/[\w./-]+)?", text):
  378. rel = rel.rstrip(".")
  379. assert (ROOT / rel).exists(), rel
  380. for needed in ("Cost box. Read this before you create anything.", "Teardown first.", "Flip the board", "## Threat model", "## Claims register"):
  381. assert needed in text
  382. # no real-looking address other than reserved documentation ranges
  383. for ip in re.findall(r"\b(\d{1,3}(?:\.\d{1,3}){3})\b", text):
  384. assert ip.startswith(("192.0.2.", "198.51.100.", "203.0.113.", "127.0.0.")) or ip == "0.0.0.0", ip
  385. def test_compose_orders_droplet_after_firewall_and_gates_assignment_on_a_known_flag():
  386. comp = (LAB / "compose" / "main.tf").read_text()
  387. droplet_block = re.search(r'module "droplet" \{(.*?)\n\}', comp, re.DOTALL).group(1)
  388. assert "depends_on = [module.firewall]" in droplet_block
  389. assert "assign = var.enable_droplet" in comp
  390. reserved = (LAB / "cloud" / "reserved-ip" / "main.tf").read_text()
  391. assert re.search(r"count\s*=\s*var\.enabled && var\.assign", reserved)
  392. assert "var.droplet_id !=" not in reserved # an unknown value cannot decide a count at plan time
  393. @pytest.mark.slow
  394. @pytest.mark.skipif(shutil.which("tofu") is None, reason="tofu is not installed")
  395. def test_tofu_all_flags_on_plans_five_resources_and_firewall_rejects_ipv6(tofu_lab):
  396. shared_env, tree = tofu_lab # copied and initialized once per session (tests/conftest.py)
  397. env = dict(shared_env, DIGITALOCEAN_TOKEN="lab-placeholder")
  398. comp = tree / "compose"
  399. base = ["tofu", "plan", "-input=false", "-lock=false", "-refresh=false", "-no-color"]
  400. flags = ["enable_project", "enable_firewall", "enable_droplet", "enable_reserved_ip", "enable_dns"]
  401. args = [a for f in flags for a in ("-var", f"{f}=true")] + ["-var", 'ssh_key_fingerprints=["aa:bb"]']
  402. on = subprocess.run(base + args, cwd=comp, env=env, capture_output=True, text=True, check=False)
  403. assert on.returncode == 0, on.stdout + on.stderr
  404. created = re.findall(r"# (module\.\S+) will be created", on.stdout)
  405. assert len(created) == 7, created # project, firewall, droplet, reserved IP and its assignment, domain, record
  406. assert any("reserved_ip_assignment" in c for c in created)
  407. off = subprocess.run(base, cwd=comp, env=env, capture_output=True, text=True, check=False)
  408. assert off.returncode == 0 and "will be created" not in off.stdout
  409. for bad in ("2001:db8::/32", "192.0.2.0/24", "0.0.0.0/0", "192.0.2.10/31"):
  410. r = subprocess.run(base + ["-var", f"admin_cidr={bad}"], cwd=comp, env=env, capture_output=True, text=True, check=False)
  411. assert r.returncode != 0 and "single IPv4 address" in (r.stdout + r.stderr).replace("\n", " ").replace("│", ""), bad
  412. ok = subprocess.run(base + ["-var", "admin_cidr=198.51.100.7/32"], cwd=comp, env=env, capture_output=True, text=True, check=False)
  413. assert ok.returncode == 0