test_metrics_firewall_aws.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. """The AWS metrics ports (issue #99, AWS half) are admitted from a security group only.
  2. tofu test proves the rendered rule lists. These tests read the sources, so an
  3. ingress rule that takes an address (cidr_blocks, ipv6_cidr_blocks, cidr_ipv4,
  4. cidr_ipv6, a prefix list) from the metrics inputs cannot appear without a test
  5. failing here. Each check also runs on a broken fixture, so a check that stops
  6. biting fails.
  7. """
  8. import re
  9. from pathlib import Path
  10. ROOT = Path(__file__).resolve().parent.parent
  11. FIREWALL = ROOT / "modules/aws/firewall"
  12. ACCESS = ROOT / "stacks/aws/10-access"
  13. INGRESS = "aws_vpc_security_group_ingress_rule"
  14. ADDRESS_ATTRS = re.compile(
  15. r"(?m)^\s*(cidr_blocks|ipv6_cidr_blocks|cidr_ipv4|cidr_ipv6|prefix_list_id)\s*="
  16. )
  17. def code(text: str) -> str:
  18. return re.sub(r"(?m)(#|//).*$", "", text)
  19. def block(text: str, header: str) -> str:
  20. """The brace-balanced body that follows `header` (first occurrence)."""
  21. start = text.index(header)
  22. open_at = text.index("{", start)
  23. depth = 0
  24. for i in range(open_at, len(text)):
  25. if text[i] == "{":
  26. depth += 1
  27. elif text[i] == "}":
  28. depth -= 1
  29. if depth == 0:
  30. return text[open_at + 1 : i]
  31. raise AssertionError("unbalanced braces")
  32. def ingress_blocks(text: str) -> dict[str, str]:
  33. """Every ingress rule resource body in the text, by resource name."""
  34. out = {}
  35. for m in re.finditer(rf'(?m)^\s*resource\s+"{INGRESS}"\s+"([A-Za-z0-9_]+)"\s*\{{', text):
  36. out[m.group(1)] = block(text[m.start() :], "resource")
  37. return out
  38. def address_sourced(blocks: dict[str, str]) -> list[str]:
  39. """Names of ingress rules that set any address-type source attribute."""
  40. return [name for name, body in blocks.items() if ADDRESS_ATTRS.search(body)]
  41. def test_the_firewall_module_has_ingress_rules_and_none_names_an_address():
  42. text = code((FIREWALL / "main.tf").read_text())
  43. blocks = ingress_blocks(text)
  44. assert sorted(blocks) == ["member", "other_group"]
  45. assert address_sourced(blocks) == []
  46. for name, body in blocks.items():
  47. assert re.search(r"(?m)^\s*referenced_security_group_id\s*=", body), name
  48. # The module as a whole has no way to say "ingress from an address".
  49. assert not re.search(r"cidr_blocks|ipv6_cidr_blocks|prefix_list", text)
  50. # The only cidr in the module is the any-address EGRESS rule.
  51. assert len(re.findall(r"cidr_ipv4", text)) == 1
  52. def test_the_guard_bites_on_an_address_sourced_ingress_rule():
  53. bad = f"""
  54. resource "{INGRESS}" "metrics" {{
  55. security_group_id = aws_security_group.this.id
  56. cidr_ipv4 = var.metrics_source_cidr
  57. ip_protocol = "tcp"
  58. }}
  59. resource "{INGRESS}" "ipv6" {{
  60. security_group_id = aws_security_group.this.id
  61. ipv6_cidr_blocks = ["::/0"]
  62. }}
  63. resource "{INGRESS}" "ok" {{
  64. security_group_id = aws_security_group.this.id
  65. referenced_security_group_id = var.source
  66. }}
  67. """
  68. blocks = ingress_blocks(bad)
  69. assert sorted(blocks) == ["ipv6", "metrics", "ok"]
  70. assert address_sourced(blocks) == ["metrics", "ipv6"]
  71. for attr in ("cidr_ipv6", "cidr_blocks", "prefix_list_id"):
  72. assert address_sourced(ingress_blocks(bad.replace("cidr_ipv4", attr)))
  73. def test_the_other_group_variable_has_no_address_field():
  74. text = code((FIREWALL / "variables.tf").read_text())
  75. body = block(text, 'variable "inbound_from_other_groups"')
  76. fields = re.findall(r"(?m)^\s*([a-z_]+)\s*=\s*string\s*$", body)
  77. assert fields == ["protocol", "port_range", "security_group_id"]
  78. type_part = body[: body.index("default")]
  79. assert not re.search(r"cidr|prefix_list|address", type_part)
  80. pattern = re.search(r'regex\("(\^sg-[^"]+)"', body).group(1)
  81. ok = re.compile(pattern)
  82. assert ok.match("sg-0abc1230abc123450")
  83. for refused in ("192.0.2.10", "0.0.0.0/0", "::/0", "", "sg-", "sg-xyz", "pl-0abc1230abc123450"):
  84. assert not ok.match(refused), refused
  85. def test_stack_feeds_the_firewall_only_security_group_sourced_metrics_rules():
  86. text = code((ACCESS / "main.tf").read_text())
  87. firewall = block(text, 'module "connector_firewall"')
  88. assert re.search(
  89. r"(?m)^\s*inbound_from_other_groups\s*=\s*local\.metrics_inbound_rules\s*$", firewall
  90. )
  91. # No other input of the firewall module can carry the metrics ports.
  92. assert "metrics" not in re.sub(r"inbound_from_other_groups\s*=\s*local\.metrics_inbound_rules", "", firewall)
  93. start = text.index("metrics_inbound_rules =")
  94. rules = text[start : text.index("\n ]\n", start) + 5]
  95. assert 'protocol = "tcp"' in rules
  96. assert "security_group_id = var.metrics_source_security_group_id" in rules
  97. assert not re.search(r"cidr|0\.0\.0\.0|::/0|prefix_list", rules)
  98. assert 'var.metrics_source_security_group_id == "" ? []' in rules
  99. # The stack declares no rule resource of its own.
  100. assert ingress_blocks(text) == {}
  101. assert not ADDRESS_ATTRS.search(text)
  102. def test_other_group_rule_refuses_its_own_group_as_source():
  103. text = code((FIREWALL / "main.tf").read_text())
  104. body = ingress_blocks(text)["other_group"]
  105. assert re.search(
  106. r"precondition\s*\{\s*condition\s*=\s*each\.value\.source\s*!=\s*aws_security_group\.this\.id",
  107. body,
  108. )
  109. out = code((ACCESS / "outputs.tf").read_text())
  110. assert re.search(
  111. r"precondition\s*\{\s*condition\s*=\s*var\.metrics_source_security_group_id\s*!=\s*module\.connector_firewall\.id",
  112. out,
  113. )
  114. # The guard bites: the check is the rule's only precondition, so removing it
  115. # leaves none (and the pattern above would fail).
  116. assert body.count("precondition") == 1
  117. def test_stack_hard_codes_no_metrics_port():
  118. text = code((ACCESS / "main.tf").read_text())
  119. assert "9100" not in text and "9999" not in text
  120. def test_the_stack_variable_refuses_addresses():
  121. text = code((ACCESS / "variables.tf").read_text())
  122. body = block(text, 'variable "metrics_source_security_group_id"')
  123. pattern = re.search(r'regex\("(\^sg-[^"]+)"', body).group(1)
  124. ok = re.compile(pattern)
  125. assert ok.match("sg-0abc1230abc123450")
  126. for refused in ("192.0.2.10", "0.0.0.0/0", "::/0", "a b", "sg-0abc/24", "10.0.0.0/8"):
  127. assert not ok.match(refused), refused
  128. # The default is empty, which means no rule.
  129. assert re.search(r'(?m)^\s*default\s*=\s*""\s*$', body)
  130. def test_no_aws_log_shipping_input_yet():
  131. # Log shipping on AWS waits for its own change (the DigitalOcean one is a
  132. # separate open PR); this one must not smuggle it in.
  133. for path in (ACCESS / "variables.tf", ACCESS / "main.tf"):
  134. assert "log_shipping" not in path.read_text()
  135. assert "log_shipping" not in (ROOT / "modules/aws/twingate-connector/variables.tf").read_text()