test_metrics_firewall.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. """The metrics ports on the connector firewall (issue #99) are tag-sourced only.
  2. tofu test proves the rendered rule lists. These tests read the sources, so an
  3. address-sourced inbound rule cannot appear without a test failing here, and they
  4. keep stack 10 and stack 20 agreeing about the metrics ports. Each check is run
  5. on a broken fixture too, so a check that stops biting fails.
  6. """
  7. import re
  8. from pathlib import Path
  9. ROOT = Path(__file__).resolve().parent.parent
  10. FIREWALL = ROOT / "modules/firewall/main.tf"
  11. ACCESS = ROOT / "stacks/10-access"
  12. TELEMETRY = ROOT / "stacks/20-telemetry"
  13. def code(text: str) -> str:
  14. return re.sub(r"(?m)(#|//).*$", "", text)
  15. def block(text: str, header: str) -> str:
  16. """The brace-balanced body that follows `header` (first occurrence)."""
  17. start = text.index(header)
  18. open_at = text.index("{", start)
  19. depth = 0
  20. for i in range(open_at, len(text)):
  21. if text[i] == "{":
  22. depth += 1
  23. elif text[i] == "}":
  24. depth -= 1
  25. if depth == 0:
  26. return text[open_at + 1 : i]
  27. raise AssertionError("unbalanced braces")
  28. def inbound_blocks(text: str) -> list[str]:
  29. """Every inbound_rule body (static or dynamic content) in the text."""
  30. out = []
  31. for m in re.finditer(r'(?m)^\s*(?:dynamic\s+")?inbound_rule"?\s*\{', text):
  32. out.append(block(text[m.start() :], "inbound_rule"))
  33. return out
  34. def address_sources(text: str) -> list[str]:
  35. """Inbound rule bodies that name an address source."""
  36. return [b for b in inbound_blocks(text) if "source_addresses" in b]
  37. def test_the_firewall_module_has_inbound_rules_and_none_names_an_address():
  38. text = code(FIREWALL.read_text())
  39. assert len(inbound_blocks(text)) == 2 # own-tag rules and other-tag rules
  40. assert address_sources(text) == []
  41. assert "source_addresses" not in text
  42. assert "source_load_balancer_uids" not in text
  43. def test_the_guard_bites_on_an_address_sourced_inbound_rule():
  44. bad = """
  45. resource "digitalocean_firewall" "this" {
  46. inbound_rule {
  47. protocol = "tcp"
  48. port_range = "9100"
  49. source_addresses = ["0.0.0.0/0", "::/0"]
  50. }
  51. }
  52. """
  53. assert len(inbound_blocks(bad)) == 1
  54. assert len(address_sources(bad)) == 1
  55. dynamic_bad = bad.replace("inbound_rule {", 'dynamic "inbound_rule" {\n content {', 1)
  56. assert address_sources(dynamic_bad + "}")
  57. def test_stack_10_feeds_the_firewall_only_tag_sourced_metrics_rules():
  58. text = code((ACCESS / "main.tf").read_text())
  59. firewall = block(text, 'module "connector_firewall"')
  60. assert re.search(r"(?m)^\s*inbound_from_other_tags\s*=\s*local\.metrics_inbound_rules\s*$", firewall)
  61. rules = text[text.index("metrics_inbound_rules =") :]
  62. rules = rules[: rules.index("\n ]\n") + 4]
  63. # protocol is fixed to tcp, the tag is the one variable, and no address key.
  64. assert 'protocol = "tcp"' in rules
  65. assert "tag = var.metrics_source_tag" in rules
  66. assert "source_addresses" not in rules and "0.0.0.0" not in rules
  67. assert 'var.metrics_source_tag == "" ? []' in rules
  68. assert address_sources(text) == []
  69. def test_stack_10_hard_codes_no_metrics_port():
  70. text = code((ACCESS / "main.tf").read_text())
  71. assert "9100" not in text and "9999" not in text
  72. def variable_default_port(variables_tf: str, name: str) -> int:
  73. body = block(variables_tf, f'variable "{name}"')
  74. found = re.search(r"optional\(number,\s*(\d+)\)", body) or re.search(
  75. r"(?m)^\s*default\s*=\s*(\d+)\s*$", body
  76. )
  77. assert found, f"no numeric default for {name}"
  78. return int(found.group(1))
  79. def test_stack_10_and_stack_20_agree_on_the_node_exporter_port_default():
  80. access = code((ACCESS / "variables.tf").read_text())
  81. telemetry = code((TELEMETRY / "variables.tf").read_text())
  82. assert variable_default_port(access, "node_exporter") == 9100
  83. assert variable_default_port(telemetry, "node_exporter_port") == 9100
  84. def test_both_stacks_keep_9100_for_the_node_exporter():
  85. # Stack 10 refuses 9100 as the connector metrics port (its variable
  86. # validation); stack 20 must refuse it too, whatever node_exporter_port is.
  87. access = code((ACCESS / "variables.tf").read_text())
  88. assert "connector_telemetry.metrics_port != 9100" in access
  89. telemetry = code((TELEMETRY / "main.tf").read_text())
  90. assert "var.metrics_port_connector != 9100" in telemetry
  91. def test_the_tag_variable_refuses_addresses():
  92. access = code((ACCESS / "variables.tf").read_text())
  93. body = block(access, 'variable "metrics_source_tag"')
  94. pattern = re.search(r'regex\("([^"]+)"', body).group(1)
  95. ok = re.compile(pattern)
  96. assert ok.match("cah-telemetry-tor1")
  97. for refused in ("192.0.2.10", "0.0.0.0/0", "::/0", "a b", "tag/x"):
  98. assert not ok.match(refused), refused