@intentius/chant-lexicon-terraform 0.124.97 → 0.124.98

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 (104) hide show
  1. package/dist/behaviour/reference-catalog.d.ts +42 -6
  2. package/dist/behaviour/reference-catalog.d.ts.map +1 -1
  3. package/dist/behaviour/reference-catalog.js +169 -8
  4. package/dist/describe-resources.js +1 -1
  5. package/dist/hcl/evaluate.d.ts +151 -0
  6. package/dist/hcl/evaluate.d.ts.map +1 -0
  7. package/dist/hcl/evaluate.js +940 -0
  8. package/dist/hcl/instances.d.ts +11 -1
  9. package/dist/hcl/instances.d.ts.map +1 -1
  10. package/dist/hcl/instances.js +89 -3
  11. package/dist/hcl/parse.d.ts +23 -1
  12. package/dist/hcl/parse.d.ts.map +1 -1
  13. package/dist/hcl/parse.js +9 -3
  14. package/dist/hcl/redact.d.ts +5 -1
  15. package/dist/hcl/redact.d.ts.map +1 -1
  16. package/dist/hcl/redact.js +7 -3
  17. package/dist/hcl/references.d.ts +12 -1
  18. package/dist/hcl/references.d.ts.map +1 -1
  19. package/dist/hcl/references.js +33 -16
  20. package/dist/integrity.json +6 -6
  21. package/dist/lint/post-synth/tf001.d.ts +4 -1
  22. package/dist/lint/post-synth/tf001.d.ts.map +1 -1
  23. package/dist/lint/post-synth/tf001.js +20 -8
  24. package/dist/lint/post-synth/tf002.d.ts +11 -5
  25. package/dist/lint/post-synth/tf002.d.ts.map +1 -1
  26. package/dist/lint/post-synth/tf002.js +42 -8
  27. package/dist/lint/post-synth/tf006.d.ts +7 -3
  28. package/dist/lint/post-synth/tf006.d.ts.map +1 -1
  29. package/dist/lint/post-synth/tf006.js +9 -3
  30. package/dist/lint/post-synth/tf022.d.ts +6 -0
  31. package/dist/lint/post-synth/tf022.d.ts.map +1 -1
  32. package/dist/lint/post-synth/tf022.js +18 -1
  33. package/dist/lint/secret-shape.d.ts +8 -0
  34. package/dist/lint/secret-shape.d.ts.map +1 -1
  35. package/dist/lint/secret-shape.js +76 -0
  36. package/dist/manifest.json +1 -1
  37. package/dist/plugin.d.ts.map +1 -1
  38. package/dist/plugin.js +7 -2
  39. package/dist/rules/tf001.ts +21 -7
  40. package/dist/rules/tf002.ts +44 -7
  41. package/dist/rules/tf006.ts +8 -3
  42. package/dist/rules/tf022.ts +18 -1
  43. package/package.json +2 -2
  44. package/src/__fixtures__/resolved-arguments/build-trusted/extras.tf +28 -0
  45. package/src/__fixtures__/resolved-arguments/build-trusted/main.tf +22 -0
  46. package/src/__fixtures__/resolved-arguments/build-trusted/serviceaccounts.tf +26 -0
  47. package/src/__fixtures__/resolved-arguments/modules/gke-cluster/main.tf +15 -0
  48. package/src/__fixtures__/resolved-arguments/modules/gke-cluster/variables.tf +12 -0
  49. package/src/__fixtures__/resolved-arguments/modules/gke-project/main.tf +9 -0
  50. package/src/__fixtures__/resolved-arguments/modules/gke-project/outputs.tf +9 -0
  51. package/src/__fixtures__/resolved-arguments/modules/gke-project/variables.tf +7 -0
  52. package/src/__fixtures__/resolved-arguments/modules/workload-identity-service-account/main.tf +16 -0
  53. package/src/__fixtures__/resolved-arguments/modules/workload-identity-service-account/outputs.tf +4 -0
  54. package/src/__fixtures__/resolved-arguments/modules/workload-identity-service-account/variables.tf +21 -0
  55. package/src/behaviour/reference-catalog.plugin.test.ts +101 -2
  56. package/src/behaviour/reference-catalog.ts +162 -9
  57. package/src/describe-resources.ts +1 -1
  58. package/src/hcl/edges.test.ts +1 -1
  59. package/src/hcl/evaluate.test.ts +215 -0
  60. package/src/hcl/evaluate.ts +899 -0
  61. package/src/hcl/instances.ts +89 -3
  62. package/src/hcl/parse.test.ts +18 -0
  63. package/src/hcl/parse.ts +28 -3
  64. package/src/hcl/redact.ts +7 -3
  65. package/src/hcl/references.test.ts +68 -0
  66. package/src/hcl/references.ts +31 -15
  67. package/src/lint/post-synth/fixtures/TF001/negative-second-block.tf +17 -0
  68. package/src/lint/post-synth/fixtures/TF002/module-cycle/cdn/back/main.tf +3 -0
  69. package/src/lint/post-synth/fixtures/TF002/module-cycle/cdn/main.tf +3 -0
  70. package/src/lint/post-synth/fixtures/TF002/module-cycle/main.tf +14 -0
  71. package/src/lint/post-synth/fixtures/TF002/module-nested/cdn/edge/main.tf +8 -0
  72. package/src/lint/post-synth/fixtures/TF002/module-nested/cdn/main.tf +3 -0
  73. package/src/lint/post-synth/fixtures/TF002/module-nested/main.tf +14 -0
  74. package/src/lint/post-synth/fixtures/TF002/module-other-provider/cdn/main.tf +8 -0
  75. package/src/lint/post-synth/fixtures/TF002/module-other-provider/main.tf +14 -0
  76. package/src/lint/post-synth/fixtures/TF002/module-pinned/cdn/main.tf +12 -0
  77. package/src/lint/post-synth/fixtures/TF002/module-pinned/main.tf +14 -0
  78. package/src/lint/post-synth/fixtures/TF002/module-unpinned/cdn/main.tf +7 -0
  79. package/src/lint/post-synth/fixtures/TF002/module-unpinned/main.tf +14 -0
  80. package/src/lint/post-synth/fixtures/TF006/negative-null-default.tf +12 -0
  81. package/src/lint/post-synth/fixtures/TF006/positive-empty-default.tf +0 -6
  82. package/src/lint/post-synth/fixtures/TF007/negative-names.tf +25 -0
  83. package/src/lint/post-synth/fixtures/TF022/negative-secret-reference.tf +32 -0
  84. package/src/lint/post-synth/fixtures/TF022/positive-secret-data.tf +8 -0
  85. package/src/lint/post-synth/fixtures/TF024/live-backend-second-block/a-versions.tf +3 -0
  86. package/src/lint/post-synth/fixtures/TF024/live-backend-second-block/b-backend.tf +10 -0
  87. package/src/lint/post-synth/fixtures/TF024/live-cloud-second-block/a-versions.tf +3 -0
  88. package/src/lint/post-synth/fixtures/TF024/live-cloud-second-block/b-cloud.tf +9 -0
  89. package/src/lint/post-synth/fixtures/TF024/sidecar-backend-second-block/a-versions.tf +3 -0
  90. package/src/lint/post-synth/fixtures/TF024/sidecar-backend-second-block/b-backend.tf +6 -0
  91. package/src/lint/post-synth/fixtures/TF024/sidecar-backend-second-block/estate.chdf.hcl +1 -0
  92. package/src/lint/post-synth/module-rules.test.ts +1 -1
  93. package/src/lint/post-synth/post-synth.test.ts +39 -0
  94. package/src/lint/post-synth/single-block.test.ts +23 -2
  95. package/src/lint/post-synth/tf001.ts +21 -7
  96. package/src/lint/post-synth/tf002.test.ts +45 -1
  97. package/src/lint/post-synth/tf002.ts +44 -7
  98. package/src/lint/post-synth/tf006.ts +8 -3
  99. package/src/lint/post-synth/tf022.ts +18 -1
  100. package/src/lint/post-synth/tf024.test.ts +21 -0
  101. package/src/lint/secret-shape.test.ts +30 -0
  102. package/src/lint/secret-shape.ts +75 -0
  103. package/src/plugin.ts +6 -2
  104. package/src/redact.test.ts +8 -0
@@ -0,0 +1,3 @@
1
+ terraform {
2
+ required_version = ">= 1.5.0"
3
+ }
@@ -0,0 +1,10 @@
1
+ terraform {
2
+ live {
3
+ estate = "fixture-estate"
4
+ }
5
+
6
+ backend "s3" {
7
+ bucket = "tfstate"
8
+ key = "fixture/terraform.tfstate"
9
+ }
10
+ }
@@ -0,0 +1,3 @@
1
+ terraform {
2
+ required_version = ">= 1.5.0"
3
+ }
@@ -0,0 +1,9 @@
1
+ terraform {
2
+ live {
3
+ estate = "fixture-estate"
4
+ }
5
+
6
+ cloud {
7
+ organization = "example"
8
+ }
9
+ }
@@ -0,0 +1,3 @@
1
+ terraform {
2
+ required_version = ">= 1.5.0"
3
+ }
@@ -0,0 +1,6 @@
1
+ terraform {
2
+ backend "gcs" {
3
+ bucket = "tfstate"
4
+ prefix = "fixture"
5
+ }
6
+ }
@@ -85,7 +85,7 @@ describe("TF020: a declaration nothing in its scope references", () => {
85
85
  expect(diags.map((d) => d.entity).sort()).toEqual([
86
86
  "TF020/data.aws_ami.ubuntu",
87
87
  "TF020/locals",
88
- "TF020/provider.aws",
88
+ "TF020/provider.aws~replica",
89
89
  "TF020/var.retention_days",
90
90
  ]);
91
91
  expect(diags.find((d) => d.entity === "TF020/locals")?.message).toContain('"local.common_tags"');
@@ -70,6 +70,45 @@ describe("TF001: root module declares no remote backend", () => {
70
70
  expect(diags).toHaveLength(0);
71
71
  });
72
72
 
73
+ // #5079: Terraform merges terraform blocks, so a backend in any of them counts,
74
+ // whichever order the blocks are read in.
75
+ test("passes a root whose backend is in a second terraform block", async () => {
76
+ const diags = tf001.check(await loadFixture("TF001", "negative-second-block"));
77
+ expect(diags).toHaveLength(0);
78
+ });
79
+
80
+ test("passes when the backend block comes first and a later block has none", () => {
81
+ const diags = tf001.check(
82
+ makeCtx({
83
+ "app/terraform": terraformBlock("app", { backend: { s3: [{ bucket: "tfstate" }] } }),
84
+ "app/terraform~2": terraformBlock("app", { required_version: ">= 1.5.0" }),
85
+ }),
86
+ );
87
+ expect(diags).toHaveLength(0);
88
+ });
89
+
90
+ test("passes when a cloud block is in a later terraform block", () => {
91
+ const diags = tf001.check(
92
+ makeCtx({
93
+ "app/terraform": terraformBlock("app", { required_version: ">= 1.5.0" }),
94
+ "app/terraform~2": terraformBlock("app", { cloud: [{ organization: "acme" }] }),
95
+ }),
96
+ );
97
+ expect(diags).toHaveLength(0);
98
+ });
99
+
100
+ test("still flags a root when no terraform block has a remote backend, naming a local one in any block", () => {
101
+ const diags = tf001.check(
102
+ makeCtx({
103
+ "app/terraform": terraformBlock("app", { required_version: ">= 1.5.0" }),
104
+ "app/terraform~2": terraformBlock("app", { backend: { local: [{}] } }),
105
+ }),
106
+ );
107
+ expect(diags).toHaveLength(1);
108
+ expect(diags[0].entity).toBe("app/terraform");
109
+ expect(diags[0].message).toContain('the backend it declares is `backend "local"`');
110
+ });
111
+
73
112
  test("fires once per root, not once per terraform block", () => {
74
113
  const diags = tf001.check(
75
114
  makeCtx({
@@ -41,9 +41,13 @@ describe("TF006: sensitive variable with a default", () => {
41
41
  expect(tf006.check(await loadFixture("TF006", "negative"))).toHaveLength(0);
42
42
  });
43
43
 
44
- test("an empty or null default still counts", async () => {
44
+ test("an empty default still counts", async () => {
45
45
  const diags = tf006.check(await loadFixture("TF006", "positive-empty-default"));
46
- expect(diags.map((d) => d.entity).sort()).toEqual(["TF006/var.blank_token", "TF006/var.null_token"]);
46
+ expect(diags.map((d) => d.entity)).toEqual(["TF006/var.blank_token"]);
47
+ });
48
+
49
+ test("a null default does not, because it commits no value (#5081)", async () => {
50
+ expect(tf006.check(await loadFixture("TF006", "negative-null-default"))).toHaveLength(0);
47
51
  });
48
52
  });
49
53
 
@@ -65,6 +69,10 @@ describe("TF007: secret-shaped literal in a variable default or a locals value",
65
69
  test("passes a sensitive variable with no default and a local that references one", async () => {
66
70
  expect(tf007.check(await loadFixture("TF007", "negative"))).toHaveLength(0);
67
71
  });
72
+
73
+ test("passes a null default and machine type and image names (#5081)", async () => {
74
+ expect(tf007.check(await loadFixture("TF007", "negative-names"))).toHaveLength(0);
75
+ });
68
76
  });
69
77
 
70
78
  describe("TF008: hardcoded credentials in a provider block", () => {
@@ -262,4 +270,17 @@ describe("TF022: credential-named resource attribute holding a literal", () => {
262
270
  test("a locator attribute is the remediation, not the finding", async () => {
263
271
  expect(tf022.check(await loadFixture("TF022", "negative-locator"))).toHaveLength(0);
264
272
  });
273
+
274
+ test("the secret id of a Secret Manager reader is a reference, not a credential (#5080)", async () => {
275
+ expect(tf022.check(await loadFixture("TF022", "negative-secret-reference"))).toHaveLength(0);
276
+ });
277
+
278
+ test("secret_data and a bare secret on another type are still judged", async () => {
279
+ const diags = tf022.check(await loadFixture("TF022", "positive-secret-data"));
280
+ expect(diags.map((d) => d.entity).sort()).toEqual([
281
+ "TF022/example_widget.w",
282
+ "TF022/google_secret_manager_secret_version.app",
283
+ ]);
284
+ expect(diags.find((d) => d.entity?.endsWith("version.app"))?.message).toContain("`secret_data`");
285
+ });
265
286
  });
@@ -21,7 +21,10 @@
21
21
  * `# chant-ignore-block: TF001` on the line above its `terraform` block
22
22
  * (chant #2111), which is what the three shipped examples do.
23
23
  *
24
- * One diagnostic per root, fired from the root's `terraform` block. A root
24
+ * One diagnostic per root, fired from the root's first `terraform` block. The
25
+ * verdict reads every `terraform` block of the root, because Terraform merges
26
+ * them and a backend often sits in `backend.tf` or `provider.tf` beside a
27
+ * `versions.tf` block of its own (#5079). A root
25
28
  * with no `terraform` block at all is not flagged: it declares no version
26
29
  * constraints either, and the missing block is a different finding.
27
30
  *
@@ -98,8 +101,14 @@ export const tf001: PostSynthCheck = {
98
101
 
99
102
  check(ctx: PostSynthContext): PostSynthDiagnostic[] {
100
103
  const diagnostics: PostSynthDiagnostic[] = [];
101
- /** Root name to the entity key of the first `terraform` block seen for it. */
102
- const flagged = new Set<string>();
104
+ /**
105
+ * Per root: the entity key of the first `terraform` block seen, whether any
106
+ * block of the root configures remote state, and whether any block names
107
+ * `backend "local"`. Terraform merges the `terraform` blocks of a module,
108
+ * so the verdict belongs to the root, not to whichever block is read first
109
+ * (#5079).
110
+ */
111
+ const roots = new Map<string, { entity: string; remote: boolean; local: boolean }>();
103
112
 
104
113
  for (const [name, entity] of ctx.entities) {
105
114
  if (entity.entityType !== TERRAFORM_TYPE) continue;
@@ -107,18 +116,23 @@ export const tf001: PostSynthCheck = {
107
116
  const props = entity.props as { root?: unknown; body?: unknown; mode?: unknown };
108
117
  if (props.mode === "live") continue;
109
118
  const root = typeof props.root === "string" ? props.root : "";
110
- if (flagged.has(root)) continue;
111
119
 
112
120
  const body = (typeof props.body === "object" && props.body !== null ? props.body : {}) as BlockBody;
113
- if (hasRemoteBackend(body)) continue;
121
+ const seen = roots.get(root) ?? { entity: name, remote: false, local: false };
122
+ seen.remote ||= hasRemoteBackend(body);
123
+ seen.local ||= backendTypes(body).includes(LOCAL_BACKEND);
124
+ roots.set(root, seen);
125
+ }
126
+
127
+ for (const [root, { entity: name, remote, local }] of roots) {
128
+ if (remote) continue;
114
129
 
115
130
  // What the root actually declares, so the message names it rather than
116
131
  // saying "no remote backend" over a block the reader can see.
117
- const found = backendTypes(body).includes(LOCAL_BACKEND)
132
+ const found = local
118
133
  ? 'the backend it declares is `backend "local"`'
119
134
  : "there is no backend block at all";
120
135
 
121
- flagged.add(root);
122
136
  diagnostics.push({
123
137
  checkId: "TF001",
124
138
  severity: "warning",
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, test } from "vitest";
2
2
  import type { PostSynthContext } from "@intentius/chant/lint/post-synth";
3
3
  import { tf002 } from "./tf002";
4
- import { loadFixture } from "./fixtures/load";
4
+ import { loadFixture, loadTreeFixture } from "./fixtures/load";
5
5
  import { TERRAFORM_TYPE, PROVIDER_TYPE, RESOURCE_TYPE, terraformEntity } from "../../hcl/parse";
6
6
 
7
7
  function makeCtx(entities: Record<string, ReturnType<typeof terraformEntity>>): PostSynthContext {
@@ -91,3 +91,47 @@ describe("TF002: provider implied by the root has no required_providers entry",
91
91
  expect(diags).toHaveLength(0);
92
92
  });
93
93
  });
94
+
95
+ describe("TF002: a version pinned in a called local module (#5108)", () => {
96
+ test("a root with only source is constrained by the module's version", async () => {
97
+ const diags = tf002.check(await loadTreeFixture("TF002", "module-pinned"));
98
+ expect(diags).toHaveLength(0);
99
+ });
100
+
101
+ test("a module that also gives only source leaves the finding", async () => {
102
+ const diags = tf002.check(await loadTreeFixture("TF002", "module-unpinned"));
103
+ expect(diags).toHaveLength(1);
104
+ expect(diags[0].message).toContain("`version`");
105
+ });
106
+
107
+ test("a version pinned two calls down counts", async () => {
108
+ const diags = tf002.check(await loadTreeFixture("TF002", "module-nested"));
109
+ expect(diags).toHaveLength(0);
110
+ });
111
+
112
+ test("a call cycle between modules ends and pins nothing", async () => {
113
+ const diags = tf002.check(await loadTreeFixture("TF002", "module-cycle"));
114
+ expect(diags).toHaveLength(1);
115
+ });
116
+
117
+ test("a module's pin for another provider does not constrain this one", async () => {
118
+ const diags = tf002.check(await loadTreeFixture("TF002", "module-other-provider"));
119
+ expect(diags).toHaveLength(1);
120
+ expect(diags[0].message).toContain('"fastly"');
121
+ });
122
+
123
+ test("the root's own entry wins and a module's entry alone does not make the root imply a provider", () => {
124
+ const ctx = makeCtx({
125
+ "app/terraform": terraformEntity(TERRAFORM_TYPE, "terraform", {}, "main.tf", "app"),
126
+ "app/module.m/terraform": terraformEntity(
127
+ TERRAFORM_TYPE,
128
+ "terraform",
129
+ { required_providers: [{ aws: { source: "hashicorp/aws", version: "~> 5.0" } }] },
130
+ "main.tf",
131
+ "app",
132
+ { callers: ["module.m"] },
133
+ ),
134
+ });
135
+ expect(tf002.check(ctx)).toHaveLength(0);
136
+ });
137
+ });
@@ -21,11 +21,17 @@
21
21
  * A root with no `terraform` block at all is out of scope, same as TF001:
22
22
  * the missing block is that rule's finding, not this one's.
23
23
  *
24
- * Scope: root modules only (#2112). A child module's own `required_providers`
25
- * are the child's business, and its resources are constrained by the root's
26
- * block at plan time, so folding a descended module's blocks into this pass
27
- * would both credit the root with requirements it never declared and judge it
28
- * on providers it never named.
24
+ * Scope: the providers a root implies come from the root's own blocks (#2112);
25
+ * a child module's resources and provider blocks are not judged here. The
26
+ * constraints, though, come from the whole local module tree (#5108).
27
+ * Terraform combines the `required_providers` of every module in a
28
+ * configuration, so a root that gives only `source` is constrained when a
29
+ * local module it calls pins the `version`, and the reverse. A field the root
30
+ * entry lacks is taken from a descended module's entry for the same provider
31
+ * name; the root's own value always wins. A root entry in the legacy bare
32
+ * string form stays a finding. Registry and git modules are never fetched, so
33
+ * only the local modules `descend.ts` already read can contribute, and its
34
+ * cycle guard is what bounds the tree.
29
35
  */
30
36
 
31
37
  import type {
@@ -105,6 +111,25 @@ function entryProblem(entry: unknown): string | undefined {
105
111
  return missing.length > 0 ? `an entry missing ${missing.join(" and ")}` : undefined;
106
112
  }
107
113
 
114
+ /** The entries the descended modules of a root hold for each provider name, . */
115
+ type ModuleEntries = Map<string, Array<Record<string, unknown>>>;
116
+
117
+ /** Fill what a root entry lacks from the called modules' entries, or return `entry` unchanged. */
118
+ function withModuleFields(
119
+ entry: unknown,
120
+ fromModules: Array<Record<string, unknown>> | undefined,
121
+ ): unknown {
122
+ if (!fromModules || fromModules.length === 0) return entry;
123
+ if (entry !== undefined && (typeof entry !== "object" || entry === null)) return entry;
124
+ const merged: Record<string, unknown> = { ...((entry as Record<string, unknown> | undefined) ?? {}) };
125
+ for (const field of ["source", "version"]) {
126
+ if (typeof merged[field] === "string" && merged[field] !== "") continue;
127
+ const found = fromModules.find((m) => typeof m[field] === "string" && m[field] !== "");
128
+ if (found) merged[field] = found[field];
129
+ }
130
+ return Object.keys(merged).length === 0 ? entry : merged;
131
+ }
132
+
108
133
  export const tf002: PostSynthCheck = {
109
134
  id: "TF002",
110
135
  description: "A provider the root implies has no required_providers entry, or an incomplete one",
@@ -113,12 +138,24 @@ export const tf002: PostSynthCheck = {
113
138
  const diagnostics: PostSynthDiagnostic[] = [];
114
139
  const roots = new Set<string>();
115
140
  const requiredByRoot = new Map<string, Record<string, unknown>>();
141
+ const moduleEntriesByRoot = new Map<string, ModuleEntries>();
116
142
 
117
143
  for (const entity of ctx.entities.values()) {
118
144
  if (entity.entityType !== TERRAFORM_TYPE || !isResourceDeclarable(entity)) continue;
119
- if (!isRootScoped(entity)) continue;
120
145
  const props = entity.props as { root?: unknown; body?: unknown };
121
146
  const root = typeof props.root === "string" ? props.root : "";
147
+ if (!isRootScoped(entity)) {
148
+ const childBody = (typeof props.body === "object" && props.body !== null ? props.body : {}) as BlockBody;
149
+ const byName: ModuleEntries = moduleEntriesByRoot.get(root) ?? new Map();
150
+ for (const [name, entry] of Object.entries(requiredProvidersMap(childBody))) {
151
+ if (typeof entry !== "object" || entry === null) continue;
152
+ const list = byName.get(name) ?? [];
153
+ list.push(entry as Record<string, unknown>);
154
+ byName.set(name, list);
155
+ }
156
+ moduleEntriesByRoot.set(root, byName);
157
+ continue;
158
+ }
122
159
  roots.add(root);
123
160
  const body = (typeof props.body === "object" && props.body !== null ? props.body : {}) as BlockBody;
124
161
  const merged = requiredByRoot.get(root) ?? {};
@@ -131,7 +168,7 @@ export const tf002: PostSynthCheck = {
131
168
  const implied = impliedProviders(ctx.entities, root);
132
169
 
133
170
  for (const name of [...implied.keys()].sort()) {
134
- const problem = entryProblem(required[name]);
171
+ const problem = entryProblem(withModuleFields(required[name], moduleEntriesByRoot.get(root)?.get(name)));
135
172
  if (!problem) continue;
136
173
  diagnostics.push({
137
174
  checkId: "TF002",
@@ -8,9 +8,13 @@
8
8
  * survives longest, because every environment that forgets to pass the variable
9
9
  * silently gets the committed one.
10
10
  *
11
- * Any default counts, not only a secret-shaped one. `default = ""` and
12
- * `default = null` are the two that look harmless, and both make a required
13
- * secret optional, which is the other half of the failure.
11
+ * Any default counts, not only a secret-shaped one. `default = ""` looks
12
+ * harmless and makes a required secret optional, which is the other half of
13
+ * the failure. `default = null` is the one exception (#5081): it commits no
14
+ * value, so nothing is in git, and it is how a variable is declared optional
15
+ * on purpose (a module that takes a credential only when a feature is on).
16
+ * The IR keeps a null default as null (see `../hcl/redact.ts`) so the rule can
17
+ * tell it apart from a literal that was redacted.
14
18
  *
15
19
  * Scope: root and child modules alike (#2112). The condition is a property
16
20
  * of the block itself, so a descended module's block is read exactly as a
@@ -35,6 +39,7 @@ export const tf006: PostSynthCheck = {
35
39
  for (const block of blocksOfType(ctx, VARIABLE_TYPE)) {
36
40
  if (block.body.sensitive !== true) continue;
37
41
  if (!("default" in block.body)) continue;
42
+ if (block.body.default === null) continue;
38
43
 
39
44
  diagnostics.push({
40
45
  checkId: "TF006",
@@ -15,6 +15,12 @@
15
15
  * shape, a reference rather than a constant, which is what the message says
16
16
  * rather than "remove this".
17
17
  *
18
+ * An argument that names a secret instead of holding one is skipped: the
19
+ * `secret` of a Secret Manager version data source is the id of the secret to
20
+ * read, and reading it at apply time is the fix (#5080). The skip is a table
21
+ * of types and attribute paths in `../secret-shape.ts`, not a rule about the
22
+ * word `secret`, so the same name on a type outside it is still judged.
23
+ *
18
24
  * Scope: root and child modules alike (#2112). The condition is a property
19
25
  * of the block itself, so a descended module's block is read exactly as a
20
26
  * root's is.
@@ -26,9 +32,16 @@ import type {
26
32
  PostSynthDiagnostic,
27
33
  } from "@intentius/chant/lint/post-synth";
28
34
  import { DATA_TYPE, RESOURCE_TYPE } from "../../hcl/parse";
29
- import { isSecretName, secretShapedAssignment } from "../secret-shape";
35
+ import { isSecretName, isSecretReferenceArgument, secretShapedAssignment } from "../secret-shape";
30
36
  import { blocksOfTypes, walkAttributes } from "./blocks";
31
37
 
38
+ /** `data.google_x.y` and `google_x.y` both give `google_x`. */
39
+ function terraformTypeOf(address: string): string {
40
+ const bare = address.startsWith("data.") ? address.slice("data.".length) : address;
41
+ const dot = bare.indexOf(".");
42
+ return dot === -1 ? bare : bare.slice(0, dot);
43
+ }
44
+
32
45
  export const tf022: PostSynthCheck = {
33
46
  id: "TF022",
34
47
  description: "Credential-named resource attribute holds a plaintext literal",
@@ -37,8 +50,12 @@ export const tf022: PostSynthCheck = {
37
50
  const diagnostics: PostSynthDiagnostic[] = [];
38
51
 
39
52
  for (const block of blocksOfTypes(ctx, [RESOURCE_TYPE, DATA_TYPE])) {
53
+ const blockType = terraformTypeOf(block.address);
40
54
  for (const attr of walkAttributes(block.body)) {
41
55
  if (!isSecretName(attr.name)) continue;
56
+ // `secret` on a Secret Manager version data source is the id of the
57
+ // secret to read, which is the fix this rule asks for (#5080).
58
+ if (isSecretReferenceArgument(blockType, attr.path)) continue;
42
59
  const shape = secretShapedAssignment(attr.name, attr.value);
43
60
  if (!shape) continue;
44
61
 
@@ -48,6 +48,27 @@ describe("TF024: live root declares a backend or cloud block", () => {
48
48
  expect(diags[0].message).toContain("no record store is derived");
49
49
  });
50
50
 
51
+ test("finds a backend in a second terraform block, beside a versions.tf block", async () => {
52
+ const diags = tf024.check(await ctxFor("live-backend-second-block"));
53
+ expect(diags).toHaveLength(1);
54
+ expect(diags[0].severity).toBe("info");
55
+ expect(diags[0].message).toContain('backend "s3"');
56
+ expect(diags[0].message).toContain("derives the record store");
57
+ });
58
+
59
+ test("finds a backend in a second terraform block of a sidecar root", async () => {
60
+ const diags = tf024.check(await ctxFor("sidecar-backend-second-block"));
61
+ expect(diags).toHaveLength(1);
62
+ expect(diags[0].message).toContain('backend "gcs"');
63
+ });
64
+
65
+ test("finds a cloud block in a second terraform block", async () => {
66
+ const diags = tf024.check(await ctxFor("live-cloud-second-block"));
67
+ expect(diags).toHaveLength(1);
68
+ expect(diags[0].severity).toBe("warning");
69
+ expect(diags[0].message).toContain("cloud block");
70
+ });
71
+
51
72
  test("passes a live root with neither block", async () => {
52
73
  const diags = tf024.check(await ctxFor("live-clean"));
53
74
  expect(diags).toHaveLength(0);
@@ -85,6 +85,36 @@ describe("the value heuristic", () => {
85
85
  expect(isCredentialShapedValue("registry.example.com/team/app-server")).toBe(false);
86
86
  });
87
87
 
88
+ test.each([
89
+ "db-custom-1-3840",
90
+ "n2-standard-4",
91
+ "e2-custom-medium-8192",
92
+ "bx2d-metal-96x384",
93
+ "ibm-ubuntu-24-04-3-minimal-s390x-2",
94
+ "debian-12-bookworm-v20240110",
95
+ "ubuntu-2204-jammy-v20240112",
96
+ "Standard_D16ads_v5",
97
+ "Standard_NC24ads_A100_v4",
98
+ ])("the machine type or image name %s is not", (value) => {
99
+ expect(isCredentialShapedValue(value)).toBe(false);
100
+ });
101
+
102
+ // The narrowing is a table of shapes, so these stay findings: a token that
103
+ // only resembles a name, and a UUID, which can be a real credential.
104
+ test.each([
105
+ "k9q2-x7m4-p3w8-z1v6-a5b3",
106
+ "46678f10-4bbb-447e-98e8-d2829589f2d8",
107
+ "8jd0hvn2xqb7sltr-4mycez1pgwfka5u",
108
+ "n2-standard-4-Zq9Xw3Lk8TmV2bRp",
109
+ ])("%s is still credential-shaped", (value) => {
110
+ expect(isCredentialShapedValue(value)).toBe(true);
111
+ });
112
+
113
+ test("a name-shaped value under a credential name is still judged by the name", () => {
114
+ expect(secretShapedAssignment("db_password", "ibm-ubuntu-24-04-3-minimal-s390x-2")?.reason).toBe("name");
115
+ expect(secretShapedAssignment("image_name", "ibm-ubuntu-24-04-3-minimal-s390x-2")).toBeUndefined();
116
+ });
117
+
88
118
  test("a value shorter than eight characters is never judged", () => {
89
119
  expect(isCredentialShapedValue("aB3$xY")).toBe(false);
90
120
  });
@@ -44,6 +44,80 @@ const SECRET_NAME_RE = /(^|_)(password|passwd|secret|token|api_key|private_key|a
44
44
  */
45
45
  const LOCATOR_SUFFIX_RE = /_(file|path|arn|id|name)$/;
46
46
 
47
+ /**
48
+ * Arguments that name a secret rather than hold one, where the name alone
49
+ * would read as a credential. `secret` on a Secret Manager version data
50
+ * source is the id of the secret to read, so a literal there is the remedy the
51
+ * rules ask for (read the value at apply time), not a committed value (#5080).
52
+ * Keyed by resource or data source type, then by the dotted attribute path, so
53
+ * a bare `secret` on some other type is still judged by name.
54
+ */
55
+ const SECRET_REFERENCE_ARGUMENTS: ReadonlyArray<{ type: RegExp; path: RegExp }> = [
56
+ // data "google_secret_manager_secret_version_access" / _version, and the
57
+ // regional variants and the resource form: `secret` is the parent secret.
58
+ { type: /^google_secret_manager_(regional_)?secret_version(_access)?$/, path: /^secret$/ },
59
+ // Cloud Functions and Cloud Run mount a secret by id, never by value.
60
+ {
61
+ type: /^google_(cloudfunctions2?_function|cloud_run(_v2)?_(service|job))$/,
62
+ path: /(^|\.)(secret_environment_variables|secret_volumes|secret_key_ref)\.secret$/,
63
+ },
64
+ ];
65
+
66
+ /**
67
+ * Is this attribute, on a block of this resource or data source type, a
68
+ * reference to a secret (an id, a name or a resource path) instead of a
69
+ * secret value? `path` is the dotted path from the block body.
70
+ */
71
+ export function isSecretReferenceArgument(blockType: string, path: string): boolean {
72
+ return SECRET_REFERENCE_ARGUMENTS.some((r) => r.type.test(blockType) && r.path.test(path));
73
+ }
74
+
75
+ /**
76
+ * Shapes of values that are public names for a kind of object, and that the
77
+ * generic high-entropy test would otherwise read as random: a machine type
78
+ * (`db-custom-1-3840`, `n2-standard-4`, `bx2-4x16`), an image name
79
+ * (`ibm-ubuntu-24-04-3-minimal-s390x-2`, `debian-12-bookworm-v20240110`) and
80
+ * an Azure size (`Standard_D16ads_v5`). Each is matched on the shape of the
81
+ * whole value, a table of shapes and not of attribute names, so a secret that
82
+ * happens to sit in a variable called `image_name` is still judged by its
83
+ * value (#5081).
84
+ *
85
+ * The hyphenated shape is deliberately strict, so that a real token is not
86
+ * waved through: every segment is a lowercase word, a number, or a short
87
+ * letters-and-digits tag (`s390x`, `e2`, `4x16`, `v20240110`); there are at
88
+ * least three segments, and at least one is a word of three or more letters
89
+ * with a vowel. A UUID, a hex string, a base64 token and an `ami-` id all have
90
+ * a segment that is none of those, so they still reach the entropy test.
91
+ */
92
+ const NAMED_SHAPES: ReadonlyArray<{ name: string; test: (value: string) => boolean }> = [
93
+ {
94
+ name: "hyphenated machine type or image name",
95
+ test(value) {
96
+ if (!/^[a-z0-9]+(-[a-z0-9]+)+$/.test(value)) return false;
97
+ const segments = value.split("-");
98
+ if (segments.length < 3) return false;
99
+ let hasWord = false;
100
+ for (const seg of segments) {
101
+ if (/^[a-z]{2,16}$/.test(seg)) {
102
+ if (seg.length >= 3 && /[aeiouy]/.test(seg)) hasWord = true;
103
+ } else if (!/^(\d+|[a-z]{1,2}\d+[a-z]{0,2}|\d+[a-z]{1,2}\d*)$/.test(seg)) {
104
+ return false;
105
+ }
106
+ }
107
+ return hasWord;
108
+ },
109
+ },
110
+ {
111
+ name: "Azure size",
112
+ test: (value) => /^(Standard|Basic|Premium)_[A-Za-z0-9]+(_[A-Za-z0-9]+)*$/.test(value),
113
+ },
114
+ ];
115
+
116
+ /** Is this value one of the public-name shapes in {@link NAMED_SHAPES}? */
117
+ export function isPublicNameShape(value: string): boolean {
118
+ return NAMED_SHAPES.some((s) => s.test(value));
119
+ }
120
+
47
121
  /** Minimum length for a value to be worth judging at all. */
48
122
  export const MIN_SECRET_LENGTH = 8;
49
123
 
@@ -111,6 +185,7 @@ function isHighEntropyToken(value: string): boolean {
111
185
  if (!/^[A-Za-z0-9+/=_-]+$/.test(value)) return false;
112
186
  if (!hasClassDiversity(value)) return false;
113
187
  if (looksLikeIdentifierSlug(value)) return false;
188
+ if (isPublicNameShape(value)) return false;
114
189
  return shannonEntropy(value) >= ENTROPY_THRESHOLD;
115
190
  }
116
191
 
package/src/plugin.ts CHANGED
@@ -297,7 +297,10 @@ export const terraformPlugin: LexiconPlugin = {
297
297
  * audited tree, a cycle) are warnings on a build; this hook returns
298
298
  * entities only, so on the audit path they are dropped rather than printed.
299
299
  *
300
- * Never throws: malformed HCL yields an empty map.
300
+ * Malformed HCL yields an empty map. The one error it lets through is a
301
+ * missing HCL parser (an error carrying `parserPackage`): returning an empty
302
+ * map for that would read as a clean directory, so `chant audit` catches it
303
+ * and reports the directories it could not read (#5083).
301
304
  */
302
305
  async auditEntities(content: string, input?: AuditEntitiesInput): Promise<Map<string, Declarable>> {
303
306
  try {
@@ -323,7 +326,8 @@ export const terraformPlugin: LexiconPlugin = {
323
326
  });
324
327
  for (const [key, entity] of children) entities.set(key, entity);
325
328
  return entities;
326
- } catch {
329
+ } catch (err) {
330
+ if (typeof (err as { parserPackage?: unknown } | null)?.parserPackage === "string") throw err;
327
331
  return new Map();
328
332
  }
329
333
  },
@@ -102,6 +102,14 @@ variable "open" {
102
102
  }
103
103
  });
104
104
 
105
+ it("keeps a null default as null, since it holds no value to leave out (#5081)", async () => {
106
+ const nullSource = 'variable "k" {\n type = string\n default = null\n sensitive = true\n}\n';
107
+ expect(redactSensitiveSource(nullSource)).toBe(nullSource);
108
+ const entities = await blocksToEntities([{ name: "main.tf", source: nullSource }], "app");
109
+ const e = entities.get("app/var.k") as TerraformEntity;
110
+ expect(e.props.body.default).toBeNull();
111
+ });
112
+
105
113
  it("leaves a non-sensitive default alone, in body and source", async () => {
106
114
  const entities = await blocksToEntities([{ name: "main.tf", source }], "app");
107
115
  const e = entities.get("app/var.open") as TerraformEntity;