test_destroy_allowlist_pins.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. """The destroy allowlist in plan.rego is pinned, and cannot be left filled.
  2. Issue #450 added two addresses to destroy_allowlist for the cah-10-access
  3. teardown and then emptied it again (the shipped state). plan_test.rego pins the allowlist by test name, in both directions:
  4. - allowlist filled: plan_test.rego has test_destroy_allowlist_is_exactly_teardown_list
  5. (matching the shipped entries) and no test_destroy_allowlist_is_empty;
  6. - allowlist empty: plan_test.rego has test_destroy_allowlist_is_empty
  7. (asserting count(spacelift.destroy_allowlist) == 0) and no teardown-list test.
  8. The follow-up pull request deletes the teardown-list test, adds the empty test
  9. and sets destroy_allowlist := {}; any other combination fails here. No Rego
  10. test may use the todo_ prefix: `opa test` exits 2 when any test is skipped, and
  11. the shared CI job cannot be told otherwise. OPA is not needed here: this reads
  12. both files as text. Each check also runs on a broken fixture, so a check that
  13. stops biting fails here.
  14. """
  15. import re
  16. from pathlib import Path
  17. ROOT = Path(__file__).resolve().parent.parent
  18. POLICY = ROOT / ".spacelift/policies/plan.rego"
  19. POLICY_TESTS = ROOT / ".spacelift/policies/plan_test.rego"
  20. TEARDOWN = {
  21. "cah-10-access": [
  22. "twingate_remote_network.this",
  23. "module.connector_firewall.digitalocean_firewall.this",
  24. ]
  25. }
  26. EXACT = "test_destroy_allowlist_is_exactly_teardown_list"
  27. EMPTY = "test_destroy_allowlist_is_empty"
  28. def strip_comments(text: str) -> str:
  29. return re.sub(r"(?m)#.*$", "", text)
  30. def parse_allowlist(policy: str) -> dict[str, list[str]]:
  31. """Stack id -> addresses from the destroy_allowlist assignment."""
  32. body = strip_comments(policy)
  33. start = body.index("destroy_allowlist := {")
  34. open_at = body.index("{", start)
  35. depth = 0
  36. for i in range(open_at, len(body)):
  37. depth += {"{": 1, "}": -1}.get(body[i], 0)
  38. if depth == 0:
  39. literal = body[open_at : i + 1]
  40. break
  41. else:
  42. raise AssertionError("unbalanced destroy_allowlist")
  43. result: dict[str, list[str]] = {}
  44. for stack in re.finditer(r'"([^"]+)":\s*\[(.*?)\]', literal, re.DOTALL):
  45. result[stack.group(1)] = re.findall(r'"([^"]+)"', stack.group(2))
  46. return result
  47. def has_test(tests: str, name: str) -> bool:
  48. """True when `name` is defined as a live rule."""
  49. return re.search(rf"(?m)^{name}\s+if\b", tests) is not None
  50. def body_of(tests: str, name: str) -> str:
  51. match = re.search(rf"(?ms)^{name}\s+if\s*\{{(.*?)^\}}", tests)
  52. return strip_comments(match.group(1)) if match else ""
  53. def skipped_tests(tests: str) -> list[str]:
  54. return re.findall(r"(?m)^(todo_\w+)", tests)
  55. def problems(policy: str, tests: str) -> list[str]:
  56. found = []
  57. allowlist = parse_allowlist(policy)
  58. exact_on, empty_on = has_test(tests, EXACT), has_test(tests, EMPTY)
  59. if skipped_tests(tests):
  60. found.append(f"skipped (todo_) tests make opa test exit 2: {skipped_tests(tests)}")
  61. if allowlist:
  62. if not exact_on:
  63. found.append(f"destroy_allowlist is filled, so {EXACT} must exist")
  64. if empty_on:
  65. found.append(f"destroy_allowlist is filled, so {EMPTY} must not exist")
  66. if allowlist != TEARDOWN:
  67. found.append(f"destroy_allowlist is {allowlist}, expected exactly {TEARDOWN}")
  68. else:
  69. if not empty_on:
  70. found.append(f"destroy_allowlist is empty, so {EMPTY} must exist")
  71. elif "count(spacelift.destroy_allowlist) == 0" not in body_of(tests, EMPTY):
  72. found.append(f"{EMPTY} must assert count(spacelift.destroy_allowlist) == 0")
  73. if exact_on:
  74. found.append(f"destroy_allowlist is empty, so {EXACT} must not exist")
  75. return found
  76. # Fixtures: a minimal policy and test file in each state.
  77. POLICY_FILLED = 'destroy_allowlist := {"cah-10-access": [\n\t"twingate_remote_network.this",\n\t"module.connector_firewall.digitalocean_firewall.this",\n]}\n'
  78. POLICY_EMPTY = "destroy_allowlist := {}\n"
  79. TESTS_EXACT = f"{EXACT} if {{\n\ttrue\n}}\n"
  80. TESTS_EMPTY = f"{EMPTY} if {{\n\tcount(spacelift.destroy_allowlist) == 0\n}}\n"
  81. def test_shipped_allowlist_and_tests_agree():
  82. policy, tests = POLICY.read_text(), POLICY_TESTS.read_text()
  83. # Shipped state after the #450 teardown: empty, pinned by the empty test.
  84. assert parse_allowlist(policy) == {}
  85. assert has_test(tests, EMPTY)
  86. assert not has_test(tests, EXACT)
  87. assert problems(policy, tests) == []
  88. def test_shipped_policy_tests_have_no_skipped_test():
  89. assert skipped_tests(POLICY_TESTS.read_text()) == []
  90. def test_allowlist_names_each_address_once():
  91. allowlist = parse_allowlist(POLICY.read_text())
  92. for addresses in [*allowlist.values(), *TEARDOWN.values()]:
  93. assert len(addresses) == len(set(addresses))
  94. def test_the_policy_test_file_names_the_same_addresses():
  95. tests = POLICY_TESTS.read_text()
  96. for addresses in TEARDOWN.values():
  97. for address in addresses:
  98. assert f'"{address}"' in tests
  99. def test_filled_allowlist_with_exact_test_is_fine():
  100. assert problems(POLICY_FILLED, TESTS_EXACT) == []
  101. def test_emptied_allowlist_with_empty_test_is_fine():
  102. assert problems(POLICY_EMPTY, TESTS_EMPTY) == []
  103. def test_guard_bites_when_allowlist_is_left_filled_after_the_flip():
  104. assert problems(POLICY_FILLED, TESTS_EMPTY)
  105. def test_guard_bites_when_allowlist_is_emptied_without_the_flip():
  106. assert problems(POLICY_EMPTY, TESTS_EXACT)
  107. def test_guard_bites_when_both_tests_exist():
  108. assert problems(POLICY_FILLED, TESTS_EXACT + TESTS_EMPTY)
  109. assert problems(POLICY_EMPTY, TESTS_EXACT + TESTS_EMPTY)
  110. def test_guard_bites_when_neither_test_exists():
  111. assert problems(POLICY_FILLED, "")
  112. assert problems(POLICY_EMPTY, "")
  113. def test_guard_bites_when_the_empty_test_does_not_assert_empty():
  114. weak = f"{EMPTY} if {{\n\ttrue\n}}\n"
  115. assert problems(POLICY_EMPTY, weak)
  116. def test_guard_bites_on_an_extra_or_missing_address():
  117. extra = POLICY_FILLED.replace("]}", '\t"module.vpc.digitalocean_vpc.this",\n]}')
  118. assert problems(extra, TESTS_EXACT)
  119. missing = 'destroy_allowlist := {"cah-10-access": ["twingate_remote_network.this"]}\n'
  120. assert problems(missing, TESTS_EXACT)
  121. def test_guard_bites_on_an_address_under_another_stack():
  122. moved = POLICY_FILLED.replace("cah-10-access", "cah-00-foundation")
  123. assert problems(moved, TESTS_EXACT)
  124. def test_guard_bites_on_a_todo_prefixed_test():
  125. skipped = TESTS_EXACT + f"todo_{EMPTY} if {{\n\ttrue\n}}\n"
  126. assert skipped_tests(skipped) == [f"todo_{EMPTY}"]
  127. assert problems(POLICY_FILLED, skipped)