test_tfvars_example.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. """terraform.tfvars.example for each live stack (stage 2 design, section 2.6).
  2. The example is committed documentation, so it must be complete, readable,
  3. valid and free of anything that looks like a real value:
  4. - every `variable` of the stack appears in the example and nothing else does
  5. (a new variable without an example fails here);
  6. - every assignment has a comment above it;
  7. - every value has the variable's declared type and the file parses with the
  8. fail-closed reader (a shape it does not understand is an error);
  9. - the example is planned with mocked providers by a generated tofu test, which
  10. runs every validation against it (the test file must be current);
  11. - no value looks like a secret or a real identifier: the identifier check's
  12. patterns, addresses only in documentation or private ranges, no host names
  13. except example.*, required placeholders that say "example", no long
  14. token-like strings, no key material.
  15. The reader and the checks are exercised on broken input, so a check that stops
  16. biting fails here.
  17. """
  18. import ipaddress
  19. import re
  20. import subprocess
  21. import sys
  22. from pathlib import Path
  23. import pytest
  24. ROOT = Path(__file__).resolve().parent.parent
  25. sys.path.insert(0, str(ROOT / "scripts"))
  26. import gen_example_tests
  27. import hcl_variables
  28. import identifier_check
  29. STACKS = ("stacks/00-foundation", "stacks/10-access", "stacks/20-telemetry", "stacks/50-edge")
  30. EXAMPLE = "terraform.tfvars.example"
  31. DOC_NETS = [
  32. ipaddress.ip_network(n)
  33. for n in ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24")
  34. ]
  35. PRIVATE_NETS = [
  36. ipaddress.ip_network(n) for n in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")
  37. ]
  38. IPV4_RE = re.compile(r"(?<![0-9.])([0-9]{1,3}(?:\.[0-9]{1,3}){3})(?![0-9])")
  39. HOST_RE = re.compile(
  40. r"\b((?:[a-z0-9-]+\.)+(?:com|net|org|io|dev|cloud|local|lan|internal|home|corp))\b",
  41. re.IGNORECASE,
  42. )
  43. HOST_OK = re.compile(r"(^|\.)example\.(com|net|org)$", re.IGNORECASE)
  44. LONG_TOKEN = re.compile(r"[A-Za-z0-9+/=_-]{32,}")
  45. # The prefixes are joined at run time so this file holds no token-shaped text.
  46. TOKEN_PREFIXES = re.compile(
  47. "("
  48. + "|".join(
  49. ["dop" + "_v1_", "doo" + "_v1_", "tf" + "p_", "gh" + "p_", "gh" + "o_",
  50. "github" + "_pat_", "xox[bap]-", "AK" + "IA", "AS" + "IA", "sk-[A-Za-z0-9]",
  51. "-----BE" + "GIN"]
  52. )
  53. + ")"
  54. )
  55. # Values that are stack wiring or a documented default, not a placeholder for a
  56. # private or secret value, so they need not say "example".
  57. NEED_NOT_SAY_EXAMPLE = {
  58. "region",
  59. "vpc_ip_range",
  60. "project_name",
  61. "baseline_tag",
  62. "connector_telemetry",
  63. "connector_telemetry_instances",
  64. "connector_telemetry_previous",
  65. "host_firewall",
  66. "host_firewall_instances",
  67. "host_firewall_ssh_sources",
  68. "log_shipping",
  69. "log_shipping_bootstrap_token",
  70. "log_shipping_instances",
  71. "metadata_lock",
  72. "metadata_lock_instances",
  73. "node_exporter",
  74. "node_exporter_instances",
  75. "reboot_times",
  76. "reserved_ranges",
  77. "resource_key",
  78. "site_name",
  79. "timezone",
  80. # Stack 20: public configuration, or private values whose example is a
  81. # documentation-range address (the address check above still applies).
  82. "logging_servers",
  83. "scrape_allowlist",
  84. "wazuh_agent_group",
  85. # Stack 50 (edge): wiring, documented defaults, and documentation-range or
  86. # private example addresses (the address checks above still apply).
  87. "core_vpc_ip_range",
  88. "droplet_size",
  89. "edge_enabled",
  90. "i2pd_port",
  91. "iperf3_allowed_sources",
  92. "reboot_time",
  93. "reticulum_port",
  94. }
  95. def text_of(stack: str) -> str:
  96. return (ROOT / stack / EXAMPLE).read_text(encoding="utf-8")
  97. def declared(stack: str) -> dict:
  98. return hcl_variables.variables_in_dir(ROOT / stack)
  99. def type_ok(type_text: str, value) -> bool:
  100. if type_text == "string":
  101. return isinstance(value, str)
  102. if type_text == "bool":
  103. return isinstance(value, bool)
  104. if type_text == "number":
  105. return isinstance(value, (int, float)) and not isinstance(value, bool)
  106. if type_text == "list(string)":
  107. return isinstance(value, list) and all(isinstance(v, str) for v in value)
  108. if type_text == "map(string)":
  109. return isinstance(value, dict) and all(isinstance(v, str) for v in value.values())
  110. if type_text.startswith("list(object("):
  111. return isinstance(value, list) and all(isinstance(v, dict) for v in value)
  112. if type_text.startswith("object({status_updates_enabled=optional(bool),log_level="):
  113. # connector_telemetry: an object whose every field is optional.
  114. allowed = {
  115. "status_updates_enabled": bool,
  116. "log_level": (int, float),
  117. "connection_logs": bool,
  118. "metrics_port": (int, float),
  119. "labels": dict,
  120. }
  121. return isinstance(value, dict) and all(
  122. k in allowed and isinstance(v, allowed[k]) for k, v in value.items()
  123. )
  124. if type_text == "object({enabled=optional(bool,false),port=optional(number,9100)})":
  125. # node_exporter: an object whose every field is optional.
  126. allowed = {"enabled": bool, "port": (int, float)}
  127. return isinstance(value, dict) and all(
  128. k in allowed and isinstance(v, allowed[k]) for k, v in value.items()
  129. )
  130. if type_text.startswith("object({enabled=optional(bool,false),manager_address="):
  131. # log_shipping: an object whose every field is optional.
  132. allowed = {
  133. "enabled": bool,
  134. "manager_address": str,
  135. "manager_port": (int, float),
  136. "enroll_port": (int, float),
  137. "agent_name_prefix": str,
  138. "agent_group": str,
  139. "apt_key_fingerprint": str,
  140. "agent_version": str,
  141. }
  142. return isinstance(value, dict) and all(
  143. k in allowed and isinstance(v, allowed[k]) for k, v in value.items()
  144. )
  145. if type_text.startswith("map(object({site_name=optional(string,"):
  146. # sites (stack 20): a map of objects whose every field is optional.
  147. allowed = {
  148. "site_name": str,
  149. "region": str,
  150. "cloud_remote_network_id": str,
  151. "connector_private_ips": dict,
  152. }
  153. return isinstance(value, dict) and all(
  154. isinstance(site, dict)
  155. and all(k in allowed and isinstance(v, allowed[k]) for k, v in site.items())
  156. for site in value.values()
  157. )
  158. raise AssertionError(f"the example check does not know the type {type_text}")
  159. def strings_in(value):
  160. if isinstance(value, str):
  161. yield value
  162. elif isinstance(value, list):
  163. for v in value:
  164. yield from strings_in(v)
  165. elif isinstance(value, dict):
  166. for v in value.values():
  167. yield from strings_in(v)
  168. def coverage_problems(text: str, variables: dict) -> list[str]:
  169. """Disagreements between an example's text and the stack's variables."""
  170. problems: list[str] = []
  171. try:
  172. values = hcl_variables.parse_assignments(text, EXAMPLE)
  173. except hcl_variables.HclError as exc:
  174. return [f"cannot read the example ({exc})"]
  175. for name in sorted(set(variables) - set(values)):
  176. problems.append(f"variable {name} has no entry in the example")
  177. for name in sorted(set(values) - set(variables)):
  178. problems.append(f"the example sets {name}, which is not a variable of the stack")
  179. for name, value in values.items():
  180. var = variables.get(name)
  181. if var is not None and not type_ok(var.type, value):
  182. problems.append(f"{name}: the value does not have the type {var.type}")
  183. lines = text.splitlines()
  184. for name in values:
  185. index = next(
  186. (i for i, line in enumerate(lines) if re.match(rf"{re.escape(name)}\s*=", line)),
  187. None,
  188. )
  189. if index is None or index == 0 or not lines[index - 1].lstrip().startswith("#"):
  190. problems.append(f"{name}: no comment on the line above it")
  191. return problems
  192. def value_problems(text: str) -> list[str]:
  193. """Anything in the example that looks like a secret or a real identifier."""
  194. problems: list[str] = []
  195. for number, line in enumerate(text.splitlines(), start=1):
  196. for kind in identifier_check.find_kinds(line):
  197. problems.append(f"line {number}: {kind}")
  198. for m in IPV4_RE.finditer(line):
  199. try:
  200. ip = ipaddress.ip_address(m.group(1))
  201. except ValueError:
  202. continue
  203. if not any(ip in n for n in DOC_NETS + PRIVATE_NETS):
  204. problems.append(f"line {number}: an address outside the documentation and private ranges")
  205. for m in HOST_RE.finditer(line):
  206. host = m.group(1)
  207. if not HOST_OK.search(host) and not host.endswith((".tf", ".json", ".md", ".yml")):
  208. problems.append(f"line {number}: a host name that is not example.com/net/org")
  209. if TOKEN_PREFIXES.search(line):
  210. problems.append(f"line {number}: looks like a token or key material")
  211. try:
  212. values = hcl_variables.parse_assignments(text, EXAMPLE)
  213. except hcl_variables.HclError as exc:
  214. return problems + [f"cannot read the example ({exc})"]
  215. for name, value in values.items():
  216. for s in strings_in(value):
  217. for m in LONG_TOKEN.finditer(s):
  218. if "example" not in m.group(0).lower():
  219. problems.append(f"{name}: a long token-like string that does not say 'example'")
  220. needs_example = (
  221. name not in NEED_NOT_SAY_EXAMPLE
  222. and isinstance(value, (str, list, dict))
  223. and value not in ("", [], {})
  224. )
  225. if needs_example and not any("example" in s.lower() for s in strings_in(value)):
  226. problems.append(f"{name}: a placeholder for a private value must say 'example'")
  227. return problems
  228. @pytest.mark.parametrize("stack", STACKS)
  229. def test_the_example_exists_and_covers_every_variable(stack):
  230. assert coverage_problems(text_of(stack), declared(stack)) == []
  231. @pytest.mark.parametrize("stack", STACKS)
  232. def test_the_example_holds_nothing_that_looks_real(stack):
  233. assert value_problems(text_of(stack)) == []
  234. @pytest.mark.parametrize("stack", STACKS)
  235. def test_the_example_has_a_real_number_of_entries(stack):
  236. # Guards against passing because nothing was read.
  237. assert len(hcl_variables.parse_assignments(text_of(stack))) >= 5
  238. @pytest.mark.parametrize("stack", STACKS)
  239. def test_the_generated_example_test_is_current(stack):
  240. path = ROOT / stack / gen_example_tests.TEST
  241. assert path.read_text(encoding="utf-8") == gen_example_tests.render(stack, ROOT)
  242. assert (
  243. subprocess.run(
  244. [sys.executable, "-I", str(ROOT / "scripts" / "gen_example_tests.py"), "--check"],
  245. capture_output=True,
  246. check=False,
  247. ).returncode
  248. == 0
  249. )
  250. @pytest.mark.parametrize("stack", STACKS)
  251. def test_the_example_is_committable_and_a_real_tfvars_is_not(stack):
  252. def ignored(name: str) -> bool:
  253. result = subprocess.run(
  254. ["git", "-C", str(ROOT), "check-ignore", "-q", "--no-index", f"{stack}/{name}"],
  255. check=False,
  256. )
  257. assert result.returncode in (0, 1)
  258. return result.returncode == 0
  259. assert not ignored("terraform.tfvars.example")
  260. assert ignored("terraform.tfvars")
  261. assert ignored("prod.auto.tfvars.json")
  262. # --- the checks bite ----------------------------------------------------------
  263. GOOD = '# one\na = "x"\n# two\nb = ["y"]\n'
  264. VARS = {
  265. "a": hcl_variables.Variable(name="a", type="string"),
  266. "b": hcl_variables.Variable(name="b", type="list(string)"),
  267. }
  268. def test_the_coverage_check_accepts_a_good_example():
  269. assert coverage_problems(GOOD, VARS) == []
  270. def test_the_coverage_check_bites_on_a_missing_entry():
  271. problems = coverage_problems('# one\na = "x"\n', VARS)
  272. assert any("variable b has no entry" in p for p in problems), problems
  273. def test_the_coverage_check_bites_on_an_unknown_entry():
  274. problems = coverage_problems(GOOD + '# c\nc = 1\n', VARS)
  275. assert any("c, which is not a variable" in p for p in problems), problems
  276. def test_the_coverage_check_bites_on_a_wrong_type():
  277. problems = coverage_problems('# one\na = 1\n# two\nb = ["y"]\n', VARS)
  278. assert any("a: the value does not have the type string" in p for p in problems)
  279. def test_the_coverage_check_bites_on_a_missing_comment():
  280. problems = coverage_problems('a = "x"\n# two\nb = ["y"]\n', VARS)
  281. assert any("a: no comment" in p for p in problems), problems
  282. problems = coverage_problems('# one\na = "x"\n\nb = ["y"]\n', VARS)
  283. assert any("b: no comment" in p for p in problems), problems
  284. @pytest.mark.parametrize(
  285. "text",
  286. [
  287. '# c\na = "x"\n# c\na = "y"\n', # assigned twice
  288. '# c\na = var.x\n', # not a literal
  289. '# c\na = "${x}"\n', # template
  290. '# c\na = <<EOT\nx\nEOT\n', # heredoc
  291. '# c\nresource "x" "y" {\n}\n', # a block
  292. '# c\na = "unterminated\n',
  293. '# c\na = [1, 2\n',
  294. '# c\na = {x = 1 y = 2}\n',
  295. ],
  296. )
  297. def test_the_reader_fails_closed_on_shapes_it_does_not_understand(text):
  298. assert coverage_problems(text, VARS)[0].startswith("cannot read the example")
  299. @pytest.mark.parametrize(
  300. "line,needle",
  301. [
  302. ('a = "8.8.8.8"', "outside the documentation"),
  303. ('a = "203.0.114.5"', "outside the documentation"),
  304. ('a = "db.corp-real.com"', "host name"),
  305. ('a = "account_id = ' + "2109" + '87654321"', "AWS account id"),
  306. ('a = "AK' + "IA" + "Q7ZXCV" + 'BNMASDFGHJ"', "AWS access key id"),
  307. ('a = "dop' + '_v1_abcdef"', "token or key material"),
  308. ('a = "-----BE' + 'GIN OPENSSH PRIVATE KEY-----"', "token or key material"),
  309. ('a = "tf' + 'p_abcdef"', "token or key material"),
  310. ],
  311. )
  312. def test_the_value_check_bites(line, needle):
  313. problems = "\n".join(value_problems(f"# c\n{line}\n"))
  314. assert needle in problems, problems
  315. def test_the_value_check_bites_on_a_long_token_and_a_placeholder_that_is_not_one():
  316. token = "A" * 20 + "b" * 20
  317. problems = "\n".join(value_problems(f'# c\nadmin_ssh_public_key = "ssh-ed25519 {token}"\n'))
  318. assert "long token-like string" in problems
  319. problems = "\n".join(value_problems('# c\ntwingate_network = "acme"\n'))
  320. assert "must say 'example'" in problems
  321. def test_the_value_check_accepts_documentation_and_private_ranges():
  322. text = '# c\nreserved_ranges = ["192.0.2.10", "198.51.100.1", "203.0.113.9", "10.99.0.0/24", "172.20.0.0/20", "192.168.4.0/24"]\n'
  323. assert value_problems(text) == []