@intentius/chant-lexicon-terraform 0.124.52 → 0.124.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (336) hide show
  1. package/README.md +7 -6
  2. package/dist/__fixtures__/pr-loop/estate.component.d.ts +7 -0
  3. package/dist/__fixtures__/pr-loop/estate.component.d.ts.map +1 -0
  4. package/dist/__fixtures__/pr-loop/estate.component.js +7 -0
  5. package/dist/__fixtures__/report/generate.d.ts +26 -0
  6. package/dist/__fixtures__/report/generate.d.ts.map +1 -0
  7. package/dist/__fixtures__/report/generate.js +58 -0
  8. package/dist/applied-state.d.ts +27 -0
  9. package/dist/applied-state.d.ts.map +1 -0
  10. package/dist/applied-state.js +44 -0
  11. package/dist/backend-config.d.ts +53 -0
  12. package/dist/backend-config.d.ts.map +1 -0
  13. package/dist/backend-config.js +136 -0
  14. package/dist/behaviour/kinds.d.ts.map +1 -1
  15. package/dist/behaviour/kinds.js +4 -0
  16. package/dist/behaviour/predict.d.ts.map +1 -1
  17. package/dist/behaviour/predict.js +6 -2
  18. package/dist/behaviour/reference-catalog.d.ts +16 -5
  19. package/dist/behaviour/reference-catalog.d.ts.map +1 -1
  20. package/dist/behaviour/reference-catalog.js +16 -5
  21. package/dist/behaviour/request.d.ts.map +1 -1
  22. package/dist/behaviour/request.js +3 -2
  23. package/dist/changed-roots.d.ts +6 -4
  24. package/dist/changed-roots.d.ts.map +1 -1
  25. package/dist/changed-roots.js +14 -18
  26. package/dist/commands.d.ts.map +1 -1
  27. package/dist/commands.js +4 -3
  28. package/dist/components/capability-plugin.d.ts +65 -3
  29. package/dist/components/capability-plugin.d.ts.map +1 -1
  30. package/dist/components/capability-plugin.js +197 -13
  31. package/dist/components/compose-group.d.ts +145 -0
  32. package/dist/components/compose-group.d.ts.map +1 -0
  33. package/dist/components/compose-group.js +407 -0
  34. package/dist/components/placeholder-preview.d.ts +78 -0
  35. package/dist/components/placeholder-preview.d.ts.map +1 -0
  36. package/dist/components/placeholder-preview.js +254 -0
  37. package/dist/compose/apply-events.d.ts +46 -0
  38. package/dist/compose/apply-events.d.ts.map +1 -0
  39. package/dist/compose/apply-events.js +77 -0
  40. package/dist/compose/estate.d.ts +194 -0
  41. package/dist/compose/estate.d.ts.map +1 -0
  42. package/dist/compose/estate.js +363 -0
  43. package/dist/compose/hcl.d.ts +99 -0
  44. package/dist/compose/hcl.d.ts.map +1 -0
  45. package/dist/compose/hcl.js +302 -0
  46. package/dist/compose/module-address.d.ts +24 -0
  47. package/dist/compose/module-address.d.ts.map +1 -0
  48. package/dist/compose/module-address.js +43 -0
  49. package/dist/compose/root.d.ts +127 -0
  50. package/dist/compose/root.d.ts.map +1 -0
  51. package/dist/compose/root.js +586 -0
  52. package/dist/compose/run.d.ts +183 -0
  53. package/dist/compose/run.d.ts.map +1 -0
  54. package/dist/compose/run.js +447 -0
  55. package/dist/compose/slice.d.ts +102 -0
  56. package/dist/compose/slice.d.ts.map +1 -0
  57. package/dist/compose/slice.js +249 -0
  58. package/dist/compose/state-address.d.ts +28 -0
  59. package/dist/compose/state-address.d.ts.map +1 -0
  60. package/dist/compose/state-address.js +154 -0
  61. package/dist/compose/state-merge.d.ts +52 -0
  62. package/dist/compose/state-merge.d.ts.map +1 -0
  63. package/dist/compose/state-merge.js +135 -0
  64. package/dist/compose.d.ts +179 -0
  65. package/dist/compose.d.ts.map +1 -0
  66. package/dist/compose.js +482 -0
  67. package/dist/composites/terraform-apply-op.d.ts.map +1 -1
  68. package/dist/composites/terraform-apply-op.js +7 -3
  69. package/dist/config.d.ts +59 -13
  70. package/dist/config.d.ts.map +1 -1
  71. package/dist/config.js +43 -9
  72. package/dist/describe-resources.d.ts +74 -12
  73. package/dist/describe-resources.d.ts.map +1 -1
  74. package/dist/describe-resources.js +374 -66
  75. package/dist/drift-read.d.ts +33 -0
  76. package/dist/drift-read.d.ts.map +1 -0
  77. package/dist/drift-read.js +243 -0
  78. package/dist/drift-record.d.ts +147 -0
  79. package/dist/drift-record.d.ts.map +1 -0
  80. package/dist/drift-record.js +383 -0
  81. package/dist/hcl/edges.d.ts.map +1 -1
  82. package/dist/hcl/edges.js +24 -1
  83. package/dist/hcl/files.d.ts +61 -0
  84. package/dist/hcl/files.d.ts.map +1 -0
  85. package/dist/hcl/files.js +221 -0
  86. package/dist/hcl/instances.d.ts +82 -0
  87. package/dist/hcl/instances.d.ts.map +1 -0
  88. package/dist/hcl/instances.js +390 -0
  89. package/dist/hcl/parse.d.ts +81 -9
  90. package/dist/hcl/parse.d.ts.map +1 -1
  91. package/dist/hcl/parse.js +114 -16
  92. package/dist/hcl/roots.d.ts.map +1 -1
  93. package/dist/hcl/roots.js +5 -0
  94. package/dist/hcl/suppressions.d.ts.map +1 -1
  95. package/dist/hcl/suppressions.js +8 -2
  96. package/dist/index.d.ts +11 -2
  97. package/dist/index.d.ts.map +1 -1
  98. package/dist/index.js +21 -2
  99. package/dist/integrity.json +3 -3
  100. package/dist/live-plan-reasons.d.ts +21 -0
  101. package/dist/live-plan-reasons.d.ts.map +1 -0
  102. package/dist/live-plan-reasons.js +47 -0
  103. package/dist/lsp/option-keys.d.ts.map +1 -1
  104. package/dist/lsp/option-keys.js +2 -0
  105. package/dist/manifest.json +1 -1
  106. package/dist/op/activities/index.d.ts +6 -2
  107. package/dist/op/activities/index.d.ts.map +1 -1
  108. package/dist/op/activities/index.js +5 -1
  109. package/dist/op/activities/live-detect.d.ts +4 -3
  110. package/dist/op/activities/live-detect.d.ts.map +1 -1
  111. package/dist/op/activities/live-detect.js +57 -32
  112. package/dist/op/activities/pin-rollout.d.ts +2 -0
  113. package/dist/op/activities/pin-rollout.d.ts.map +1 -1
  114. package/dist/op/activities/pin-rollout.js +1 -0
  115. package/dist/op/activities/terraform.d.ts +153 -5
  116. package/dist/op/activities/terraform.d.ts.map +1 -1
  117. package/dist/op/activities/terraform.js +205 -20
  118. package/dist/op/activity-contracts.d.ts +27 -0
  119. package/dist/op/activity-contracts.d.ts.map +1 -1
  120. package/dist/op/activity-contracts.js +19 -1
  121. package/dist/op/builders.d.ts +7 -1
  122. package/dist/op/builders.d.ts.map +1 -1
  123. package/dist/op/builders.js +9 -0
  124. package/dist/pin/edit.d.ts.map +1 -1
  125. package/dist/pin/edit.js +35 -0
  126. package/dist/pin/rollout.d.ts +2 -0
  127. package/dist/pin/rollout.d.ts.map +1 -1
  128. package/dist/pin/rollout.js +14 -11
  129. package/dist/plan-shape.d.ts +30 -0
  130. package/dist/plan-shape.d.ts.map +1 -0
  131. package/dist/plan-shape.js +125 -0
  132. package/dist/plugin.d.ts.map +1 -1
  133. package/dist/plugin.js +32 -18
  134. package/dist/report.d.ts +15 -6
  135. package/dist/report.d.ts.map +1 -1
  136. package/dist/report.js +28 -55
  137. package/dist/skills/chant-terraform.md +1 -1
  138. package/dist/state/azure-blob.d.ts +68 -0
  139. package/dist/state/azure-blob.d.ts.map +1 -0
  140. package/dist/state/azure-blob.js +201 -0
  141. package/dist/state/backend.d.ts +158 -0
  142. package/dist/state/backend.d.ts.map +1 -0
  143. package/dist/state/backend.js +406 -0
  144. package/dist/state/exec.d.ts +39 -0
  145. package/dist/state/exec.d.ts.map +1 -0
  146. package/dist/state/exec.js +80 -0
  147. package/dist/state/gcs.d.ts +62 -0
  148. package/dist/state/gcs.d.ts.map +1 -0
  149. package/dist/state/gcs.js +224 -0
  150. package/dist/state/index.d.ts +15 -0
  151. package/dist/state/index.d.ts.map +1 -0
  152. package/dist/state/index.js +14 -0
  153. package/dist/state/locks.d.ts +105 -0
  154. package/dist/state/locks.d.ts.map +1 -0
  155. package/dist/state/locks.js +130 -0
  156. package/dist/state/object-store.d.ts +37 -0
  157. package/dist/state/object-store.d.ts.map +1 -0
  158. package/dist/state/object-store.js +20 -0
  159. package/dist/state/root-states.d.ts +131 -0
  160. package/dist/state/root-states.d.ts.map +1 -0
  161. package/dist/state/root-states.js +241 -0
  162. package/dist/state/s3.d.ts +68 -0
  163. package/dist/state/s3.d.ts.map +1 -0
  164. package/dist/state/s3.js +170 -0
  165. package/dist/state/store.d.ts +51 -0
  166. package/dist/state/store.d.ts.map +1 -0
  167. package/dist/state/store.js +185 -0
  168. package/dist/terragrunt/affected.d.ts.map +1 -1
  169. package/dist/terragrunt/affected.js +2 -1
  170. package/package.json +7 -3
  171. package/src/__fixtures__/ACCEPTANCE.md +69 -7
  172. package/src/__fixtures__/compose/apply-failed-in-app.jsonl +12 -0
  173. package/src/__fixtures__/compose/state-app.json +66 -0
  174. package/src/__fixtures__/compose/state-edge.json +40 -0
  175. package/src/__fixtures__/compose/state-net.json +58 -0
  176. package/src/__fixtures__/compose/three-app.plan.json +184 -0
  177. package/src/__fixtures__/compose/three-composed.plan.json +509 -0
  178. package/src/__fixtures__/compose/three-edge.plan.json +144 -0
  179. package/src/__fixtures__/compose/three-net.plan.json +174 -0
  180. package/src/__fixtures__/compose/unknown-composed.plan.json +228 -0
  181. package/src/__fixtures__/compose/working-after-apply.json +145 -0
  182. package/src/__fixtures__/config-blocks/app/main.tf +61 -0
  183. package/src/__fixtures__/config-blocks/app/modules/network/main.tf +4 -0
  184. package/src/__fixtures__/config-blocks/app-json/main.tf.json +39 -0
  185. package/src/__fixtures__/config-files/shadow/main.tf +3 -0
  186. package/src/__fixtures__/config-files/shadow/main.tofu +3 -0
  187. package/src/__fixtures__/config-files/shadow/other.tf +3 -0
  188. package/src/__fixtures__/config-files/tf/main.tf +11 -0
  189. package/src/__fixtures__/config-files/tf-json/main.tf.json +18 -0
  190. package/src/__fixtures__/config-files/tofu/main.tofu +11 -0
  191. package/src/__fixtures__/config-files/tofu-json/main.tofu.json +18 -0
  192. package/src/__fixtures__/config-files/tofu-only/main.tofu +3 -0
  193. package/src/__fixtures__/drift-record/README.md +11 -0
  194. package/src/__fixtures__/drift-record/live-plan-sections.json +27 -0
  195. package/src/__fixtures__/instance-forms/app/main.tf +110 -0
  196. package/src/__fixtures__/instance-forms/app/modules/svc/main.tf +3 -0
  197. package/src/__fixtures__/instance-vars/app/main.tf +52 -0
  198. package/src/__fixtures__/instance-vars/app/modules/app/main.tf +12 -0
  199. package/src/__fixtures__/instance-vars/app/modules/edge/main.tf +3 -0
  200. package/src/__fixtures__/instance-vars/app/terraform.tfvars +1 -0
  201. package/src/__fixtures__/live-module-keyed/live-graph.json +259 -0
  202. package/src/__fixtures__/live-module-keyed/live-plan.json +87 -0
  203. package/src/__fixtures__/live-module-keyed/root/estate.chdf.hcl +1 -0
  204. package/src/__fixtures__/live-module-keyed/root/main.tf +21 -0
  205. package/src/__fixtures__/live-module-keyed/root/modules/app/main.tf +17 -0
  206. package/src/__fixtures__/live-module-keyed/root/modules/edge/main.tf +7 -0
  207. package/src/__fixtures__/live-module-keyed/root/versions.tf +30 -0
  208. package/src/__fixtures__/live-module-keyed/show-state.json +146 -0
  209. package/src/__fixtures__/pr-loop/README.md +50 -0
  210. package/src/__fixtures__/pr-loop/chant.config.json +13 -0
  211. package/src/__fixtures__/pr-loop/estate.component.ts +10 -0
  212. package/src/__fixtures__/pr-loop/roots/a/main.tf +11 -0
  213. package/src/__fixtures__/pr-loop/roots/app/main.tf +19 -0
  214. package/src/__fixtures__/pr-loop/roots/b/main.tf +7 -0
  215. package/src/__fixtures__/pr-loop/roots/dns/main.tf +3 -0
  216. package/src/__fixtures__/pr-loop/roots/net/main.tf +7 -0
  217. package/src/__fixtures__/report/applied.show.json +51 -0
  218. package/src/__fixtures__/report/generate.ts +63 -0
  219. package/src/__fixtures__/report/plan.show.json +200 -0
  220. package/src/__fixtures__/report/tf-apply/change-set.json +170 -0
  221. package/src/__fixtures__/report/tf-apply/report.json +338 -0
  222. package/src/__fixtures__/report/tf-plan/change-set.json +170 -0
  223. package/src/__fixtures__/report/tf-plan/report.json +320 -0
  224. package/src/__fixtures__/three-cloud-azure.graph.json +290 -0
  225. package/src/applied-state.ts +52 -0
  226. package/src/backend-config.test.ts +105 -0
  227. package/src/backend-config.ts +133 -0
  228. package/src/behaviour/kinds.ts +4 -0
  229. package/src/behaviour/predict.ts +5 -2
  230. package/src/behaviour/reference-catalog.plugin.test.ts +65 -0
  231. package/src/behaviour/reference-catalog.ts +16 -5
  232. package/src/behaviour/request.ts +3 -2
  233. package/src/change-set-instances.test.ts +98 -0
  234. package/src/changed-roots.ts +14 -16
  235. package/src/commands.ts +4 -3
  236. package/src/components/capability-plugin.test.ts +172 -5
  237. package/src/components/capability-plugin.ts +212 -11
  238. package/src/components/change-set-graph.e2e.test.ts +11 -5
  239. package/src/components/compose-group.test.ts +486 -0
  240. package/src/components/compose-group.ts +489 -0
  241. package/src/components/demo-composed-roots.e2e.test.ts +440 -0
  242. package/src/components/member-outputs.test.ts +76 -0
  243. package/src/components/placeholder-preview.test.ts +147 -0
  244. package/src/components/placeholder-preview.ts +257 -0
  245. package/src/components/pr-loop-compose.tofu.e2e.test.ts +363 -0
  246. package/src/components/pr-loop.tofu.test.ts +112 -56
  247. package/src/compose/apply-events.test.ts +62 -0
  248. package/src/compose/apply-events.ts +100 -0
  249. package/src/compose/estate.choudoufu.e2e.test.ts +112 -0
  250. package/src/compose/estate.test.ts +421 -0
  251. package/src/compose/estate.ts +443 -0
  252. package/src/compose/hcl.ts +311 -0
  253. package/src/compose/module-address.ts +49 -0
  254. package/src/compose/root.test.ts +416 -0
  255. package/src/compose/root.ts +592 -0
  256. package/src/compose/run.test.ts +440 -0
  257. package/src/compose/run.tofu.test.ts +176 -0
  258. package/src/compose/run.ts +527 -0
  259. package/src/compose/slice.test.ts +184 -0
  260. package/src/compose/slice.ts +290 -0
  261. package/src/compose/state-address.ts +157 -0
  262. package/src/compose/state-merge.test.ts +131 -0
  263. package/src/compose/state-merge.ts +148 -0
  264. package/src/compose.test.ts +248 -0
  265. package/src/compose.ts +627 -0
  266. package/src/composites/terraform-apply-op.test.ts +9 -0
  267. package/src/composites/terraform-apply-op.ts +7 -3
  268. package/src/config-file-listers.test.ts +265 -0
  269. package/src/config.ts +44 -9
  270. package/src/describe-resources.engine-facts.test.ts +412 -0
  271. package/src/describe-resources.live-module-keyed.test.ts +290 -0
  272. package/src/describe-resources.ts +416 -70
  273. package/src/drift-read.ts +284 -0
  274. package/src/drift-record.test.ts +223 -0
  275. package/src/drift-record.ts +455 -0
  276. package/src/hcl/config-blocks.test.ts +174 -0
  277. package/src/hcl/edges.ts +21 -1
  278. package/src/hcl/files.ts +234 -0
  279. package/src/hcl/instance-forms.test.ts +94 -0
  280. package/src/hcl/instances.test.ts +137 -0
  281. package/src/hcl/instances.ts +422 -0
  282. package/src/hcl/parse.test.ts +139 -1
  283. package/src/hcl/parse.ts +149 -16
  284. package/src/hcl/roots.ts +6 -0
  285. package/src/hcl/suppressions.ts +8 -2
  286. package/src/index.ts +76 -0
  287. package/src/live-plan-reasons.ts +54 -0
  288. package/src/lsp/completions.test.ts +1 -1
  289. package/src/lsp/option-keys.ts +2 -0
  290. package/src/op/activities/choudoufu-plan-set-op.test.ts +111 -0
  291. package/src/op/activities/index.ts +9 -0
  292. package/src/op/activities/live-detect.ts +55 -26
  293. package/src/op/activities/pin-rollout.ts +3 -0
  294. package/src/op/activities/registry.test.ts +2 -1
  295. package/src/op/activities/terraform.test.ts +55 -0
  296. package/src/op/activities/terraform.ts +266 -22
  297. package/src/op/activity-contracts.test.ts +1 -0
  298. package/src/op/activity-contracts.ts +24 -1
  299. package/src/op/builders.ts +14 -0
  300. package/src/pin/bundle.test.ts +2 -0
  301. package/src/pin/edit.ts +30 -0
  302. package/src/pin/rollout.ts +16 -11
  303. package/src/plan-shape.test.ts +148 -0
  304. package/src/plan-shape.ts +128 -0
  305. package/src/plugin.ts +33 -19
  306. package/src/report.test.ts +82 -1
  307. package/src/report.ts +31 -54
  308. package/src/signal-only-root.test.ts +72 -0
  309. package/src/skills/chant-terraform.md +1 -1
  310. package/src/state/azure-blob.ts +223 -0
  311. package/src/state/backend-verdict.test.ts +187 -0
  312. package/src/state/backend.test.ts +127 -0
  313. package/src/state/backend.ts +488 -0
  314. package/src/state/exec.ts +111 -0
  315. package/src/state/gcs.ts +254 -0
  316. package/src/state/index.ts +15 -0
  317. package/src/state/locks.test.ts +84 -0
  318. package/src/state/locks.ts +201 -0
  319. package/src/state/object-store.ts +35 -0
  320. package/src/state/root-states-floci.e2e.test.ts +66 -0
  321. package/src/state/root-states.test.ts +462 -0
  322. package/src/state/root-states.ts +309 -0
  323. package/src/state/s3.ts +193 -0
  324. package/src/state/store.ts +225 -0
  325. package/src/terragrunt/affected.ts +2 -1
  326. package/src/workspace-kinds.test.ts +4 -17
  327. package/workspace-kinds.json +1 -24
  328. package/dist/workspace-member.d.ts +0 -30
  329. package/dist/workspace-member.d.ts.map +0 -1
  330. package/dist/workspace-member.js +0 -91
  331. package/schemas/pulumi.schema.json +0 -34
  332. package/src/testdata/pulumi-member/Pulumi.yaml +0 -2
  333. package/src/testdata/pulumi-member/stack-export.json +0 -53
  334. package/src/testdata/pulumi-unexported/Pulumi.yaml +0 -2
  335. package/src/workspace-member.test.ts +0 -89
  336. package/src/workspace-member.ts +0 -126
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Where a root's state is (#4437). Carried over from terragucci at c493e0e:
3
+ * test/state-versions.test.ts "where a root's state is" and
4
+ * test/state-stores.test.ts "where a gcs or azurerm root's state is", with
5
+ * the refusals chant adds (no lock file, a cloud block, any other backend).
6
+ */
7
+ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
9
+ import { tmpdir } from "node:os";
10
+ import { dirname, join } from "node:path";
11
+ import { describe, expect, it } from "vitest";
12
+ import { initialisedBackend, isRefused, s3StateKey, stateLocation, stateObject, workspaceOf } from "./backend";
13
+
14
+ const tmp = (): string => mkdtempSync(join(tmpdir(), "chant-state-"));
15
+ const write = (dir: string, files: Record<string, string>): string => {
16
+ for (const [f, text] of Object.entries(files)) {
17
+ mkdirSync(dirname(join(dir, f)), { recursive: true });
18
+ writeFileSync(join(dir, f), text);
19
+ }
20
+ return dir;
21
+ };
22
+ /** A root whose `.terraform` records `type` and `config`, as init leaves it. */
23
+ const initialised = (type: string, config: Record<string, unknown>, files: Record<string, string> = {}): string =>
24
+ write(tmp(), { ".terraform/terraform.tfstate": JSON.stringify({ version: 3, backend: { type, config, hash: 1 } }), ...files });
25
+
26
+ const ENV = { AWS_ACCESS_KEY_ID: "AK", AWS_SECRET_ACCESS_KEY: "SK", AWS_REGION: "us-east-1" };
27
+ const S3_CONFIG = { bucket: "acme-state", key: "envs/dev/platform.tfstate", region: "eu-west-1", use_lockfile: true, endpoints: { s3: "http://floci:4566", dynamodb: null }, access_key: null, workspace_key_prefix: null };
28
+ const GCS = { bucket: "acme-state", prefix: "envs/dev/app", storage_custom_endpoint: "http://gcs.test/storage/v1/", access_token: "backend-token" };
29
+ const AZ = { storage_account_name: "acme", container_name: "tfstate", key: "app.tfstate", access_key: Buffer.from("key").toString("base64") };
30
+
31
+ describe("where an s3 or local root's state is", () => {
32
+ it("reads the backend init recorded, s3 with its bucket, key, region and endpoint", () => {
33
+ const dir = initialised("s3", S3_CONFIG);
34
+ expect(initialisedBackend(dir)?.type).toBe("s3");
35
+ const o = stateObject(dir, ENV);
36
+ expect(o).toMatchObject({ backend: "s3", bucket: "acme-state", key: "envs/dev/platform.tfstate", region: "eu-west-1", endpoint: "http://floci:4566", lockfile: true });
37
+ expect(stateLocation(o)).toBe("s3://acme-state/envs/dev/platform.tfstate");
38
+ });
39
+
40
+ it("takes the endpoint from AWS_ENDPOINT_URL when the backend names none, and the key of another workspace", () => {
41
+ const dir = initialised("s3", { ...S3_CONFIG, endpoints: null, workspace_key_prefix: "ws" });
42
+ expect(stateObject(dir, { ...ENV, AWS_ENDPOINT_URL: "http://floci:4566/", TF_WORKSPACE: "blue" })).toMatchObject({ endpoint: "http://floci:4566", key: "ws/blue/envs/dev/platform.tfstate" });
43
+ expect(s3StateKey("k", "default")).toBe("k");
44
+ expect(s3StateKey("k", "green")).toBe("env:/green/k");
45
+ });
46
+
47
+ it("reads the workspace select recorded, and TF_DATA_DIR in place of .terraform", () => {
48
+ const dir = write(tmp(), { "data/terraform.tfstate": JSON.stringify({ backend: { type: "s3", config: S3_CONFIG } }), "data/environment": "green\n" });
49
+ expect(workspaceOf(dir, { TF_DATA_DIR: "data" })).toBe("green");
50
+ expect(stateObject(dir, { ...ENV, TF_DATA_DIR: "data" })).toMatchObject({ key: "env:/green/envs/dev/platform.tfstate" });
51
+ });
52
+
53
+ it("signs with the backend's own static keys when its configuration names them", () => {
54
+ const o = stateObject(initialised("s3", { ...S3_CONFIG, access_key: "BACKENDKEY", secret_key: "s" }), ENV);
55
+ expect(o).toMatchObject({ target: { accessKeyId: "BACKENDKEY", secretAccessKey: "s" } });
56
+ });
57
+
58
+ it("is a local file when init recorded no backend or a local one", () => {
59
+ expect(stateObject(tmp(), ENV)).toEqual({ backend: "local", path: "terraform.tfstate" });
60
+ expect(stateObject(initialised("local", { path: "state/x.tfstate" }), ENV)).toEqual({ backend: "local", path: "state/x.tfstate" });
61
+ expect(stateObject(initialised("local", {}), { TF_WORKSPACE: "blue" })).toEqual({ backend: "local", path: join("terraform.tfstate.d", "blue", "terraform.tfstate") });
62
+ });
63
+ });
64
+
65
+ describe("where a gcs or azurerm root's state is", () => {
66
+ it("names a gcs state <prefix>/<workspace>.tfstate, its lock beside it, with the backend's own credentials first", () => {
67
+ expect(stateObject(initialised("gcs", GCS), { GOOGLE_APPLICATION_CREDENTIALS: "/job/creds.json" })).toMatchObject({ backend: "gcs", bucket: "acme-state", key: "envs/dev/app/default.tfstate", lock: "envs/dev/app/default.tflock", target: { endpoint: "http://gcs.test", accessToken: "backend-token" } });
68
+ expect(stateObject(initialised("gcs", { bucket: "b", prefix: "p/" }), { TF_WORKSPACE: "blue", GOOGLE_APPLICATION_CREDENTIALS: "/job/creds.json" })).toMatchObject({ key: "p/blue.tfstate", lock: "p/blue.tflock", target: { endpoint: "https://storage.googleapis.com", credentialsFile: "/job/creds.json" } });
69
+ expect(stateObject(initialised("gcs", { bucket: "b" }), { GOOGLE_CREDENTIALS: '{"type":"service_account"}' })).toMatchObject({ key: "default.tfstate", target: { credentialsJson: '{"type":"service_account"}' } });
70
+ expect(stateObject(initialised("gcs", { bucket: "b", impersonate_service_account: "sa@p.iam.gserviceaccount.com" }), { GOOGLE_OAUTH_ACCESS_TOKEN: "t" })).toMatchObject({ target: { accessToken: "t", impersonate: "sa@p.iam.gserviceaccount.com" } });
71
+ expect(stateObject(initialised("gcs", { bucket: "b" }), {})).toMatchObject({ backend: "gcs", refused: "credentials" });
72
+ });
73
+
74
+ it("names an azurerm blob by its key, <key>env:<workspace> in another workspace, at the cloud's endpoint, with the key, a SAS or the job's OIDC identity", () => {
75
+ expect(stateObject(initialised("azurerm", AZ), {})).toMatchObject({ backend: "azurerm", account: "acme", container: "tfstate", key: "app.tfstate", endpoint: "https://acme.blob.core.windows.net", auth: { accountKey: AZ.access_key } });
76
+ expect(stateObject(initialised("azurerm", { ...AZ, access_key: null, environment: "usgovernment" }), { TF_WORKSPACE: "blue", ARM_SAS_TOKEN: "sv=x&sig=y" })).toMatchObject({ key: "app.tfstateenv:blue", endpoint: "https://acme.blob.core.usgovcloudapi.net", auth: { sas: "sv=x&sig=y" } });
77
+ const oidc = { ARM_TENANT_ID: "tenant", ARM_CLIENT_ID: "client", ARM_OIDC_TOKEN_FILE_PATH: "/t" };
78
+ expect(stateObject(initialised("azurerm", { ...AZ, access_key: null, snapshot: true }), oidc)).toMatchObject({ snapshot: true, auth: { oidc: { tenantId: "tenant", clientId: "client", tokenFile: "/t", authority: "https://login.microsoftonline.com" } } });
79
+ expect(stateObject(initialised("azurerm", { ...AZ, access_key: null }), {})).toMatchObject({ refused: "credentials" });
80
+ expect(stateObject(initialised("azurerm", { key: "k" }), {})).toMatchObject({ refused: "config", reason: expect.stringContaining("storage_account_name, container_name or key") });
81
+ });
82
+ });
83
+
84
+ describe("a state chant does not lock", () => {
85
+ it("is an s3 backend without use_lockfile, named as such", () => {
86
+ for (const use_lockfile of [undefined, false]) {
87
+ const o = stateObject(initialised("s3", { ...S3_CONFIG, use_lockfile }), ENV);
88
+ expect(o).toMatchObject({ backend: "s3", refused: "no-lockfile", reason: expect.stringContaining("use_lockfile = true is unset") });
89
+ expect(stateLocation(o)).toBeUndefined();
90
+ }
91
+ });
92
+
93
+ it("is a root with a cloud block, in .tf or .tf.json code, or one init recorded as cloud", () => {
94
+ const hcl = write(tmp(), { "main.tf": 'terraform {\n cloud {\n organization = "acme"\n }\n}\n' });
95
+ expect(stateObject(hcl, ENV)).toMatchObject({ refused: "cloud", reason: expect.stringContaining("cloud block") });
96
+ const json = write(tmp(), { "cdk.tf.json": JSON.stringify({ terraform: [{ required_version: ">= 1.10" }, { cloud: { organization: "acme" } }] }) });
97
+ expect(stateObject(json, ENV)).toMatchObject({ refused: "cloud" });
98
+ expect(stateObject(initialised("cloud", { organization: "acme" }), ENV)).toMatchObject({ backend: "cloud", refused: "cloud" });
99
+ // A cloud block added after init recorded s3: the code and the record disagree, and the refusal names both (chant#4478).
100
+ expect(stateObject(initialised("s3", S3_CONFIG, { "main.tf": "terraform {\n cloud {}\n}\n" }), ENV)).toMatchObject({
101
+ refused: "disagree",
102
+ reason: expect.stringContaining("names the cloud backend and init recorded s3"),
103
+ });
104
+ });
105
+
106
+ it("is any other backend, named by its type", () => {
107
+ for (const type of ["pg", "kubernetes", "consul", "http", "remote", "cos"]) {
108
+ const o = stateObject(initialised(type, {}), ENV);
109
+ expect(isRefused(o)).toBe(true);
110
+ expect(o).toMatchObject({ backend: type, refused: "backend", reason: expect.stringContaining(`backend is ${type}`) });
111
+ }
112
+ });
113
+
114
+ it("is an s3 backend without its bucket or key, or without credentials", () => {
115
+ expect(stateObject(initialised("s3", { ...S3_CONFIG, key: null }), ENV)).toMatchObject({ refused: "config" });
116
+ expect(stateObject(initialised("s3", S3_CONFIG), {})).toMatchObject({ refused: "credentials", reason: expect.stringContaining("s3://acme-state") });
117
+ });
118
+ });
119
+
120
+ describe("the state module", () => {
121
+ it("is plain lexicon code: nothing in it imports from @intentius/chant/components", () => {
122
+ const here = dirname(fileURLToPath(import.meta.url));
123
+ const sources = readdirSync(here).filter((f) => f.endsWith(".ts") && !f.endsWith(".test.ts"));
124
+ expect(sources.length).toBeGreaterThan(5);
125
+ for (const f of sources) expect(readFileSync(join(here, f), "utf-8"), f).not.toMatch(/@intentius\/chant\/components/);
126
+ });
127
+ });
@@ -0,0 +1,488 @@
1
+ /**
2
+ * Where an initialised root's state is, read from the backend the binary
3
+ * initialised: `<root>/.terraform/terraform.tfstate` (or
4
+ * `$TF_DATA_DIR/terraform.tfstate`), which `init` writes with the backend's
5
+ * type and its whole configuration, whether the root's code, a
6
+ * `-backend-config` file or the job's flags supplied it. Nothing here reads
7
+ * a state's contents.
8
+ *
9
+ * chant locks and writes four backends: s3 with `use_lockfile`, gcs, azurerm
10
+ * and local. Every other backend, and a root with a `cloud` block, comes back
11
+ * as a {@link StateRefusal} naming why, and is never locked.
12
+ *
13
+ * This is also the one place that answers which backend a root has and
14
+ * whether chant can lock it (chant#4478). Before `init` the answer comes
15
+ * from the root's code with the `-backend-config` pairs over it
16
+ * ({@link declaredBackend}); after, from what `init` recorded. When both
17
+ * exist and disagree the root is refused with a reason naming both
18
+ * ({@link readBackend}, {@link lockRefusal}). The composition's `backend`
19
+ * fallback and the state refusals both call {@link lockRefusal}, so one root
20
+ * gets one verdict.
21
+ *
22
+ * Lifted from terragucci's `backend.ts` (c493e0e): `initialisedBackend`,
23
+ * `dataDir`, `workspaceOf`, `s3StateKey`, `stateObject`, `isStored`,
24
+ * `stateLocation`, and the cloud block check of `migrate.ts`'s `refusal`.
25
+ */
26
+ import { existsSync, readFileSync } from "node:fs";
27
+ import { isAbsolute, join } from "node:path";
28
+ import { AZURE_AUTHORITY, type AzureOidc } from "./azure-blob";
29
+ import { GCS_ENDPOINT, type GcsTarget } from "./gcs";
30
+ import { s3FromEnv, type S3Target } from "./s3";
31
+ import { isJsonConfigFile, listConfigFilesSafe } from "../hcl/files";
32
+ import { blockBody, jsonBlocks, rootTexts } from "../compose/hcl";
33
+ import { backendConfigFileKeys, literalAttributes } from "../backend-config";
34
+
35
+ /** The backend `init` recorded: its type and configuration. */
36
+ export interface InitialisedBackend {
37
+ type: string;
38
+ config: Record<string, unknown>;
39
+ }
40
+
41
+ /** A state in an S3 bucket. */
42
+ export interface S3State {
43
+ backend: "s3";
44
+ bucket: string;
45
+ key: string;
46
+ region: string;
47
+ endpoint?: string;
48
+ /** `use_lockfile = true`: the backend locks with `<key>.tflock` beside the state. */
49
+ lockfile: boolean;
50
+ target: S3Target;
51
+ }
52
+
53
+ /** A state in a GCS bucket: `<prefix>/<workspace>.tfstate`, locked by `<prefix>/<workspace>.tflock`. */
54
+ export interface GcsState {
55
+ backend: "gcs";
56
+ bucket: string;
57
+ key: string;
58
+ lock: string;
59
+ target: GcsTarget;
60
+ }
61
+
62
+ /** How a request to Azure Blob Storage is authorized: an account key, a SAS, or the job's OIDC identity. */
63
+ export type AzureAuth = { accountKey: string } | { sas: string } | { oidc: AzureOidc };
64
+
65
+ /** A state blob in an Azure storage container, locked by a lease on it. */
66
+ export interface AzureState {
67
+ backend: "azurerm";
68
+ account: string;
69
+ container: string;
70
+ key: string;
71
+ /** The backend snapshots the blob before each write (`snapshot = true`). */
72
+ snapshot: boolean;
73
+ /** The account's blob endpoint. */
74
+ endpoint: string;
75
+ auth: AzureAuth;
76
+ }
77
+
78
+ /** A local state file, its path relative to the root (or absolute). */
79
+ export interface LocalState {
80
+ backend: "local";
81
+ path: string;
82
+ }
83
+
84
+ /** Why chant does not lock or write a root's state. */
85
+ export type StateRefusalKind = "cloud" | "no-lockfile" | "backend" | "config" | "credentials" | "disagree";
86
+
87
+ export interface StateRefusal {
88
+ backend: string;
89
+ refused: StateRefusalKind;
90
+ reason: string;
91
+ }
92
+
93
+ /** Where a root's state lives, or why chant does not lock it. */
94
+ export type StateObject = S3State | GcsState | AzureState | LocalState | StateRefusal;
95
+
96
+ /** A state in a bucket or a container. */
97
+ export type StoredState = S3State | GcsState | AzureState;
98
+
99
+ /** A state chant locks and writes. */
100
+ export type LockableState = StoredState | LocalState;
101
+
102
+ export const isRefused = (o: StateObject): o is StateRefusal => "refused" in o;
103
+
104
+ /** Whether the state is in a bucket or a container: s3, gcs or azurerm. */
105
+ export const isStored = (o: StateObject): o is StoredState => !isRefused(o) && o.backend !== "local";
106
+
107
+ /** The backend types whose state chant locks and writes itself, s3 only with `use_lockfile = true` (#4437). The one list (chant#4478). */
108
+ export const LOCKABLE_BACKENDS: readonly string[] = ["s3", "gcs", "azurerm", "local"];
109
+
110
+ /** What a refusal says chant locks, spelled from {@link LOCKABLE_BACKENDS}. */
111
+ export const LOCKS = (() => {
112
+ const names = LOCKABLE_BACKENDS.map((b) => (b === "s3" ? "s3 (with use_lockfile = true)" : b));
113
+ return `chant locks and writes ${names.slice(0, -1).join(", ")} and ${names.at(-1)} states`;
114
+ })();
115
+
116
+ const str = (v: unknown): string | undefined => (typeof v === "string" && v !== "" ? v : undefined);
117
+
118
+ /** The root's data dir: `TF_DATA_DIR` (relative to the root, as the binary run with `-chdir` reads it), else `.terraform`. */
119
+ export function dataDir(dir: string, env: NodeJS.ProcessEnv = process.env): string {
120
+ const d = env.TF_DATA_DIR;
121
+ if (!d) return join(dir, ".terraform");
122
+ return isAbsolute(d) ? d : join(dir, d);
123
+ }
124
+
125
+ /** The backend `init` recorded for the root, or undefined when it has not been initialised with one. */
126
+ export function initialisedBackend(dir: string, env: NodeJS.ProcessEnv = process.env): InitialisedBackend | undefined {
127
+ const file = join(dataDir(dir, env), "terraform.tfstate");
128
+ if (!existsSync(file)) return undefined;
129
+ try {
130
+ const parsed = JSON.parse(readFileSync(file, "utf-8")) as { backend?: { type?: unknown; config?: unknown } };
131
+ const type = str(parsed.backend?.type);
132
+ if (!type) return undefined;
133
+ const config = parsed.backend?.config && typeof parsed.backend.config === "object" ? (parsed.backend.config as Record<string, unknown>) : {};
134
+ return { type, config };
135
+ } catch {
136
+ return undefined;
137
+ }
138
+ }
139
+
140
+ /** The workspace the binary runs in: `TF_WORKSPACE`, else the one `workspace select` recorded, else `default`. */
141
+ export function workspaceOf(dir: string, env: NodeJS.ProcessEnv = process.env): string {
142
+ if (env.TF_WORKSPACE) return env.TF_WORKSPACE;
143
+ const file = join(dataDir(dir, env), "environment");
144
+ if (existsSync(file)) {
145
+ const ws = readFileSync(file, "utf-8").trim();
146
+ if (ws) return ws;
147
+ }
148
+ return "default";
149
+ }
150
+
151
+ /** The S3 key of a workspace's state, as the S3 backend names it: the key in `default`, else `<workspace_key_prefix>/<workspace>/<key>`. */
152
+ export function s3StateKey(key: string, workspace: string, prefix = "env:"): string {
153
+ return workspace === "default" ? key : `${prefix}/${workspace}/${key}`;
154
+ }
155
+
156
+ /** Whether a root's JSON code gives a `terraform` block a `cloud` block, as `terraform.cloud` or a list of terraform blocks. */
157
+ function jsonCloud(doc: unknown): boolean {
158
+ const tf = doc && typeof doc === "object" ? (doc as Record<string, unknown>).terraform : undefined;
159
+ const blocks = Array.isArray(tf) ? tf : tf ? [tf] : [];
160
+ return blocks.some((b) => b && typeof b === "object" && "cloud" in (b as object));
161
+ }
162
+
163
+ /**
164
+ * Whether the root's code has a `cloud` block, over the configuration files
165
+ * `binary` reads: `.tf` and `.tf.json`, plus `.tofu` and `.tofu.json` for a
166
+ * tofu or choudoufu root, from the lexicon's one lister (chant#4457).
167
+ */
168
+ export function hasCloudBlock(dir: string, binary?: string): boolean {
169
+ for (const f of listConfigFilesSafe(dir, binary)) {
170
+ let text: string;
171
+ try {
172
+ text = readFileSync(join(dir, f), "utf-8");
173
+ } catch {
174
+ continue;
175
+ }
176
+ if (!isJsonConfigFile(f)) {
177
+ if (/^\s*cloud\s*\{/m.test(text)) return true;
178
+ continue;
179
+ }
180
+ try {
181
+ if (jsonCloud(JSON.parse(text))) return true;
182
+ } catch {
183
+ // Not JSON: the binary reports it.
184
+ }
185
+ }
186
+ return false;
187
+ }
188
+
189
+ const CLOUD_REASON = "the root has a cloud block, whose state HCP Terraform keeps and locks";
190
+
191
+ /** Where a root's backend is read from, before `init` runs. */
192
+ export interface DeclaredBackendInput {
193
+ /** `terraform.roots.<name>.backendConfig`: the `-backend-config` pairs chant's own init passes, last. */
194
+ backendConfig?: Readonly<Record<string, string>>;
195
+ /** `terraform.roots.<name>.backendConfigFiles`: the backend-config files chant's own init passes before the pairs (chant#4459), relative to the root. */
196
+ backendConfigFiles?: readonly string[];
197
+ /** The job's environment: its `TF_CLI_ARGS` and `TF_CLI_ARGS_init` may carry `-backend-config` flags. */
198
+ env?: NodeJS.ProcessEnv;
199
+ /** `terraform.binary`, which says which of the root's files are its code (chant#4457). */
200
+ binary?: string;
201
+ }
202
+
203
+ /** A `-backend-config` value as init would type it: `true` and `false` are booleans, anything else a string. */
204
+ const typed = (v: string): unknown => (v === "true" ? true : v === "false" ? false : v);
205
+
206
+ /** The `-backend-config` flags in `TF_CLI_ARGS` then `TF_CLI_ARGS_init`, in order: `key=value` pairs, and the paths of backend-config files. */
207
+ export function cliBackendConfig(env: NodeJS.ProcessEnv = {}): { pairs: Record<string, string>; files: string[]; ordered: Array<{ file: string } | { key: string; value: string }> } {
208
+ const pairs: Record<string, string> = {};
209
+ const files: string[] = [];
210
+ const ordered: Array<{ file: string } | { key: string; value: string }> = [];
211
+ const unquote = (t: string): string => t.replace(/^(["'])(.*)\1$/, "$2");
212
+ for (const line of [env.TF_CLI_ARGS, env.TF_CLI_ARGS_init]) {
213
+ const tokens = (line ?? "").match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g) ?? [];
214
+ for (let i = 0; i < tokens.length; i++) {
215
+ const t = unquote(tokens[i]!);
216
+ const flag = /^--?backend-config(?:=(.*))?$/.exec(t);
217
+ if (!flag) continue;
218
+ const value = flag[1] !== undefined ? unquote(flag[1]) : tokens[i + 1] !== undefined ? unquote(tokens[++i]!) : undefined;
219
+ if (value === undefined || value === "") continue;
220
+ const eq = value.indexOf("=");
221
+ if (eq > 0) {
222
+ pairs[value.slice(0, eq)] = value.slice(eq + 1);
223
+ ordered.push({ key: value.slice(0, eq), value: value.slice(eq + 1) });
224
+ } else {
225
+ files.push(value);
226
+ ordered.push({ file: value });
227
+ }
228
+ }
229
+ }
230
+ return { pairs, files, ordered };
231
+ }
232
+
233
+ const plain = (v: unknown): v is string | number | boolean => typeof v === "string" || typeof v === "number" || typeof v === "boolean";
234
+
235
+ /**
236
+ * The backend the root's code declares, with the `-backend-config` flags of
237
+ * `TF_CLI_ARGS`, `TF_CLI_ARGS_init` and then `backendConfig` over it, in the
238
+ * order init applies them: what `init` would record, as far as chant can read
239
+ * it before init runs. A `cloud` block is `{ type: "cloud" }`. Undefined when
240
+ * the code declares neither, which init records as no backend (local).
241
+ */
242
+ export function declaredBackend(dir: string, input: DeclaredBackendInput = {}): InitialisedBackend | undefined {
243
+ let found: InitialisedBackend | undefined;
244
+ for (const { text, json } of rootTexts(dir, input.binary)) {
245
+ if (found) break;
246
+ if (json) {
247
+ let doc: unknown;
248
+ try {
249
+ doc = JSON.parse(text);
250
+ } catch {
251
+ continue;
252
+ }
253
+ for (const t of jsonBlocks(doc, "terraform")) {
254
+ if (t.cloud !== undefined) {
255
+ found = { type: "cloud", config: {} };
256
+ break;
257
+ }
258
+ const backends = t.backend && typeof t.backend === "object" && !Array.isArray(t.backend) ? (t.backend as Record<string, unknown>) : {};
259
+ const type = Object.keys(backends)[0];
260
+ if (!type) continue;
261
+ const raw = backends[type];
262
+ const body = (Array.isArray(raw) ? raw[0] : raw) as Record<string, unknown> | undefined;
263
+ found = { type, config: Object.fromEntries(Object.entries(body ?? {}).filter(([, v]) => plain(v) && !(typeof v === "string" && /\$\{/.test(v)))) };
264
+ break;
265
+ }
266
+ continue;
267
+ }
268
+ const m = text.match(/\bbackend\s+"([^"]+)"\s*\{/);
269
+ if (m) {
270
+ found = { type: m[1]!, config: literalAttributes(blockBody(text, m.index!), 1) };
271
+ break;
272
+ }
273
+ if (/^\s*cloud\s*\{/m.test(text)) found = { type: "cloud", config: {} };
274
+ }
275
+ if (!found || found.type === "cloud") return found;
276
+ // The order init applies them: the job's TF_CLI_ARGS flags first, then the
277
+ // flags chant's own init passes, its files before its pairs (chant#4459).
278
+ // A file's keys are read from it, relative to the root as init reads it.
279
+ const config = { ...found.config };
280
+ for (const flag of cliBackendConfig(input.env).ordered) {
281
+ if ("file" in flag) Object.assign(config, backendConfigFileKeys(dir, [flag.file]).config);
282
+ else config[flag.key] = typed(flag.value);
283
+ }
284
+ Object.assign(config, backendConfigFileKeys(dir, input.backendConfigFiles).config);
285
+ for (const [k, v] of Object.entries(input.backendConfig ?? {})) config[k] = typed(v);
286
+ return { type: found.type, config };
287
+ }
288
+
289
+ /** Configuration keys whose values a reason names but never prints. */
290
+ const SECRET_KEYS = /(^|_)(key|secret|token|password|credentials|sas)($|_)/;
291
+
292
+ const shown = (k: string, v: unknown): string => (SECRET_KEYS.test(k) && k !== "key" ? `${k} (value hidden)` : `${k} = ${JSON.stringify(v)}`);
293
+
294
+ /** A root's backend as both sources give it, and the one the verdict reads. */
295
+ export interface BackendReading {
296
+ /** From the root's code and the `-backend-config` flags, before init. */
297
+ declared?: InitialisedBackend;
298
+ /** What `init` recorded. */
299
+ recorded?: InitialisedBackend;
300
+ /** The recorded backend when there is one, else the declared one, else local. */
301
+ backend: InitialisedBackend;
302
+ /** Why the two disagree, naming both, when both exist and they do. */
303
+ disagreement?: string;
304
+ }
305
+
306
+ /** Where a root's backend is read from: {@link DeclaredBackendInput}, plus what `init` recorded, which the root's data dir holds unless given. */
307
+ export interface ReadBackendInput extends DeclaredBackendInput {
308
+ /** What `init` recorded; `null` for none. Read from the root's data dir when absent. */
309
+ recorded?: InitialisedBackend | null;
310
+ }
311
+
312
+ /**
313
+ * A root's backend from its code and flags and from what `init` recorded,
314
+ * compared (chant#4478). They disagree when both exist and name another type,
315
+ * or when a key both give a plain value has two values; a key only one side
316
+ * gives (a default init filled in, a value from a backend-config file chant
317
+ * did not read) is no disagreement. Code that declares no backend leaves the
318
+ * record to stand.
319
+ */
320
+ export function readBackend(dir: string, input: ReadBackendInput = {}): BackendReading {
321
+ const env = input.env ?? process.env;
322
+ const declared = declaredBackend(dir, input);
323
+ const recorded = input.recorded === undefined ? initialisedBackend(dir, env) : (input.recorded ?? undefined);
324
+ const backend = recorded ?? declared ?? { type: "local", config: {} };
325
+ const out: BackendReading = { ...(declared ? { declared } : {}), ...(recorded ? { recorded } : {}), backend };
326
+ if (!declared || !recorded) return out;
327
+ if (declared.type !== recorded.type) {
328
+ out.disagreement = `the root's code names the ${declared.type} backend and init recorded ${recorded.type}`;
329
+ return out;
330
+ }
331
+ const differ: string[] = [];
332
+ for (const [k, d] of Object.entries(declared.config)) {
333
+ const r = recorded.config[k];
334
+ if (!plain(d) || !plain(r) || String(d) === String(r)) continue;
335
+ differ.push(`${shown(k, d)} in the code and flags, ${shown(k, r)} in what init recorded`);
336
+ }
337
+ if (differ.length > 0) out.disagreement = `the root's ${declared.type} backend has ${differ.join("; ")}`;
338
+ return out;
339
+ }
340
+
341
+ /**
342
+ * Whether chant can lock the root's state, from one {@link BackendReading}:
343
+ * undefined when it can, else the refusal and why. The one verdict the
344
+ * composition's `backend` fallback (#4438) and the state refusals (#4437)
345
+ * both give (chant#4478).
346
+ */
347
+ export function lockRefusal(reading: BackendReading): StateRefusal | undefined {
348
+ const b = reading.backend;
349
+ if (reading.disagreement) return { backend: b.type, refused: "disagree", reason: `${reading.disagreement}, so chant cannot tell which state to lock; run init again with the configuration the root means; ${LOCKS}` };
350
+ if (b.type === "cloud") return { backend: b.type, refused: "cloud", reason: `${CLOUD_REASON}; ${LOCKS}` };
351
+ if (!LOCKABLE_BACKENDS.includes(b.type)) return { backend: b.type, refused: "backend", reason: `the root's backend is ${b.type}; ${LOCKS}` };
352
+ if (b.type === "s3" && b.config.use_lockfile !== true && b.config.use_lockfile !== "true") {
353
+ return { backend: "s3", refused: "no-lockfile", reason: `the s3 backend takes no lock file (use_lockfile = true is unset), so chant cannot hold its lock; ${LOCKS}` };
354
+ }
355
+ return undefined;
356
+ }
357
+
358
+ /**
359
+ * Where the root's state is, or why chant does not lock it, from
360
+ * {@link readBackend}: what `init` recorded (`backend` stands in for it),
361
+ * compared with the root's code, `backendConfigFiles` and `backendConfig`. A root neither declares
362
+ * nor records a backend for reads as a local one.
363
+ */
364
+ export function stateObject(
365
+ dir: string,
366
+ env: NodeJS.ProcessEnv = process.env,
367
+ backend: InitialisedBackend | undefined = initialisedBackend(dir, env),
368
+ binary?: string,
369
+ flags: Pick<DeclaredBackendInput, "backendConfig" | "backendConfigFiles"> = {},
370
+ ): StateObject {
371
+ const reading = readBackend(dir, {
372
+ env,
373
+ recorded: backend ?? null,
374
+ ...(binary ? { binary } : {}),
375
+ ...(flags.backendConfig ? { backendConfig: flags.backendConfig } : {}),
376
+ ...(flags.backendConfigFiles ? { backendConfigFiles: flags.backendConfigFiles } : {}),
377
+ });
378
+ const refusal = lockRefusal(reading);
379
+ if (refusal) return refusal;
380
+ const chosen = reading.backend;
381
+ const ws = workspaceOf(dir, env);
382
+ if (chosen.type === "local") {
383
+ const c = chosen.config;
384
+ const path = ws === "default" ? (str(c.path) ?? "terraform.tfstate") : join(str(c.workspace_dir) ?? "terraform.tfstate.d", ws, "terraform.tfstate");
385
+ return { backend: "local", path };
386
+ }
387
+ if (chosen.type === "gcs") return gcsObject(chosen.config, ws, env);
388
+ if (chosen.type === "azurerm") return azureObject(chosen.config, ws, env);
389
+ const c = chosen.config;
390
+ const bucket = str(c.bucket);
391
+ const key = str(c.key);
392
+ if (!bucket || !key) return { backend: "s3", refused: "config", reason: "the s3 backend's bucket or key is not in its configuration (the code and flags, or what init recorded)" };
393
+ const endpoints = c.endpoints && typeof c.endpoints === "object" ? (c.endpoints as Record<string, unknown>) : {};
394
+ const endpoint = str(endpoints.s3) ?? str(c.endpoint) ?? env.AWS_ENDPOINT_URL_S3 ?? env.AWS_ENDPOINT_URL;
395
+ const region = str(c.region) ?? env.AWS_REGION ?? env.AWS_DEFAULT_REGION ?? "us-east-1";
396
+ const access = str(c.access_key);
397
+ const secret = str(c.secret_key);
398
+ const jobEnv = { ...env, AWS_REGION: region, ...(access && secret ? { AWS_ACCESS_KEY_ID: access, AWS_SECRET_ACCESS_KEY: secret, AWS_SESSION_TOKEN: str(c.token) ?? "" } : {}) };
399
+ let target: S3Target;
400
+ try {
401
+ target = s3FromEnv({ bucket, ...(endpoint ? { endpoint } : {}) }, jobEnv);
402
+ } catch (e) {
403
+ return { backend: "s3", refused: "credentials", reason: `the job has no credentials to read s3://${bucket}: ${(e as Error).message}` };
404
+ }
405
+ return {
406
+ backend: "s3",
407
+ bucket,
408
+ key: s3StateKey(key, ws, str(c.workspace_key_prefix)),
409
+ region,
410
+ ...(endpoint ? { endpoint: endpoint.replace(/\/+$/, "") } : {}),
411
+ lockfile: true,
412
+ target,
413
+ };
414
+ }
415
+
416
+ /** A gcs backend's custom endpoint (`storage_custom_endpoint`, `https://host/storage/v1/`) as the JSON API's address: no path, no trailing slash. */
417
+ const gcsEndpoint = (e: string): string => e.replace(/\/+$/, "").replace(/\/storage\/v1$/, "");
418
+
419
+ /**
420
+ * A gcs backend's state: `<prefix>/<workspace>.tfstate` and its lock beside
421
+ * it, with the credentials the backend would use, first match wins:
422
+ * `access_token` (or GOOGLE_OAUTH_ACCESS_TOKEN), `credentials` (a file or its
423
+ * JSON), GOOGLE_BACKEND_CREDENTIALS, GOOGLE_CREDENTIALS, and
424
+ * GOOGLE_APPLICATION_CREDENTIALS.
425
+ */
426
+ function gcsObject(c: Record<string, unknown>, ws: string, env: NodeJS.ProcessEnv): StateObject {
427
+ const bucket = str(c.bucket);
428
+ if (!bucket) return { backend: "gcs", refused: "config", reason: "the gcs backend's bucket is not in the configuration init recorded" };
429
+ const raw = str(c.prefix) ?? "";
430
+ const prefix = raw === "" || raw.endsWith("/") ? raw : `${raw}/`;
431
+ const endpoint = gcsEndpoint(str(c.storage_custom_endpoint) ?? env.GOOGLE_BACKEND_STORAGE_CUSTOM_ENDPOINT ?? env.GOOGLE_STORAGE_CUSTOM_ENDPOINT ?? GCS_ENDPOINT);
432
+ const impersonate = str(c.impersonate_service_account) ?? env.GOOGLE_BACKEND_IMPERSONATE_SERVICE_ACCOUNT ?? env.GOOGLE_IMPERSONATE_SERVICE_ACCOUNT;
433
+ const where = { bucket, endpoint, ...(impersonate ? { impersonate } : {}) };
434
+ const token = str(c.access_token) ?? env.GOOGLE_OAUTH_ACCESS_TOKEN;
435
+ const creds = str(c.credentials) ?? env.GOOGLE_BACKEND_CREDENTIALS ?? env.GOOGLE_CREDENTIALS;
436
+ let target: GcsTarget;
437
+ if (token) target = { ...where, accessToken: token };
438
+ else if (creds) target = creds.trim().startsWith("{") ? { ...where, credentialsJson: creds } : { ...where, credentialsFile: creds };
439
+ else if (env.GOOGLE_APPLICATION_CREDENTIALS) target = { ...where, credentialsFile: env.GOOGLE_APPLICATION_CREDENTIALS };
440
+ else return { backend: "gcs", refused: "credentials", reason: `the job has no credentials to read gs://${bucket}: set GOOGLE_APPLICATION_CREDENTIALS, GOOGLE_CREDENTIALS or GOOGLE_OAUTH_ACCESS_TOKEN` };
441
+ return { backend: "gcs", bucket, key: `${prefix}${ws}.tfstate`, lock: `${prefix}${ws}.tflock`, target };
442
+ }
443
+
444
+ /** Each Azure cloud's storage suffix and Entra ID, by the azurerm backend's `environment`. */
445
+ const CLOUD_ENDPOINTS: Record<string, { storage: string; authority: string }> = {
446
+ public: { storage: "core.windows.net", authority: AZURE_AUTHORITY },
447
+ china: { storage: "core.chinacloudapi.cn", authority: "https://login.chinacloudapi.cn" },
448
+ usgovernment: { storage: "core.usgovcloudapi.net", authority: "https://login.microsoftonline.us" },
449
+ };
450
+
451
+ /**
452
+ * An azurerm backend's state: the blob `key` in `container_name` of
453
+ * `storage_account_name`, `<key>env:<workspace>` in another workspace, with
454
+ * the credentials the backend would use: `access_key` (ARM_ACCESS_KEY),
455
+ * `sas_token` (ARM_SAS_TOKEN), else the job's OIDC identity. An
456
+ * `environment` other than public, china or usgovernment is refused: its
457
+ * storage suffix would need the metadata lookup terragucci makes and chant
458
+ * does not.
459
+ */
460
+ function azureObject(c: Record<string, unknown>, ws: string, env: NodeJS.ProcessEnv): StateObject {
461
+ const account = str(c.storage_account_name);
462
+ const container = str(c.container_name);
463
+ const base = str(c.key);
464
+ if (!account || !container || !base) return { backend: "azurerm", refused: "config", reason: "the azurerm backend's storage_account_name, container_name or key is not in the configuration init recorded" };
465
+ const key = ws === "default" ? base : `${base}env:${ws}`;
466
+ const cloud = CLOUD_ENDPOINTS[str(c.environment) ?? env.ARM_ENVIRONMENT ?? "public"];
467
+ if (!cloud) return { backend: "azurerm", refused: "config", reason: `the azurerm backend's environment ${str(c.environment) ?? env.ARM_ENVIRONMENT} is not public, china or usgovernment` };
468
+ const accessKey = str(c.access_key) ?? env.ARM_ACCESS_KEY;
469
+ const sas = str(c.sas_token) ?? env.ARM_SAS_TOKEN;
470
+ const tenantId = str(c.tenant_id) ?? env.ARM_TENANT_ID;
471
+ const clientId = str(c.client_id) ?? env.ARM_CLIENT_ID;
472
+ const tokenFile = str(c.oidc_token_file_path) ?? env.ARM_OIDC_TOKEN_FILE_PATH;
473
+ let auth: AzureAuth;
474
+ if (accessKey) auth = { accountKey: accessKey };
475
+ else if (sas) auth = { sas };
476
+ else if (tenantId && clientId && tokenFile) auth = { oidc: { tenantId, clientId, tokenFile, authority: (env.AZURE_AUTHORITY_HOST || cloud.authority).replace(/\/+$/, "") } };
477
+ else return { backend: "azurerm", refused: "credentials", reason: `the job has no credentials to read the container ${container} of ${account}: set ARM_ACCESS_KEY, ARM_SAS_TOKEN, or ARM_TENANT_ID, ARM_CLIENT_ID and ARM_OIDC_TOKEN_FILE_PATH` };
478
+ return { backend: "azurerm", account, container, key, snapshot: c.snapshot === true || env.ARM_SNAPSHOT === "true", endpoint: `https://${account}.blob.${cloud.storage}`, auth };
479
+ }
480
+
481
+ /** `s3://<bucket>/<key>`, `gs://<bucket>/<key>`, `az://<account>/<container>/<key>`, or the local file's path; undefined for a refusal. */
482
+ export function stateLocation(o: StateObject): string | undefined {
483
+ if (isRefused(o)) return undefined;
484
+ if (o.backend === "local") return o.path;
485
+ if (o.backend === "gcs") return `gs://${o.bucket}/${o.key}`;
486
+ if (o.backend === "azurerm") return `az://${o.account}/${o.container}/${o.key}`;
487
+ return `s3://${o.bucket}/${o.key}`;
488
+ }