test_edge_stack.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. """Guards on the public edge (DMZ) stack, issue #122.
  2. The edge ships DISABLED and UNAPPLIED: the stage is not approved and the cost
  3. gate cannot price a reserved IP yet. These tests keep it that way on purpose:
  4. every resource is behind the switch, the switch defaults to off, the stack is
  5. not registered anywhere that could apply it, the cost manifest prices nothing,
  6. and the cloud-init carries no admin path, no unpinned service package and no
  7. secret-shaped value. Turning the edge on is a deliberate change that has to
  8. edit the tests below in the same reviewed diff.
  9. """
  10. import json
  11. import re
  12. import shutil
  13. import sys
  14. from pathlib import Path
  15. import pytest
  16. ROOT = Path(__file__).resolve().parent.parent
  17. sys.path.insert(0, str(ROOT / "scripts"))
  18. import cost_check
  19. STACK = ROOT / "stacks/50-edge"
  20. MODULE = ROOT / "modules/edge-host"
  21. def read(path):
  22. return path.read_text(encoding="utf-8")
  23. def strip_comments(text):
  24. return re.sub(r"(?m)(#|//).*$", "", text)
  25. def blocks(text, kind):
  26. """(labels, body) of each top-level `kind` block; bodies are brace-balanced."""
  27. out = []
  28. for m in re.finditer(rf'(?m)^{kind}((?:\s+"[^"]+")+)\s*\{{', text):
  29. depth, i = 1, m.end()
  30. while depth and i < len(text):
  31. depth += {"{": 1, "}": -1}.get(text[i], 0)
  32. i += 1
  33. out.append((re.findall(r'"([^"]+)"', m.group(1)), text[m.end() : i - 1]))
  34. return out
  35. def test_the_switch_defaults_to_off():
  36. variables = strip_comments(read(STACK / "variables.tf"))
  37. (_, body), = [b for b in blocks(variables, "variable") if b[0] == ["edge_enabled"]]
  38. assert re.search(r"(?m)^\s*default\s*=\s*false\s*$", body)
  39. assert re.search(r"(?m)^\s*nullable\s*=\s*false\s*$", body)
  40. def test_every_resource_and_module_of_the_stack_is_behind_the_switch():
  41. main = strip_comments(read(STACK / "main.tf"))
  42. found = blocks(main, "resource") + blocks(main, "module")
  43. assert len(found) >= 4, "the scan lost its targets"
  44. for labels, body in found:
  45. assert re.search(r"(?m)^\s*count\s*=\s*local\.on\s*$", body), (
  46. f"{labels}: count = local.on is missing, so it would exist with the switch off"
  47. )
  48. assert re.search(r"(?m)^\s*on\s*=\s*var\.edge_enabled\s*\?\s*1\s*:\s*0\s*$", main)
  49. def test_the_cost_manifest_prices_nothing_and_the_stage_is_not_approved():
  50. manifest = json.loads(read(STACK / "cost.json"))
  51. assert manifest["resources"] == []
  52. assert manifest["edge_network_approved"] is False
  53. approved = json.loads(read(ROOT / "docs/stages/approved.json"))
  54. assert approved["current_phase"] != "edge"
  55. assert approved["phases"]["edge"]["status"] == "planned"
  56. assert approved["providers"]["digitalocean"]["approved_monthly_total"] == 12.0
  57. def test_the_stack_is_not_registered_for_a_spacelift_apply():
  58. # A stanza in .spacelift/config.yml is what lets a stack load secrets and
  59. # apply. It is added in the pull request that approves the stage.
  60. config = read(ROOT / ".spacelift/config.yml")
  61. assert "50-edge" not in config
  62. assert "edge" not in config
  63. def test_i2pd_and_iperf3_are_closed_to_everyone_in_the_network_stack():
  64. # Both stay closed until their own stacks exist: no variable, no rule, no port.
  65. code = strip_comments(read(STACK / "main.tf") + read(STACK / "variables.tf") + read(STACK / "outputs.tf"))
  66. for needle in ("i2pd", "iperf3", "5201", "source_addresses = var."):
  67. assert needle not in code, needle
  68. assert 'source_addresses = ["0.0.0.0/0"]' in code
  69. # The module's restricted ports stay IPv4-only whenever a service stack uses them.
  70. module_vars = strip_comments(read(MODULE / "variables.tf"))
  71. ((_, body),) = [b for b in blocks(module_vars, "variable") if b[0] == ["restricted_ports"]]
  72. assert 'strcontains(s, ":")' in body and 's != "0.0.0.0/0"' in body
  73. def test_no_edge_service_stack_exists_yet():
  74. # Each service is its own stack, built and approved later. Until then nothing
  75. # calls modules/edge-host, no service is installed and no droplet is declared.
  76. for path in (ROOT / "stacks").rglob("*.tf"):
  77. if ".terraform" in path.parts:
  78. continue
  79. code = strip_comments(read(path))
  80. assert "modules/edge-host" not in code, f"{path}: a service stack appeared"
  81. assert 'resource "digitalocean_droplet"' not in code, path
  82. def test_the_module_attaches_droplet_and_reserved_ip_to_the_project():
  83. main = strip_comments(read(MODULE / "main.tf"))
  84. assert re.search(r'resource "digitalocean_project_resources" "edge"', main)
  85. assert "digitalocean_droplet.edge.urn" in main and "digitalocean_reserved_ip.edge.urn" in main
  86. assert "var.project_id" in main
  87. def parse_slots():
  88. data = json.loads(read(MODULE / "reboot-slots.json"))
  89. return data["timezone"], data["slots"]
  90. def minutes(hhmm):
  91. h, m = hhmm.split(":")
  92. return int(h) * 60 + int(m)
  93. def test_reboot_slots_are_unique_staggered_and_clear_of_the_connectors():
  94. tz, slots = parse_slots()
  95. assert len(slots) == 5
  96. times = [minutes(v) for v in slots.values()]
  97. assert len(set(times)) == len(times), "two edge droplets share a reboot minute"
  98. assert all(60 <= t <= 180 for t in times), "slots are 01:00 to 03:00 Eastern"
  99. access = read(ROOT / "stacks/10-access/variables.tf")
  100. connectors = [minutes(m) for m in re.findall(r'(?m)^\s*[ab]\s*=\s*"(\d\d:\d\d)"', access)]
  101. assert sorted(connectors) == [240, 300], "the connectors' reboot defaults changed; revisit the slots"
  102. assert not set(times) & set(connectors)
  103. assert tz == "America/New_York"
  104. assert re.search(r'variable "timezone".*?default\s*=\s*"America/New_York"', access, re.DOTALL)
  105. module_vars = read(MODULE / "variables.tf")
  106. assert re.search(r'variable "timezone".*?default\s*=\s*"America/New_York"', module_vars, re.DOTALL)
  107. def test_every_slot_service_has_its_own_doppler_config_name():
  108. _, slots = parse_slots()
  109. variables = read(MODULE / "variables.tf")
  110. listed = re.search(r'contains\(\[([^\]]*)\], var\.service\)', variables).group(1)
  111. assert sorted(re.findall(r'"([a-z0-9]+)"', listed)) == sorted(slots)
  112. main = read(MODULE / "main.tf")
  113. assert 'doppler_config = "cah-edge-${var.service}"' in main
  114. names = {f"cah-edge-{svc}" for svc in slots}
  115. assert len(names) == len(slots)
  116. def test_the_default_vpc_range_is_disjoint_from_the_core_default():
  117. import ipaddress
  118. def default_of(name):
  119. variables = strip_comments(read(STACK / "variables.tf"))
  120. (_, body), = [b for b in blocks(variables, "variable") if b[0] == [name]]
  121. return ipaddress.ip_network(re.search(r'default\s*=\s*"([^"]+)"', body).group(1))
  122. core = re.search(
  123. r'variable "vpc_ip_range".*?default\s*=\s*"([^"]+)"',
  124. read(ROOT / "stacks/00-foundation/variables.tf"),
  125. re.DOTALL,
  126. ).group(1)
  127. assert str(default_of("core_vpc_ip_range")) == core
  128. assert not default_of("vpc_ip_range").overlaps(ipaddress.ip_network(core))
  129. def test_no_peering_and_no_core_tag_in_the_edge_code():
  130. peering = re.compile(r"digitalocean_vpc_peering|peering", re.IGNORECASE)
  131. core_tags = re.compile(r"cah-baseline|cah-access|cah-connector")
  132. for path in [*STACK.glob("*.tf"), *MODULE.glob("*.tf")]:
  133. text = strip_comments(read(path))
  134. assert not peering.search(text), f"{path.name}: VPC peering must never exist"
  135. assert not core_tags.search(text), f"{path.name}: references a core tag"
  136. def test_the_droplet_has_no_admin_path():
  137. main = strip_comments(read(MODULE / "main.tf"))
  138. ((_, droplet),) = [b for b in blocks(main, "resource") if b[0][0] == "digitalocean_droplet"]
  139. assert not re.search(r"(?m)^\s*ssh_keys\s*=", droplet)
  140. assert re.search(r"(?m)^\s*ipv6\s*=\s*false\s*$", droplet)
  141. assert re.search(r"(?m)^\s*backups\s*=\s*false\s*$", droplet)
  142. template = read(MODULE / "cloud-init.yaml.tftpl")
  143. body = "\n".join(l for l in template.splitlines() if not l.lstrip().startswith("#") or l.startswith("#cloud-config"))
  144. assert "ssh_authorized_keys" not in body
  145. assert not re.search(r"(?m)^users:", body)
  146. assert "dport 22" not in body
  147. assert "mask, ssh.service, ssh.socket" in body
  148. assert "passwd, -l, root" in body
  149. assert "disable_root: true" in body
  150. def packages_section(template):
  151. m = re.search(r"(?ms)^packages:\n(.*?)^[a-z_]+:", template)
  152. assert m, "no packages: section"
  153. return [l.strip() for l in m.group(1).splitlines() if l.strip() and not l.strip().startswith("#")]
  154. def test_the_cloud_init_installs_only_os_packages_and_no_service():
  155. template = read(MODULE / "cloud-init.yaml.tftpl")
  156. assert packages_section(template) == ["- unattended-upgrades", "- chrony", "- nftables"]
  157. variables = strip_comments(read(MODULE / "variables.tf"))
  158. assert "service_packages" not in variables and "service_packages" not in read(MODULE / "main.tf")
  159. for needle in ("rnsd", "lxmd", "i2pd", "mosquitto", "iperf3", "%{ for"):
  160. assert needle not in template, needle
  161. SECRET_SHAPED = re.compile(r"token|secret|password|passwd|api[_-]?key|private[_-]?key|credential", re.IGNORECASE)
  162. # The design allows exactly one secret-shaped field in user-data, a short-lived
  163. # read-only Doppler token for the service's own config (risk 6). It arrives with
  164. # each service stack, not with this module, so none today.
  165. ALLOWED_SECRET_FIELDS: set[str] = set()
  166. def test_the_user_data_carries_no_secret_shaped_field():
  167. main = strip_comments(read(MODULE / "main.tf"))
  168. call = re.search(r"templatefile\([^,]+,\s*\{(.*?)\n\s*\}\)", main, re.DOTALL).group(1)
  169. names = set(re.findall(r"(?m)^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=", call))
  170. assert names, "the scan lost the templatefile arguments"
  171. assert {n for n in names if SECRET_SHAPED.search(n)} <= ALLOWED_SECRET_FIELDS
  172. # A fetched credential's name must not appear in the template either.
  173. template = read(MODULE / "cloud-init.yaml.tftpl")
  174. for needle in ("iperf3_key", "mqtt_password", "TWINGATE_", "authorized-users", "rsa-private-key", "DOPPLER"):
  175. assert needle not in template
  176. # No variable of the module is secret-shaped.
  177. for (name,), _ in blocks(strip_comments(read(MODULE / "variables.tf")), "variable"):
  178. assert not SECRET_SHAPED.search(name), name
  179. def test_the_user_data_is_never_an_output():
  180. for path in (MODULE / "outputs.tf", STACK / "outputs.tf"):
  181. assert "user_data" not in strip_comments(read(path))
  182. def test_the_host_firewall_is_default_drop_and_mirrors_the_cloud_firewall_input():
  183. template = read(MODULE / "cloud-init.yaml.tftpl")
  184. assert "policy drop;" in template
  185. stack = strip_comments(read(STACK / "main.tf"))
  186. # The Cloud Firewall is built from one list; a service stack passes the same
  187. # list to the module so the host firewall mirrors it (the module's tests).
  188. assert re.search(r"for_each\s*=\s*local\.public_ports", stack)
  189. @pytest.fixture()
  190. def tree(tmp_path):
  191. """A copy of what the gate reads, to be edited on purpose."""
  192. for top in ("stacks", "modules", "docs"):
  193. shutil.copytree(
  194. ROOT / top,
  195. tmp_path / top,
  196. ignore=shutil.ignore_patterns(".terraform", "wiki", "images", "superpowers", "threat-model"),
  197. )
  198. shutil.copytree(ROOT / ".spacelift", tmp_path / ".spacelift")
  199. return tmp_path
  200. def test_the_repository_gate_is_green_with_the_edge_present(tree):
  201. approved = json.loads(read(tree / "docs/stages/approved.json"))
  202. problems, _ = cost_check.gate_problems(tree, approved)
  203. assert problems == []
  204. def test_a_droplet_in_the_network_stack_is_refused(tree):
  205. # The shared network stack owns no droplet; one priced there has no connector
  206. # module block and no edge-host call to match.
  207. manifest = tree / "stacks/50-edge/cost.json"
  208. manifest.write_text(
  209. json.dumps({"stage": 5, "resources": [{"name": "edge", "kind": "droplet", "size": "s-1vcpu-1gb", "backups": False}]})
  210. )
  211. approved = json.loads(read(tree / "docs/stages/approved.json"))
  212. problems, _ = cost_check.gate_problems(tree, approved)
  213. assert any("stacks/50-edge" in p and "twingate-connector module block" in p for p in problems), problems
  214. def test_a_reserved_ip_entry_cannot_be_priced_yet(tree):
  215. manifest = tree / "stacks/50-edge/cost.json"
  216. manifest.write_text(json.dumps({"stage": 5, "resources": [{"name": "edge-ip", "kind": "reserved_ip", "assigned_to": "edge"}]}))
  217. approved = json.loads(read(tree / "docs/stages/approved.json"))
  218. with pytest.raises(ValueError, match="no price model for kind 'reserved_ip'"):
  219. cost_check.gate_problems(tree, approved)
  220. def test_turning_the_switch_on_is_refused_by_the_stacks_own_guard():
  221. outputs = strip_comments(read(STACK / "outputs.tf"))
  222. assert "!var.edge_enabled || try(local.cost.edge_network_approved, false) == true" in outputs
  223. # --- edge-host module calls are held to the connector's rules -----------------
  224. CALL = 'module "edge_host" {\n source = "../../modules/edge-host"\n%s}\n'
  225. SYN = "stacks/51-edge-example"
  226. SYN_LOCALS = (
  227. "locals {\n on = var.edge_enabled ? 1 : 0\n"
  228. ' cost = jsondecode(file("${path.module}/cost.json"))\n'
  229. " edge_droplet = { size = var.droplet_size }\n}\n"
  230. )
  231. SYN_OUT = (
  232. 'output "edge_enabled" {\n value = var.edge_enabled\n precondition {\n'
  233. " condition = !var.edge_enabled || (\n"
  234. ' length([for r in local.cost.resources : r if r.kind == "droplet"]) == 1 &&\n'
  235. ' length([for r in local.cost.resources : r if r.kind == "reserved_ip"]) == 1\n )\n'
  236. ' error_message = "price it"\n }\n}\n'
  237. )
  238. def syn_stack(tree, body="__good__", entries=(), main=None, outputs=None):
  239. """A stand-in service stack (none exists yet) that calls modules/edge-host."""
  240. d = tree / SYN
  241. d.mkdir(exist_ok=True)
  242. body = GOOD_BODY if body == "__good__" else body
  243. (d / "main.tf").write_text(main if main is not None else SYN_LOCALS + CALL % body)
  244. (d / "outputs.tf").write_text(outputs if outputs is not None else SYN_OUT)
  245. (d / "cost.json").write_text(json.dumps({"stage": 5, "resources": list(entries)}))
  246. def edge_tree(tree, body, entries=()):
  247. syn_stack(tree, body, entries)
  248. return cost_check.edge_module_problems(tree)[0]
  249. GOOD_BODY = " count = local.on\n size = local.edge_droplet.size\n"
  250. DROP = {"name": "edge", "kind": "droplet", "size": "s-1vcpu-1gb", "backups": False}
  251. RIP = {"name": "ip", "kind": "reserved_ip", "assigned_to": "edge"}
  252. def test_a_conforming_call_passes(tree):
  253. assert edge_tree(tree, GOOD_BODY) == []
  254. assert edge_tree(tree, GOOD_BODY, [DROP, RIP]) == []
  255. @pytest.mark.parametrize(
  256. "body",
  257. [
  258. " count = 2\n size = local.edge_droplet.size\n",
  259. " count = var.n\n size = local.edge_droplet.size\n",
  260. ' for_each = toset(["a"])\n size = local.edge_droplet.size\n',
  261. ],
  262. )
  263. def test_count_other_than_the_switch_and_for_each_are_refused(tree, body):
  264. assert any("uses" in p for p in edge_tree(tree, body))
  265. @pytest.mark.parametrize("size", ['"s-1vcpu-1gb"', "var.droplet_size", "lower(local.edge_droplet.size)"])
  266. def test_a_size_that_is_not_a_plain_local_reference_is_refused(tree, size):
  267. assert any("plain reference" in p for p in edge_tree(tree, f" count = local.on\n size = {size}\n"))
  268. def test_a_missing_size_is_refused(tree):
  269. assert any("plain reference" in p for p in edge_tree(tree, " count = local.on\n"))
  270. def test_manifest_entries_must_match_the_module_calls(tree):
  271. assert any("2 droplet" in p for p in edge_tree(tree, GOOD_BODY, [DROP, {**DROP, "name": "b"}]))
  272. assert any("2 reserved_ip" in p for p in edge_tree(tree, GOOD_BODY, [RIP, {**RIP, "name": "b"}]))
  273. # --- zero manifest entries need a verified switch; other droplets still count --
  274. def test_the_stand_in_stack_has_a_verified_switch(tree):
  275. syn_stack(tree)
  276. assert cost_check.edge_switch_verified(tree, SYN)
  277. assert cost_check.edge_module_problems(tree)[0] == []
  278. def test_zero_entries_are_refused_when_the_call_has_no_switch(tree):
  279. syn_stack(tree, body=" size = local.edge_droplet.size\n")
  280. assert any("0 droplet" in p for p in cost_check.edge_module_problems(tree)[0])
  281. def test_zero_entries_are_refused_when_the_switch_is_not_a_variable_ternary(tree):
  282. syn_stack(tree, main=(SYN_LOCALS + CALL % GOOD_BODY).replace("on = var.edge_enabled ? 1 : 0", "on = 0"))
  283. assert any("0 droplet" in p for p in cost_check.edge_module_problems(tree)[0])
  284. def test_zero_entries_are_refused_when_the_precondition_is_gone(tree):
  285. syn_stack(tree, outputs=SYN_OUT.replace("!var.edge_enabled ||", "true ||"))
  286. assert any("0 droplet" in p for p in cost_check.edge_module_problems(tree)[0])
  287. def test_a_non_edge_droplet_in_a_service_manifest_is_still_counted(tree):
  288. # One droplet is the service's and is subtracted; the second has no connector
  289. # module block, so the connector reconciliation still reports it.
  290. syn_stack(tree, entries=[DROP, {**DROP, "name": "stray"}, RIP])
  291. problems = cost_check.structure_problems(tree)
  292. assert any(f"{SYN}: 0 twingate-connector module block(s) but 1 machine" in p for p in problems), problems