test_cost_check_multicloud.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  1. """Cost gate across providers: manifests, plans, approval and the shared ceiling."""
  2. import json
  3. import sys
  4. from pathlib import Path
  5. import pytest
  6. sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
  7. import cost_check
  8. DO_PRICES = {
  9. "backups_fraction": 0.2,
  10. "backups_fraction_verified": False,
  11. "droplets": {"s-1vcpu-1gb": 6},
  12. }
  13. AWS_PRICES = json.loads(
  14. (Path(__file__).resolve().parents[1] / "docs/cost-prices/aws.json").read_text()
  15. )
  16. CONNECTOR = (
  17. 'module "c{i}" {{\n source = "../../../modules/aws/twingate-connector"\n'
  18. " instance_type = local.c.type\n}}\n"
  19. )
  20. DO_CONNECTOR = (
  21. 'module "c{i}" {{\n source = "../../modules/twingate-connector"\n'
  22. " size = local.c.size\n}}\n"
  23. )
  24. def instance(name="connector-a", itype="t4g.micro", root_gb=8, public_ip=True):
  25. return {
  26. "name": name,
  27. "kind": "instance",
  28. "type": itype,
  29. "root_gb": root_gb,
  30. "public_ip": public_ip,
  31. }
  32. def build(
  33. tmp_path, *, aws=None, do_droplets=1, aws_cap=21.0, aws_active=False, ceiling=30.0
  34. ):
  35. """A repo with a DigitalOcean stack and (optionally) an AWS stack."""
  36. (tmp_path / "docs/stages").mkdir(parents=True)
  37. (tmp_path / "docs/cost-prices").mkdir(parents=True)
  38. (tmp_path / "docs/cost-prices.json").write_text(json.dumps(DO_PRICES))
  39. (tmp_path / "docs/cost-prices/aws.json").write_text(json.dumps(AWS_PRICES))
  40. providers = {
  41. "digitalocean": {
  42. "approved_monthly_total": 6.0 * do_droplets,
  43. "active": True,
  44. "allowed_sources": {
  45. "digitalocean_droplet": ["modules/twingate-connector/main.tf"]
  46. },
  47. }
  48. }
  49. if aws is not None:
  50. providers["aws"] = {
  51. "approved_monthly_total": aws_cap,
  52. "active": aws_active,
  53. "allowed_sources": {
  54. "aws_instance": ["modules/aws/twingate-connector/main.tf"]
  55. },
  56. }
  57. (tmp_path / "docs/stages/approved.json").write_text(
  58. json.dumps({"stage": 1, "ceiling": ceiling, "providers": providers})
  59. )
  60. do = tmp_path / "stacks/10-access"
  61. do.mkdir(parents=True)
  62. do.joinpath("cost.json").write_text(
  63. json.dumps(
  64. {
  65. "resources": [
  66. {
  67. "name": f"d{i}",
  68. "kind": "droplet",
  69. "size": "s-1vcpu-1gb",
  70. "backups": False,
  71. }
  72. for i in range(do_droplets)
  73. ]
  74. }
  75. )
  76. )
  77. do.joinpath("m.tf").write_text(
  78. "".join(DO_CONNECTOR.format(i=i) for i in range(do_droplets))
  79. )
  80. for rel in (
  81. "modules/twingate-connector/main.tf",
  82. "modules/aws/twingate-connector/main.tf",
  83. ):
  84. p = tmp_path / rel
  85. p.parent.mkdir(parents=True, exist_ok=True)
  86. p.write_text(
  87. 'resource "digitalocean_droplet" "a" {}\n'
  88. if "aws" not in rel
  89. else 'resource "aws_instance" "a" {}\n'
  90. )
  91. if aws is not None:
  92. stack = tmp_path / "stacks/aws/10-access"
  93. stack.mkdir(parents=True)
  94. stack.joinpath("cost.json").write_text(json.dumps({"resources": aws}))
  95. stack.joinpath("m.tf").write_text(
  96. "".join(
  97. CONNECTOR.format(i=i)
  98. for i in range(sum(1 for r in aws if r["kind"] == "instance"))
  99. )
  100. )
  101. return tmp_path
  102. def run(root, capsys, *args):
  103. code = cost_check.main(["--root", str(root), *args])
  104. return code, capsys.readouterr()
  105. TWO = [instance("connector-a"), instance("connector-b")]
  106. def test_the_two_connector_aws_stack_costs_the_phase_zero_figure(tmp_path):
  107. root = build(tmp_path, aws=TWO)
  108. assert cost_check.provider_totals(root)["aws"] == 20.84
  109. def test_aws_stack_in_a_provider_directory_is_found_and_counted(tmp_path, capsys):
  110. root = build(tmp_path, aws=TWO)
  111. code, out = run(root, capsys)
  112. assert code == 0, out.err
  113. assert "aws: planned $20.84/mo" in out.out
  114. def test_aws_manifest_over_its_approved_figure_fails(tmp_path, capsys):
  115. root = build(tmp_path, aws=TWO, aws_cap=15.0)
  116. code, out = run(root, capsys)
  117. assert code == 1 and "aws: planned $20.84 is above approved $15.00" in out.err
  118. def test_aws_approval_above_the_ceiling_fails(tmp_path, capsys):
  119. root = build(tmp_path, aws=TWO, aws_cap=35.0)
  120. code, out = run(root, capsys)
  121. assert code == 1 and "above the ceiling" in out.err
  122. def test_two_active_providers_together_above_the_ceiling_fail(tmp_path, capsys):
  123. root = build(tmp_path, aws=TWO, do_droplets=2, aws_cap=21.0, aws_active=True)
  124. code, out = run(root, capsys)
  125. assert code == 1 and "active providers add up to $33.00" in out.err
  126. def test_the_same_providers_pass_when_aws_is_inactive(tmp_path, capsys):
  127. root = build(tmp_path, aws=TWO, do_droplets=2, aws_cap=21.0, aws_active=False)
  128. assert run(root, capsys)[0] == 0
  129. def test_a_stack_directory_without_a_manifest_fails(tmp_path, capsys):
  130. root = build(tmp_path, aws=TWO)
  131. (root / "stacks/aws/10-access/cost.json").unlink()
  132. code, out = run(root, capsys)
  133. assert (
  134. code == 1
  135. and "stacks/aws/10-access: has OpenTofu files but no cost.json" in out.err
  136. )
  137. def test_an_unapproved_provider_with_paid_types_fails(tmp_path, capsys):
  138. root = build(tmp_path, aws=None)
  139. (root / "stacks/10-access/x.tf").write_text('resource "aws_instance" "x" {}\n')
  140. code, out = run(root, capsys)
  141. assert code == 1 and "provider aws is not in approved.json" in out.err
  142. def test_a_provider_with_a_manifest_but_no_approval_fails(tmp_path, capsys):
  143. root = build(tmp_path, aws=TWO)
  144. approved = json.loads((root / "docs/stages/approved.json").read_text())
  145. del approved["providers"]["aws"]
  146. (root / "docs/stages/approved.json").write_text(json.dumps(approved))
  147. code, out = run(root, capsys)
  148. assert code == 1 and "no entry in approved.json" in out.err
  149. def test_a_nat_gateway_is_rejected_even_if_approved_sources_names_it(tmp_path, capsys):
  150. root = build(tmp_path, aws=TWO)
  151. (root / "modules/aws/nat.tf").write_text('resource "aws_nat_gateway" "n" {}\n')
  152. approved = json.loads((root / "docs/stages/approved.json").read_text())
  153. approved["providers"]["aws"]["allowed_sources"]["aws_nat_gateway"] = [
  154. "modules/aws/nat.tf"
  155. ]
  156. (root / "docs/stages/approved.json").write_text(json.dumps(approved))
  157. code, out = run(root, capsys)
  158. assert code == 1 and "aws_nat_gateway is rejected" in out.err
  159. @pytest.mark.parametrize(
  160. "rtype",
  161. [
  162. "aws_vpc",
  163. "aws_subnet",
  164. "aws_internet_gateway",
  165. "aws_security_group",
  166. "aws_default_security_group",
  167. ],
  168. )
  169. def test_free_aws_types_pass(tmp_path, capsys, rtype):
  170. root = build(tmp_path, aws=TWO)
  171. (root / "stacks/aws/10-access/x.tf").write_text(f'resource "{rtype}" "x" {{}}\n')
  172. assert run(root, capsys)[0] == 0
  173. @pytest.mark.parametrize(
  174. "rtype", ["aws_eip", "aws_lb", "aws_db_instance", "aws_vpc_endpoint"]
  175. )
  176. def test_other_aws_types_fail_unless_listed(tmp_path, capsys, rtype):
  177. root = build(tmp_path, aws=TWO)
  178. (root / "stacks/aws/10-access/x.tf").write_text(f'resource "{rtype}" "x" {{}}\n')
  179. code, out = run(root, capsys)
  180. assert code == 1 and rtype in out.err
  181. def test_connector_reconciliation_is_per_stack_not_repository_wide(tmp_path, capsys):
  182. root = build(tmp_path, aws=TWO, do_droplets=2)
  183. assert run(root, capsys)[0] == 0
  184. # one extra AWS connector block must fail in the AWS stack and not be hidden
  185. # by the DigitalOcean stack's blocks
  186. (root / "stacks/aws/10-access/extra.tf").write_text(CONNECTOR.format(i=9))
  187. code, out = run(root, capsys)
  188. assert code == 1 and "stacks/aws/10-access: 3 twingate-connector" in out.err
  189. def test_an_instance_must_state_its_disk_and_address(tmp_path):
  190. bad = [{"name": "a", "kind": "instance", "type": "t4g.micro"}]
  191. root = build(tmp_path, aws=bad)
  192. with pytest.raises(ValueError, match="root_gb and public_ip"):
  193. cost_check.provider_totals(root)
  194. def test_an_unknown_instance_type_has_no_price(tmp_path):
  195. root = build(tmp_path, aws=[instance(itype="m7g.16xlarge")])
  196. with pytest.raises(ValueError, match="no price for instance type"):
  197. cost_check.provider_totals(root)
  198. # ---- plan JSON --------------------------------------------------------------
  199. def change(rtype, name, after, unknown=None, actions=("create",)):
  200. return {
  201. "address": f"{rtype}.{name}",
  202. "type": rtype,
  203. "change": {
  204. "actions": list(actions),
  205. "after": after,
  206. "after_unknown": unknown or {},
  207. },
  208. }
  209. def inst(name="a", itype="t4g.micro", gb=8, public=True, **extra):
  210. extra.setdefault("credit_specification", [{"cpu_credits": "standard"}])
  211. if extra["credit_specification"] is None:
  212. del extra["credit_specification"]
  213. after = {
  214. "instance_type": itype,
  215. "root_block_device": [{"volume_size": gb}],
  216. **extra,
  217. }
  218. if public is not None:
  219. after["associate_public_ip_address"] = public
  220. return change("aws_instance", name, after)
  221. def plan(*changes):
  222. return {"resource_changes": list(changes)}
  223. def test_a_plan_of_the_two_connectors_matches_the_manifest():
  224. total, problems = cost_check.plan_cost(plan(inst("a"), inst("b")), AWS_PRICES)
  225. assert (total, problems) == (20.84, [])
  226. def test_an_instance_with_the_address_unset_is_priced_as_public():
  227. total, _ = cost_check.plan_cost(plan(inst(public=None)), AWS_PRICES)
  228. assert total == round(0.0084 * 730 + 0.005 * 730 + 8 * 0.08, 2)
  229. def test_an_instance_with_the_address_explicitly_off_is_not_charged_for_it():
  230. total, _ = cost_check.plan_cost(plan(inst(public=False)), AWS_PRICES)
  231. assert total == round(0.0084 * 730 + 8 * 0.08, 2)
  232. def test_a_large_root_volume_is_priced():
  233. total, _ = cost_check.plan_cost(plan(inst(gb=500)), AWS_PRICES)
  234. assert total == round(0.0084 * 730 + 0.005 * 730 + 500 * 0.08, 2)
  235. def test_an_extra_ebs_block_device_is_priced():
  236. total, _ = cost_check.plan_cost(
  237. plan(inst(ebs_block_device=[{"volume_size": 100}])), AWS_PRICES
  238. )
  239. assert total == round(0.0084 * 730 + 0.005 * 730 + 108 * 0.08, 2)
  240. def test_an_explicit_elastic_address_is_priced():
  241. total, _ = cost_check.plan_cost(
  242. plan(inst(public=False), change("aws_eip", "e", {})), AWS_PRICES
  243. )
  244. assert total == round(0.0084 * 730 + 8 * 0.08 + 0.005 * 730, 2)
  245. def test_a_nat_gateway_in_a_plan_is_rejected():
  246. _, problems = cost_check.plan_cost(
  247. plan(change("aws_nat_gateway", "n", {})), AWS_PRICES
  248. )
  249. assert problems and "rejected" in problems[0]
  250. def test_for_each_expands_to_one_change_per_instance():
  251. plan_json = plan(*(inst(f"web[{k!r}]") for k in ("a", "b", "c")))
  252. total, _ = cost_check.plan_cost(plan_json, AWS_PRICES)
  253. assert total == round(3 * (0.0084 * 730 + 0.005 * 730 + 8 * 0.08), 2)
  254. def test_a_destroyed_instance_is_not_charged():
  255. gone = inst()
  256. gone["change"]["actions"] = ["delete"]
  257. assert cost_check.plan_cost(plan(gone), AWS_PRICES) == (0.0, [])
  258. def test_an_unknown_type_is_a_problem_not_a_zero():
  259. _, problems = cost_check.plan_cost(plan(change("aws_lb", "l", {})), AWS_PRICES)
  260. assert problems and "no price" in problems[0]
  261. def test_a_missing_root_volume_is_a_problem():
  262. bare = change("aws_instance", "a", {"instance_type": "t4g.micro"})
  263. _, problems = cost_check.plan_cost(plan(bare), AWS_PRICES)
  264. assert problems and "root_block_device" in problems[0]
  265. def test_an_unknown_instance_type_in_the_plan_is_a_problem():
  266. unk = change("aws_instance", "a", {"instance_type": None}, {"instance_type": True})
  267. _, problems = cost_check.plan_cost(plan(unk), AWS_PRICES)
  268. assert problems and "instance_type" in problems[0]
  269. def test_non_aws_resources_in_the_plan_are_ignored():
  270. assert cost_check.plan_cost(
  271. plan(change("twingate_group", "g", {})), AWS_PRICES
  272. ) == (0.0, [])
  273. def test_main_checks_a_plan_against_the_manifest(tmp_path, capsys):
  274. root = build(tmp_path, aws=TWO)
  275. good = tmp_path / "good.json"
  276. good.write_text(json.dumps(plan(inst("a"), inst("b"))))
  277. assert (
  278. run(root, capsys, "--plan", str(good), "--stack", "stacks/aws/10-access")[0]
  279. == 0
  280. )
  281. # the plan has a third instance the manifest does not declare
  282. bad = tmp_path / "bad.json"
  283. bad.write_text(json.dumps(plan(inst("a"), inst("b"), inst("c"))))
  284. code, out = run(root, capsys, "--plan", str(bad), "--stack", "stacks/aws/10-access")
  285. assert code == 1 and "plan costs $31.27 but cost.json declares $20.84" in out.err
  286. def test_main_fails_when_the_plan_has_a_nat_gateway(tmp_path, capsys):
  287. root = build(tmp_path, aws=TWO)
  288. bad = tmp_path / "nat.json"
  289. bad.write_text(
  290. json.dumps(plan(inst("a"), inst("b"), change("aws_nat_gateway", "n", {})))
  291. )
  292. code, out = run(root, capsys, "--plan", str(bad), "--stack", "stacks/aws/10-access")
  293. assert code == 1 and "rejected" in out.err
  294. def test_plan_needs_a_stack(tmp_path, capsys):
  295. root = build(tmp_path, aws=TWO)
  296. p = tmp_path / "p.json"
  297. p.write_text("{}")
  298. code, out = run(root, capsys, "--plan", str(p))
  299. assert code == 1 and "--plan needs --stack" in out.err
  300. # ---- review findings: each was a way to pass the gate -----------------------
  301. def test_a_commented_local_source_does_not_hide_a_remote_one(tmp_path, capsys):
  302. root = build(tmp_path, aws=TWO)
  303. (root / "stacks/aws/10-access/db.tf").write_text(
  304. 'module "db" {\n /*\n source = "./looks-local"\n */\n # source = "./also-local"\n source = "terraform-aws-modules/rds/aws"\n}\n'
  305. )
  306. code, out = run(root, capsys)
  307. assert code == 1 and "non-local source" in out.err
  308. def test_a_brace_in_a_string_or_comment_does_not_end_a_connector_block(
  309. tmp_path, capsys
  310. ):
  311. root = build(tmp_path, aws=TWO)
  312. (root / "stacks/aws/10-access/m.tf").write_text(
  313. 'module "c" {\n source = "../../../modules/aws/twingate-connector"\n instance_type = local.c.type\n note = "}"\n # }\n count = 100\n}\n'
  314. + CONNECTOR.format(i=7)
  315. )
  316. code, out = run(root, capsys)
  317. assert code == 1 and "uses count" in out.err
  318. def test_a_commented_out_resource_is_not_flagged(tmp_path, capsys):
  319. root = build(tmp_path, aws=TWO)
  320. (root / "stacks/aws/10-access/x.tf").write_text('# resource "aws_lb" "x" {}\n')
  321. assert run(root, capsys)[0] == 0
  322. def test_approved_json_cannot_approve_a_type_with_no_price_model(tmp_path, capsys):
  323. root = build(tmp_path, aws=TWO)
  324. (root / "modules/aws/lb.tf").write_text('resource "aws_lb" "l" {}\n')
  325. approved = json.loads((root / "docs/stages/approved.json").read_text())
  326. approved["providers"]["aws"]["allowed_sources"]["aws_lb"] = ["modules/aws/lb.tf"]
  327. (root / "docs/stages/approved.json").write_text(json.dumps(approved))
  328. code, out = run(root, capsys)
  329. assert code == 1 and "no price model" in out.err
  330. @pytest.mark.parametrize("bad", ["nan", "inf", "-1", "abc", None])
  331. def test_a_non_finite_or_negative_approval_fails(tmp_path, capsys, bad):
  332. root = build(tmp_path, aws=TWO)
  333. approved = json.loads((root / "docs/stages/approved.json").read_text())
  334. approved["providers"]["aws"]["approved_monthly_total"] = bad
  335. (root / "docs/stages/approved.json").write_text(json.dumps(approved))
  336. code, out = run(root, capsys)
  337. assert code == 1 and "cost-check:" in out.err
  338. def test_a_nan_ceiling_fails(tmp_path, capsys):
  339. root = build(tmp_path, aws=TWO)
  340. approved = json.loads((root / "docs/stages/approved.json").read_text())
  341. approved["ceiling"] = "nan"
  342. (root / "docs/stages/approved.json").write_text(json.dumps(approved))
  343. assert run(root, capsys)[0] == 1
  344. def test_unknown_extra_disks_are_a_problem_not_zero():
  345. unk = inst(public=False, ebs_block_device=[])
  346. unk["change"]["after_unknown"] = {"ebs_block_device": True}
  347. _, problems = cost_check.plan_cost(plan(unk), AWS_PRICES)
  348. assert problems and "ebs_block_device" in problems[0]
  349. def test_a_stack_directly_under_stacks_aws_is_aws(tmp_path):
  350. assert cost_check.provider_of_stack("stacks/aws") == "aws"
  351. assert cost_check.provider_of_stack("stacks/aws/10-access") == "aws"
  352. assert cost_check.provider_of_stack("stacks/10-access") == "digitalocean"
  353. def test_a_malformed_manifest_exits_nonzero_instead_of_crashing(tmp_path, capsys):
  354. root = build(tmp_path, aws=TWO)
  355. (root / "stacks/aws/10-access/cost.json").write_text(
  356. '{"resources": [{"kind": "instance"}]}'
  357. )
  358. code, _ = run(root, capsys)
  359. assert code == 1
  360. def test_malformed_plan_shapes_exit_nonzero(tmp_path, capsys):
  361. root = build(tmp_path, aws=TWO)
  362. p = tmp_path / "p.json"
  363. p.write_text(
  364. json.dumps(
  365. {
  366. "resource_changes": [
  367. {
  368. "type": "aws_instance",
  369. "change": {
  370. "actions": ["create"],
  371. "after": {
  372. "instance_type": "t4g.micro",
  373. "root_block_device": ["x"],
  374. },
  375. },
  376. }
  377. ]
  378. }
  379. )
  380. )
  381. assert (
  382. run(root, capsys, "--plan", str(p), "--stack", "stacks/aws/10-access")[0] == 1
  383. )
  384. def test_inactive_providers_are_reported_as_an_attestation(tmp_path, capsys):
  385. root = build(tmp_path, aws=TWO, aws_active=False)
  386. out = run(root, capsys)[1].out
  387. assert "aws: planned $20.84/mo, approved $21.00, inactive" in out
  388. def test_data_sources_in_the_plan_are_neither_priced_nor_rejected():
  389. ami = change("aws_ami", "x", {})
  390. ami["mode"] = "data"
  391. lookup = inst()
  392. lookup["mode"] = "data"
  393. assert cost_check.plan_cost(plan(ami, lookup), AWS_PRICES) == (0.0, [])
  394. @pytest.mark.parametrize(
  395. "block",
  396. [
  397. {"volume_size": 8, "volume_type": "io2"},
  398. {"volume_size": 8, "volume_type": "gp2"},
  399. {"volume_size": 8, "iops": 16000},
  400. {"volume_size": 8, "throughput": 1000},
  401. ],
  402. )
  403. def test_unpriced_root_volume_shapes_are_a_problem(block):
  404. bad = inst()
  405. bad["change"]["after"]["root_block_device"] = [block]
  406. _, problems = cost_check.plan_cost(plan(bad), AWS_PRICES)
  407. assert problems
  408. def test_gp3_at_baseline_is_priced():
  409. ok = inst()
  410. ok["change"]["after"]["root_block_device"] = [
  411. {"volume_size": 8, "volume_type": "gp3", "iops": 3000, "throughput": 125}
  412. ]
  413. assert cost_check.plan_cost(plan(ok), AWS_PRICES)[1] == []
  414. def test_standalone_and_extra_volumes_are_shape_checked():
  415. vol = change("aws_ebs_volume", "v", {"size": 10, "type": "io1", "iops": 5000})
  416. assert cost_check.plan_cost(plan(vol), AWS_PRICES)[1]
  417. extra = inst(ebs_block_device=[{"volume_size": 10, "volume_type": "st1"}])
  418. assert cost_check.plan_cost(plan(extra), AWS_PRICES)[1]
  419. # ---- adversarial review: parser-differential bypasses ------------------------
  420. #
  421. # Each of these exited 0 before the fix. The baseline `build(aws=TWO)` repo
  422. # passes, so any failure below comes from the one file the test adds.
  423. AWS_STACK = "stacks/aws/10-access"
  424. NAT = 'resource "aws_nat_gateway" "n" {}\n'
  425. def add(root, rel, text):
  426. path = root / rel
  427. path.parent.mkdir(parents=True, exist_ok=True)
  428. path.write_text(text)
  429. return path
  430. def fails(root, capsys, *needles):
  431. code, out = run(root, capsys)
  432. assert code == 1, out.err
  433. for needle in needles:
  434. assert needle in out.err, out.err
  435. def test_baseline_repo_for_the_review_tests_passes(tmp_path, capsys):
  436. assert run(build(tmp_path, aws=TWO), capsys)[0] == 0
  437. # 1. labels --------------------------------------------------------------------
  438. @pytest.mark.parametrize(
  439. "text",
  440. [
  441. 'resource aws_nat_gateway "n" {}\n',
  442. 'resource "aws_nat_gateway" n {}\n',
  443. "resource aws_nat_gateway n {}\n",
  444. 'resource\t"aws_nat_gateway"\t"n"\t{}\n',
  445. ],
  446. )
  447. def test_bare_resource_labels_are_read(tmp_path, capsys, text):
  448. root = build(tmp_path, aws=TWO)
  449. add(root, f"{AWS_STACK}/x.tf", text)
  450. fails(root, capsys, "aws_nat_gateway")
  451. def test_bare_module_label_with_a_remote_source_fails(tmp_path, capsys):
  452. root = build(tmp_path, aws=TWO)
  453. add(
  454. root,
  455. f"{AWS_STACK}/x.tf",
  456. 'module r {\n source = "git::https://example.invalid/x.git"\n}\n',
  457. )
  458. fails(root, capsys, "non-local source")
  459. def test_a_bare_labelled_local_module_still_passes(tmp_path, capsys):
  460. root = build(tmp_path, aws=TWO)
  461. add(root, f"{AWS_STACK}/x.tf", 'module r {\n source = "./x"\n}\n')
  462. assert run(root, capsys)[0] == 0
  463. @pytest.mark.parametrize(
  464. "text,line",
  465. [
  466. ('resource "aws_nat\\u005fgateway" "n" {}\n', 1),
  467. ('\n\nresource "aws_nat_gateway" "n\\u0041" {}\n', 3),
  468. ('resource "aws_nat\\x" "n" {}\n', 1),
  469. ('\nmodule "r\\u0041" {\n source = "./x"\n}\n', 2),
  470. ],
  471. )
  472. def test_a_backslash_in_a_label_fails_naming_file_and_line(
  473. tmp_path, capsys, text, line
  474. ):
  475. root = build(tmp_path, aws=TWO)
  476. add(root, f"{AWS_STACK}/x.tf", text)
  477. fails(root, capsys, f"{AWS_STACK}/x.tf:{line}", "backslash")
  478. # 2. OpenTofu file kinds -------------------------------------------------------
  479. def test_tofu_files_are_scanned_for_resources(tmp_path, capsys):
  480. root = build(tmp_path, aws=TWO)
  481. add(root, f"{AWS_STACK}/x.tofu", NAT)
  482. fails(root, capsys, "aws_nat_gateway", "x.tofu")
  483. def test_tofu_files_are_scanned_for_modules(tmp_path, capsys):
  484. root = build(tmp_path, aws=TWO)
  485. add(root, f"{AWS_STACK}/extra.tofu", CONNECTOR.format(i=9))
  486. fails(root, capsys, f"{AWS_STACK}: 3 twingate-connector")
  487. @pytest.mark.parametrize("name", ["x.tofu.json", "x.tf.json"])
  488. def test_json_configuration_is_refused(tmp_path, capsys, name):
  489. root = build(tmp_path, aws=TWO)
  490. add(root, f"{AWS_STACK}/{name}", "{}")
  491. fails(root, capsys, name)
  492. def test_a_stack_of_only_tofu_files_needs_a_manifest(tmp_path, capsys):
  493. root = build(tmp_path, aws=TWO)
  494. add(root, "stacks/aws/20-new/main.tofu", 'resource "twingate_group" "g" {}\n')
  495. fails(root, capsys, "stacks/aws/20-new: has OpenTofu files but no cost.json")
  496. @pytest.mark.parametrize("name", ["override.tf", "main_override.tf", "override.tofu"])
  497. def test_override_files_are_scanned(tmp_path, capsys, name):
  498. root = build(tmp_path, aws=TWO)
  499. add(root, f"{AWS_STACK}/{name}", NAT)
  500. fails(root, capsys, "aws_nat_gateway", name)
  501. # 3. hidden directories and stack names ---------------------------------------
  502. @pytest.mark.parametrize("hidden", [".claude", ".hidden", ".git", ".venv"])
  503. def test_a_hidden_directory_under_stacks_is_a_failure(tmp_path, capsys, hidden):
  504. root = build(tmp_path, aws=TWO)
  505. add(root, f"stacks/10-access/{hidden}/z/main.tf", NAT)
  506. fails(root, capsys, "hidden directory", f"stacks/10-access/{hidden}")
  507. def test_a_hidden_directory_under_modules_is_a_failure(tmp_path, capsys):
  508. root = build(tmp_path, aws=TWO)
  509. add(root, "modules/.claude/m/main.tf", NAT)
  510. fails(root, capsys, "hidden directory")
  511. @pytest.mark.parametrize(
  512. "source", ["./.claude/m", "../../.claude/m", "./a/.hidden/b", "../.git/x"]
  513. )
  514. def test_a_module_source_through_a_dot_directory_fails(tmp_path, capsys, source):
  515. root = build(tmp_path, aws=TWO)
  516. add(root, f"{AWS_STACK}/x.tf", f'module "m" {{\n source = "{source}"\n}}\n')
  517. fails(root, capsys, "hidden directory", f"{AWS_STACK}/x.tf:1")
  518. def test_a_module_source_that_leaves_the_repository_fails(tmp_path, capsys):
  519. root = build(tmp_path, aws=TWO)
  520. add(root, "stacks/10-access/x.tf", 'module "m" {\n source = "../../../x"\n}\n')
  521. fails(root, capsys, "outside the repository")
  522. def test_terraform_cache_and_root_tool_directories_are_still_ignored(tmp_path, capsys):
  523. root = build(tmp_path, aws=TWO)
  524. add(root, f"{AWS_STACK}/.terraform/modules/x/main.tf", NAT)
  525. add(root, ".claude/worktrees/w/stacks/10-access/main.tf", NAT)
  526. add(root, ".git/x.tf", NAT)
  527. add(root, ".venv/lib/x.tf", NAT)
  528. assert run(root, capsys)[0] == 0
  529. @pytest.mark.parametrize(
  530. "rel",
  531. [
  532. "stacks/AWS/10-access/main.tf",
  533. "stacks/aws-foo/10-access/main.tf",
  534. "stacks/Azure/10-access/main.tf",
  535. "stacks/foo/main.tf",
  536. "stacks/aws/foo/main.tf",
  537. "stacks/10/main.tf",
  538. "stacks/-x/main.tf",
  539. ],
  540. )
  541. def test_stack_directory_names_are_exact(tmp_path, capsys, rel):
  542. root = build(tmp_path, aws=TWO)
  543. add(root, rel, 'resource "twingate_group" "g" {}\n')
  544. fails(root, capsys, "stack directory name")
  545. @pytest.mark.parametrize("rel", ["stacks/gcp/05-x/main.tf", "stacks/azure/99-a-b/m.tf"])
  546. def test_known_provider_and_numbered_names_are_accepted(tmp_path, capsys, rel):
  547. root = build(tmp_path, aws=TWO)
  548. add(root, rel, 'resource "twingate_group" "g" {}\n')
  549. out = run(root, capsys)[1]
  550. assert "stack directory name" not in out.err
  551. # 4. heredocs ------------------------------------------------------------------
  552. OPEN_C = "locals {\n a = <<EOT\n/*\nEOT\n}\n"
  553. CLOSE_C = "locals {\n b = <<EOT\n*/\nEOT\n}\n"
  554. def test_a_comment_opener_inside_a_heredoc_does_not_hide_a_resource(tmp_path, capsys):
  555. root = build(tmp_path, aws=TWO)
  556. add(root, f"{AWS_STACK}/x.tf", OPEN_C + NAT + CLOSE_C)
  557. fails(root, capsys, "aws_nat_gateway")
  558. def test_the_same_trick_with_an_indented_heredoc(tmp_path, capsys):
  559. root = build(tmp_path, aws=TWO)
  560. text = OPEN_C.replace("<<EOT", "<<-EOT") + NAT + CLOSE_C.replace("<<EOT", "<<-EOT")
  561. add(root, f"{AWS_STACK}/x.tf", text.replace("\nEOT\n", "\n EOT\n"))
  562. fails(root, capsys, "aws_nat_gateway")
  563. def test_a_comment_opener_inside_a_heredoc_does_not_hide_a_connector(tmp_path, capsys):
  564. root = build(tmp_path, aws=TWO)
  565. add(root, f"{AWS_STACK}/x.tf", OPEN_C + CONNECTOR.format(i=9) + CLOSE_C)
  566. fails(root, capsys, f"{AWS_STACK}: 3 twingate-connector")
  567. def test_a_lone_brace_in_a_heredoc_does_not_end_a_connector_block(tmp_path, capsys):
  568. root = build(tmp_path, aws=TWO)
  569. add(
  570. root,
  571. f"{AWS_STACK}/m.tf",
  572. 'module "c" {\n source = "../../../modules/aws/twingate-connector"\n'
  573. " instance_type = local.c.type\n user_data = <<EOT\n}\nEOT\n count = 3\n}\n"
  574. + CONNECTOR.format(i=7),
  575. )
  576. fails(root, capsys, "uses count")
  577. def test_a_resource_or_module_keyword_inside_a_heredoc_is_text(tmp_path, capsys):
  578. root = build(tmp_path, aws=TWO)
  579. add(
  580. root,
  581. f"{AWS_STACK}/x.tf",
  582. "locals {\n doc = <<EOT\n"
  583. + NAT
  584. + 'module "m" {\n source = "git::x"\n}\nEOT\n}\n',
  585. )
  586. assert run(root, capsys)[0] == 0
  587. def test_an_unterminated_heredoc_fails_closed(tmp_path, capsys):
  588. root = build(tmp_path, aws=TWO)
  589. add(root, f"{AWS_STACK}/x.tf", "locals {\n a = <<EOT\nnever closed\n")
  590. fails(root, capsys, "unterminated heredoc", f"{AWS_STACK}/x.tf")
  591. # 5. top-level attributes only -------------------------------------------------
  592. def test_a_nested_source_does_not_stand_in_for_the_real_one(tmp_path, capsys):
  593. root = build(tmp_path, aws=TWO)
  594. add(
  595. root,
  596. f"{AWS_STACK}/x.tf",
  597. 'module "r" {\n tags = { source = "./fake" }\n'
  598. ' source = "git::https://example.invalid/x.git"\n}\n',
  599. )
  600. fails(root, capsys, "non-local source")
  601. def test_a_nested_source_alone_is_not_a_source(tmp_path, capsys):
  602. root = build(tmp_path, aws=TWO)
  603. add(
  604. root,
  605. f"{AWS_STACK}/x.tf",
  606. 'module "r" {\n tags = {\n source = "./fake"\n }\n}\n',
  607. )
  608. fails(root, capsys, "non-local source")
  609. def test_a_nested_count_on_a_connector_is_not_a_top_level_count(tmp_path, capsys):
  610. root = build(tmp_path, aws=TWO)
  611. (root / f"{AWS_STACK}/m.tf").write_text(
  612. 'module "c0" {\n source = "../../../modules/aws/twingate-connector"\n'
  613. " instance_type = local.c.type\n tags = { count = 1 }\n}\n"
  614. + CONNECTOR.format(i=1)
  615. )
  616. assert run(root, capsys)[0] == 0
  617. def test_duplicate_top_level_sources_fail(tmp_path, capsys):
  618. root = build(tmp_path, aws=TWO)
  619. add(
  620. root,
  621. f"{AWS_STACK}/x.tf",
  622. 'module "r" {\n source = "./a"\n source = "git::x"\n}\n',
  623. )
  624. fails(root, capsys, "more than one source")
  625. # 6. the machine size must come from the manifest -----------------------------
  626. @pytest.mark.parametrize(
  627. "line",
  628. [
  629. 'size = "s-32vcpu-192gb"',
  630. "size = var.size",
  631. "size = local.connector_a.size == null ? local.x.size : local.y.size",
  632. "size = local.connector_a.cost.size",
  633. "size = local.connector_a.size_big",
  634. 'size = "${local.connector_a.size}"',
  635. ],
  636. )
  637. def test_a_do_connector_size_must_be_a_manifest_reference(tmp_path, capsys, line):
  638. root = build(tmp_path, aws=TWO)
  639. (root / "stacks/10-access/m.tf").write_text(
  640. f'module "c0" {{\n source = "../../modules/twingate-connector"\n {line}\n}}\n'
  641. )
  642. fails(root, capsys, "stacks/10-access/m.tf:1", "docs/cost.md")
  643. def test_a_connector_with_no_size_at_all_fails(tmp_path, capsys):
  644. root = build(tmp_path, aws=TWO)
  645. (root / "stacks/10-access/m.tf").write_text(
  646. 'module "c0" {\n source = "../../modules/twingate-connector"\n}\n'
  647. )
  648. fails(root, capsys, "docs/cost.md")
  649. def test_an_aws_connector_literal_instance_type_fails(tmp_path, capsys):
  650. root = build(tmp_path, aws=TWO)
  651. (root / f"{AWS_STACK}/m.tf").write_text(
  652. 'module "c0" {\n source = "../../../modules/aws/twingate-connector"\n'
  653. ' instance_type = "m7g.16xlarge"\n}\n' + CONNECTOR.format(i=1)
  654. )
  655. fails(root, capsys, "docs/cost.md")
  656. def test_a_size_in_a_nested_object_does_not_satisfy_the_rule(tmp_path, capsys):
  657. root = build(tmp_path, aws=TWO)
  658. (root / "stacks/10-access/m.tf").write_text(
  659. 'module "c0" {\n source = "../../modules/twingate-connector"\n'
  660. " other = { size = local.c.size }\n}\n"
  661. )
  662. fails(root, capsys, "docs/cost.md")
  663. def test_the_repo_connectors_pass_the_size_rule():
  664. root = Path(__file__).resolve().parents[1]
  665. problems, _ = cost_check.module_problems(root)
  666. assert problems == []
  667. # 7. unknown provider prefixes ------------------------------------------------
  668. @pytest.mark.parametrize(
  669. "rtype",
  670. [
  671. "linode_instance",
  672. "hcloud_server",
  673. "vultr_instance",
  674. "oci_core_instance",
  675. "kubernetes_namespace",
  676. "scaleway_instance_server",
  677. "foo",
  678. ],
  679. )
  680. def test_an_unknown_provider_prefix_fails(tmp_path, capsys, rtype):
  681. root = build(tmp_path, aws=TWO)
  682. add(root, f"{AWS_STACK}/x.tf", f'resource "{rtype}" "x" {{}}\n')
  683. fails(root, capsys, rtype, "is not known to the gate", f"{AWS_STACK}/x.tf")
  684. @pytest.mark.parametrize(
  685. "rtype",
  686. [
  687. "twingate_group",
  688. "terraform_data",
  689. "null_resource",
  690. "random_id",
  691. "time_sleep",
  692. "tls_private_key",
  693. "local_file",
  694. ],
  695. )
  696. def test_safe_non_cloud_prefixes_pass(tmp_path, capsys, rtype):
  697. root = build(tmp_path, aws=TWO)
  698. add(root, f"{AWS_STACK}/x.tf", f'resource "{rtype}" "x" {{}}\n')
  699. assert run(root, capsys)[0] == 0
  700. def test_the_repository_itself_uses_only_known_prefixes():
  701. root = Path(__file__).resolve().parents[1]
  702. approved = json.loads((root / "docs/stages/approved.json").read_text())
  703. found = cost_check.uncosted_sources(
  704. root, cost_check.allowed_sources(approved), set(approved["providers"])
  705. )
  706. assert found == []
  707. # 8. count / for_each on a costed resource ------------------------------------
  708. @pytest.mark.parametrize(
  709. "rel,rtype,meta",
  710. [
  711. ("modules/aws/twingate-connector/main.tf", "aws_instance", "count = 50"),
  712. ("modules/aws/twingate-connector/main.tf", "aws_instance", "for_each = var.x"),
  713. ("modules/twingate-connector/main.tf", "digitalocean_droplet", "count = 9"),
  714. ("modules/twingate-connector/main.tf", "digitalocean_droplet", "for_each = {}"),
  715. ],
  716. )
  717. def test_a_costed_resource_with_count_or_for_each_fails(
  718. tmp_path, capsys, rel, rtype, meta
  719. ):
  720. root = build(tmp_path, aws=TWO)
  721. add(root, rel, f'resource "{rtype}" "a" {{\n ami = "x"\n {meta}\n}}\n')
  722. fails(root, capsys, f"{rel}:1", "without a plan")
  723. def test_costed_resource_in_a_bare_labelled_block_with_count_fails(tmp_path, capsys):
  724. root = build(tmp_path, aws=TWO)
  725. add(
  726. root,
  727. "modules/aws/twingate-connector/main.tf",
  728. "resource aws_instance a {\n count = 50\n}\n",
  729. )
  730. fails(root, capsys, "without a plan")
  731. def test_nested_count_or_a_free_resource_with_count_is_fine(tmp_path, capsys):
  732. root = build(tmp_path, aws=TWO)
  733. add(
  734. root,
  735. "modules/aws/twingate-connector/main.tf",
  736. 'resource "aws_instance" "a" {\n tags = { count = 5 }\n}\n',
  737. )
  738. add(root, f"{AWS_STACK}/x.tf", 'resource "aws_subnet" "s" {\n count = 3\n}\n')
  739. assert run(root, capsys)[0] == 0
  740. def test_count_behind_a_heredoc_brace_in_a_costed_resource_fails(tmp_path, capsys):
  741. root = build(tmp_path, aws=TWO)
  742. add(
  743. root,
  744. "modules/aws/twingate-connector/main.tf",
  745. 'resource "aws_instance" "a" {\n user_data = <<EOT\n}\nEOT\n count = 50\n}\n',
  746. )
  747. fails(root, capsys, "without a plan")
  748. # 9. plan: attributes the gate does not price ---------------------------------
  749. @pytest.mark.parametrize(
  750. "extra",
  751. [
  752. {"tenancy": "dedicated"},
  753. {"tenancy": "host"},
  754. {"credit_specification": [{"cpu_credits": "unlimited"}]},
  755. {"instance_market_options": [{"market_type": "spot"}]},
  756. {"placement_group": "pg-1"},
  757. {"host_id": "h-123"},
  758. {"monitoring": True},
  759. {"network_interface": [{"device_index": 0}]},
  760. {"launch_template": [{"id": "lt-1"}]},
  761. {"license_specification": [{"license_configuration_arn": "arn:x"}]},
  762. {"host_resource_group_arn": "arn:x"},
  763. ],
  764. )
  765. def test_an_unpriced_instance_attribute_is_a_problem(extra):
  766. problems = cost_check.plan_cost(plan(inst("a", **extra)), AWS_PRICES)[1]
  767. assert any("unpriced attribute" in p for p in problems), problems
  768. @pytest.mark.parametrize(
  769. "extra",
  770. [
  771. {"tenancy": "default"},
  772. {"tenancy": None},
  773. {"credit_specification": [{"cpu_credits": "standard"}]},
  774. {"instance_market_options": []},
  775. {"placement_group": ""},
  776. {"monitoring": False},
  777. ],
  778. )
  779. def test_priced_shapes_of_those_attributes_pass(extra):
  780. problems = cost_check.plan_cost(plan(inst("a", **extra)), AWS_PRICES)[1]
  781. assert problems == []
  782. def test_main_fails_a_plan_with_a_dedicated_instance(tmp_path, capsys):
  783. root = build(tmp_path, aws=TWO)
  784. p = tmp_path / "plan.json"
  785. p.write_text(json.dumps(plan(inst("a", tenancy="dedicated"), inst("b"))))
  786. code, out = run(root, capsys, "--plan", str(p), "--stack", AWS_STACK)
  787. assert code == 1 and "unpriced attribute" in out.err
  788. # ---- second review round -----------------------------------------------------
  789. def test_a_utf8_bom_does_not_hide_the_first_block(tmp_path, capsys):
  790. root = build(tmp_path, aws=TWO)
  791. (root / f"{AWS_STACK}/bom.tf").write_bytes(b"\xef\xbb\xbf" + NAT.encode())
  792. fails(root, capsys, "aws_nat_gateway")
  793. def test_a_bom_before_a_module_is_read(tmp_path, capsys):
  794. root = build(tmp_path, aws=TWO)
  795. (root / f"{AWS_STACK}/bom.tf").write_bytes(
  796. b'\xef\xbb\xbfmodule "r" {\n source = "git::x"\n}\n'
  797. )
  798. fails(root, capsys, "non-local source")
  799. def test_crlf_files_are_read(tmp_path, capsys):
  800. root = build(tmp_path, aws=TWO)
  801. text = (
  802. (
  803. 'module "c" {\r\n source = "../../../modules/aws/twingate-connector"\r\n'
  804. " instance_type = local.c.type\r\n count = 4\r\n}\r\n" + NAT
  805. )
  806. .replace("\n", "\r\n")
  807. .replace("\r\r", "\r")
  808. )
  809. (root / f"{AWS_STACK}/crlf.tf").write_bytes(text.encode())
  810. fails(root, capsys, "uses count", "aws_nat_gateway")
  811. def test_a_crlf_connector_size_reference_passes(tmp_path, capsys):
  812. root = build(tmp_path, aws=TWO)
  813. (root / f"{AWS_STACK}/m.tf").write_bytes(
  814. b'module "c0" {\r\n source = "../../../modules/aws/twingate-connector"\r\n'
  815. b" instance_type = local.c.type\r\n}\r\n" + CONNECTOR.format(i=1).encode()
  816. )
  817. assert run(root, capsys)[0] == 0
  818. def test_a_root_level_directory_symlink_is_refused(tmp_path, capsys):
  819. root = build(tmp_path, aws=TWO)
  820. outside = tmp_path.parent / (tmp_path.name + "-ext")
  821. (outside / "twingate-connector").mkdir(parents=True)
  822. (outside / "twingate-connector/main.tf").write_text(
  823. 'resource "digitalocean_kubernetes_cluster" "x" {}\n'
  824. )
  825. (root / "vendor").symlink_to(outside)
  826. add(
  827. root,
  828. f"{AWS_STACK}/x.tf",
  829. 'module "v" {\n source = "../../../vendor/twingate-connector"\n size = local.c.size\n}\n',
  830. )
  831. fails(root, capsys, "vendor: symlinked directory is refused")
  832. def test_a_symlinked_module_target_escaping_the_root_is_refused(tmp_path, capsys):
  833. root = build(tmp_path, aws=TWO)
  834. outside = tmp_path.parent / (tmp_path.name + "-ext2")
  835. outside.mkdir()
  836. link = root / "stacks/10-access/ln"
  837. link.symlink_to(outside)
  838. add(
  839. root,
  840. f"{AWS_STACK}/x.tf",
  841. 'module "v" {\n source = "../../../stacks/10-access/ln"\n}\n',
  842. )
  843. fails(root, capsys, "outside the repository")
  844. def test_a_symlinked_tf_file_is_refused(tmp_path, capsys):
  845. root = build(tmp_path, aws=TWO)
  846. target = tmp_path.parent / (tmp_path.name + "-f.tf")
  847. target.write_text(NAT)
  848. (root / f"{AWS_STACK}/link.tf").symlink_to(target)
  849. fails(root, capsys, "symlink")
  850. @pytest.mark.parametrize(
  851. "text",
  852. [
  853. 'locals {\n x = "${1 /* } " <<FAKE */ + 2}"\n}\n',
  854. 'locals {\n x = "${(1 # } " <<FAKE\n + 2)}"\n}\n',
  855. 'locals {\n x = "${(1 // } " <<FAKE\n + 2)}"\n}\n',
  856. ],
  857. )
  858. def test_comments_inside_interpolation_are_comments(tmp_path, capsys, text):
  859. root = build(tmp_path, aws=TWO)
  860. add(root, f"{AWS_STACK}/x.tf", text)
  861. assert run(root, capsys)[0] == 0
  862. def test_a_connector_in_an_ordinary_module_directory_is_not_a_stack(tmp_path, capsys):
  863. root = build(tmp_path, aws=TWO)
  864. add(
  865. root,
  866. "modules/wrapper/main.tf",
  867. 'locals {\n c = { size = "s-1vcpu-1gb" }\n}\n\n'
  868. 'module "inner" {\n source = "../twingate-connector"\n size = local.c.size\n}\n',
  869. )
  870. assert run(root, capsys)[0] == 0
  871. def test_a_connector_in_a_module_directory_still_has_its_source_and_size_checked(
  872. tmp_path, capsys
  873. ):
  874. root = build(tmp_path, aws=TWO)
  875. add(
  876. root,
  877. "modules/wrapper/main.tf",
  878. 'module "inner" {\n source = "../twingate-connector"\n size = "s-32vcpu-192gb"\n}\n',
  879. )
  880. fails(root, capsys, "docs/cost.md")
  881. # ---- third review round -------------------------------------------------------
  882. @pytest.mark.parametrize("target", ["outside", ".claude/payload"])
  883. def test_any_root_level_directory_symlink_is_refused(tmp_path, capsys, target):
  884. root = build(tmp_path, aws=TWO)
  885. if target == "outside":
  886. dest = tmp_path.parent / (tmp_path.name + "-shared")
  887. else:
  888. dest = root / target
  889. (dest / "twingate-connector").mkdir(parents=True)
  890. (dest / "twingate-connector/main.tf").write_text(NAT)
  891. (root / "shared").symlink_to(dest)
  892. add(
  893. root,
  894. f"{AWS_STACK}/x.tf",
  895. 'module "v" {\n source = "../../../shared/twingate-connector"\n size = local.c.size\n}\n',
  896. )
  897. fails(root, capsys, "shared: symlinked directory is refused")
  898. def test_a_symlink_nested_deep_in_the_tree_is_refused(tmp_path, capsys):
  899. root = build(tmp_path, aws=TWO)
  900. (root / "docs/deep").mkdir()
  901. (root / "docs/deep/ln").symlink_to(root / "modules")
  902. fails(root, capsys, "docs/deep/ln: symlinked directory is refused")
  903. # ordinary object attributes named like block keywords
  904. @pytest.mark.parametrize(
  905. "text",
  906. [
  907. "locals {\n module = { enabled = true }\n}\n",
  908. "locals {\n resource = { enabled = true }\n}\n",
  909. "locals {\n cfg = {\n module = {\n a = 1\n }\n resource = {\n b = 2\n }\n data = {}\n }\n}\n",
  910. 'variable "x" {\n default = {\n module = { on = true }\n resource = { on = false }\n }\n}\n',
  911. "locals {\n module = {\n on = true\n }\n}\n",
  912. ],
  913. )
  914. def test_object_attributes_named_module_or_resource_are_not_blocks(
  915. tmp_path, capsys, text
  916. ):
  917. root = build(tmp_path, aws=TWO)
  918. add(root, f"{AWS_STACK}/x.tf", text)
  919. code, out = run(root, capsys)
  920. assert code == 0, out.err
  921. @pytest.mark.parametrize(
  922. "text",
  923. [
  924. "resource = aws_nat_gateway n {}\n",
  925. "resource aws_nat_gateway = {}\n",
  926. "module r = {\n}\n",
  927. ],
  928. )
  929. def test_a_label_cannot_contain_an_equals_sign(text):
  930. assert cost_check.find_blocks(text) == []
  931. # unknown plan values
  932. def with_config(pl, expressions):
  933. """Attach a `configuration` block shaped like `tofu show -json`: a resource's
  934. config lists only the attributes the configuration sets."""
  935. pl["configuration"] = {
  936. "root_module": {
  937. "resources": [
  938. {
  939. "address": address,
  940. "mode": "managed",
  941. "type": "aws_instance",
  942. "name": address.split(".")[-1],
  943. "expressions": exprs,
  944. }
  945. for address, exprs in expressions.items()
  946. ]
  947. }
  948. }
  949. return pl
  950. def inst_unknown(unknown, **after_extra):
  951. change_ = inst("a", **after_extra)
  952. change_["change"]["after_unknown"] = unknown
  953. return change_
  954. UNKNOWN_CASES = [
  955. ("monitoring", {"monitoring": True}, {"monitoring": None}),
  956. ("tenancy", {"tenancy": True}, {}),
  957. (
  958. "credit_specification",
  959. {"credit_specification": [{"cpu_credits": True}]},
  960. {"credit_specification": [{"cpu_credits": "standard"}]},
  961. ),
  962. ("instance_market_options", {"instance_market_options": True}, {}),
  963. ("placement_group", {"placement_group": True}, {}),
  964. ("host_id", {"host_id": True}, {}),
  965. ("host_resource_group_arn", {"host_resource_group_arn": True}, {}),
  966. ("license_specification", {"license_specification": True}, {}),
  967. ("network_interface", {"network_interface": True}, {}),
  968. ("launch_template", {"launch_template": [{"id": True}]}, {}),
  969. ]
  970. @pytest.mark.parametrize("attr,unknown,after", UNKNOWN_CASES)
  971. def test_an_unknown_value_the_config_sets_is_a_problem(attr, unknown, after):
  972. pl = plan(inst_unknown(unknown, **after))
  973. with_config(
  974. pl, {"aws_instance.a": {attr: {"references": ["terraform_data.x.output"]}}}
  975. )
  976. problems = cost_check.plan_cost(pl, AWS_PRICES)[1]
  977. assert any("unpriced attribute" in p and attr in p for p in problems), problems
  978. @pytest.mark.parametrize("attr,unknown,after", UNKNOWN_CASES)
  979. def test_an_unknown_computed_default_the_config_does_not_set_passes(
  980. attr, unknown, after
  981. ):
  982. pl = plan(inst_unknown(unknown, **after))
  983. with_config(
  984. pl, {"aws_instance.a": {"instance_type": {"constant_value": "t4g.micro"}}}
  985. )
  986. assert cost_check.plan_cost(pl, AWS_PRICES)[1] == []
  987. @pytest.mark.parametrize("attr,unknown,after", UNKNOWN_CASES)
  988. def test_an_unknown_value_with_no_configuration_fails_closed(attr, unknown, after):
  989. pl = plan(inst_unknown(unknown, **after))
  990. problems = cost_check.plan_cost(pl, AWS_PRICES)[1]
  991. assert any("unpriced attribute" in p and attr in p for p in problems), problems
  992. def module_plan(expressions):
  993. change_ = inst_unknown({"tenancy": True})
  994. change_["address"] = "module.m.aws_instance.a[0]"
  995. change_["module_address"] = "module.m"
  996. pl = plan(change_)
  997. pl["configuration"] = {
  998. "root_module": {
  999. "module_calls": {
  1000. "m": {
  1001. "module": {
  1002. "resources": [
  1003. {
  1004. "mode": "managed",
  1005. "type": "aws_instance",
  1006. "name": "a",
  1007. "expressions": expressions,
  1008. }
  1009. ]
  1010. }
  1011. }
  1012. }
  1013. }
  1014. }
  1015. return pl
  1016. def test_an_unknown_value_in_a_module_instance_is_found_through_module_calls():
  1017. pl = module_plan({"tenancy": {"references": ["var.t"]}})
  1018. problems = cost_check.plan_cost(pl, AWS_PRICES)[1]
  1019. assert any("unpriced attribute" in p and "tenancy" in p for p in problems)
  1020. def test_a_module_instance_whose_config_does_not_set_it_passes():
  1021. assert cost_check.plan_cost(module_plan({}), AWS_PRICES)[1] == []
  1022. @pytest.mark.parametrize("itype", ["t3.micro", "t4g.micro", "t3a.small", "t2.micro"])
  1023. def test_a_burstable_instance_without_standard_credits_fails_closed(itype):
  1024. prices = dict(AWS_PRICES)
  1025. prices["instances"] = {**AWS_PRICES["instances"], itype: 0.01}
  1026. for spec in (None, [], [{"cpu_credits": ""}]):
  1027. _, problems = cost_check.plan_cost(
  1028. plan(inst(itype=itype, credit_specification=spec)), prices
  1029. )
  1030. assert problems and "credit_specification" in problems[0], (itype, spec)
  1031. def test_a_burstable_instance_with_standard_credits_is_priced():
  1032. total, problems = cost_check.plan_cost(plan(inst("a"), inst("b")), AWS_PRICES)
  1033. assert (total, problems) == (20.84, [])
  1034. def test_a_non_burstable_type_does_not_need_credit_specification():
  1035. prices = dict(AWS_PRICES)
  1036. prices["instances"] = {**AWS_PRICES["instances"], "m7g.large": 0.0816}
  1037. _, problems = cost_check.plan_cost(
  1038. plan(inst(itype="m7g.large", credit_specification=None)), prices
  1039. )
  1040. assert problems == []