test_cost_check_labs.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. # SPDX-License-Identifier: Apache-2.0
  2. """Option L1: the cost gate's narrow exemption for the top-level labs/ directory.
  3. labs/ is still parsed for syntax, but the type allowlist, count/for_each and
  4. module-source rules do not apply there. stacks/ and modules/ are unchanged.
  5. """
  6. import json
  7. import os
  8. import sys
  9. from pathlib import Path
  10. import pytest
  11. sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
  12. import cost_check
  13. from test_cost_check import droplet, make_repo
  14. ROOT = Path(__file__).resolve().parent.parent
  15. COSTED = 'resource "digitalocean_droplet" "lab" {}\n'
  16. VOLUME = 'resource "digitalocean_volume" "v" {}\n'
  17. LOOPED = 'resource "digitalocean_droplet" "lab" {\n count = 2\n}\n'
  18. def problems_for(tmp_path, files):
  19. root = make_repo(tmp_path, [droplet()], tf_files=files)
  20. approved = json.loads((root / "docs/stages/approved.json").read_text())
  21. problems, _ = cost_check.gate_problems(root, approved)
  22. return problems
  23. def mentions(problems, needle):
  24. return any(needle in p for p in problems)
  25. def test_costed_type_under_labs_passes(tmp_path):
  26. files = {"labs/vm/main.tf": COSTED, "labs/vm/vol.tf": VOLUME, "labs/vm/loop.tf": LOOPED}
  27. assert problems_for(tmp_path, files) == []
  28. @pytest.mark.parametrize("where", ["stacks/10-access/extra.tf", "modules/other/main.tf"])
  29. def test_same_file_outside_labs_fails(tmp_path, where):
  30. problems = problems_for(tmp_path, {where: VOLUME})
  31. assert mentions(problems, where)
  32. @pytest.mark.parametrize("where", ["stacks/10-access/loop.tf", "modules/ok/main.tf"])
  33. def test_count_on_costed_resource_outside_labs_fails(tmp_path, where):
  34. problems = problems_for(tmp_path, {where: LOOPED})
  35. assert mentions(problems, "uses count")
  36. def test_syntax_error_under_labs_fails(tmp_path):
  37. problems = problems_for(tmp_path, {"labs/vm/bad.tf": 'resource "x" "y" {\n a = "unterminated\n'})
  38. assert mentions(problems, "labs/vm/bad.tf") and mentions(problems, "unreadable HCL")
  39. def test_tf_json_under_labs_still_refused(tmp_path):
  40. problems = problems_for(tmp_path, {"labs/vm/main.tf.json": "{}"})
  41. assert mentions(problems, "labs/vm/main.tf.json")
  42. @pytest.mark.parametrize(
  43. "where",
  44. [
  45. "Labs/vm/main.tf",
  46. "LABS/vm/main.tf",
  47. "labs2/vm/main.tf",
  48. "lab/vm/main.tf",
  49. "docs/labs/vm/main.tf",
  50. "stacks/labs/main.tf",
  51. "modules/labs/main.tf",
  52. "stacks/10-access/labs/main.tf",
  53. ],
  54. )
  55. def test_lookalike_paths_are_not_exempt(tmp_path, where):
  56. root = make_repo(tmp_path, [droplet()], tf_files={where: VOLUME})
  57. assert not cost_check.lab_file(root, where)
  58. found = cost_check.uncosted_sources(root, {})
  59. assert mentions(found, where)
  60. @pytest.mark.parametrize(
  61. "rel",
  62. ["labs/../stacks/10-access/x.tf", "labs/a/../../modules/x.tf", "/etc/x.tf", "labs", "labs/"],
  63. )
  64. def test_traversal_and_bare_paths_are_not_exempt(tmp_path, rel):
  65. root = make_repo(tmp_path, [droplet()])
  66. (root / "labs").mkdir()
  67. assert not cost_check.lab_file(root, rel)
  68. def test_real_lab_file_is_exempt(tmp_path):
  69. root = make_repo(tmp_path, [droplet()], tf_files={"labs/a/b/main.tf": COSTED})
  70. assert cost_check.lab_file(root, "labs/a/b/main.tf")
  71. def test_symlink_from_labs_into_stacks_is_not_exempt(tmp_path):
  72. root = make_repo(tmp_path, [droplet()], tf_files={"stacks/10-access/extra.tf": VOLUME})
  73. (root / "labs").mkdir()
  74. (root / "labs/link").symlink_to(root / "stacks/10-access", target_is_directory=True)
  75. assert not cost_check.lab_file(root, "labs/link/extra.tf")
  76. approved = json.loads((root / "docs/stages/approved.json").read_text())
  77. problems, _ = cost_check.gate_problems(root, approved)
  78. assert mentions(problems, "labs/link: symlinked directory is refused")
  79. def test_symlinked_file_under_labs_is_not_exempt(tmp_path):
  80. root = make_repo(tmp_path, [droplet()], tf_files={"stacks/10-access/extra.tf": VOLUME})
  81. (root / "labs").mkdir()
  82. (root / "labs/x.tf").symlink_to(root / "stacks/10-access/extra.tf")
  83. assert not cost_check.lab_file(root, "labs/x.tf")
  84. approved = json.loads((root / "docs/stages/approved.json").read_text())
  85. problems, _ = cost_check.gate_problems(root, approved)
  86. assert mentions(problems, "labs/x.tf: symlinked OpenTofu file is refused")
  87. def test_symlinked_labs_directory_is_not_exempt(tmp_path):
  88. root = make_repo(tmp_path, [droplet()], tf_files={"stacks/10-access/extra.tf": VOLUME})
  89. os.symlink(root / "stacks/10-access", root / "labs", target_is_directory=True)
  90. assert not cost_check.lab_file(root, "labs/extra.tf")
  91. approved = json.loads((root / "docs/stages/approved.json").read_text())
  92. problems, _ = cost_check.gate_problems(root, approved)
  93. assert mentions(problems, "labs: symlinked directory is refused")
  94. def project_roots(node, where="config"):
  95. """Every (path, value) of a project_root key anywhere in the parsed config."""
  96. if isinstance(node, dict):
  97. for key, value in node.items():
  98. if key == "project_root" and isinstance(value, str):
  99. yield f"{where}.{key}", value
  100. else:
  101. yield from project_roots(value, f"{where}.{key}")
  102. elif isinstance(node, list):
  103. for i, value in enumerate(node):
  104. yield from project_roots(value, f"{where}[{i}]")
  105. def labs_registration_problems(approved, spacelift_dir, root):
  106. """Every way labs/ could be approved or handed to Spacelift."""
  107. found = []
  108. for provider, entry in approved["providers"].items():
  109. for kind, files in entry.get("allowed_sources", {}).items():
  110. for f in files:
  111. if "labs" in [part.lower() for part in Path(f).parts]:
  112. found.append(f"approved.json {provider} {kind}: {f}")
  113. for path in sorted(p for p in Path(spacelift_dir).rglob("*") if p.is_file()):
  114. text = path.read_text(encoding="utf-8").lower()
  115. if "labs/" in text or "/labs" in text:
  116. found.append(f"{path.name} refers to labs/")
  117. config = Path(spacelift_dir, "config.yml")
  118. if config.exists():
  119. import yaml
  120. loaded = yaml.safe_load(config.read_text(encoding="utf-8"))
  121. ids = cost_check.manifest_ids(root)
  122. for where, root_value in project_roots(loaded):
  123. parts = [x.lower() for x in Path(os.path.normpath(root_value)).parts]
  124. if "labs" in parts:
  125. found.append(f"{where} has project_root {root_value!r}")
  126. for sid in loaded["stacks"]:
  127. for manifest in ids.get(sid, []):
  128. if str(manifest).startswith("labs/"):
  129. found.append(f"stack {sid} is backed by {manifest}")
  130. return found
  131. def test_nothing_under_labs_is_approved_or_a_spacelift_stack():
  132. """The exemption is not an approval and Spacelift never applies labs/."""
  133. approved = json.loads((ROOT / "docs/stages/approved.json").read_text())
  134. assert labs_registration_problems(approved, ROOT / ".spacelift", ROOT) == []
  135. def test_guard_catches_allowed_source_and_spacelift_reference(tmp_path):
  136. approved = {
  137. "providers": {"digitalocean": {"allowed_sources": {"digitalocean_droplet": ["Labs/vm/main.tf"]}}}
  138. }
  139. sl = tmp_path / ".spacelift"
  140. sl.mkdir()
  141. (sl / "config.yml").write_text("stacks:\n cah-x:\n project_root: labs/vm\n")
  142. found = labs_registration_problems(approved, sl, tmp_path)
  143. assert any("approved.json" in f for f in found)
  144. assert any("refers to labs/" in f for f in found)
  145. def module_ref(source):
  146. return f'module "m" {{\n source = "{source}"\n}}\n'
  147. def module_problems_for(tmp_path, files, symlinks=()):
  148. root = make_repo(tmp_path, [droplet()], tf_files=files)
  149. for link, target in symlinks:
  150. (root / link).parent.mkdir(parents=True, exist_ok=True)
  151. (root / link).symlink_to(root / target, target_is_directory=True)
  152. approved = json.loads((root / "docs/stages/approved.json").read_text())
  153. problems, _ = cost_check.gate_problems(root, approved)
  154. return problems
  155. @pytest.mark.parametrize(
  156. "where,source",
  157. [
  158. ("stacks/10-access/ref.tf", "../../labs/y"),
  159. ("modules/x/main.tf", "../../labs/y"),
  160. ("modules/x/main.tf", "../../modules/../labs/y"),
  161. ],
  162. )
  163. def test_module_outside_labs_may_not_source_labs(tmp_path, where, source):
  164. files = {where: module_ref(source), "labs/y/main.tf": COSTED}
  165. assert mentions(module_problems_for(tmp_path, files), "points into labs/")
  166. def test_symlinked_dir_into_labs_is_refused(tmp_path):
  167. files = {"stacks/10-access/ref.tf": module_ref("../../modules/viz"), "labs/y/main.tf": COSTED}
  168. problems = module_problems_for(tmp_path, files, symlinks=[("modules/viz", "labs/y")])
  169. assert mentions(problems, "symlinked directory is refused")
  170. def test_resolved_symlink_target_in_labs_is_refused(tmp_path):
  171. # Reached through a symlinked path the walk does not follow: the module
  172. # block still resolves into labs/ and is refused on its own.
  173. root = make_repo(tmp_path, [droplet()], tf_files={"labs/y/main.tf": COSTED})
  174. (root / "stacks/10-access/link").symlink_to(root / "labs/y", target_is_directory=True)
  175. block = cost_check.find_blocks(module_ref("./link"))[0]
  176. _, problem = cost_check.module_source_problem(root, "stacks/10-access/ref.tf", block)
  177. assert problem and "points into labs/" in problem
  178. def test_labs2_lookalike_source_behaves_as_before(tmp_path):
  179. files = {"stacks/10-access/ref.tf": module_ref("../../labs2/y"), "labs2/y/main.tf": VOLUME}
  180. problems = module_problems_for(tmp_path, files)
  181. assert not mentions(problems, "points into labs/")
  182. assert mentions(problems, "labs2/y/main.tf")
  183. def test_lab_may_call_a_module_read_only(tmp_path):
  184. """Decision: a lab may call modules/ by relative path. modules/ is scanned
  185. by the gate in full on its own, so nothing is hidden; the lab's own
  186. arguments are unpriced like the rest of the lab. A lab may even name
  187. stacks/ code: that is not a gate bypass (stacks/ is scanned wherever it is
  188. called from) and Spacelift never runs labs/."""
  189. files = {
  190. "labs/y/main.tf": module_ref("../../modules/ok"),
  191. "modules/ok/other.tf": 'resource "random_id" "r" {}\n',
  192. }
  193. assert problems_for(tmp_path, files) == []
  194. @pytest.mark.parametrize("value", ["labs", "./labs", "labs/", "Labs", "stacks/../labs", "labs/vm"])
  195. def test_guard_catches_a_bare_labs_project_root(tmp_path, value):
  196. sl = tmp_path / ".spacelift"
  197. sl.mkdir()
  198. (sl / "config.yml").write_text(f"stacks:\n cah-x:\n project_root: '{value}'\n")
  199. found = labs_registration_problems({"providers": {}}, sl, tmp_path)
  200. assert any("project_root" in f for f in found), value