test_email_security_lesson.py 26 KB

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