cost_check.py 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386
  1. #!/usr/bin/env python3
  2. """Monthly cost gate for Clouds Against Humanity.
  3. Totals every stack's cost.json manifest, per cloud provider, against that
  4. provider's price table and docs/stages/approved.json. It fails when:
  5. - a stack directory has no cost.json (stacks/**/ , found recursively);
  6. - a provider's total is above its approved figure, or the approved figures of
  7. the active providers together are above the current phase's ceiling
  8. (approved.json `phases` and `current_phase`; see docs/cost.md);
  9. - the per-phase ceilings are malformed, one is lower than the phase before it
  10. without an explicit `lowers`, or one is above `hard_max`;
  11. - a size or instance type has no price, or backups are priced from an
  12. unverified fraction;
  13. - a resource type from a provider (digitalocean_, aws_, azurerm_, google_) is
  14. not on that provider's free list or allowed file, or a rejected type such as
  15. a NAT gateway appears;
  16. - the number of twingate-connector module blocks in a stack differs from the
  17. machines in that stack's manifest (or a block uses count/for_each);
  18. - a connector module's size is not a plain `local.<name>.size` reference (its
  19. instance_type likewise), a costed resource uses count or for_each, a resource
  20. type's provider prefix is neither a known cloud nor in SAFE_PREFIXES, or a
  21. label holds a backslash;
  22. - a module source is not local or goes through a dot-directory, a stack
  23. directory is misnamed, a dot-directory exists under stacks/ or modules/, or a
  24. *.tf.json / *.tofu.json file exists (*.tf and *.tofu are both read);
  25. - a stack instance manifest (stacks/sites/<resource_key>/<stack>/cost.json with
  26. instance_of) is malformed, names no stack with its own manifest, carries code,
  27. does not match the connector modules of the stack it names, or shares a stack
  28. id with another manifest; or a provider's optional `sites` map does not fit
  29. (see docs/cost.md, "Stack instances");
  30. - with --plan, the cost of the planned values in an OpenTofu plan (JSON) differs
  31. from the manifest, or the plan holds a type the gate cannot price.
  32. HCL is scanned (comments, strings and heredocs understood) and never executed,
  33. so the source scan is a guardrail, not a proof; the plan check below is the
  34. guarantee. The plan check is the stronger one for attributes
  35. (a public address, a disk size, count/for_each) that source cannot show, and it
  36. is only as trustworthy as where the plan came from: a plan produced by the
  37. trusted run, not a file anyone can edit in a pull request.
  38. """
  39. from __future__ import annotations
  40. import argparse
  41. import datetime
  42. import json
  43. import math
  44. import os
  45. import posixpath
  46. import re
  47. import sys
  48. from decimal import Decimal
  49. from pathlib import Path
  50. HOURS_PER_MONTH = 730
  51. # Provider by resource-type prefix, and by stack path (stacks/<provider>/...).
  52. # A stack outside a provider directory is DigitalOcean's, as it always was.
  53. PROVIDER_PREFIXES = {
  54. "digitalocean_": "digitalocean",
  55. "aws_": "aws",
  56. "azurerm_": "azure",
  57. "google_": "gcp",
  58. }
  59. STACK_PROVIDER_DIRS = frozenset({"aws", "azure", "gcp"})
  60. # Resource types that cost nothing, per provider. Every other type with that
  61. # provider's prefix fails the gate unless approved.json allows it in a file, so
  62. # a new paid type cannot slip in unnoticed.
  63. FREE_TYPES = {
  64. "digitalocean": frozenset(
  65. {
  66. "digitalocean_project",
  67. "digitalocean_project_resources",
  68. "digitalocean_tag",
  69. "digitalocean_vpc",
  70. "digitalocean_firewall",
  71. "digitalocean_ssh_key",
  72. # No charge of its own; the reserved IP it assigns is the priced
  73. # type, and reserved_ip_problems() pairs the two.
  74. "digitalocean_reserved_ip_assignment",
  75. # An access key is free; the bucket it reaches is the priced type.
  76. "digitalocean_spaces_key",
  77. }
  78. ),
  79. "aws": frozenset(
  80. {
  81. "aws_vpc",
  82. "aws_subnet",
  83. "aws_internet_gateway",
  84. "aws_route_table",
  85. "aws_route",
  86. "aws_route_table_association",
  87. "aws_security_group",
  88. "aws_default_security_group",
  89. "aws_vpc_security_group_ingress_rule",
  90. "aws_vpc_security_group_egress_rule",
  91. "aws_key_pair",
  92. }
  93. ),
  94. "azure": frozenset(),
  95. "gcp": frozenset(),
  96. }
  97. # Costed types: allowed only in the files named in approved.json.
  98. COSTED_TYPES = {
  99. # A reserved IP is free only while assigned ($5.00 a month when not, design
  100. # section 5.1), so it is allowed in the files approved.json names, each paired
  101. # with one assignment. The manifest has no `reserved_ip` kind yet, so a
  102. # stack cannot cost one: that is the cost-gate follow-up.
  103. # A Spaces bucket is a flat monthly subscription (docs/cost-prices.json
  104. # "spaces"), priced from a `spaces` manifest entry; its module is reconciled
  105. # against the stack's manifest by spaces_module_problems().
  106. "digitalocean": frozenset(
  107. {
  108. "digitalocean_droplet",
  109. "digitalocean_reserved_ip",
  110. "digitalocean_spaces_bucket",
  111. }
  112. ),
  113. "aws": frozenset({"aws_instance", "aws_eip", "aws_ebs_volume"}),
  114. "azure": frozenset(),
  115. "gcp": frozenset(),
  116. }
  117. # Never allowed at the current ceiling, whatever approved.json says.
  118. REJECTED_TYPES = {
  119. "aws_nat_gateway": "a NAT gateway costs about $36.50 a month before any traffic; "
  120. "give the machines public addresses and no inbound rule instead",
  121. }
  122. MACHINE_KINDS = frozenset({"droplet", "instance"})
  123. # Skipped at the repository top level only: tool state and agent worktrees.
  124. TOP_SKIP_DIRS = frozenset({".git", ".venv", ".claude"})
  125. # Directories whose contents the gate must be able to read in full.
  126. GUARDED_TOP = frozenset({"stacks", "modules"})
  127. HCL_SUFFIXES = (".tf", ".tofu")
  128. # Learner labs (option L1 of the composable-labs design, approved 2026-10-22).
  129. # Files under this one top-level directory are still parsed for syntax, but
  130. # the resource-type allowlist, the count/for_each rule and the module-source
  131. # rules do not apply to them. It is not an approval and Spacelift never
  132. # applies anything here (see lab_file and docs/cost.md).
  133. LABS_DIR = "labs"
  134. JSON_SUFFIXES = (".tf.json", ".tofu.json")
  135. SITES_DIR = "stacks/sites"
  136. RESOURCE_KEY_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
  137. STACK_NAME_RE = re.compile(r"^[0-9]+-[A-Za-z0-9][A-Za-z0-9_-]*$")
  138. CONNECTOR_SOURCE_SUFFIX = "twingate-connector"
  139. EDGE_SOURCE_SUFFIX = "edge-host"
  140. SPACES_SOURCE_SUFFIX = "spaces-bucket"
  141. SPACES_MODULE_DIR = "modules/spaces-bucket"
  142. DOCKER_SOURCE_SUFFIX = "docker-host"
  143. DOCKER_MODULE_DIR = "modules/docker-host"
  144. # The manifest entry the workload droplet is priced from (kind droplet, this name).
  145. DOCKER_ENTRY_NAME = "workload"
  146. # The only count an edge-host module call may carry: the stack's own switch.
  147. EDGE_COUNT_RE = re.compile(r"local\.on")
  148. RESERVED_IP = "digitalocean_reserved_ip"
  149. RESERVED_IP_ASSIGNMENT = "digitalocean_reserved_ip_assignment"
  150. # The only shapes the scanner accepts for an assignment: a plain reference to a
  151. # reserved IP and to a droplet, both resources of the same file.
  152. RESERVED_IP_REF_RE = re.compile(
  153. r"digitalocean_reserved_ip\.(?P<name>[A-Za-z_][A-Za-z0-9_-]*)\.ip_address"
  154. )
  155. DROPLET_ID_REF_RE = re.compile(
  156. r"digitalocean_droplet\.[A-Za-z_][A-Za-z0-9_-]*\.id"
  157. )
  158. # Connector size attribute -> the manifest key its local must read.
  159. CONNECTOR_SIZE_ATTRS = {"size": "size", "instance_type": "type"}
  160. # Providers that create nothing billable. Any other prefix that is not a known
  161. # cloud fails the gate until it is added here deliberately.
  162. SAFE_PREFIXES = (
  163. "twingate_",
  164. "terraform_",
  165. "null_",
  166. "random_",
  167. "time_",
  168. "tls_",
  169. "local_",
  170. )
  171. # aws_instance plan attributes that change the bill and that the gate does not
  172. # model. Setting any of them to a non-empty value is a problem, not a zero;
  173. # tenancy and credit_specification have their own rule in unpriced_instance_attrs.
  174. # A value unknown in the plan is refused when the configuration sets the attribute
  175. # (see unknown_unpriced_attrs); an unset computed default is not.
  176. AWS_INSTANCE_UNPRICED_ATTRS = (
  177. "instance_market_options",
  178. "placement_group",
  179. "host_id",
  180. "host_resource_group_arn",
  181. "license_specification",
  182. "network_interface",
  183. "launch_template",
  184. "monitoring",
  185. )
  186. # Every attribute the unknown-value rule looks at.
  187. AWS_INSTANCE_CHECKED_ATTRS = AWS_INSTANCE_UNPRICED_ATTRS + (
  188. "tenancy",
  189. "credit_specification",
  190. )
  191. def _no_duplicate_keys(pairs):
  192. """Python keeps the last of a repeated key, so the value enforced would
  193. differ from the one a reviewer reads first. Refuse the file instead."""
  194. seen = set()
  195. for key, _ in pairs:
  196. if key in seen:
  197. raise ValueError(f"duplicate key {key!r} in a JSON object")
  198. seen.add(key)
  199. return dict(pairs)
  200. def _no_constant(name):
  201. raise ValueError(f"{name} is not a JSON number")
  202. def parse_json(text):
  203. """json.loads that rejects duplicate keys and NaN/Infinity literals."""
  204. return json.loads(
  205. text, object_pairs_hook=_no_duplicate_keys, parse_constant=_no_constant
  206. )
  207. def load_json(path):
  208. try:
  209. return parse_json(Path(path).read_text())
  210. except ValueError as err:
  211. raise ValueError(f"{path}: {err}") from None
  212. def num(value, label):
  213. """A finite, non-negative number, or ValueError. NaN would make every
  214. comparison false and silently disable a limit, so it is refused here."""
  215. try:
  216. out = float(value)
  217. except (TypeError, ValueError, OverflowError):
  218. raise ValueError(f"{label}: {value!r} is not a number") from None
  219. if not math.isfinite(out) or out < 0:
  220. raise ValueError(f"{label}: {value!r} must be a finite number, zero or more")
  221. return out
  222. def provider_of_type(rtype):
  223. for prefix, provider in PROVIDER_PREFIXES.items():
  224. if rtype.startswith(prefix):
  225. return provider
  226. return None
  227. def provider_of_stack(rel):
  228. parts = Path(rel).parts
  229. if len(parts) >= 2 and parts[0] == "stacks" and parts[1] in STACK_PROVIDER_DIRS:
  230. return parts[1]
  231. return "digitalocean"
  232. def price_table_path(root, provider):
  233. if provider == "digitalocean":
  234. return Path(root, "docs/cost-prices.json")
  235. return Path(root, f"docs/cost-prices/{provider}.json")
  236. def load_prices(root, provider):
  237. path = price_table_path(root, provider)
  238. if not path.exists():
  239. raise ValueError(
  240. f"no price table for provider {provider!r} (expected {path.relative_to(root)})"
  241. )
  242. return load_json(path)
  243. # ---- pricing ----------------------------------------------------------------
  244. def droplet_cost(res, prices):
  245. size = res["size"]
  246. table = prices["droplets"]
  247. if size not in table:
  248. raise ValueError(f"no price for size {size!r} ({res['name']})")
  249. cost = num(table[size], f"price of {size}")
  250. backups = res.get("backups", False)
  251. if type(backups) is not bool:
  252. raise ValueError(
  253. f"{res['name']}: backups must be true or false, not {backups!r}"
  254. )
  255. extras = sorted(k for k in res if k.startswith("backup") and k != "backups")
  256. if not backups:
  257. if extras:
  258. raise ValueError(
  259. f"{res['name']}: {', '.join(extras)} stated while backups is false; "
  260. "the gate refuses a backup setting it cannot reconcile"
  261. )
  262. else:
  263. plan = res.get("backup_plan")
  264. if plan == "daily":
  265. raise ValueError(
  266. f"{res['name']}: daily backups are not priced or verified (the gate "
  267. "prices the basic weekly plan only); refused"
  268. )
  269. if plan != "weekly":
  270. raise ValueError(
  271. f'{res["name"]}: backups need backup_plan "weekly" (the only plan '
  272. f"the gate prices); got {plan!r}. DigitalOcean defaults to daily "
  273. "when no plan is stated, so a missing plan is refused"
  274. )
  275. other = [k for k in extras if k != "backup_plan"]
  276. if other:
  277. raise ValueError(
  278. f"{res['name']}: backup setting(s) {', '.join(other)} are not "
  279. "priced (usage-based and other plans are refused)"
  280. )
  281. if not prices.get("backups_fraction_verified"):
  282. raise ValueError(
  283. "backups requested but the backup price fraction is unverified"
  284. )
  285. cost += cost * num(prices["backups_fraction"], "backups_fraction")
  286. return cost
  287. def spaces_cost(res, prices):
  288. """A Spaces subscription is a flat monthly price read only from the price
  289. table: an entry in a manifest cannot state its own amount."""
  290. entry = prices.get("spaces")
  291. if not isinstance(entry, dict) or "monthly" not in entry:
  292. raise ValueError(
  293. f"no price for spaces ({res.get('name')}); docs/cost-prices.json needs a "
  294. '"spaces" entry with a "monthly" amount'
  295. )
  296. if type(entry["monthly"]) is bool:
  297. raise ValueError("price of spaces: a boolean is not a number")
  298. return num(entry["monthly"], "price of spaces")
  299. def aws_instance_cost(itype, root_gb, public_ip, prices, name="instance"):
  300. table = prices["instances"]
  301. if itype not in table:
  302. raise ValueError(f"no price for instance type {itype!r} ({name})")
  303. cost = num(table[itype], f"price of {itype}") * HOURS_PER_MONTH
  304. if public_ip:
  305. cost += (
  306. num(prices["public_ipv4_hourly"], "public_ipv4_hourly") * HOURS_PER_MONTH
  307. )
  308. cost += num(root_gb, f"root_gb of {name}") * num(
  309. prices["ebs_gp3_gb_month"], "ebs_gp3_gb_month"
  310. )
  311. return cost
  312. def resource_cost(res, prices, provider="digitalocean"):
  313. kind = res.get("kind")
  314. if provider == "digitalocean" and kind == "droplet":
  315. return droplet_cost(res, prices)
  316. if provider == "digitalocean" and kind == "spaces":
  317. return spaces_cost(res, prices)
  318. if provider == "aws":
  319. if kind == "instance":
  320. if "root_gb" not in res or "public_ip" not in res:
  321. raise ValueError(
  322. f"instance {res.get('name')!r} must state root_gb and public_ip; the AMI default and the subnet default are not known to the gate"
  323. )
  324. return aws_instance_cost(
  325. res["type"], res["root_gb"], res["public_ip"], prices, res["name"]
  326. )
  327. if kind == "eip":
  328. return (
  329. num(prices["public_ipv4_hourly"], "public_ipv4_hourly")
  330. * HOURS_PER_MONTH
  331. )
  332. if kind == "ebs_volume":
  333. return num(res["gb"], "gb") * num(
  334. prices["ebs_gp3_gb_month"], "ebs_gp3_gb_month"
  335. )
  336. raise ValueError(
  337. f"no price model for kind {kind!r} ({res.get('name')}) on {provider}"
  338. )
  339. def stack_manifests(root):
  340. """Yield (stack dir relative path, manifest path) for every cost.json under stacks/."""
  341. for rel in walk_repo(root)[0]:
  342. if (
  343. rel.startswith("stacks/")
  344. and rel.endswith("/cost.json")
  345. and not is_hidden(rel)
  346. ):
  347. yield str(Path(rel).parent.as_posix()), Path(root, rel)
  348. def is_instance_dir(rel):
  349. """True for a directory at or under stacks/sites/ (data-only stack instances)."""
  350. return rel == SITES_DIR or rel.startswith(SITES_DIR + "/")
  351. def instance_key(rel):
  352. """The resource_key of stacks/sites/<resource_key>/..., or None."""
  353. parts = Path(rel).parts
  354. return parts[2] if is_instance_dir(rel) and len(parts) >= 3 else None
  355. def declared_instance_of(data):
  356. return data.get("instance_of") if isinstance(data, dict) else None
  357. def instance_of_problem(value):
  358. """Why `instance_of` is not a plain stack path, or None."""
  359. if not isinstance(value, str) or not value:
  360. return "must be a non-empty string such as stacks/10-access"
  361. parts = value.split("/")
  362. if (
  363. value != posixpath.normpath(value)
  364. or parts[0] != "stacks"
  365. or len(parts) < 2
  366. or "" in parts
  367. or any(p in (".", "..") for p in parts)
  368. ):
  369. return f"{value!r} must be a normalized stack path such as stacks/10-access"
  370. if is_instance_dir(value):
  371. return (
  372. f"{value!r} must not point into stacks/sites (an instance is not a stack)"
  373. )
  374. return None
  375. def manifest_provider(rel, data):
  376. """Provider of a manifest. An instance takes it from the stack it names;
  377. an unusable instance_of falls back to the path (structure_problems fails it)."""
  378. if is_instance_dir(rel):
  379. target = declared_instance_of(data)
  380. if instance_of_problem(target) is None:
  381. return provider_of_stack(target)
  382. return provider_of_stack(rel)
  383. def priced_manifests(root):
  384. """Yield (rel, provider, site key or None, manifest data) for every manifest."""
  385. for rel, manifest in stack_manifests(root):
  386. data = load_json(manifest)
  387. yield rel, manifest_provider(rel, data), instance_key(rel), data
  388. def site_totals(root):
  389. """Return {provider: {"": base stacks total, <resource_key>: site total}}."""
  390. totals, cache = {}, {}
  391. for rel, provider, key, data in priced_manifests(root):
  392. if provider not in cache:
  393. cache[provider] = load_prices(root, provider)
  394. bucket = totals.setdefault(provider, {})
  395. bucket.setdefault(key or "", 0.0)
  396. for res in data["resources"]:
  397. bucket[key or ""] = bucket.get(key or "", 0.0) + resource_cost(
  398. res, cache[provider], provider
  399. )
  400. return totals
  401. def provider_totals(root):
  402. """Return {provider: total} summed from the manifests."""
  403. return {p: round(sum(parts.values()), 2) for p, parts in site_totals(root).items()}
  404. def stack_id(rel, instance_of):
  405. """The Spacelift stack id a manifest directory answers to.
  406. stacks/<path> -> cah-<path with / as ->
  407. stacks/sites/<key>/<path> (an instance) -> cah-<path with / as ->-<key>
  408. """
  409. if is_instance_dir(rel):
  410. base = Path(instance_of).parts[1:]
  411. return "cah-" + "-".join(base) + "-" + instance_key(rel)
  412. return "cah-" + "-".join(Path(rel).parts[1:])
  413. def manifest_ids(root):
  414. """{stack id: [manifest directories]} for every manifest with a usable
  415. instance_of (an instance with a bad one maps to no id)."""
  416. ids = {}
  417. for rel, _, _, data in priced_manifests(root):
  418. target = declared_instance_of(data)
  419. if is_instance_dir(rel) and (
  420. instance_key(rel) is None or instance_of_problem(target)
  421. ):
  422. continue
  423. ids.setdefault(stack_id(rel, target), []).append(rel)
  424. return ids
  425. def total_cost(root, prices=None):
  426. """Sum of every provider's manifests. `prices` overrides the DigitalOcean table (tests)."""
  427. if prices is not None:
  428. total = 0.0
  429. for _, provider, _, data in priced_manifests(root):
  430. if provider == "digitalocean":
  431. for res in data["resources"]:
  432. total += resource_cost(res, prices)
  433. return round(total, 2)
  434. return round(sum(provider_totals(root).values()), 2)
  435. # ---- plan JSON --------------------------------------------------------------
  436. def plan_cost(plan, prices):
  437. """Cost the planned values of an AWS plan (tofu show -json). Returns (total, problems).
  438. The plan resolves count, for_each and defaults, which the source cannot.
  439. Anything it cannot price is a problem, never a zero.
  440. """
  441. total, problems = 0.0, []
  442. free = FREE_TYPES["aws"]
  443. for rc in plan.get("resource_changes", []):
  444. rtype, addr = rc.get("type", ""), rc.get("address", "?")
  445. change = rc.get("change", {})
  446. if rc.get("mode") == "data" or change.get("actions") == ["delete"]:
  447. continue
  448. if not rtype.startswith("aws_"):
  449. continue
  450. if rtype in REJECTED_TYPES:
  451. problems.append(f"{addr}: {rtype} is rejected: {REJECTED_TYPES[rtype]}")
  452. continue
  453. after, unknown = change.get("after") or {}, change.get("after_unknown") or {}
  454. if rtype in free:
  455. continue
  456. try:
  457. if rtype == "aws_instance":
  458. total += plan_instance_cost(
  459. addr, after, unknown, prices, config_expressions(plan, rc)
  460. )
  461. elif rtype == "aws_eip":
  462. total += (
  463. num(prices["public_ipv4_hourly"], "public_ipv4_hourly")
  464. * HOURS_PER_MONTH
  465. )
  466. elif rtype == "aws_ebs_volume":
  467. total += plan_volume_gb(addr, after, unknown, "size") * num(
  468. prices["ebs_gp3_gb_month"], "ebs_gp3_gb_month"
  469. )
  470. else:
  471. problems.append(f"{addr}: {rtype} has no price in the gate")
  472. except ValueError as err:
  473. problems.append(str(err))
  474. return round(total, 2), problems
  475. GP3_BASELINE = {"iops": 3000, "throughput": 125}
  476. def check_volume_shape(addr, block, unknown, type_key):
  477. """The price table is gp3 at baseline performance. Anything else costs
  478. more or differently, so it is refused until it is modeled."""
  479. vtype = block.get(type_key)
  480. if unknown.get(type_key) or vtype not in (None, "gp3"):
  481. raise ValueError(f"{addr}: volume type {vtype!r} is not priced (only gp3 is)")
  482. for key, baseline in GP3_BASELINE.items():
  483. value = block.get(key)
  484. if unknown.get(key) or value not in (None, 0, baseline):
  485. raise ValueError(
  486. f"{addr}: provisioned {key} {value!r} is above the gp3 baseline and is not priced"
  487. )
  488. def plan_volume_gb(addr, block, unknown, key):
  489. check_volume_shape(addr, block, unknown, "type" if key == "size" else "volume_type")
  490. if unknown.get(key) or block.get(key) is None:
  491. raise ValueError(
  492. f"{addr}: volume size is not known in the plan; set it explicitly"
  493. )
  494. return num(block[key], f"{addr}: {key}")
  495. def mask_has_unknown(mask):
  496. """True when an after_unknown mask marks anything, at any depth, unknown."""
  497. if isinstance(mask, dict):
  498. return any(mask_has_unknown(v) for v in mask.values())
  499. if isinstance(mask, list):
  500. return any(mask_has_unknown(v) for v in mask)
  501. return mask is True
  502. def config_expressions(plan, rc):
  503. """The configuration's `expressions` for a resource change, or None when the
  504. plan does not carry that configuration (shape unknown, so callers fail closed).
  505. In `tofu show -json`, configuration.root_module.resources[].expressions lists
  506. only the attributes the configuration sets; an unset computed attribute is
  507. absent there while still being unknown in after_unknown. Resources in modules
  508. sit under module_calls.<name>.module.resources.
  509. """
  510. node = (plan.get("configuration") or {}).get("root_module")
  511. address = rc.get("address", "")
  512. module_address = rc.get("module_address")
  513. if module_address is None:
  514. lead = re.match(r"^((?:module\.[^.\[]+(?:\[[^\]]*\])?\.)*)", address)
  515. module_address = lead.group(1)
  516. for name in re.findall(r"module\.([^.\[]+)", module_address or ""):
  517. if not isinstance(node, dict):
  518. return None
  519. node = ((node.get("module_calls") or {}).get(name) or {}).get("module")
  520. if not isinstance(node, dict):
  521. return None
  522. name = rc.get("name") or re.sub(r"\[.*$", "", address.rsplit(".", 1)[-1])
  523. for res in node.get("resources") or []:
  524. if (
  525. res.get("mode", "managed") == "managed"
  526. and res.get("type") == rc.get("type")
  527. and res.get("name") == name
  528. ):
  529. expr = res.get("expressions")
  530. return expr if isinstance(expr, dict) else {}
  531. return None
  532. def unknown_unpriced_attrs(unknown, expressions):
  533. """Attributes the plan cannot value and that the configuration sets (or that
  534. cannot be told apart from set, when the configuration is missing).
  535. Not flagged: an unknown attribute the configuration does not set. That is a
  536. provider default computed at apply (tenancy, placement_group, ...), which a
  537. normal plan shows as unknown. Not caught either way: a default that is itself
  538. priced differently (CPU credits on a T-family type have their own rule in
  539. require_standard_credits).
  540. """
  541. found = []
  542. for attr in AWS_INSTANCE_CHECKED_ATTRS:
  543. if mask_has_unknown(unknown.get(attr)):
  544. if expressions is None:
  545. found.append(
  546. f"{attr} (unknown in the plan and the plan carries no configuration to show it unset)"
  547. )
  548. elif attr in expressions:
  549. found.append(
  550. f"{attr} (set by the configuration but unknown in the plan)"
  551. )
  552. return found
  553. def unpriced_instance_attrs(after):
  554. """Names (with values) of aws_instance attributes the gate does not price."""
  555. found = []
  556. if after.get("tenancy") not in (None, "default"):
  557. found.append(f"tenancy={after['tenancy']!r}")
  558. for spec in after.get("credit_specification") or []:
  559. if str((spec or {}).get("cpu_credits", "")).lower() == "unlimited":
  560. found.append("credit_specification.cpu_credits='unlimited'")
  561. for attr in AWS_INSTANCE_UNPRICED_ATTRS:
  562. if after.get(attr) not in (None, "", False, [], {}):
  563. found.append(f"{attr}={after[attr]!r}")
  564. return found
  565. # Burstable families launch in unlimited CPU-credit mode when nothing is set,
  566. # and surplus credits are billed on top of the hourly price. Fail closed: the
  567. # plan must say "standard" for these, because the omitted default is not priced.
  568. BURSTABLE_FAMILIES = ("t2.", "t3.", "t3a.", "t4g.")
  569. def require_standard_credits(addr, after):
  570. itype = str(after.get("instance_type") or "")
  571. if not itype.startswith(BURSTABLE_FAMILIES):
  572. return
  573. specs = after.get("credit_specification") or []
  574. if not any(
  575. str((spec or {}).get("cpu_credits", "")).lower() == "standard" for spec in specs
  576. ):
  577. raise ValueError(
  578. f"{addr}: {itype} is burstable and credit_specification.cpu_credits is not "
  579. "'standard' in the plan; the omitted default is unlimited, whose surplus "
  580. "credits are not priced"
  581. )
  582. def plan_instance_cost(addr, after, unknown, prices, expressions=None):
  583. extras = unpriced_instance_attrs(after) + unknown_unpriced_attrs(
  584. unknown, expressions
  585. )
  586. if extras:
  587. raise ValueError(
  588. f"{addr}: unpriced attribute {'; '.join(extras)}; the gate prices the "
  589. "instance type, root disk and public address only"
  590. )
  591. if unknown.get("instance_type") or not after.get("instance_type"):
  592. raise ValueError(f"{addr}: instance_type is not known in the plan")
  593. roots = after.get("root_block_device") or []
  594. if not roots:
  595. raise ValueError(
  596. f"{addr}: no root_block_device.volume_size; the AMI default is not priced, set it explicitly"
  597. )
  598. gb = plan_volume_gb(
  599. addr, roots[0], (unknown.get("root_block_device") or [{}])[0], "volume_size"
  600. )
  601. if unknown.get("ebs_block_device"):
  602. raise ValueError(f"{addr}: ebs_block_device is not fully known in the plan")
  603. for extra in after.get("ebs_block_device") or []:
  604. gb += plan_volume_gb(addr, extra, {}, "volume_size")
  605. require_standard_credits(addr, after)
  606. # Only an explicit false avoids the address. Unset or unknown is treated as
  607. # public: the subnet default and the later assignment are not visible here.
  608. public = after.get("associate_public_ip_address") is not False
  609. return aws_instance_cost(after["instance_type"], gb, public, prices, addr)
  610. def plan_problems(plan_path, stack, root):
  611. """Compare the cost of a plan with the same stack's manifest."""
  612. manifest = Path(root, stack, "cost.json")
  613. if not manifest.exists():
  614. return [f"{stack}: no cost.json to reconcile the plan against"]
  615. # An instance (stacks/sites/...) takes its provider from instance_of and is
  616. # compared with its own manifest, not the base stack's.
  617. provider = manifest_provider(stack, load_json(manifest))
  618. if provider != "aws":
  619. return [f"--plan costing is implemented for aws only, not {provider}"]
  620. prices = load_prices(root, "aws")
  621. declared = round(
  622. sum(resource_cost(r, prices, "aws") for r in load_json(manifest)["resources"]),
  623. 2,
  624. )
  625. planned, problems = plan_cost(load_json(plan_path), prices)
  626. if abs(planned - declared) > 0.005:
  627. problems.append(
  628. f"{stack}: the plan costs ${planned:.2f} but cost.json declares ${declared:.2f}; they must match"
  629. )
  630. return problems
  631. # ---- source scan ------------------------------------------------------------
  632. #
  633. # The source scan reads HCL with a small tokenizer-aware scanner. It understands
  634. # comments, quoted strings (with ${...} interpolation) and heredocs, so that a
  635. # `/*`, a brace or the word `resource` inside a string or heredoc is text and
  636. # not code. It is still a guardrail, not a parser: see the module docstring.
  637. class HclError(ValueError):
  638. """The file has a shape this scanner will not guess at (fail closed)."""
  639. HEREDOC_OPEN_RE = re.compile(
  640. r"<<(?P<dash>-?)(?P<ident>[A-Za-z_][A-Za-z0-9_-]*)[ \t]*\r?\n"
  641. )
  642. # A bare label is an identifier: "=", ":" and braces are not label characters, so
  643. # `module = { ... }` inside an object is an attribute, not a block header.
  644. LABEL = r'"(?:[^"\\\n]|\\.)*"|[^\W\d][\w-]*'
  645. LABEL_RE = re.compile(LABEL)
  646. HEADER_RE = re.compile(
  647. rf"^[ \t]*(?P<kind>resource|module)(?P<labels>(?:[ \t]+(?:{LABEL}))*)[ \t]*\{{",
  648. re.MULTILINE,
  649. )
  650. ATTR_RE = re.compile(
  651. r"\s*(?P<name>[A-Za-z_][A-Za-z0-9_-]*)\s*=(?!=)\s*(?P<value>.*?)\s*$", re.DOTALL
  652. )
  653. STRING_LITERAL_RE = re.compile(r'"(?P<text>[^"\\$%\n]*)"')
  654. # `size = local.<name>.size`: nothing else ties a droplet to cost.json.
  655. LOCAL_REF_RE = r"local\.[A-Za-z_][A-Za-z0-9_-]*\.{key}"
  656. def blank(text):
  657. """Spaces for every character but newlines, so line numbers survive."""
  658. return re.sub(r"[^\n]", " ", text)
  659. def skip_interpolation(text, j):
  660. """j is just after `${` or `%{`; return the index after the matching `}`."""
  661. depth, n = 1, len(text)
  662. while j < n:
  663. c = text[j]
  664. if c == '"':
  665. j = skip_string(text, j)
  666. continue
  667. if c == "#" or text.startswith("//", j):
  668. nl = text.find("\n", j)
  669. j = n if nl == -1 else nl
  670. continue
  671. if text.startswith("/*", j):
  672. end = text.find("*/", j + 2)
  673. if end == -1:
  674. raise HclError("unterminated /* comment in an interpolation")
  675. j = end + 2
  676. continue
  677. if c == "{":
  678. depth += 1
  679. elif c == "}":
  680. depth -= 1
  681. if depth == 0:
  682. return j + 1
  683. j += 1
  684. raise HclError("unterminated ${...} interpolation")
  685. def skip_string(text, i):
  686. """i is at an opening quote; return the index after the closing quote.
  687. A raw newline ends nothing: HCL quoted strings are single-line, so one that
  688. runs past the line is refused rather than guessed at.
  689. """
  690. j, n = i + 1, len(text)
  691. while j < n:
  692. c = text[j]
  693. if c == '"':
  694. return j + 1
  695. if c == "\n":
  696. break
  697. if c == "\\":
  698. j += 2
  699. elif text.startswith(("$${", "%%{"), j):
  700. j += 3
  701. elif text.startswith(("${", "%{"), j):
  702. j = skip_interpolation(text, j + 2)
  703. else:
  704. j += 1
  705. raise HclError("unterminated string")
  706. def strip_comments(text):
  707. """Remove comments and heredoc bodies; leave quoted strings alone.
  708. #, // and /* */ comments become nothing (newlines are kept, so line numbers
  709. stay true). A heredoc, `<<ID` or `<<-ID` at the end of a line, is string
  710. content through the line whose stripped text equals ID: its body is blanked,
  711. so a `/*`, a brace or a `resource` word inside it is never read as code.
  712. Without this a commented-out `source = "./x"` before the real, remote source
  713. is read as the module's source, and a brace inside a comment or heredoc ends
  714. a block early.
  715. """
  716. out, i, n = [], 0, len(text)
  717. while i < n:
  718. c = text[i]
  719. if c == '"':
  720. j = skip_string(text, i)
  721. out.append(text[i:j])
  722. i = j
  723. elif c == "#" or text.startswith("//", i):
  724. while i < n and text[i] != "\n":
  725. i += 1
  726. elif text.startswith("/*", i):
  727. end = text.find("*/", i + 2)
  728. if end == -1:
  729. raise HclError("unterminated /* comment")
  730. out.append(blank(text[i : end + 2]))
  731. i = end + 2
  732. elif text.startswith("<<", i):
  733. match = HEREDOC_OPEN_RE.match(text, i)
  734. if not match:
  735. raise HclError("a << that is not a heredoc opener this scanner reads")
  736. out.append(match.group(0))
  737. ident, pos = match.group("ident"), match.end()
  738. while True:
  739. if pos >= n:
  740. raise HclError(f"unterminated heredoc <<{ident}")
  741. eol = text.find("\n", pos)
  742. eol = n if eol == -1 else eol
  743. if text[pos:eol].strip() == ident:
  744. out.append(blank(text[match.end() : eol]))
  745. i = eol
  746. break
  747. pos = eol + 1
  748. else:
  749. out.append(c)
  750. i += 1
  751. return "".join(out)
  752. def block_end(text, i):
  753. """i is just after a `{`; return the index of its matching `}`."""
  754. depth, n = 1, len(text)
  755. while i < n:
  756. c = text[i]
  757. if c == '"':
  758. i = skip_string(text, i)
  759. continue
  760. if c == "{":
  761. depth += 1
  762. elif c == "}":
  763. depth -= 1
  764. if depth == 0:
  765. return i
  766. i += 1
  767. raise HclError("unbalanced braces")
  768. class Block:
  769. """A `resource` or `module` block header and body from comment-free text."""
  770. def __init__(self, kind, raw_labels, line, body):
  771. self.kind, self.raw_labels, self.line, self.body = kind, raw_labels, line, body
  772. self.labels = [
  773. lab[1:-1] if lab.startswith('"') and lab.endswith('"') else lab
  774. for lab in raw_labels
  775. ]
  776. self.problem = None
  777. if any("\\" in lab for lab in raw_labels):
  778. self.problem = (
  779. f"backslash in a {kind} label {' '.join(raw_labels)}; "
  780. "the gate does not decode escapes in labels"
  781. )
  782. elif len(raw_labels) != (2 if kind == "resource" else 1):
  783. self.problem = (
  784. f"{kind} header with labels {' '.join(raw_labels)!r} is not understood"
  785. )
  786. def attrs(self):
  787. return top_level_attrs(self.body)
  788. def find_blocks(text):
  789. """Every resource/module block in already-stripped text (nested ones too)."""
  790. blocks = []
  791. for match in HEADER_RE.finditer(text):
  792. line = text.count("\n", 0, match.start("kind")) + 1
  793. try:
  794. end = block_end(text, match.end())
  795. except HclError as err:
  796. raise HclError(f"line {line}: {err}") from None
  797. blocks.append(
  798. Block(
  799. match.group("kind"),
  800. LABEL_RE.findall(match.group("labels")),
  801. line,
  802. text[match.end() : end],
  803. )
  804. )
  805. return blocks
  806. def top_level_attrs(body):
  807. """[(name, value)] for the attributes written directly in a block body.
  808. Anything inside a nested {...}, [...] or (...) is not an attribute of the
  809. block, so a `source = ...` in a tags object cannot stand in for the real one.
  810. """
  811. attrs, depth, start, i, n = [], 0, 0, 0, len(body)
  812. def flush(segment):
  813. match = ATTR_RE.fullmatch(segment)
  814. if match:
  815. attrs.append((match.group("name"), match.group("value")))
  816. while i < n:
  817. c = body[i]
  818. if c == '"':
  819. i = skip_string(body, i)
  820. continue
  821. if c in "{[(":
  822. depth += 1
  823. elif c in "}])":
  824. depth = max(depth - 1, 0)
  825. elif c == "\n" and depth == 0:
  826. flush(body[start:i])
  827. start = i + 1
  828. i += 1
  829. flush(body[start:])
  830. return attrs
  831. def walk_repo(root):
  832. """Return (sorted relative file paths, layout problems).
  833. Skipped: .git, .venv and .claude at the repository top level (tool and
  834. worktree directories) and a .terraform cache anywhere. Nothing else is
  835. hidden from the scan. Under stacks/ and modules/ any other directory whose
  836. name starts with a dot is a failure, a symlinked directory is a failure,
  837. and a stack directory must be named NN-name or be a provider directory.
  838. """
  839. root = Path(root)
  840. files, problems = [], []
  841. for dirpath, dirnames, filenames in os.walk(root):
  842. rel_dir = Path(dirpath).relative_to(root)
  843. keep = []
  844. for name in sorted(dirnames):
  845. if name == ".terraform" or (not rel_dir.parts and name in TOP_SKIP_DIRS):
  846. continue
  847. child = rel_dir / name
  848. where = child.as_posix()
  849. guarded = child.parts[0] in GUARDED_TOP
  850. if Path(dirpath, name).is_symlink():
  851. problems.append(
  852. f"{where}: symlinked directory is refused; the gate does not follow it, OpenTofu does"
  853. )
  854. continue
  855. if guarded and name.startswith("."):
  856. problems.append(
  857. f"{where}: hidden directory under {child.parts[0]}/ is refused; "
  858. "the gate does not scan it, so nothing may live there"
  859. )
  860. elif (
  861. child.parts[0] == "stacks"
  862. and len(child.parts) == 3
  863. and child.parts[1] == "sites"
  864. and not RESOURCE_KEY_RE.match(child.parts[2])
  865. ):
  866. problems.append(
  867. f"{where}: resource_key must be lowercase letters, digits and dashes, "
  868. "starting with a letter or digit"
  869. )
  870. elif child.parts[0] == "stacks" and not stack_name_ok(child.parts):
  871. problems.append(
  872. f"{where}: stack directory name must be NN-name (digits, a dash, then a name) "
  873. f"or one of {', '.join(sorted(STACK_PROVIDER_DIRS))} exactly, lowercase"
  874. )
  875. keep.append(name)
  876. dirnames[:] = keep
  877. for f in sorted(filenames):
  878. if f.endswith(HCL_SUFFIXES) and Path(dirpath, f).is_symlink():
  879. problems.append(
  880. f"{(rel_dir / f).as_posix()}: symlinked OpenTofu file is refused"
  881. )
  882. continue
  883. files.append((rel_dir / f).as_posix())
  884. return sorted(files), problems
  885. def stack_name_ok(parts):
  886. """Naming rule for stacks/<x>, stacks/<provider>/<x> and the data-only
  887. stacks/sites/<resource_key>/<stack path> (the key is checked by the caller)."""
  888. if len(parts) >= 2 and parts[1] == "sites":
  889. return len(parts) < 4 or stack_name_ok(("stacks", *parts[3:]))
  890. if len(parts) == 2:
  891. return parts[1] in STACK_PROVIDER_DIRS or bool(STACK_NAME_RE.match(parts[1]))
  892. if len(parts) == 3 and parts[1] in STACK_PROVIDER_DIRS:
  893. return bool(STACK_NAME_RE.match(parts[2]))
  894. return True
  895. def is_hidden(rel):
  896. return any(part.startswith(".") for part in Path(rel).parts)
  897. def lab_file(root, rel):
  898. """True only for a file that really lives under <root>/labs.
  899. The exemption is narrow on purpose: the first path component must be exactly
  900. `labs` (case-sensitive, so `Labs` and `stacks/labs` are not), the path may
  901. not contain `..`, and the real path of both the file and the labs directory
  902. must sit inside the real repository root (so a symlinked labs/ or a symlink
  903. leading from labs/ into stacks/ is not exempt).
  904. """
  905. parts = Path(rel).parts
  906. if len(parts) < 2 or parts[0] != LABS_DIR or ".." in parts or Path(rel).is_absolute():
  907. return False
  908. real_root = os.path.realpath(root)
  909. real_labs = os.path.realpath(os.path.join(real_root, LABS_DIR))
  910. if real_labs != os.path.join(real_root, LABS_DIR):
  911. return False
  912. real_file = os.path.realpath(os.path.join(real_root, rel))
  913. return real_file.startswith(real_labs + os.sep)
  914. def hcl_files(root):
  915. """Yield (rel, stripped text, error) for every *.tf and *.tofu file."""
  916. for rel in walk_repo(root)[0]:
  917. if not rel.endswith(HCL_SUFFIXES):
  918. continue
  919. try:
  920. yield (
  921. rel,
  922. strip_comments(Path(root, rel).read_text(encoding="utf-8-sig")),
  923. None,
  924. )
  925. except (HclError, UnicodeDecodeError) as err:
  926. yield rel, None, str(err)
  927. def file_blocks(root):
  928. """Yield (rel, Block) for every readable block; unreadable files are skipped
  929. here and reported once by block_problems."""
  930. for rel, text, error in hcl_files(root):
  931. if error or lab_file(root, rel):
  932. continue
  933. try:
  934. blocks = find_blocks(text)
  935. except HclError:
  936. continue
  937. for block in blocks:
  938. yield rel, block
  939. def provider_prefix(rtype):
  940. head, sep, _ = rtype.partition("_")
  941. return head + sep
  942. def uncosted_sources(root, allowed, approved_providers=None):
  943. """Allowlist check over every provider's resource types.
  944. `allowed` maps a costed type to the files that may contain it. A type with a
  945. provider prefix that is neither free, nor costed-and-in-its-file fails; a
  946. rejected type fails whatever `allowed` says. A provider that is not
  947. approved at all fails every non-free type it uses. A prefix that is neither
  948. a known cloud nor in SAFE_PREFIXES fails: an unknown cloud is not "free".
  949. """
  950. found = []
  951. for rel, block in file_blocks(root):
  952. if block.kind != "resource" or block.problem:
  953. continue
  954. kind = block.labels[0]
  955. provider = provider_of_type(kind)
  956. if provider is None:
  957. if not kind.startswith(SAFE_PREFIXES):
  958. found.append(
  959. f"{rel}:{block.line}: {kind} (provider prefix {provider_prefix(kind)!r} "
  960. "is not known to the gate; add it deliberately)"
  961. )
  962. continue
  963. if kind in REJECTED_TYPES:
  964. found.append(f"{rel}: {kind} is rejected: {REJECTED_TYPES[kind]}")
  965. continue
  966. if kind in FREE_TYPES[provider]:
  967. continue
  968. if approved_providers is not None and provider not in approved_providers:
  969. found.append(f"{rel}: {kind} (provider {provider} is not in approved.json)")
  970. elif kind not in COSTED_TYPES[provider]:
  971. # approved.json can place a priced type in a file, but cannot
  972. # approve a type the gate has no price model for.
  973. found.append(f"{rel}: {kind} (the gate has no price model for it)")
  974. elif rel not in allowed.get(kind, []):
  975. found.append(f"{rel}: {kind}")
  976. return found
  977. def module_blocks(text):
  978. """Return (name, body) for each module block in the text."""
  979. return [
  980. (block.labels[0], block.body)
  981. for block in find_blocks(strip_comments(text))
  982. if block.kind == "module" and not block.problem
  983. ]
  984. def module_source_problem(root, rel, block):
  985. """(source or None, problem or None) for one module block."""
  986. sources = [v for k, v in block.attrs() if k == "source"]
  987. if len(sources) > 1:
  988. return (
  989. None,
  990. f"{rel}:{block.line}: module {block.labels[0]!r} has more than one source",
  991. )
  992. match = STRING_LITERAL_RE.fullmatch(sources[0]) if sources else None
  993. source = match.group("text") if match else ""
  994. if not source.startswith(("./", "../")):
  995. return (
  996. None,
  997. f"{rel}: module {block.labels[0]!r} has a non-local source {source!r}",
  998. )
  999. if any(seg.startswith(".") and seg not in (".", "..") for seg in source.split("/")):
  1000. return None, (
  1001. f"{rel}:{block.line}: module {block.labels[0]!r} source {source!r} goes through a hidden "
  1002. "directory (a dot-directory is never scanned, so no module may live there)"
  1003. )
  1004. target = posixpath.normpath(posixpath.join(posixpath.dirname(rel), source))
  1005. if target == ".." or target.startswith("../"):
  1006. return None, (
  1007. f"{rel}:{block.line}: module {block.labels[0]!r} source {source!r} is outside the repository"
  1008. )
  1009. resolved = Path(root, posixpath.dirname(rel), source).resolve()
  1010. if not resolved.is_relative_to(Path(root).resolve()):
  1011. return None, (
  1012. f"{rel}:{block.line}: module {block.labels[0]!r} source {source!r} is outside the repository "
  1013. "once symlinks are resolved"
  1014. )
  1015. real_labs = Path(os.path.realpath(root), LABS_DIR)
  1016. if not lab_file(root, rel) and (
  1017. resolved.is_relative_to(real_labs) or target.split("/")[0] == LABS_DIR
  1018. ):
  1019. return None, (
  1020. f"{rel}:{block.line}: module {block.labels[0]!r} source {source!r} points into {LABS_DIR}/, "
  1021. "which the gate does not cost; a stack or module may not compose lab code"
  1022. )
  1023. return source, None
  1024. def module_problems(root):
  1025. """Check module blocks. Returns (problems, {stack dir: connector module count})."""
  1026. problems, connectors = [], {}
  1027. manifests = dict(stack_manifests(root))
  1028. for rel, block in file_blocks(root):
  1029. if block.kind != "module" or block.problem:
  1030. continue
  1031. name = block.labels[0]
  1032. source, problem = module_source_problem(root, rel, block)
  1033. if problem:
  1034. problems.append(problem)
  1035. continue
  1036. if source.rstrip("/").endswith(CONNECTOR_SOURCE_SUFFIX):
  1037. stack = str(Path(rel).parent.as_posix())
  1038. # Only a stack's own connector blocks reconcile with its manifest; a
  1039. # module directory may compose one without being a stack.
  1040. if stack in manifests or stack.startswith("stacks/"):
  1041. connectors[stack] = connectors.get(stack, 0) + 1
  1042. attrs = block.attrs()
  1043. for key, _ in attrs:
  1044. if key in ("count", "for_each"):
  1045. problems.append(
  1046. f"{rel}: module {name!r} uses {key}; the connector is costed as a single instance"
  1047. )
  1048. break
  1049. sizes = [(k, v) for k, v in attrs if k in CONNECTOR_SIZE_ATTRS]
  1050. ok = bool(sizes) and all(
  1051. re.fullmatch(LOCAL_REF_RE.format(key=CONNECTOR_SIZE_ATTRS[k]), v)
  1052. for k, v in sizes
  1053. )
  1054. if not ok:
  1055. problems.append(
  1056. f"{rel}:{block.line}: connector module {name!r} must set size (or instance_type) "
  1057. "to a plain reference such as local.connector_a.size, read from cost.json; "
  1058. "a literal or other expression is not tied to the priced manifest (see docs/cost.md)"
  1059. )
  1060. return problems, connectors
  1061. EDGE_SWITCH_DEF_RE = re.compile(r"(?m)^\s*on\s*=\s*var\.(?P<var>[A-Za-z_][A-Za-z0-9_]*)\s*\?\s*1\s*:\s*0\s*$")
  1062. def edge_switch_verified(root, stack, kind="edge"):
  1063. """The stack defines `on = var.<x> ? 1 : 0` and an output precondition refuses
  1064. <x> being true unless the manifest (local.cost.resources) prices the module.
  1065. The proof is per kind: for kind "spaces" the precondition must count the
  1066. manifest's entries of kind "spaces", so a switch that only proves the edge
  1067. host's droplet and reserved IP does not stand in for the bucket. For kind
  1068. "docker" the proof is structural and exact (see docker_switch_verified)."""
  1069. if kind == "docker":
  1070. return docker_switch_verified(root, stack)
  1071. texts = []
  1072. for path in sorted(Path(root, stack).glob("*.tf")):
  1073. try:
  1074. texts.append(strip_comments(path.read_text(encoding="utf-8")))
  1075. except (OSError, UnicodeDecodeError, HclError):
  1076. return False
  1077. text = "\n".join(texts)
  1078. match = EDGE_SWITCH_DEF_RE.search(text)
  1079. if not match:
  1080. return False
  1081. var = match.group("var")
  1082. middle = r"[^{}]*?local\.cost\.resources"
  1083. if kind == "spaces":
  1084. middle += r"[^{}]*?\bkind\s*==\s*\"spaces\""
  1085. return bool(
  1086. re.search(r"precondition\s*\{[^{}]*?!var\." + re.escape(var) + r"\s*\|\|" + middle, text, re.DOTALL)
  1087. )
  1088. DOCKER_FILTER_RE = (
  1089. r"\[\s*for\s+(?P<r>[A-Za-z_]\w*)\s+in\s+local\.cost\.resources\s*:\s*(?P=r)\s+"
  1090. r"if\s+(?P=r)\.name\s*==\s*\"" + DOCKER_ENTRY_NAME + r"\"\s*&&\s*(?P=r)\.kind\s*==\s*\"droplet\"\s*\]"
  1091. )
  1092. # The one condition form accepted for the switch: the negated switch, or exactly one
  1093. # workload droplet entry in the manifest. Matched against the whole `condition` value.
  1094. DOCKER_CONDITION_RE = re.compile(
  1095. r"!var\.(?P<var>[A-Za-z_]\w*)\s*\|\|\s*(?:length\(\s*" + DOCKER_FILTER_RE + r"\s*\)\s*==\s*1"
  1096. r"|\(\s*length\(\s*" + DOCKER_FILTER_RE.replace("(?P<r>", "(?P<r2>").replace("(?P=r)", "(?P=r2)")
  1097. + r"\s*\)\s*==\s*1\s*\))"
  1098. )
  1099. # local.priced_workload and local.workload_size: the only way the size reaches the module.
  1100. DOCKER_PRICED_LOCAL_RE = re.compile(DOCKER_FILTER_RE)
  1101. DOCKER_SIZE_LOCAL_RE = re.compile(
  1102. r"length\(\s*local\.(?P<p>[A-Za-z_]\w*)\s*\)\s*==\s*1\s*\?\s*"
  1103. r"local\.(?P=p)\[0\]\.size\s*:\s*local\.cost\.planned\.workload\.size"
  1104. )
  1105. def _stack_text(root, stack):
  1106. """The comment-free text of a stack's *.tf files, or None when unreadable."""
  1107. texts = []
  1108. for path in sorted(Path(root, stack).glob("*.tf")):
  1109. try:
  1110. texts.append(strip_comments(path.read_text(encoding="utf-8")))
  1111. except (OSError, UnicodeDecodeError, HclError):
  1112. return None
  1113. return "\n".join(texts)
  1114. def _top_level_blocks(text, header):
  1115. """[body] of every block whose header matches `header` (a regex ending at the
  1116. opening brace) and that sits at brace depth 0 of `text`."""
  1117. bodies = []
  1118. try:
  1119. for match in re.finditer(header, text):
  1120. if _depth_at(text, match.start()) != 0:
  1121. continue
  1122. bodies.append(text[match.end() : block_end(text, match.end())])
  1123. except HclError:
  1124. return []
  1125. return bodies
  1126. def _depth_at(text, pos):
  1127. depth, i = 0, 0
  1128. while i < pos:
  1129. c = text[i]
  1130. if c == '"':
  1131. i = skip_string(text, i)
  1132. continue
  1133. if c == "{":
  1134. depth += 1
  1135. elif c == "}":
  1136. depth -= 1
  1137. i += 1
  1138. return depth
  1139. def stack_locals(text):
  1140. """{name: expression} for every top-level `locals` block; a name defined twice
  1141. maps to None (ambiguous, so never trusted)."""
  1142. found = {}
  1143. for body in _top_level_blocks(text, r"(?m)^[ \t]*locals[ \t]*\{"):
  1144. for name, value in top_level_attrs(body):
  1145. found[name] = None if name in found else value.strip()
  1146. return found
  1147. def docker_switch_verified(root, stack):
  1148. """Structural proof for the workload switch: the stack defines
  1149. `on = var.<x> ? 1 : 0`, and some output's `precondition` block has a
  1150. `condition` attribute (its own, at the top of that block, not text elsewhere)
  1151. that is exactly `!var.<x> || length([for r in local.cost.resources : r if
  1152. r.name == "workload" && r.kind == "droplet"]) == 1`."""
  1153. text = _stack_text(root, stack)
  1154. if text is None:
  1155. return False
  1156. match = EDGE_SWITCH_DEF_RE.search(text)
  1157. if not match:
  1158. return False
  1159. var = match.group("var")
  1160. for out in _top_level_blocks(text, r"(?m)^[ \t]*output[ \t]+\"[^\"\n]*\"[ \t]*\{"):
  1161. for pre in _top_level_blocks(out, r"(?m)^[ \t]*precondition[ \t]*\{"):
  1162. for name, value in top_level_attrs(pre):
  1163. cond = DOCKER_CONDITION_RE.fullmatch(value.strip()) if name == "condition" else None
  1164. if cond and cond.group("var") == var:
  1165. return True
  1166. return False
  1167. def docker_size_problem(root, stack, size_expr):
  1168. """None when `size_expr` is `local.<n>` and local.<n> is defined once as the
  1169. manifest-derived form; otherwise a reason."""
  1170. ref = re.fullmatch(r"local\.([A-Za-z_]\w*)", size_expr)
  1171. text = _stack_text(root, stack)
  1172. if not ref or text is None:
  1173. return "is not a plain local reference"
  1174. defs = stack_locals(text)
  1175. expr = defs.get(ref.group(1))
  1176. sized = DOCKER_SIZE_LOCAL_RE.fullmatch(expr) if expr else None
  1177. if not sized:
  1178. return f"local.{ref.group(1)} is not defined once as the manifest-derived size"
  1179. priced = defs.get(sized.group("p"))
  1180. if not priced or not DOCKER_PRICED_LOCAL_RE.fullmatch(priced):
  1181. return f"local.{sized.group('p')} is not the filtered cost.json workload droplet list"
  1182. if defs.get("cost") is None or not re.fullmatch(
  1183. r'jsondecode\(\s*file\(\s*"\$\{path\.module\}/cost\.json"\s*\)\s*\)', defs["cost"]
  1184. ):
  1185. return "local.cost is not jsondecode(file(\"${path.module}/cost.json\"))"
  1186. return None
  1187. def edge_module_problems(root):
  1188. """Hold modules/edge-host to the connector's rules (it may hold a droplet and
  1189. a reserved IP, both priced from a stack's cost.json).
  1190. Per stack: no for_each; count only as the plain switch `local.on`; size a
  1191. plain `local.<name>.size`; and the manifest's droplet entries and
  1192. reserved_ip entries each number either 0 (switched off, priced nothing) or
  1193. the number of edge-host module calls."""
  1194. problems, calls, switched = [], {}, {}
  1195. manifests = dict(stack_manifests(root))
  1196. for rel, block in file_blocks(root):
  1197. if block.kind != "module" or block.problem:
  1198. continue
  1199. source, problem = module_source_problem(root, rel, block)
  1200. if problem or not source.rstrip("/").endswith(EDGE_SOURCE_SUFFIX):
  1201. continue
  1202. name, stack = block.labels[0], str(Path(rel).parent.as_posix())
  1203. calls[stack] = calls.get(stack, 0) + 1
  1204. attrs = block.attrs()
  1205. counts = [v.strip() for k, v in attrs if k == "count"]
  1206. switched[stack] = switched.get(stack, True) and len(counts) == 1 and bool(
  1207. EDGE_COUNT_RE.fullmatch(counts[0])
  1208. )
  1209. for key, value in attrs:
  1210. if key == "for_each" or (key == "count" and not EDGE_COUNT_RE.fullmatch(value.strip())):
  1211. problems.append(
  1212. f"{rel}: module {name!r} uses {key} {value.strip()!r}; the edge host is costed from "
  1213. "the manifest, so only count = local.on (the stack's switch) is accepted"
  1214. )
  1215. sizes = [v for k, v in attrs if k == "size"]
  1216. if len(sizes) != 1 or not re.fullmatch(LOCAL_REF_RE.format(key="size"), sizes[0]):
  1217. problems.append(
  1218. f"{rel}:{block.line}: edge-host module {name!r} must set size to a plain reference such "
  1219. "as local.edge_droplet.size, tied to cost.json (see docs/cost.md)"
  1220. )
  1221. for stack in sorted(calls):
  1222. if stack not in manifests:
  1223. continue
  1224. entries = load_json(manifests[stack])["resources"]
  1225. off_ok = switched[stack] and edge_switch_verified(root, stack)
  1226. for kind in ("droplet", "reserved_ip"):
  1227. have = sum(1 for r in entries if r.get("kind") == kind)
  1228. if have != calls[stack] and not (have == 0 and off_ok):
  1229. problems.append(
  1230. f"{stack}: {have} {kind} manifest entr(ies) but {calls[stack]} edge-host module call(s); "
  1231. "they must match (0 is accepted only when every call is count = local.on and the "
  1232. "stack defines that switch and ties it to the manifest)"
  1233. )
  1234. return problems, calls
  1235. def spaces_module_problems(root):
  1236. """Hold modules/spaces-bucket to the edge host's off-switch rule.
  1237. The bucket resource may not use count (it is a costed type), so a stack
  1238. switches the whole module with `count = local.on`, the same plain switch the
  1239. edge host uses. Per stack: no for_each; count only as `local.on`; and the
  1240. manifest's `spaces` entries number the module calls, or 0 (switched off,
  1241. priced nothing) only when every call is `count = local.on` and the stack
  1242. defines that switch and ties it to the manifest."""
  1243. problems, calls, switched = [], {}, {}
  1244. manifests = dict(stack_manifests(root))
  1245. for rel, block in file_blocks(root):
  1246. if block.kind != "module" or block.problem:
  1247. continue
  1248. source, problem = module_source_problem(root, rel, block)
  1249. # Collect loosely (any source that names a spaces-bucket directory once
  1250. # normalized), then assert strictly below.
  1251. if problem or posixpath.basename(posixpath.normpath(source)) != SPACES_SOURCE_SUFFIX:
  1252. continue
  1253. name, stack = block.labels[0], str(Path(rel).parent.as_posix())
  1254. target = posixpath.normpath(posixpath.join(posixpath.dirname(rel), source))
  1255. if target != SPACES_MODULE_DIR or source != posixpath.normpath(source):
  1256. problems.append(
  1257. f"{rel}:{block.line}: module {name!r} source {source!r} resolves to {target!r}; a "
  1258. f"spaces-bucket call must use the plain relative path to {SPACES_MODULE_DIR} "
  1259. "(no dotted, doubled or trailing-slash alias, no copy of the module elsewhere)"
  1260. )
  1261. calls[stack] = calls.get(stack, 0) + 1
  1262. attrs = block.attrs()
  1263. counts = [v.strip() for k, v in attrs if k == "count"]
  1264. switched[stack] = switched.get(stack, True) and len(counts) == 1 and bool(
  1265. EDGE_COUNT_RE.fullmatch(counts[0])
  1266. )
  1267. for key, value in attrs:
  1268. if key == "for_each" or (key == "count" and not EDGE_COUNT_RE.fullmatch(value.strip())):
  1269. problems.append(
  1270. f"{rel}: module {name!r} (spaces-bucket) uses {key} {value.strip()!r}; the bucket is "
  1271. "costed from the manifest, so only count = local.on (the stack's switch) is accepted"
  1272. )
  1273. for stack in sorted(calls):
  1274. if stack not in manifests:
  1275. problems.append(
  1276. f"{stack}: calls {SPACES_MODULE_DIR} but has no cost.json; the bucket is priced from a "
  1277. "stack's manifest, so a wrapper module or a directory without one is refused"
  1278. )
  1279. continue
  1280. have = sum(1 for r in load_json(manifests[stack])["resources"] if r.get("kind") == "spaces")
  1281. off_ok = switched[stack] and edge_switch_verified(root, stack, kind="spaces")
  1282. if have != calls[stack] and not (have == 0 and off_ok):
  1283. problems.append(
  1284. f"{stack}: {have} spaces manifest entr(ies) but {calls[stack]} spaces-bucket module call(s); "
  1285. "they must match (0 is accepted only when every call is count = local.on and the "
  1286. "stack defines that switch and ties it to the manifest)"
  1287. )
  1288. return problems
  1289. def docker_module_problems(root):
  1290. """Hold modules/docker-host to the edge host's off-switch rule.
  1291. The workload droplet is priced from the stack's cost.json entry named
  1292. "workload" (kind droplet, a size from docs/cost-prices.json) and counted only
  1293. when the manifest carries it. Per stack: the module path must be exactly
  1294. modules/docker-host; no for_each; count only as `local.on`; size a plain
  1295. local reference; the caller's directory must have a cost.json; and the
  1296. manifest's "workload" entries number the module calls, or 0 (switched off,
  1297. priced nothing) only when every call is `count = local.on` and the stack
  1298. defines that switch and ties it to the "workload" droplet entry.
  1299. Returns (problems, {stack dir: docker-host module call count})."""
  1300. problems, calls, switched = [], {}, {}
  1301. manifests = dict(stack_manifests(root))
  1302. for rel, block in file_blocks(root):
  1303. if block.kind != "module" or block.problem:
  1304. continue
  1305. source, problem = module_source_problem(root, rel, block)
  1306. # Collect loosely (any source that names a docker-host directory once
  1307. # normalized), then assert strictly below.
  1308. if problem or posixpath.basename(posixpath.normpath(source)) != DOCKER_SOURCE_SUFFIX:
  1309. continue
  1310. name, stack = block.labels[0], str(Path(rel).parent.as_posix())
  1311. target = posixpath.normpath(posixpath.join(posixpath.dirname(rel), source))
  1312. if target != DOCKER_MODULE_DIR or source != posixpath.normpath(source):
  1313. problems.append(
  1314. f"{rel}:{block.line}: module {name!r} source {source!r} resolves to {target!r}; a "
  1315. f"docker-host call must use the plain relative path to {DOCKER_MODULE_DIR} "
  1316. "(no dotted, doubled or trailing-slash alias, no copy of the module elsewhere)"
  1317. )
  1318. calls[stack] = calls.get(stack, 0) + 1
  1319. attrs = block.attrs()
  1320. counts = [v.strip() for k, v in attrs if k == "count"]
  1321. switched[stack] = switched.get(stack, True) and len(counts) == 1 and bool(
  1322. EDGE_COUNT_RE.fullmatch(counts[0])
  1323. )
  1324. for key, value in attrs:
  1325. if key == "for_each" or (key == "count" and not EDGE_COUNT_RE.fullmatch(value.strip())):
  1326. problems.append(
  1327. f"{rel}: module {name!r} (docker-host) uses {key} {value.strip()!r}; the workload "
  1328. "droplet is costed from the manifest, so only count = local.on (the stack's switch) "
  1329. "is accepted"
  1330. )
  1331. sizes = [v.strip() for k, v in attrs if k == "size"]
  1332. why = "is missing or set more than once" if len(sizes) != 1 else docker_size_problem(root, stack, sizes[0])
  1333. if why:
  1334. problems.append(
  1335. f"{rel}:{block.line}: docker-host module {name!r} size {why}; it must be a plain "
  1336. "local reference derived from the priced workload entry of the stack's cost.json "
  1337. "manifest (see docs/cost.md), never a literal or a variable"
  1338. )
  1339. for stack in sorted(calls):
  1340. if stack not in manifests:
  1341. problems.append(
  1342. f"{stack}: calls {DOCKER_MODULE_DIR} but has no cost.json; the workload droplet is priced "
  1343. "from a stack's manifest, so a wrapper module or a directory without one is refused"
  1344. )
  1345. continue
  1346. have = sum(
  1347. 1
  1348. for r in load_json(manifests[stack])["resources"]
  1349. if r.get("kind") == "droplet" and r.get("name") == DOCKER_ENTRY_NAME
  1350. )
  1351. planned = (load_json(manifests[stack]).get("planned") or {}).get(DOCKER_ENTRY_NAME) or {}
  1352. if "size" in planned and planned["size"] not in load_prices(root, "digitalocean").get("droplets", {}):
  1353. problems.append(
  1354. f"{stack}: planned {DOCKER_ENTRY_NAME} size {planned['size']!r} is not in "
  1355. "docs/cost-prices.json; the planned droplet must be priced"
  1356. )
  1357. off_ok = switched[stack] and edge_switch_verified(root, stack, kind="docker")
  1358. if have != calls[stack] and not (have == 0 and off_ok):
  1359. problems.append(
  1360. f"{stack}: {have} {DOCKER_ENTRY_NAME} manifest entr(ies) but {calls[stack]} docker-host "
  1361. "module call(s); they must match (0 is accepted only when every call is count = local.on "
  1362. "and the stack defines that switch and ties it to the manifest)"
  1363. )
  1364. return problems, calls
  1365. def reserved_ip_problems(root):
  1366. """Each reserved IP is assigned exactly once, in the file that declares it.
  1367. An unassigned reserved IP costs $5.00 a month, so the scanner wants, per
  1368. file, as many assignments as reserved IPs, each assignment's ip_address a
  1369. plain reference to a distinct reserved IP of that file and its droplet_id a
  1370. plain reference to a droplet. A shape it cannot read fails. The scanner does
  1371. not execute HCL; the end-state check on a plan is a later change (design
  1372. section 5.6 item 4)."""
  1373. problems, per_file = [], {}
  1374. for rel, block in file_blocks(root):
  1375. if block.kind != "resource" or block.problem:
  1376. continue
  1377. if block.labels[0] in (RESERVED_IP, RESERVED_IP_ASSIGNMENT):
  1378. per_file.setdefault(rel, {RESERVED_IP: [], RESERVED_IP_ASSIGNMENT: []})[
  1379. block.labels[0]
  1380. ].append(block)
  1381. for rel, found in sorted(per_file.items()):
  1382. ips, assigns = found[RESERVED_IP], found[RESERVED_IP_ASSIGNMENT]
  1383. names = {b.labels[1] for b in ips}
  1384. if len(ips) != len(assigns):
  1385. problems.append(
  1386. f"{rel}: {len(ips)} {RESERVED_IP} block(s) but {len(assigns)} "
  1387. f"{RESERVED_IP_ASSIGNMENT} block(s); an unassigned reserved IP costs money, "
  1388. "so each needs exactly one assignment in the same file"
  1389. )
  1390. seen = []
  1391. for block in assigns:
  1392. attrs = dict(block.attrs())
  1393. ip = RESERVED_IP_REF_RE.fullmatch(attrs.get("ip_address", "").strip())
  1394. if not ip or ip.group("name") not in names:
  1395. problems.append(
  1396. f"{rel}:{block.line}: assignment {block.labels[1]!r} must set ip_address to a plain "
  1397. f"reference to a {RESERVED_IP} of this file"
  1398. )
  1399. continue
  1400. if ip.group("name") in seen:
  1401. problems.append(
  1402. f"{rel}:{block.line}: reserved IP {ip.group('name')!r} is assigned more than once"
  1403. )
  1404. seen.append(ip.group("name"))
  1405. if not DROPLET_ID_REF_RE.fullmatch(attrs.get("droplet_id", "").strip()):
  1406. problems.append(
  1407. f"{rel}:{block.line}: assignment {block.labels[1]!r} must set droplet_id to a plain "
  1408. "reference to a droplet of the same file"
  1409. )
  1410. return problems
  1411. STATEMENT_START_RE = re.compile(r"\s*(?P<name>[A-Za-z_][A-Za-z0-9_-]*)\s*(?P<next>[={]?)")
  1412. def top_level_statement_names(body):
  1413. """[(name, next char)] for each statement written directly in a block body:
  1414. the leading identifier and the `{` (nested block) or `=` (attribute) after it.
  1415. Words inside quoted strings, interpolations, brackets or nested blocks are
  1416. not statements of this block; comments and heredocs are already stripped."""
  1417. found, depth, i, n, at_start = [], 0, 0, len(body), True
  1418. while i < n:
  1419. if at_start and depth == 0:
  1420. match = STATEMENT_START_RE.match(body, i)
  1421. if match:
  1422. found.append((match.group("name"), match.group("next")))
  1423. at_start = False
  1424. c = body[i]
  1425. if c == '"':
  1426. i = skip_string(body, i)
  1427. continue
  1428. if c in "{[(":
  1429. depth += 1
  1430. elif c in "}])":
  1431. depth = max(depth - 1, 0)
  1432. elif c == "\n" and depth == 0:
  1433. at_start = True
  1434. i += 1
  1435. return found
  1436. def droplet_backup_problems(rel, block):
  1437. """The source must leave droplet backups off. With backups on, DigitalOcean
  1438. defaults to the daily plan, and backup_policy selects daily or weekly; the
  1439. gate prices neither from source, so any way of turning them on is refused
  1440. (the manifest path prices the weekly plan; see droplet_cost)."""
  1441. where = f"{rel}:{block.line}: digitalocean_droplet {block.labels[1]!r}"
  1442. found = []
  1443. if any(name == "backup_policy" for name, _ in top_level_statement_names(block.body)):
  1444. found.append(
  1445. f"{where} sets backup_policy; backup plans are not priced from source, refused"
  1446. )
  1447. for key, value in block.attrs():
  1448. if key == "backups" and value.strip() != "false":
  1449. found.append(
  1450. f"{where} sets backups to {value.strip()!r}; it must be the literal false "
  1451. "(backups default to the unpriced daily plan)"
  1452. )
  1453. return found
  1454. HCL_WORD_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_-]*")
  1455. # A provisioner block header after the word: an optional label, then the brace.
  1456. # HCL needs no whitespace between a keyword and a quoted label, between two quoted
  1457. # labels, or before the brace; whitespace is required only before a bare label.
  1458. _WS = r"[ \t\r]*"
  1459. _WS1 = r"[ \t\r]+"
  1460. _QUOTED = r'"[^"\n]*"'
  1461. _BARE = r"[A-Za-z_][A-Za-z0-9_-]*"
  1462. PROVISIONER_TAIL_RE = re.compile(rf"(?:{_WS}{_QUOTED}|{_WS1}{_BARE})?{_WS}\{{")
  1463. # `data "external" "name" {` after the word `data`, in any legal spacing. The first
  1464. # label may be quoted (a backslash in it could spell "external" as an escape, so any
  1465. # escaped first label is treated as external) or bare.
  1466. _EXTERNAL_LABEL = rf'(?:{_WS}"(?:external|[^"\n]*\\[^"\n]*)"|{_WS1}external(?![A-Za-z0-9_-]))'
  1467. # The second label is optional here: a malformed header is refused too (fail closed).
  1468. EXTERNAL_DATA_TAIL_RE = re.compile(rf"{_EXTERNAL_LABEL}(?:{_WS}{_QUOTED}|{_WS}{_BARE})?{_WS}\{{")
  1469. def run_hook_problems(rel, text):
  1470. """Provisioner blocks (local-exec, remote-exec, file) and external data
  1471. sources, wherever they sit. They run commands at apply or plan time, which
  1472. the gate can neither read nor cost, so each one fails the gate. Quoted
  1473. strings are skipped and comments and heredocs are already stripped, so the
  1474. words only count where the configuration is code."""
  1475. found, i, n = [], 0, len(text)
  1476. while i < n:
  1477. if text[i] == '"':
  1478. i = skip_string(text, i)
  1479. continue
  1480. word = HCL_WORD_RE.match(text, i)
  1481. if not word:
  1482. i += 1
  1483. continue
  1484. line = text.count("\n", 0, i) + 1
  1485. if word.group(0) == "provisioner" and PROVISIONER_TAIL_RE.match(text, word.end()):
  1486. found.append(
  1487. f"{rel}:{line}: a provisioner block runs commands at apply time and is "
  1488. "refused; the gate cannot read or cost what it does"
  1489. )
  1490. elif word.group(0) == "data" and EXTERNAL_DATA_TAIL_RE.match(text, word.end()):
  1491. found.append(
  1492. f"{rel}:{line}: an external data source runs a program at plan time and "
  1493. "is refused; the gate cannot read or cost what it does"
  1494. )
  1495. i = word.end()
  1496. return found
  1497. def block_problems(root):
  1498. """Everything wrong with how the files themselves read: unreadable HCL,
  1499. escapes in labels, headers the scanner does not understand, count or
  1500. for_each on a costed resource (the manifest cannot be reconciled with it
  1501. without a plan), and provisioners or external data sources anywhere."""
  1502. problems = []
  1503. costed = set().union(*COSTED_TYPES.values())
  1504. for rel, text, error in hcl_files(root):
  1505. if error:
  1506. problems.append(f"{rel}: unreadable HCL, refused: {error}")
  1507. continue
  1508. if not lab_file(root, rel):
  1509. problems += run_hook_problems(rel, text)
  1510. try:
  1511. blocks = find_blocks(text)
  1512. except HclError as err:
  1513. problems.append(f"{rel}: unreadable HCL, refused: {err}")
  1514. continue
  1515. for block in blocks:
  1516. if block.problem:
  1517. problems.append(f"{rel}:{block.line}: {block.problem}")
  1518. elif lab_file(root, rel):
  1519. continue # syntax is checked above; the cost rules do not apply to labs/
  1520. elif block.kind == "resource" and block.labels[0] in costed:
  1521. if block.labels[0] == "digitalocean_droplet":
  1522. problems += droplet_backup_problems(rel, block)
  1523. for key, _ in block.attrs():
  1524. if key in ("count", "for_each"):
  1525. problems.append(
  1526. f"{rel}:{block.line}: {block.labels[0]} {block.labels[1]!r} uses {key}; "
  1527. "the manifest cannot be reconciled without a plan, so a costed resource "
  1528. "may not use it"
  1529. )
  1530. return problems
  1531. def stack_dirs(root):
  1532. """Every directory under stacks/ that holds OpenTofu files."""
  1533. dirs = set()
  1534. for rel in walk_repo(root)[0]:
  1535. if (
  1536. rel.startswith("stacks/")
  1537. and rel.endswith(HCL_SUFFIXES)
  1538. and not is_hidden(rel)
  1539. ):
  1540. dirs.add(str(Path(rel).parent.as_posix()))
  1541. return sorted(dirs)
  1542. def structure_problems(root):
  1543. """Everything the cost total cannot see: manifests, modules, unreadable HCL.
  1544. Limits: HCL is read with a scanner and never executed. This is a guardrail,
  1545. not a proof. Dynamic module sources, string-built resource types and
  1546. `dynamic` blocks are not understood; *.tf.json and *.tofu.json are refused
  1547. outright. *.tf and *.tofu (override files included) are read.
  1548. """
  1549. files, problems = walk_repo(root)
  1550. manifests = dict(stack_manifests(root))
  1551. bases = {k: v for k, v in manifests.items() if not is_instance_dir(k)}
  1552. if not manifests:
  1553. problems.append(
  1554. "no stacks/**/cost.json manifest found; at least one is required"
  1555. )
  1556. for stack in stack_dirs(root):
  1557. if is_instance_dir(stack):
  1558. continue
  1559. if stack not in manifests:
  1560. problems.append(
  1561. f"{stack}: has OpenTofu files but no cost.json; every stack needs a manifest"
  1562. )
  1563. for rel in files:
  1564. for suffix in JSON_SUFFIXES:
  1565. if rel.endswith(suffix):
  1566. problems.append(
  1567. f"{rel}: *{suffix} cannot be read by this gate and is refused"
  1568. )
  1569. if (
  1570. is_instance_dir(str(Path(rel).parent.as_posix()))
  1571. and rel.endswith(HCL_SUFFIXES)
  1572. and not is_hidden(rel)
  1573. ):
  1574. problems.append(
  1575. f"{rel}: instances carry no code; stacks/sites holds data (cost.json) only"
  1576. )
  1577. problems += block_problems(root)
  1578. problems += reserved_ip_problems(root)
  1579. mod_problems, connectors = module_problems(root)
  1580. problems += mod_problems
  1581. edge_problems, edge_calls = edge_module_problems(root)
  1582. problems += edge_problems
  1583. problems += spaces_module_problems(root)
  1584. docker_problems, docker_calls = docker_module_problems(root)
  1585. problems += docker_problems
  1586. for stack in sorted(set(connectors) | set(bases)):
  1587. machines = 0
  1588. if stack in bases:
  1589. machines = machine_count(bases[stack])
  1590. if stack in edge_calls:
  1591. # The edge-host droplets are reconciled by edge_module_problems.
  1592. # Only as many as there are edge-host calls: any other droplet
  1593. # is still counted and must match a connector module block.
  1594. machines -= min(
  1595. edge_calls[stack],
  1596. sum(1 for r in load_json(bases[stack])["resources"] if r.get("kind") == "droplet"),
  1597. )
  1598. if stack in docker_calls:
  1599. # The workload droplet is reconciled by docker_module_problems.
  1600. machines -= min(
  1601. docker_calls[stack],
  1602. sum(
  1603. 1
  1604. for r in load_json(bases[stack])["resources"]
  1605. if r.get("kind") == "droplet" and r.get("name") == DOCKER_ENTRY_NAME
  1606. ),
  1607. )
  1608. have = connectors.get(stack, 0)
  1609. if have != machines:
  1610. problems.append(
  1611. f"{stack}: {have} twingate-connector module block(s) but {machines} machine entr(ies) in its cost.json; they must match"
  1612. )
  1613. problems += instance_problems(manifests, bases, connectors)
  1614. problems += config_problems(root)
  1615. return problems
  1616. def config_problems(root):
  1617. """Every stack id in .spacelift/config.yml answers to exactly one manifest.
  1618. No config file (a fixture) is not a problem; one that cannot be read is."""
  1619. config = Path(root, ".spacelift/config.yml")
  1620. if not config.exists():
  1621. return []
  1622. try:
  1623. import yaml
  1624. except ImportError:
  1625. return [".spacelift/config.yml exists but PyYAML is not installed to read it"]
  1626. try:
  1627. loaded = yaml.safe_load(config.read_text(encoding="utf-8"))
  1628. stacks = loaded["stacks"]
  1629. if not isinstance(stacks, dict):
  1630. raise TypeError("stacks is not a map")
  1631. except (yaml.YAMLError, OSError, KeyError, TypeError) as err:
  1632. return [f".spacelift/config.yml is unreadable or has no stacks map: {err!r}"]
  1633. ids = manifest_ids(root)
  1634. return [
  1635. f".spacelift/config.yml stack id {sid} has {len(ids.get(sid, []))} manifest(s), expected exactly 1"
  1636. for sid in stacks
  1637. if len(ids.get(sid, [])) != 1
  1638. ]
  1639. def machine_count(manifest):
  1640. return sum(
  1641. 1 for r in load_json(manifest)["resources"] if r.get("kind") in MACHINE_KINDS
  1642. )
  1643. def shared_code_problems(rel, data, base_manifest, target):
  1644. """An instance deploys the base stack's code, which reads its resources from
  1645. the base stack's own cost.json and creates ALL of them again. Until a stack
  1646. can select the instance manifest, the instance's resource list (machines,
  1647. volumes, addresses, every costed entry) must equal the base manifest's,
  1648. entry by entry, matched by name."""
  1649. mine = {r.get("name"): r for r in data["resources"]}
  1650. base = {r.get("name"): r for r in load_json(base_manifest)["resources"]}
  1651. if set(mine) != set(base) or len(mine) != len(data["resources"]):
  1652. return [
  1653. (
  1654. f"{rel}: resource names must equal the base stack's ({target}); "
  1655. "the shared code deploys every resource of the base manifest"
  1656. )
  1657. ]
  1658. return [
  1659. (
  1660. f"{rel}: resource {name!r} is {res!r} but must equal the base stack's entry "
  1661. f"{base[name]!r} in {target}/cost.json (the shared code reads the base manifest; "
  1662. "a site-specific size needs the stack to read the instance manifest)"
  1663. )
  1664. for name, res in sorted(mine.items(), key=lambda kv: str(kv[0]))
  1665. if res != base[name]
  1666. ]
  1667. def instance_problems(manifests, bases, connectors):
  1668. """Rules for stacks/sites/<resource_key>/<stack path>/cost.json (data only)."""
  1669. problems, owners = [], {}
  1670. for rel, manifest in sorted(manifests.items()):
  1671. data = load_json(manifest)
  1672. target = declared_instance_of(data)
  1673. if not is_instance_dir(rel):
  1674. if isinstance(data, dict) and "instance_of" in data:
  1675. problems.append(
  1676. f"{rel}: instance_of is only allowed under stacks/sites/<resource_key>/"
  1677. )
  1678. continue
  1679. key = instance_key(rel)
  1680. if key is None or len(Path(rel).parts) < 4:
  1681. problems.append(
  1682. f"{rel}: an instance manifest must sit at stacks/sites/<resource_key>/<stack path>/cost.json"
  1683. )
  1684. continue
  1685. if target is None:
  1686. problems.append(
  1687. f"{rel}: instance_of is missing; an instance manifest must name the stack whose code it deploys"
  1688. )
  1689. continue
  1690. bad = instance_of_problem(target)
  1691. if bad:
  1692. problems.append(f"{rel}: instance_of {bad}")
  1693. continue
  1694. expected = f"{SITES_DIR}/{key}/{target[len('stacks/') :]}"
  1695. if rel != expected:
  1696. problems.append(
  1697. f"{rel}: must sit at stacks/sites/<resource_key>/{target[len('stacks/') :]} "
  1698. f"to be an instance of {target}"
  1699. )
  1700. continue
  1701. if target not in bases:
  1702. problems.append(
  1703. f"{rel}: instance_of {target!r} names no stack directory with its own cost.json"
  1704. )
  1705. continue
  1706. owners.setdefault(stack_id(rel, target), []).append(rel)
  1707. problems += shared_code_problems(rel, data, bases[target], target)
  1708. machines = machine_count(manifest)
  1709. have = connectors.get(target, 0)
  1710. if have != machines:
  1711. problems.append(
  1712. f"{rel}: {have} twingate-connector module block(s) in {target} but {machines} machine "
  1713. "entr(ies) in this instance manifest; they must match"
  1714. )
  1715. for rel in bases:
  1716. owners.setdefault(stack_id(rel, None), []).append(rel)
  1717. for sid, rels in sorted(owners.items()):
  1718. if len(rels) > 1:
  1719. problems.append(
  1720. f"duplicate stack id {sid}: {', '.join(sorted(rels))}; "
  1721. "every stack id must have exactly one manifest"
  1722. )
  1723. return problems
  1724. # ---- approval ---------------------------------------------------------------
  1725. def sites_problems(provider, entry, cap, parts):
  1726. """The optional per-site approvals under one provider.
  1727. `parts` is {"": base stacks total, <resource_key>: site total}. With no
  1728. `sites` map nothing here applies. With one, every instance must be named in
  1729. it, each site stays inside its own figure, the sites together stay inside
  1730. the provider figure, and the base stacks get what the sites leave.
  1731. """
  1732. if "sites" not in entry:
  1733. return []
  1734. sites = entry["sites"]
  1735. if not isinstance(sites, dict) or not sites:
  1736. return [
  1737. f"{provider}: sites must be a non-empty map of resource_key to an object"
  1738. ]
  1739. problems, approved_sum = [], 0.0
  1740. for key, site in sites.items():
  1741. if not isinstance(key, str) or not RESOURCE_KEY_RE.match(key):
  1742. problems.append(f"{provider}: site key {key!r} is not a valid resource_key")
  1743. continue
  1744. figure = site.get("approved_monthly_total") if isinstance(site, dict) else None
  1745. if isinstance(figure, bool) or not isinstance(figure, (int, float)):
  1746. problems.append(
  1747. f"{provider}: site {key} needs a numeric approved_monthly_total"
  1748. )
  1749. continue
  1750. site_cap = money(site["approved_monthly_total"], f"{provider} site {key}")
  1751. approved_sum += site_cap
  1752. planned = parts.get(key)
  1753. if planned is not None:
  1754. planned = round(planned, 2)
  1755. site_cap = round(site_cap, 2)
  1756. if planned is not None and planned > site_cap:
  1757. problems.append(
  1758. f"{provider}: site {key} planned ${planned:.2f} is above its approved ${site_cap:.2f}"
  1759. )
  1760. for key in sorted(k for k in parts if k and k not in sites):
  1761. problems.append(
  1762. f"{provider}: site {key} has a manifest but is not in the approved sites map"
  1763. )
  1764. approved_sum = round(approved_sum, 2)
  1765. cap = round(cap, 2)
  1766. if approved_sum > cap:
  1767. problems.append(
  1768. f"{provider}: approved sites add up to ${approved_sum:.2f}, above the provider approved ${cap:.2f}"
  1769. )
  1770. base = round(parts.get("", 0.0), 2)
  1771. if base > round(cap - approved_sum, 2):
  1772. problems.append(
  1773. f"{provider}: base stacks planned ${base:.2f} are above approved ${cap:.2f} minus sites ${approved_sum:.2f}"
  1774. )
  1775. return problems
  1776. PHASE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
  1777. PHASE_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
  1778. PHASE_STATUSES = ("planned", "current", "done")
  1779. def money(value, label):
  1780. """A dollar figure in approved.json: a JSON number (not a string, not a
  1781. bool), finite, zero or more, with at most two decimal places so the
  1782. comparison the gate makes is the one a reviewer reads. Else ValueError."""
  1783. if isinstance(value, bool) or not isinstance(value, (int, float)):
  1784. raise ValueError(f"{label}: {value!r} must be a JSON number") # noqa: TRY004
  1785. if isinstance(value, int) and abs(value) > sys.float_info.max:
  1786. raise ValueError(f"{label}: the number is too large")
  1787. out = num(value, label)
  1788. if Decimal(repr(out)).as_tuple().exponent < -2:
  1789. raise ValueError(f"{label}: {value!r} has more than two decimal places")
  1790. return out
  1791. def phase_number(value):
  1792. """money() or None, for the phase checks that report their own message."""
  1793. try:
  1794. return money(value, "value")
  1795. except ValueError:
  1796. return None
  1797. def current_ceiling(approved):
  1798. """(phase id, ceiling, reason) the gate enforces.
  1799. With `phases` the ceiling is the `current_phase` entry's. A legacy top-level
  1800. `ceiling` is read only when `phases` is absent. Raises ValueError when no
  1801. usable ceiling can be found; phase_problems() explains why."""
  1802. if "phases" not in approved:
  1803. return "legacy", money(approved["ceiling"], "ceiling"), "legacy top-level ceiling"
  1804. phases, current = approved["phases"], approved.get("current_phase")
  1805. if not isinstance(phases, dict) or current not in phases:
  1806. raise ValueError(f"current_phase {current!r} is not in phases")
  1807. entry = phases[current]
  1808. if not isinstance(entry, dict):
  1809. raise ValueError(f"phase {current}: not an object") # noqa: TRY004
  1810. ceiling = money(entry.get("ceiling"), f"phase {current} ceiling")
  1811. return current, ceiling, str(entry.get("reason", ""))
  1812. def phase_date_ok(value):
  1813. if not isinstance(value, str) or not PHASE_DATE_RE.match(value):
  1814. return False
  1815. try:
  1816. datetime.date.fromisoformat(value)
  1817. except ValueError:
  1818. return False
  1819. return True
  1820. STATUS_RANK = {"done": 0, "current": 1, "planned": 2}
  1821. def lifecycle_order_problems(phases):
  1822. """Phases run planned -> current -> done, in declared order: every done phase
  1823. comes before the current one and every planned phase after it. A done phase
  1824. therefore cannot be quietly switched back on without also moving others."""
  1825. problems, last, last_key = [], -1, None
  1826. for key, entry in phases.items():
  1827. rank = STATUS_RANK.get(entry.get("status")) if isinstance(entry, dict) else None
  1828. if rank is None:
  1829. continue
  1830. if rank < last:
  1831. problems.append(
  1832. f"phase {key}: status {entry['status']} comes after {last_key}; phases are done, then current, then planned, in declared order"
  1833. )
  1834. else:
  1835. last, last_key = rank, key
  1836. return problems
  1837. def finished_phase_problems(phases, current):
  1838. """A finished phase may not be above the live ceiling.
  1839. One file cannot show that a done phase is genuine, and a large ceiling
  1840. planted in one (followed by a "lowers" on the next phase) could be switched
  1841. on later. So a done phase above the current phase's ceiling is refused
  1842. outright: finished phases are a ratchet, and the ceiling cannot be lowered
  1843. below a phase that already ran. The cost is that a ceiling lower than any
  1844. finished phase is not supported in this file (see docs/cost.md)."""
  1845. entry = phases.get(current) if isinstance(phases, dict) else None
  1846. live = phase_number(entry.get("ceiling")) if isinstance(entry, dict) else None
  1847. if live is None:
  1848. return []
  1849. problems = []
  1850. for key, value in phases.items():
  1851. if not isinstance(value, dict) or value.get("status") != "done":
  1852. continue
  1853. done = phase_number(value.get("ceiling"))
  1854. if done is not None and done > live:
  1855. problems.append(
  1856. f"phase {key}: done at ${done:.2f}, above the current ceiling ${live:.2f}; "
  1857. "a finished phase may not exceed the live ceiling"
  1858. )
  1859. return problems
  1860. def transition_problems(old, new):
  1861. """Lifecycle of each phase between two versions of approved.json.
  1862. planned -> current -> done only. A done phase never changes again, so a
  1863. large ceiling planted in one cannot be switched on; a phase that is current
  1864. stops being current only when another becomes current (the new file has
  1865. exactly one). A new phase arrives planned or current. Not used by the
  1866. plain gate (it sees one file); cost_raise runs it, and the gate runs it with
  1867. --base-approved FILE when CI can supply the merge base's copy."""
  1868. old_phases, new_phases = old.get("phases"), new.get("phases")
  1869. if not isinstance(old_phases, dict) or not isinstance(new_phases, dict):
  1870. return []
  1871. problems = []
  1872. for key, was in old_phases.items():
  1873. if not isinstance(was, dict):
  1874. continue
  1875. now = new_phases.get(key)
  1876. if now is None:
  1877. problems.append(
  1878. f"phase {key} ({was.get('status')}) may not be removed; change it instead"
  1879. )
  1880. continue
  1881. if was.get("status") == "done" and now != was:
  1882. problems.append(f"phase {key} is done and may not change")
  1883. continue
  1884. before, after = was.get("status"), (now or {}).get("status")
  1885. if before != after and (before, after) not in (
  1886. ("planned", "current"),
  1887. ("current", "done"),
  1888. ):
  1889. problems.append(
  1890. f"phase {key}: status may not go from {before} to {after} (planned, then current, then done)"
  1891. )
  1892. for key, now in new_phases.items():
  1893. if (
  1894. key not in old_phases
  1895. and isinstance(now, dict)
  1896. and now.get("status") == "done"
  1897. ):
  1898. problems.append(f"phase {key} is new and may not start as done")
  1899. return problems
  1900. def effective_change(old, new):
  1901. """(old, new) of (phase id, ceiling), or None where one cannot be read."""
  1902. out = []
  1903. for doc in (old, new):
  1904. try:
  1905. out.append(current_ceiling(doc)[:2])
  1906. except (ValueError, KeyError, TypeError):
  1907. out.append(None)
  1908. return tuple(out)
  1909. def phase_problems(approved):
  1910. """Shape of the per-phase ceilings (docs/cost.md, "Ceilings per phase")."""
  1911. hard_max = None
  1912. if "hard_max" in approved:
  1913. hard_max = phase_number(approved["hard_max"])
  1914. if hard_max is None:
  1915. return [
  1916. f"hard_max {approved['hard_max']!r} must be a finite number, zero or more"
  1917. ]
  1918. if "phases" in approved and "hard_max" not in approved:
  1919. hard_problem = [
  1920. "hard_max is required when phases exist (the absolute limit no phase may pass)"
  1921. ]
  1922. else:
  1923. hard_problem = []
  1924. if "phases" not in approved:
  1925. legacy = phase_number(approved.get("ceiling"))
  1926. if legacy is not None and hard_max is not None and legacy > hard_max:
  1927. return [f"ceiling ${legacy:.2f} is above hard_max ${hard_max:.2f}"]
  1928. return []
  1929. problems = list(hard_problem)
  1930. if hard_max is not None:
  1931. why = approved.get("hard_max_reason")
  1932. if not isinstance(why, str) or not why.strip():
  1933. problems.append("hard_max_reason must say why hard_max is that number")
  1934. if "ceiling" in approved:
  1935. problems.append(
  1936. "approved.json has phases and a top-level ceiling; remove the top-level ceiling, the current phase decides"
  1937. )
  1938. phases = approved["phases"]
  1939. if not isinstance(phases, dict) or not phases:
  1940. return problems + ["phases must be a non-empty map of phase id to an object"]
  1941. current = approved.get("current_phase")
  1942. if not isinstance(current, str) or current not in phases:
  1943. problems.append(f"current_phase {current} is not in phases")
  1944. now = [
  1945. k
  1946. for k, v in phases.items()
  1947. if isinstance(v, dict) and v.get("status") == "current"
  1948. ]
  1949. if len(now) != 1:
  1950. found = f" ({', '.join(now)})" if now else ""
  1951. problems.append(
  1952. f"exactly one phase must have status current, found {len(now)}{found}"
  1953. )
  1954. elif now[0] != current:
  1955. problems.append(
  1956. f"phase {now[0]} has status current but current_phase is {current}"
  1957. )
  1958. problems += lifecycle_order_problems(phases)
  1959. previous = None
  1960. for index, (key, entry) in enumerate(phases.items()):
  1961. if not isinstance(key, str) or not PHASE_ID_RE.match(key):
  1962. problems.append(
  1963. f"phase id {key!r} must be lowercase letters, digits and dashes"
  1964. )
  1965. previous = None
  1966. continue
  1967. if not isinstance(entry, dict):
  1968. problems.append(f"phase {key}: must be an object")
  1969. previous = None
  1970. continue
  1971. ceiling = phase_number(entry.get("ceiling"))
  1972. if ceiling is None:
  1973. problems.append(
  1974. f"phase {key}: ceiling {entry.get('ceiling')!r} must be a finite number, zero or more"
  1975. )
  1976. reason = entry.get("reason")
  1977. if not isinstance(reason, str) or not reason.strip():
  1978. problems.append(f"phase {key}: reason must be a non-empty string")
  1979. if not phase_date_ok(entry.get("decided")):
  1980. problems.append(
  1981. f"phase {key}: decided {entry.get('decided')!r} must be an ISO date (YYYY-MM-DD)"
  1982. )
  1983. if entry.get("status") not in PHASE_STATUSES:
  1984. problems.append(
  1985. f"phase {key}: status {entry.get('status')!r} must be one of {', '.join(PHASE_STATUSES)}"
  1986. )
  1987. lowers = entry.get("lowers", False)
  1988. if not isinstance(lowers, bool):
  1989. problems.append(f"phase {key}: lowers must be true or false")
  1990. lowers = False
  1991. if ceiling is not None and hard_max is not None and ceiling > hard_max:
  1992. problems.append(
  1993. f"phase {key}: ceiling ${ceiling:.2f} is above hard_max ${hard_max:.2f}"
  1994. )
  1995. if lowers and previous is None and index == 0:
  1996. problems.append(
  1997. f"phase {key}: marked lowers but it is the first phase, nothing comes before it"
  1998. )
  1999. if ceiling is not None and previous is not None:
  2000. prev_key, prev_ceiling = previous
  2001. decreased = ceiling < prev_ceiling
  2002. if decreased and not lowers:
  2003. problems.append(
  2004. f"phase {key}: ceiling ${ceiling:.2f} is below {prev_key} ${prev_ceiling:.2f}; "
  2005. 'a lower ceiling needs "lowers": true and a reason'
  2006. )
  2007. if lowers and not decreased:
  2008. problems.append(
  2009. f"phase {key}: marked lowers but the ceiling does not go below {prev_key} ${prev_ceiling:.2f}"
  2010. )
  2011. previous = (key, ceiling) if ceiling is not None else None
  2012. problems += finished_phase_problems(phases, current)
  2013. return problems
  2014. def approval_problems(approved, totals, parts=None):
  2015. """Per-provider approval and the current phase's ceiling. `parts` is site_totals()."""
  2016. problems = phase_problems(approved)
  2017. parts = parts or {}
  2018. try:
  2019. ceiling = current_ceiling(approved)[1]
  2020. except ValueError:
  2021. return problems or ["approved.json has no usable ceiling"]
  2022. providers = approved["providers"]
  2023. for provider in totals:
  2024. if provider not in providers:
  2025. problems.append(
  2026. f"provider {provider} has a manifest but no entry in approved.json"
  2027. )
  2028. active = 0.0
  2029. for provider, entry in providers.items():
  2030. cap = money(entry["approved_monthly_total"], f"{provider} approved_monthly_total")
  2031. if cap > ceiling:
  2032. problems.append(
  2033. f"{provider}: approved ${cap:.2f} is above the ceiling ${ceiling:.2f}"
  2034. )
  2035. if entry.get("active"):
  2036. active += cap
  2037. planned = totals.get(provider, 0.0)
  2038. if planned > cap:
  2039. problems.append(
  2040. f"{provider}: planned ${planned:.2f} is above approved ${cap:.2f}"
  2041. )
  2042. problems += sites_problems(provider, entry, cap, parts.get(provider, {}))
  2043. if active > ceiling:
  2044. problems.append(
  2045. f"the approved figures of the active providers add up to ${active:.2f}, above the shared ceiling ${ceiling:.2f}; "
  2046. "mark one inactive or lower an approval"
  2047. )
  2048. return problems
  2049. def allowed_sources(approved):
  2050. merged = {}
  2051. for entry in approved["providers"].values():
  2052. for kind, files in entry.get("allowed_sources", {}).items():
  2053. merged.setdefault(kind, []).extend(files)
  2054. return merged
  2055. def fmt_effective(pair):
  2056. return "unreadable" if pair is None else f"phase {pair[0]} ${pair[1]:.2f}"
  2057. def gate_problems(root, approved, plan=None, stack=None):
  2058. """Every problem the gate finds and the per-provider totals. Raises
  2059. ValueError/KeyError/TypeError/IndexError/AttributeError on unreadable input."""
  2060. parts = site_totals(root)
  2061. totals = {p: round(sum(v.values()), 2) for p, v in parts.items()}
  2062. problems = [
  2063. f"resource type not on the free list, not approved, or outside its allowed file: {item}"
  2064. for item in uncosted_sources(
  2065. root, allowed_sources(approved), set(approved["providers"])
  2066. )
  2067. ]
  2068. problems += structure_problems(root)
  2069. problems += approval_problems(approved, totals, parts)
  2070. if plan:
  2071. if not stack:
  2072. problems.append("--plan needs --stack")
  2073. else:
  2074. problems += plan_problems(plan, stack, root)
  2075. return problems, totals
  2076. def main(argv=None):
  2077. parser = argparse.ArgumentParser(
  2078. description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
  2079. )
  2080. parser.add_argument("--root", default=".")
  2081. parser.add_argument(
  2082. "--plan",
  2083. help="OpenTofu plan as JSON (tofu show -json), costed and compared with the manifest",
  2084. )
  2085. parser.add_argument(
  2086. "--stack",
  2087. help="the stack directory the --plan belongs to, for example stacks/aws/10-access",
  2088. )
  2089. parser.add_argument(
  2090. "--base-approved",
  2091. help="the merge base's docs/stages/approved.json; checks the phase lifecycle (planned, current, done) and reports a change of the effective ceiling",
  2092. )
  2093. args = parser.parse_args(argv)
  2094. root = Path(args.root)
  2095. try:
  2096. approved = load_json(root / "docs/stages/approved.json")
  2097. base = load_json(args.base_approved) if args.base_approved else None
  2098. except (OSError, ValueError) as err:
  2099. print(f"cost-check: unreadable approved.json: {err}", file=sys.stderr)
  2100. return 1
  2101. try:
  2102. problems, totals = gate_problems(root, approved, args.plan, args.stack)
  2103. except (ValueError, KeyError, TypeError, IndexError, AttributeError, OverflowError) as err:
  2104. print(
  2105. f"cost-check: unreadable manifest, price table, approval or plan input: {err!r}",
  2106. file=sys.stderr,
  2107. )
  2108. return 1
  2109. if base is not None:
  2110. problems += transition_problems(base, approved)
  2111. was, now = effective_change(base, approved)
  2112. if was != now:
  2113. print(
  2114. f"cost-check: EFFECTIVE CEILING CHANGED: {fmt_effective(was)} -> {fmt_effective(now)}"
  2115. )
  2116. for provider, total in sorted(totals.items()):
  2117. entry = approved["providers"].get(provider, {})
  2118. state = (
  2119. "active"
  2120. if entry.get("active")
  2121. else "inactive (the maintainer attests it is not applied)"
  2122. )
  2123. print(
  2124. f"cost-check: {provider}: planned ${total:.2f}/mo, approved ${float(entry.get('approved_monthly_total', 0.0)):.2f}, {state}"
  2125. )
  2126. try:
  2127. phase_id, phase_ceiling, phase_reason = current_ceiling(approved)
  2128. print(
  2129. f"cost-check: phase {phase_id} ceiling ${phase_ceiling:.2f} (reason: {phase_reason})"
  2130. )
  2131. except ValueError:
  2132. pass # approval_problems() already reported why
  2133. for problem in problems:
  2134. print(f"cost-check: {problem}", file=sys.stderr)
  2135. return 1 if problems else 0
  2136. if __name__ == "__main__":
  2137. sys.exit(main())