test_workloads_stack.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. """Guards on the stage 3 workload stack, issue #111.
  2. The stack ships DISABLED and UNAPPLIED: stage 3 is not approved. These tests
  3. keep it that way on purpose and keep its network shape narrow: every block is
  4. behind the switch, the switch defaults to off, the stack is not registered
  5. anywhere that could apply it, the cost manifest prices nothing, the firewall
  6. admits only the connector tag, nothing is published on a wildcard address, and
  7. the Docker API never gets a network socket. Turning the stack on is a deliberate
  8. change that has to edit the tests below in the same reviewed diff.
  9. The checks are functions over text, each with a negative case, so a check that
  10. stops biting fails here.
  11. """
  12. import json
  13. import re
  14. from pathlib import Path
  15. ROOT = Path(__file__).resolve().parent.parent
  16. STACK = ROOT / "stacks/30-workloads"
  17. MODULE = ROOT / "modules/docker-host"
  18. WILDCARDS = ("0.0.0.0", "[::]", '"::"', "::/0", "network_mode: host", "network_mode: \"host\"")
  19. def read(path):
  20. return path.read_text(encoding="utf-8")
  21. def strip_comments(text):
  22. return re.sub(r"(?m)(#|//).*$", "", text)
  23. def blocks(text, kind):
  24. """(labels, body) of each top-level `kind` block; bodies are brace-balanced."""
  25. out = []
  26. for m in re.finditer(rf'(?m)^{kind}((?:\s+"[^"]+")+)\s*\{{', text):
  27. depth, i = 1, m.end()
  28. while depth and i < len(text):
  29. depth += {"{": 1, "}": -1}.get(text[i], 0)
  30. i += 1
  31. out.append((re.findall(r'"([^"]+)"', m.group(1)), text[m.end() : i - 1]))
  32. return out
  33. # --- checks over text ----------------------------------------------------------
  34. def unswitched(text):
  35. """Labels of every resource, data and module block without count = local.on."""
  36. found = blocks(text, "resource") + blocks(text, "data") + blocks(text, "module")
  37. return [
  38. labels
  39. for labels, body in found
  40. if not re.search(r"(?m)^\s*count\s*=\s*local\.on\s*$", body)
  41. ]
  42. def firewall_problems(text):
  43. """Everything in the stack source that could admit more than the connector tag."""
  44. text = strip_comments(text)
  45. problems = []
  46. for needle in (
  47. "source_addresses",
  48. "source_droplet_ids",
  49. "source_load_balancer_uids",
  50. "source_kubernetes_ids",
  51. "inbound_from_tag_rules",
  52. "extra_outbound_rules",
  53. "outbound_to_tag_rules",
  54. "outbound_to_other_tags",
  55. ):
  56. if needle in text:
  57. problems.append(f"uses {needle}")
  58. if "0.0.0.0" in text or "::/0" in text:
  59. problems.append("names a world address")
  60. rules = re.findall(r"\{\s*protocol\s*=\s*\"(\w+)\",\s*port_range\s*=\s*([^,]+),\s*tag\s*=\s*([^}\s]+)\s*\}", text)
  61. if len(rules) != 2:
  62. problems.append(f"expected two inbound rules, found {len(rules)}")
  63. for protocol, port, tag in rules:
  64. if protocol != "tcp":
  65. problems.append(f"non-tcp inbound rule {protocol}")
  66. if tag != "var.connector_tag":
  67. problems.append(f"inbound source is {tag}, not var.connector_tag")
  68. if port not in ("local.ssh_port", "tostring(local.portainer_port)"):
  69. problems.append(f"inbound port {port} is neither SSH nor Portainer")
  70. return problems
  71. def wildcard_problems(text):
  72. """Wildcard binds and host networking in a cloud-init template or compose text."""
  73. found = [w for w in WILDCARDS if w in text]
  74. # A published port needs an address in front of it.
  75. found += re.findall(r"(?m)^\s+- \"?\d+:\d+\"?\s*$", text)
  76. return found
  77. def docker_api_problems(text):
  78. """Any way of giving the Docker daemon a network socket."""
  79. return [w for w in ('"hosts"', "tcp://", "2375", "2376", "-H tcp", "--host=tcp") if w in text]
  80. # --- the stack ------------------------------------------------------------------
  81. def test_the_switch_defaults_to_off():
  82. variables = strip_comments(read(STACK / "variables.tf"))
  83. (_, body), = [b for b in blocks(variables, "variable") if b[0] == ["workload_enabled"]]
  84. assert re.search(r"(?m)^\s*default\s*=\s*false\s*$", body)
  85. assert re.search(r"(?m)^\s*nullable\s*=\s*false\s*$", body)
  86. def test_every_block_of_the_stack_is_behind_the_switch():
  87. main = strip_comments(read(STACK / "main.tf"))
  88. found = blocks(main, "resource") + blocks(main, "data") + blocks(main, "module")
  89. assert len(found) >= 7, "the scan lost its targets"
  90. assert unswitched(main) == []
  91. assert re.search(r"(?m)^\s*on\s*=\s*var\.workload_enabled\s*\?\s*1\s*:\s*0\s*$", main)
  92. def test_the_switch_check_bites():
  93. bad = 'resource "digitalocean_tag" "x" {\n name = "x"\n}\n'
  94. assert unswitched(bad) == [["digitalocean_tag", "x"]]
  95. def test_the_cost_manifest_prices_nothing_and_the_stage_is_not_approved():
  96. manifest = json.loads(read(STACK / "cost.json"))
  97. assert manifest["resources"] == []
  98. assert manifest["workload_approved"] is False
  99. assert manifest["planned"]["workload"]["kind"] == "droplet"
  100. assert manifest["planned"]["workload"]["backups"] is False
  101. approved = json.loads(read(ROOT / "docs/stages/approved.json"))
  102. # Stage 3 is the current phase (maintainer approval 2026-10-31), but the
  103. # stack stays off: the DigitalOcean total is not raised to cover the droplet
  104. # until the switching-on pull request, which sets workload_approved.
  105. assert approved["current_phase"] == "stage-3"
  106. total = approved["providers"]["digitalocean"]["approved_monthly_total"]
  107. assert total == 12.0 # the two connectors only; the switching-on PR raises it to 24 (29 with the bucket)
  108. def test_the_planned_size_is_priced_in_the_price_table():
  109. manifest = json.loads(read(STACK / "cost.json"))
  110. prices = json.loads(read(ROOT / "docs/cost-prices.json"))
  111. assert manifest["planned"]["workload"]["size"] in prices["droplets"]
  112. def test_the_stack_is_not_registered_for_a_spacelift_apply():
  113. # A stanza in .spacelift/config.yml is what lets a stack load secrets and
  114. # apply. It is added in the pull request that approves the stage.
  115. config = read(ROOT / ".spacelift/config.yml")
  116. assert "30-workloads" not in config
  117. def test_the_firewall_admits_the_connector_tag_on_two_ports_and_nothing_else():
  118. assert firewall_problems(read(STACK / "main.tf")) == []
  119. def test_the_firewall_check_bites():
  120. good = read(STACK / "main.tf")
  121. for bad in (
  122. good.replace("tag = var.connector_tag }", "tag = var.baseline_tag }", 1),
  123. good.replace('protocol = "tcp", port_range = local.ssh_port', 'protocol = "tcp", source_addresses = ["0.0.0.0/0"], port_range = local.ssh_port', 1),
  124. good + "\n# extra\nmodule \"x\" {\n inbound_from_tag_rules = []\n}\n",
  125. good.replace("tostring(local.portainer_port)", '"2375"', 1),
  126. ):
  127. assert firewall_problems(bad), "a widened firewall was not noticed"
  128. EXPECTED_TWINGATE = [
  129. ["twingate_resource", "portainer"],
  130. ["twingate_resource", "ssh"],
  131. ["twingate_resource", "workload_web"],
  132. ]
  133. # A rule that opens the Docker API ports or every port.
  134. OPEN_PORT_RE = re.compile(r'2375|2376|ALLOW_ALL|\b[01]\s*-\s*65535|"all"|"\*"', re.IGNORECASE)
  135. def stack_texts():
  136. """{file name: comment-free text} of every .tf file in the stack directory."""
  137. return {
  138. path.name: strip_comments(read(path))
  139. for path in sorted(STACK.glob("*.tf"))
  140. if ".terraform" not in path.parts
  141. }
  142. def twingate_problems(texts):
  143. """Every Twingate resource of every file: the set must be the expected one,
  144. each narrow (TCP restricted, UDP denied, no ICMP), and no file may name the
  145. Docker API ports or an all-ports rule."""
  146. problems = []
  147. found = []
  148. for name, text in texts.items():
  149. for labels, body in blocks(text, "resource"):
  150. if labels[0] == "twingate_resource":
  151. found.append(labels)
  152. for needle in (r'policy\s*=\s*"RESTRICTED"', r'udp\s*=\s*\{\s*policy\s*=\s*"DENY_ALL"', r"allow_icmp\s*=\s*false"):
  153. if not re.search(needle, body):
  154. problems.append(f"{name}: {labels[1]} lacks {needle}")
  155. if OPEN_PORT_RE.search(text):
  156. problems.append(f"{name}: names a Docker API port or an all-ports rule")
  157. if sorted(found) != EXPECTED_TWINGATE:
  158. problems.append(f"Twingate resources are {sorted(found)}, expected {EXPECTED_TWINGATE}")
  159. return problems
  160. def test_the_twingate_resources_of_every_file_are_the_expected_narrow_three():
  161. texts = stack_texts()
  162. assert {"main.tf", "workload_web.tf", "variables.tf", "outputs.tf"} <= set(texts), "the scan lost its files"
  163. assert twingate_problems(texts) == []
  164. def test_the_twingate_check_sees_a_resource_in_any_file_and_open_ports():
  165. texts = stack_texts()
  166. extra = 'resource "twingate_resource" "extra" {\n protocols = {}\n}\n'
  167. assert twingate_problems({**texts, "another.tf": extra})
  168. assert twingate_problems({**texts, "main.tf": texts["main.tf"] + extra})
  169. web = texts["workload_web.tf"]
  170. for bad in (
  171. web.replace('policy = "RESTRICTED"', 'policy = "ALLOW_ALL"', 1),
  172. web.replace("ports = [each.key]", 'ports = ["2375"]', 1),
  173. web.replace("ports = [each.key]", 'ports = ["2376"]', 1),
  174. web.replace("ports = [each.key]", 'ports = ["1-65535"]', 1),
  175. web.replace("ports = [each.key]", 'ports = ["0-65535"]', 1),
  176. web.replace("allow_icmp = false", "allow_icmp = true", 1),
  177. ):
  178. assert twingate_problems({**texts, "workload_web.tf": bad}), bad[-200:]
  179. assert twingate_problems({k: v for k, v in texts.items() if k != "workload_web.tf"})
  180. def test_the_stack_has_no_wildcard_anywhere():
  181. for path in (STACK / "main.tf", STACK / "variables.tf", STACK / "outputs.tf"):
  182. assert wildcard_problems(strip_comments(read(path))) == [], path.name
  183. # --- the module -----------------------------------------------------------------
  184. def test_the_cloud_init_publishes_nothing_on_a_wildcard_and_has_no_docker_api_socket():
  185. template = read(MODULE / "cloud-init.yaml.tftpl")
  186. assert "portainer/portainer-ce:" in template, "the scan lost its target"
  187. assert wildcard_problems(template) == []
  188. assert docker_api_problems(template) == []
  189. def test_the_wildcard_and_docker_api_checks_bite():
  190. assert wildcard_problems('ports:\n - "9443:9443"\n')
  191. assert wildcard_problems('ports:\n - "0.0.0.0:9443:9443"\n')
  192. assert wildcard_problems("network_mode: host\n")
  193. assert wildcard_problems('bind = "[::]:22"\n')
  194. assert docker_api_problems('{"hosts": ["tcp://0.0.0.0:2375"]}')
  195. assert not wildcard_problems('ports:\n - "${PORTAINER_BIND:?}:9443:9443"\n')
  196. def test_the_module_pins_portainer_and_never_pipes_an_installer():
  197. template = read(MODULE / "cloud-init.yaml.tftpl")
  198. assert "portainer-ce:latest" not in template
  199. assert "get.docker.com" not in template
  200. assert not re.search(r"curl[^\n]*\|\s*(ba)?sh", template)
  201. assert "cah-apt-key-check /root/docker.gpg.key" in template
  202. PINNED_PORTAINER_RE = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+@sha256:[0-9a-f]{64}$")
  203. def portainer_pin_problems(variables):
  204. """The portainer_version default and validation must both demand tag plus digest."""
  205. found = [b for b in blocks(strip_comments(variables), "variable") if b[0] == ["portainer_version"]]
  206. if len(found) != 1:
  207. return ["portainer_version variable missing"]
  208. body = found[0][1]
  209. problems = []
  210. default = re.search(r'(?m)^\s*default\s*=\s*"([^"]*)"\s*$', body)
  211. if not default or not PINNED_PORTAINER_RE.match(default.group(1)):
  212. problems.append("the default is not <version>@sha256:<64 hex>")
  213. if "@sha256:[0-9a-f]{64}$" not in body:
  214. problems.append("the validation does not demand a digest")
  215. return problems
  216. def test_portainer_is_pinned_by_tag_and_digest_in_the_module_and_the_stack():
  217. for path in (MODULE / "variables.tf", STACK / "variables.tf"):
  218. assert portainer_pin_problems(read(path)) == [], path.as_posix()
  219. def test_the_portainer_pin_check_bites():
  220. good = read(MODULE / "variables.tf")
  221. tag_only = good.replace("@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e", "", 1)
  222. assert portainer_pin_problems(tag_only)
  223. assert portainer_pin_problems(good.replace("@sha256:[0-9a-f]{64}$", "$", 1))
  224. def test_the_module_droplet_leaves_backups_off_and_has_no_public_v6():
  225. main = strip_comments(read(MODULE / "main.tf"))
  226. ((_, body),) = blocks(main, "resource")
  227. assert re.search(r"(?m)^\s*backups\s*=\s*false\s*$", body)
  228. assert re.search(r"(?m)^\s*ipv6\s*=\s*false\s*$", body)
  229. assert "backup_policy" not in body
  230. def test_only_the_workloads_stack_calls_the_module():
  231. callers = []
  232. for tf in sorted((ROOT / "stacks").rglob("*.tf")):
  233. if ".terraform" in tf.parts:
  234. continue
  235. if re.search(r'source\s*=\s*"(\.\./)+modules/docker-host"', read(tf)):
  236. callers.append(tf.relative_to(ROOT).as_posix())
  237. assert callers == ["stacks/30-workloads/main.tf"]
  238. # --- the optional workload web ports (issue #437) ---------------------------------
  239. def web_port_problems(variables, web):
  240. """Guards on the web port list: default empty, switch-gated, connector tag only."""
  241. problems = []
  242. variables = strip_comments(variables)
  243. web = strip_comments(web)
  244. found = [b for b in blocks(variables, "variable") if b[0] == ["workload_web_ports"]]
  245. if len(found) != 1:
  246. return ["workload_web_ports variable missing"]
  247. body = found[0][1]
  248. if not re.search(r"(?m)^\s*default\s*=\s*\[\]\s*$", body):
  249. problems.append("the port list does not default to empty")
  250. if not re.search(r"(?m)^\s*nullable\s*=\s*false\s*$", body):
  251. problems.append("the port list is nullable")
  252. resources = [b for b in blocks(web, "resource") if b[0][0] == "twingate_resource"]
  253. if len(resources) != 1:
  254. problems.append(f"expected one web Twingate resource, found {len(resources)}")
  255. for _, rbody in resources:
  256. if not re.search(r"for_each\s*=\s*local\.workload_web_ports\b", rbody):
  257. problems.append("the web resource is not driven by local.workload_web_ports")
  258. for needle in (r'policy\s*=\s*"RESTRICTED"', r'udp\s*=\s*\{\s*policy\s*=\s*"DENY_ALL"', r"allow_icmp\s*=\s*false", r"module\.workload\[0\]\.private_ip"):
  259. if not re.search(needle, rbody):
  260. problems.append(f"web resource lacks {needle}")
  261. if not re.search(r"workload_web_ports\s*=\s*var\.workload_enabled\s*\?", web):
  262. problems.append("the port map is not gated by the master switch")
  263. for needle in ("source_addresses", "0.0.0.0", "::/0", "inbound_from_tag_rules"):
  264. if needle in web:
  265. problems.append(f"uses {needle}")
  266. rules = re.findall(r"\{\s*protocol\s*=\s*\"(\w+)\",\s*port_range\s*=\s*([^,]+),\s*tag\s*=\s*([^}\s]+)\s*\}", web)
  267. if len(rules) != 1:
  268. problems.append(f"expected one rule template, found {len(rules)}")
  269. for protocol, port, tag in rules:
  270. if protocol != "tcp" or tag != "var.connector_tag" or port != "tostring(p)":
  271. problems.append(f"rule {protocol}/{port}/{tag} is not tcp from the connector tag on a listed port")
  272. return problems
  273. def test_the_web_ports_are_default_empty_switch_gated_and_connector_tag_only():
  274. variables = read(STACK / "variables.tf")
  275. web = read(STACK / "workload_web.tf")
  276. assert web_port_problems(variables, web) == []
  277. main = strip_comments(read(STACK / "main.tf"))
  278. assert "concat(" in main and "local.workload_web_firewall_rules" in main
  279. def test_the_web_port_check_bites():
  280. variables = read(STACK / "variables.tf")
  281. web = read(STACK / "workload_web.tf")
  282. for bad_vars, bad_web in (
  283. (variables.replace("default = []", "default = [8080]", 1), web),
  284. (variables, web.replace("tag = var.connector_tag", "tag = var.baseline_tag", 1)),
  285. (variables, web.replace('port_range = tostring(p)', 'port_range = "1-65535"', 1)),
  286. (variables, web.replace("var.workload_enabled ?", "true ?", 1)),
  287. (variables, web.replace('policy = "DENY_ALL"', 'policy = "ALLOW_ALL"', 1)),
  288. (variables, web + "\n# x\nresource \"twingate_resource\" \"extra\" {\n for_each = local.workload_web_ports\n}\n"),
  289. (variables, web.replace("module.workload[0].private_ip", '"0.0.0.0"', 1)),
  290. ):
  291. assert web_port_problems(bad_vars, bad_web), "a widened web port setup was not noticed"