@intentius/chant-lexicon-aws 0.44.14 → 0.46.0

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 (100) hide show
  1. package/dist/agentcore/trace-fetch.d.ts +4 -1
  2. package/dist/agentcore/trace-fetch.d.ts.map +1 -1
  3. package/dist/api/read-client.d.ts +31 -1
  4. package/dist/api/read-client.d.ts.map +1 -1
  5. package/dist/codegen/docs.d.ts.map +1 -1
  6. package/dist/components/capability-plugin.d.ts.map +1 -1
  7. package/dist/components/cloud-executor.d.ts +9 -0
  8. package/dist/components/cloud-executor.d.ts.map +1 -1
  9. package/dist/composites/agentcore-agent.d.ts +33 -19
  10. package/dist/composites/agentcore-agent.d.ts.map +1 -1
  11. package/dist/composites/index.d.ts +1 -1
  12. package/dist/composites/index.d.ts.map +1 -1
  13. package/dist/composites/lambda-function.d.ts +4 -4
  14. package/dist/composites/lambda-function.d.ts.map +1 -1
  15. package/dist/deep-observe.d.ts +21 -0
  16. package/dist/deep-observe.d.ts.map +1 -1
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/integrity.json +5 -3
  20. package/dist/lint/audit-catalog.d.ts.map +1 -1
  21. package/dist/lint/post-synth/cf-refs.d.ts +7 -0
  22. package/dist/lint/post-synth/cf-refs.d.ts.map +1 -1
  23. package/dist/lint/post-synth/index.d.ts.map +1 -1
  24. package/dist/lint/post-synth/waw059.d.ts +36 -0
  25. package/dist/lint/post-synth/waw059.d.ts.map +1 -0
  26. package/dist/lint/post-synth/waw060.d.ts +16 -0
  27. package/dist/lint/post-synth/waw060.d.ts.map +1 -0
  28. package/dist/manifest.json +1 -1
  29. package/dist/okf/index.md +2 -0
  30. package/dist/okf/rules/WAW059.md +25 -0
  31. package/dist/okf/rules/WAW060.md +17 -0
  32. package/dist/okf/types/Action.md +1 -0
  33. package/dist/okf/types/Bucket.md +1 -0
  34. package/dist/okf/types/GlobalTable.md +4 -0
  35. package/dist/okf/types/IamPolicy.md +2 -0
  36. package/dist/okf/types/InstanceProfile.md +4 -0
  37. package/dist/okf/types/ManagedPolicy.md +2 -0
  38. package/dist/okf/types/Map.md +1 -0
  39. package/dist/okf/types/Queue.md +1 -0
  40. package/dist/okf/types/Role.md +1 -0
  41. package/dist/okf/types/Table.md +1 -0
  42. package/dist/okf/types/Type.md +2 -0
  43. package/dist/op/activities/aws-apply.d.ts +62 -9
  44. package/dist/op/activities/aws-apply.d.ts.map +1 -1
  45. package/dist/op/activities/index.d.ts +5 -4
  46. package/dist/op/activities/index.d.ts.map +1 -1
  47. package/dist/ownership.d.ts +18 -0
  48. package/dist/ownership.d.ts.map +1 -1
  49. package/dist/plugin.d.ts.map +1 -1
  50. package/dist/properties.d.ts +4 -3
  51. package/dist/properties.d.ts.map +1 -1
  52. package/dist/rules/cf-refs.ts +22 -0
  53. package/dist/rules/waw059.ts +353 -0
  54. package/dist/rules/waw060.ts +91 -0
  55. package/dist/serializer.d.ts.map +1 -1
  56. package/dist/spec/fetch.d.ts +12 -1
  57. package/dist/spec/fetch.d.ts.map +1 -1
  58. package/dist/teardown.d.ts +85 -0
  59. package/dist/teardown.d.ts.map +1 -0
  60. package/package.json +2 -2
  61. package/src/agentcore/trace-fetch.test.ts +17 -0
  62. package/src/agentcore/trace-fetch.ts +7 -2
  63. package/src/api/read-client.test.ts +87 -0
  64. package/src/api/read-client.ts +57 -1
  65. package/src/codegen/docs-links.test.ts +44 -30
  66. package/src/codegen/docs.ts +2 -1034
  67. package/src/components/capability-plugin.ts +5 -2
  68. package/src/components/cloud-executor.test.ts +29 -1
  69. package/src/components/cloud-executor.ts +33 -6
  70. package/src/composites/agentcore-agent.test.ts +32 -12
  71. package/src/composites/agentcore-agent.ts +43 -23
  72. package/src/composites/index.ts +1 -1
  73. package/src/composites/microvm-app.test.ts +2 -2
  74. package/src/deep-observe.test.ts +94 -0
  75. package/src/deep-observe.ts +58 -2
  76. package/src/import/roundtrip-fixtures.test.ts +1 -1
  77. package/src/index.ts +3 -1
  78. package/src/lifecycle-integration.test.ts +93 -0
  79. package/src/lint/audit-catalog.ts +5 -0
  80. package/src/lint/post-synth/cf-refs.ts +22 -0
  81. package/src/lint/post-synth/index.ts +4 -0
  82. package/src/lint/post-synth/waw059.test.ts +309 -0
  83. package/src/lint/post-synth/waw059.ts +353 -0
  84. package/src/lint/post-synth/waw060.test.ts +131 -0
  85. package/src/lint/post-synth/waw060.ts +91 -0
  86. package/src/op/activities/aws-apply.test.ts +151 -4
  87. package/src/op/activities/aws-apply.ts +123 -13
  88. package/src/op/activities/index.ts +5 -3
  89. package/src/ownership.test.ts +24 -1
  90. package/src/ownership.ts +37 -0
  91. package/src/plugin.ts +52 -35
  92. package/src/properties.test.ts +5 -5
  93. package/src/properties.ts +6 -5
  94. package/src/serializer-ownership.test.ts +18 -0
  95. package/src/serializer.test.ts +73 -33
  96. package/src/serializer.ts +9 -1
  97. package/src/spec/fetch.test.ts +40 -0
  98. package/src/spec/fetch.ts +24 -3
  99. package/src/teardown.test.ts +258 -0
  100. package/src/teardown.ts +276 -0
@@ -0,0 +1,353 @@
1
+ /**
2
+ * WAW059: Wildcard Resource where the declared graph enumerates the touched set
3
+ *
4
+ * An identity policy that allows resource-scopable actions on `Resource: "*"`
5
+ * (or a service-wide ARN pattern) when every consumer of the attached role
6
+ * only touches resources declared in the same template. In that case the
7
+ * declared graph already enumerates the touched set, so the statement can be
8
+ * tightened to the `Fn::GetAtt` Arn list of those declared entities.
9
+ *
10
+ * Deliberately narrow (#1225). Fires only when ALL of these hold:
11
+ * - the statement is an `Effect: Allow` identity-policy statement (role inline
12
+ * policy, IAM::Policy, IAM::ManagedPolicy) — trust policies carry a
13
+ * Principal and are skipped, resource policies live on other types;
14
+ * - no Condition/NotAction/NotResource and no intrinsics in Action/Resource;
15
+ * - `Resource` is `"*"` or a service-wide ARN pattern;
16
+ * - every Action is in the curated resource-scopable table (s3, dynamodb,
17
+ * sqs) — actions that genuinely need `"*"` (s3:ListAllMyBuckets,
18
+ * dynamodb:ListTables, sqs:ListQueues) are not in the table;
19
+ * - the attached principal resolves to declared roles only, those roles have
20
+ * consumers in the template, and no consumer carries a foreign edge (a
21
+ * literal ARN of the service) or an intrinsic edge (Fn::ImportValue) that
22
+ * would put resources outside the declared graph in reach.
23
+ *
24
+ * Anything the static graph cannot prove stays quiet.
25
+ */
26
+
27
+ import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth";
28
+ import {
29
+ parseCFTemplate,
30
+ walkPolicyStatements,
31
+ findResourceRefs,
32
+ buildReverseRefIndex,
33
+ isIntrinsic,
34
+ type CFTemplate,
35
+ type CFResource,
36
+ } from "./cf-refs";
37
+
38
+ /**
39
+ * Curated table of actions that support resource-level permissions, per
40
+ * service. Lower-cased (IAM action matching is case-insensitive). An action
41
+ * outside this table gates the whole statement off — it may legitimately
42
+ * require `Resource: "*"`.
43
+ */
44
+ export const RESOURCE_SCOPABLE_ACTIONS: Record<string, ReadonlySet<string>> = {
45
+ s3: new Set([
46
+ "getobject",
47
+ "getobjectversion",
48
+ "getobjectacl",
49
+ "getobjecttagging",
50
+ "putobject",
51
+ "putobjectacl",
52
+ "putobjecttagging",
53
+ "deleteobject",
54
+ "deleteobjectversion",
55
+ "listbucket",
56
+ "listbucketversions",
57
+ "listbucketmultipartuploads",
58
+ "listmultipartuploadparts",
59
+ "abortmultipartupload",
60
+ "getbucketlocation",
61
+ ]),
62
+ dynamodb: new Set([
63
+ "getitem",
64
+ "batchgetitem",
65
+ "query",
66
+ "scan",
67
+ "putitem",
68
+ "updateitem",
69
+ "deleteitem",
70
+ "batchwriteitem",
71
+ "conditioncheckitem",
72
+ "describetable",
73
+ "getrecords",
74
+ "getsharditerator",
75
+ "describestream",
76
+ ]),
77
+ sqs: new Set([
78
+ "sendmessage",
79
+ "sendmessagebatch",
80
+ "receivemessage",
81
+ "deletemessage",
82
+ "deletemessagebatch",
83
+ "changemessagevisibility",
84
+ "changemessagevisibilitybatch",
85
+ "getqueueattributes",
86
+ "getqueueurl",
87
+ "purgequeue",
88
+ ]),
89
+ };
90
+
91
+ /** CloudFormation types that declare an entity of each curated service. */
92
+ const SERVICE_RESOURCE_TYPES: Record<string, ReadonlySet<string>> = {
93
+ s3: new Set(["AWS::S3::Bucket"]),
94
+ dynamodb: new Set(["AWS::DynamoDB::Table", "AWS::DynamoDB::GlobalTable"]),
95
+ sqs: new Set(["AWS::SQS::Queue"]),
96
+ };
97
+
98
+ /**
99
+ * ARN resource segments that make an ARN service-wide rather than
100
+ * entity-scoped. `arn:aws:s3:::my-bucket/*` is bucket-scoped and NOT here.
101
+ */
102
+ const SERVICE_WIDE_REST: Record<string, ReadonlySet<string>> = {
103
+ s3: new Set(["*"]),
104
+ dynamodb: new Set(["*", "table/*"]),
105
+ sqs: new Set(["*"]),
106
+ };
107
+
108
+ const IAM_TYPES = new Set(["AWS::IAM::Policy", "AWS::IAM::Role", "AWS::IAM::ManagedPolicy"]);
109
+
110
+ const ARN_SERVICE_RE = /arn:[^:\s]*:([a-z0-9-]+):/g;
111
+
112
+ function asStringArray(value: unknown): string[] | null {
113
+ if (typeof value === "string") return [value];
114
+ if (Array.isArray(value) && value.every((v) => typeof v === "string")) {
115
+ return value as string[];
116
+ }
117
+ return null;
118
+ }
119
+
120
+ /** `"*"`, or an ARN whose service is in `services` and whose resource segment is service-wide. */
121
+ function isServiceWideResource(value: string, services: Set<string>): boolean {
122
+ if (value === "*") return true;
123
+ const m = /^arn:[^:]*:([^:]*):[^:]*:[^:]*:(.+)$/.exec(value);
124
+ if (!m) return false;
125
+ const [, service, rest] = m;
126
+ if (!services.has(service)) return false;
127
+ return SERVICE_WIDE_REST[service]?.has(rest) ?? false;
128
+ }
129
+
130
+ /**
131
+ * The services an Allow statement touches, if every action lands in the
132
+ * curated resource-scopable table. Null when any action is outside it
133
+ * (or malformed / an action-name wildcard).
134
+ */
135
+ function curatedServices(actions: string[]): Set<string> | null {
136
+ const services = new Set<string>();
137
+ for (const action of actions) {
138
+ const m = /^([a-z0-9-]+):([A-Za-z0-9]+)$/.exec(action);
139
+ if (!m) return null;
140
+ const [, service, name] = m;
141
+ const table = RESOURCE_SCOPABLE_ACTIONS[service];
142
+ if (!table || !table.has(name.toLowerCase())) return null;
143
+ services.add(service);
144
+ }
145
+ return services.size > 0 ? services : null;
146
+ }
147
+
148
+ /**
149
+ * Resolve which declared roles a policy resource is attached to. Null means
150
+ * "cannot prove" (users/groups, literal role names, no roles at all).
151
+ */
152
+ function attachedRoles(logicalId: string, resource: CFResource, template: CFTemplate): Set<string> | null {
153
+ const resources = template.Resources ?? {};
154
+ if (resource.Type === "AWS::IAM::Role") return new Set([logicalId]);
155
+
156
+ const props = resource.Properties ?? {};
157
+ // Users/groups have no consumers in the resource graph — untraceable.
158
+ if (Array.isArray(props.Users) && props.Users.length > 0) return null;
159
+ if (Array.isArray(props.Groups) && props.Groups.length > 0) return null;
160
+
161
+ const roles = new Set<string>();
162
+ if (props.Roles !== undefined) {
163
+ if (!Array.isArray(props.Roles)) return null;
164
+ for (const entry of props.Roles) {
165
+ // A literal role name points outside the declared graph.
166
+ if (typeof entry === "string") return null;
167
+ const refs = findResourceRefs(entry);
168
+ if (refs.size !== 1) return null;
169
+ const [id] = refs;
170
+ if (resources[id]?.Type !== "AWS::IAM::Role") return null;
171
+ roles.add(id);
172
+ }
173
+ }
174
+
175
+ // A managed policy can also be attached from the role side (ManagedPolicyArns).
176
+ if (resource.Type === "AWS::IAM::ManagedPolicy") {
177
+ for (const [roleId, candidate] of Object.entries(resources)) {
178
+ if (candidate.Type !== "AWS::IAM::Role") continue;
179
+ if (findResourceRefs(candidate.Properties?.ManagedPolicyArns).has(logicalId)) {
180
+ roles.add(roleId);
181
+ }
182
+ }
183
+ }
184
+
185
+ return roles.size > 0 ? roles : null;
186
+ }
187
+
188
+ /**
189
+ * The non-IAM resources that reference any of the roles (the role's
190
+ * consumers). An IAM::InstanceProfile is a pass-through hop: its own
191
+ * consumers count instead.
192
+ */
193
+ function consumersOf(
194
+ roleIds: Set<string>,
195
+ reverseIndex: Map<string, Set<string>>,
196
+ template: CFTemplate,
197
+ ): Array<[string, CFResource]> {
198
+ const resources = template.Resources ?? {};
199
+ const seen = new Set<string>();
200
+ const queue = [...roleIds].flatMap((id) => [...(reverseIndex.get(id) ?? [])]);
201
+ const consumers: Array<[string, CFResource]> = [];
202
+
203
+ while (queue.length > 0) {
204
+ const id = queue.shift() as string;
205
+ if (seen.has(id)) continue;
206
+ seen.add(id);
207
+ const resource = resources[id];
208
+ if (!resource) continue;
209
+ if (resource.Type === "AWS::IAM::InstanceProfile") {
210
+ queue.push(...(reverseIndex.get(id) ?? []));
211
+ continue;
212
+ }
213
+ if (resource.Type.startsWith("AWS::IAM::")) continue; // attachment, not consumption
214
+ consumers.push([id, resource]);
215
+ }
216
+
217
+ return consumers;
218
+ }
219
+
220
+ /**
221
+ * A consumer edge the declared graph cannot enumerate: a literal ARN of one
222
+ * of the statement's services (a foreign, undeclared entity) or an
223
+ * Fn::ImportValue anywhere in the consumer (a cross-stack edge).
224
+ */
225
+ function hasForeignOrIntrinsicEdge(value: unknown, services: Set<string>): boolean {
226
+ if (value === null || value === undefined) return false;
227
+ if (typeof value === "string") {
228
+ for (const m of value.matchAll(ARN_SERVICE_RE)) {
229
+ if (services.has(m[1])) return true;
230
+ }
231
+ return false;
232
+ }
233
+ if (typeof value !== "object") return false;
234
+ if (Array.isArray(value)) {
235
+ return value.some((item) => hasForeignOrIntrinsicEdge(item, services));
236
+ }
237
+ const obj = value as Record<string, unknown>;
238
+ if ("Fn::ImportValue" in obj) return true;
239
+ return Object.values(obj).some((v) => hasForeignOrIntrinsicEdge(v, services));
240
+ }
241
+
242
+ const S3_OBJECT_ACTIONS = new Set([
243
+ "getobject",
244
+ "getobjectversion",
245
+ "getobjectacl",
246
+ "getobjecttagging",
247
+ "putobject",
248
+ "putobjectacl",
249
+ "putobjecttagging",
250
+ "deleteobject",
251
+ "deleteobjectversion",
252
+ "listmultipartuploadparts",
253
+ "abortmultipartupload",
254
+ ]);
255
+
256
+ function policyKind(type: string): string {
257
+ if (type === "AWS::IAM::Role") return "role";
258
+ if (type === "AWS::IAM::ManagedPolicy") return "managed policy";
259
+ return "policy";
260
+ }
261
+
262
+ export function checkWildcardResourceEnumerable(ctx: PostSynthContext): PostSynthDiagnostic[] {
263
+ const diagnostics: PostSynthDiagnostic[] = [];
264
+
265
+ for (const [_lexicon, output] of ctx.outputs) {
266
+ const template = parseCFTemplate(output);
267
+ if (!template?.Resources) continue;
268
+
269
+ const reverseIndex = buildReverseRefIndex(template);
270
+
271
+ for (const [logicalId, resource] of Object.entries(template.Resources)) {
272
+ if (!IAM_TYPES.has(resource.Type)) continue;
273
+
274
+ // walkPolicyStatements also yields a role's AssumeRolePolicyDocument
275
+ // statements; those always carry a Principal and are gated off below.
276
+ for (const stmt of walkPolicyStatements(resource)) {
277
+ if (stmt.Effect !== "Allow") continue;
278
+ if ("Condition" in stmt || "NotAction" in stmt || "NotResource" in stmt) continue;
279
+ if ("Principal" in stmt || "NotPrincipal" in stmt) continue;
280
+ if (isIntrinsic(stmt.Action) || isIntrinsic(stmt.Resource)) continue;
281
+
282
+ const actions = asStringArray(stmt.Action);
283
+ const resources = asStringArray(stmt.Resource);
284
+ if (!actions || !resources || actions.length === 0 || resources.length === 0) continue;
285
+
286
+ const services = curatedServices(actions);
287
+ if (!services) continue;
288
+ if (!resources.every((r) => isServiceWideResource(r, services))) continue;
289
+
290
+ const roles = attachedRoles(logicalId, resource, template);
291
+ if (!roles) continue;
292
+
293
+ const consumers = consumersOf(roles, reverseIndex, template);
294
+ if (consumers.length === 0) continue;
295
+
296
+ // Every consumer edge must stay inside the declared graph.
297
+ if (consumers.some(([, c]) => hasForeignOrIntrinsicEdge(c.Properties, services))) continue;
298
+
299
+ // The declared entities of each granted service the consumers touch.
300
+ const touched = new Set<string>();
301
+ let enumerable = true;
302
+ for (const service of services) {
303
+ const types = SERVICE_RESOURCE_TYPES[service];
304
+ const serviceTouched = new Set<string>();
305
+ for (const [, consumer] of consumers) {
306
+ for (const ref of findResourceRefs(consumer.Properties)) {
307
+ if (types.has(template.Resources[ref]?.Type ?? "")) serviceTouched.add(ref);
308
+ }
309
+ }
310
+ if (serviceTouched.size === 0) {
311
+ enumerable = false;
312
+ break;
313
+ }
314
+ for (const id of serviceTouched) touched.add(id);
315
+ }
316
+ if (!enumerable) continue;
317
+
318
+ const suggestion = JSON.stringify(
319
+ [...touched].sort().map((id) => ({ "Fn::GetAtt": [id, "Arn"] })),
320
+ );
321
+ const objectHint = actions.some((a) => {
322
+ const [service, name] = a.split(":");
323
+ return service === "s3" && S3_OBJECT_ACTIONS.has(name.toLowerCase());
324
+ })
325
+ ? ' (s3 object-level actions also need the "/*" object suffix on the bucket Arn)'
326
+ : "";
327
+
328
+ diagnostics.push({
329
+ checkId: "WAW059",
330
+ severity: "warning",
331
+ message:
332
+ `IAM ${policyKind(resource.Type)} "${logicalId}" allows ${actions.join(", ")} on ` +
333
+ `Resource ${JSON.stringify(stmt.Resource)}, but the declared graph enumerates the touched set — ` +
334
+ `tighten Resource to ${suggestion}${objectHint}`,
335
+ entity: logicalId,
336
+ lexicon: "aws",
337
+ });
338
+ }
339
+ }
340
+ }
341
+
342
+ return diagnostics;
343
+ }
344
+
345
+ export const waw059: PostSynthCheck = {
346
+ id: "WAW059",
347
+ description:
348
+ "Wildcard Resource where the declared graph enumerates the touched set — tighten to the consumers' declared Arns",
349
+
350
+ check(ctx: PostSynthContext): PostSynthDiagnostic[] {
351
+ return checkWildcardResourceEnumerable(ctx);
352
+ },
353
+ };
@@ -0,0 +1,131 @@
1
+ import { describe, test, expect } from "vitest";
2
+ import { createPostSynthContext } from "@intentius/chant-test-utils";
3
+ import { waw060, checkPolicyUnattached } from "./waw060";
4
+
5
+ function makeCtx(template: object) {
6
+ return createPostSynthContext({ aws: template });
7
+ }
8
+
9
+ const ALLOW_S3_READ = {
10
+ Version: "2012-10-17",
11
+ Statement: [{ Effect: "Allow", Action: ["s3:GetObject"], Resource: "arn:aws:s3:::data/*" }],
12
+ };
13
+
14
+ function managedPolicy(extra?: Record<string, unknown>) {
15
+ return {
16
+ Type: "AWS::IAM::ManagedPolicy",
17
+ Properties: { PolicyDocument: ALLOW_S3_READ, ...extra },
18
+ };
19
+ }
20
+
21
+ function inlinePolicy(extra?: Record<string, unknown>) {
22
+ return {
23
+ Type: "AWS::IAM::Policy",
24
+ Properties: { PolicyName: "read", PolicyDocument: ALLOW_S3_READ, ...extra },
25
+ };
26
+ }
27
+
28
+ function role(extra?: Record<string, unknown>) {
29
+ return {
30
+ Type: "AWS::IAM::Role",
31
+ Properties: {
32
+ AssumeRolePolicyDocument: {
33
+ Version: "2012-10-17",
34
+ Statement: [{ Effect: "Allow", Principal: { Service: "lambda.amazonaws.com" }, Action: "sts:AssumeRole" }],
35
+ },
36
+ ...extra,
37
+ },
38
+ };
39
+ }
40
+
41
+ describe("WAW060: IAM policy attached to no principal", () => {
42
+ test("check metadata", () => {
43
+ expect(waw060.id).toBe("WAW060");
44
+ expect(waw060.description).toContain("principal");
45
+ });
46
+
47
+ test("flags an unattached IAM::Policy", () => {
48
+ const ctx = makeCtx({ Resources: { Orphan: inlinePolicy() } });
49
+ const diags = checkPolicyUnattached(ctx);
50
+ expect(diags).toHaveLength(1);
51
+ expect(diags[0].checkId).toBe("WAW060");
52
+ expect(diags[0].severity).toBe("warning");
53
+ expect(diags[0].entity).toBe("Orphan");
54
+ expect(diags[0].message).toContain("grants nothing");
55
+ });
56
+
57
+ test("flags an unattached ManagedPolicy and one with empty principal lists", () => {
58
+ const ctx = makeCtx({
59
+ Resources: {
60
+ Orphan: managedPolicy(),
61
+ EmptyLists: managedPolicy({ Roles: [], Users: [], Groups: [] }),
62
+ },
63
+ });
64
+ const diags = checkPolicyUnattached(ctx);
65
+ expect(diags.map((d) => d.entity).sort()).toEqual(["EmptyLists", "Orphan"]);
66
+ });
67
+
68
+ test("quiet when a role's ManagedPolicyArns references the policy", () => {
69
+ const ctx = makeCtx({
70
+ Resources: {
71
+ ReadPolicy: managedPolicy(),
72
+ AppRole: role({ ManagedPolicyArns: [{ Ref: "ReadPolicy" }] }),
73
+ },
74
+ });
75
+ expect(checkPolicyUnattached(ctx)).toHaveLength(0);
76
+ });
77
+
78
+ test("quiet when the policy declares a Roles list", () => {
79
+ const ctx = makeCtx({
80
+ Resources: {
81
+ AppRole: role(),
82
+ ReadPolicy: managedPolicy({ Roles: [{ Ref: "AppRole" }] }),
83
+ InlineRead: inlinePolicy({ Roles: [{ Ref: "AppRole" }] }),
84
+ },
85
+ });
86
+ expect(checkPolicyUnattached(ctx)).toHaveLength(0);
87
+ });
88
+
89
+ test("AWS-managed ARN strings elsewhere do not attach the template's own policy", () => {
90
+ const ctx = makeCtx({
91
+ Resources: {
92
+ Orphan: managedPolicy(),
93
+ AppRole: role({ ManagedPolicyArns: ["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"] }),
94
+ },
95
+ });
96
+ const diags = checkPolicyUnattached(ctx);
97
+ expect(diags).toHaveLength(1);
98
+ expect(diags[0].entity).toBe("Orphan");
99
+ });
100
+
101
+ test("quiet on attachment-style resources and GetAtt edges", () => {
102
+ const ctx = makeCtx({
103
+ Resources: {
104
+ ReadPolicy: managedPolicy(),
105
+ Attachment: {
106
+ Type: "AWS::SSO::PermissionSet",
107
+ Properties: { ManagedPolicies: [{ "Fn::GetAtt": ["ReadPolicy", "PolicyArn"] }] },
108
+ },
109
+ },
110
+ });
111
+ expect(checkPolicyUnattached(ctx)).toHaveLength(0);
112
+ });
113
+
114
+ test("an Output exporting the policy counts as a reference", () => {
115
+ const ctx = makeCtx({
116
+ Resources: { SharedPolicy: managedPolicy() },
117
+ Outputs: { SharedPolicyArn: { Value: { Ref: "SharedPolicy" }, Export: { Name: "shared-read" } } },
118
+ });
119
+ expect(checkPolicyUnattached(ctx)).toHaveLength(0);
120
+ });
121
+
122
+ test("intrinsic principal lists are skipped, and non-policy IAM types are ignored", () => {
123
+ const ctx = makeCtx({
124
+ Resources: {
125
+ Conditional: managedPolicy({ Roles: { "Fn::If": ["UseRole", [{ Ref: "AppRole" }], []] } }),
126
+ AppRole: role(),
127
+ },
128
+ });
129
+ expect(checkPolicyUnattached(ctx)).toHaveLength(0);
130
+ });
131
+ });
@@ -0,0 +1,91 @@
1
+ /**
2
+ * WAW060: IAM Policy Attached to No Principal
3
+ *
4
+ * Flags AWS::IAM::Policy / AWS::IAM::ManagedPolicy resources with empty or
5
+ * absent Roles, Users, and Groups that no other part of the template
6
+ * references. A policy attached to no principal grants nothing — the same
7
+ * detached-guardrail shape WAW057 catches for SCPs. Any Ref/GetAtt edge to
8
+ * the policy (a role's ManagedPolicyArns, an attachment-style resource, a
9
+ * stack Output exporting it for another stack to attach) keeps it quiet;
10
+ * plain AWS-managed ARN strings elsewhere are not references to the
11
+ * template's own policy.
12
+ */
13
+
14
+ import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth";
15
+ import { parseCFTemplate, findResourceRefs, isIntrinsic, type CFTemplate } from "./cf-refs";
16
+
17
+ const POLICY_TYPES = new Set(["AWS::IAM::Policy", "AWS::IAM::ManagedPolicy"]);
18
+ const PRINCIPAL_PROPS = ["Roles", "Users", "Groups"] as const;
19
+
20
+ /**
21
+ * Collect every logical id referenced via Ref/Fn::GetAtt from anywhere in the
22
+ * template except the policy resources themselves — other resources'
23
+ * properties and the Outputs section. An Output edge counts as attachment
24
+ * evidence: the policy may be exported for a consuming stack to attach.
25
+ */
26
+ function collectExternalRefs(template: CFTemplate, excludeIds: Set<string>): Set<string> {
27
+ const refs = new Set<string>();
28
+ for (const [logicalId, resource] of Object.entries(template.Resources ?? {})) {
29
+ if (excludeIds.has(logicalId)) continue;
30
+ for (const ref of findResourceRefs(resource)) refs.add(ref);
31
+ }
32
+ for (const ref of findResourceRefs(template.Outputs)) refs.add(ref);
33
+ return refs;
34
+ }
35
+
36
+ export function checkPolicyUnattached(ctx: PostSynthContext): PostSynthDiagnostic[] {
37
+ const diagnostics: PostSynthDiagnostic[] = [];
38
+
39
+ for (const [_lexicon, output] of ctx.outputs) {
40
+ const template = parseCFTemplate(output);
41
+ if (!template?.Resources) continue;
42
+
43
+ const policyIds = new Set(
44
+ Object.entries(template.Resources)
45
+ .filter(([, resource]) => POLICY_TYPES.has(resource.Type))
46
+ .map(([logicalId]) => logicalId),
47
+ );
48
+ if (policyIds.size === 0) continue;
49
+
50
+ const externalRefs = collectExternalRefs(template, policyIds);
51
+
52
+ for (const logicalId of policyIds) {
53
+ const resource = template.Resources[logicalId];
54
+ const props = resource.Properties ?? {};
55
+
56
+ // Any declared principal list keeps the policy quiet. An intrinsic
57
+ // can't be statically evaluated, so it counts as attached.
58
+ let attached = false;
59
+ for (const prop of PRINCIPAL_PROPS) {
60
+ const value = props[prop];
61
+ if (isIntrinsic(value)) attached = true;
62
+ else if (Array.isArray(value) && value.length > 0) attached = true;
63
+ }
64
+ if (attached) continue;
65
+
66
+ // Reverse lookup: anything else in the template holding a Ref/GetAtt
67
+ // edge to this policy attaches (or exports) it.
68
+ if (externalRefs.has(logicalId)) continue;
69
+
70
+ const kind = resource.Type === "AWS::IAM::ManagedPolicy" ? "Managed policy" : "Policy";
71
+ diagnostics.push({
72
+ checkId: "WAW060",
73
+ severity: "warning",
74
+ message: `${kind} "${logicalId}" is attached to no principal — no Roles/Users/Groups and nothing in the template references it; an unattached policy grants nothing`,
75
+ entity: logicalId,
76
+ lexicon: "aws",
77
+ });
78
+ }
79
+ }
80
+
81
+ return diagnostics;
82
+ }
83
+
84
+ export const waw060: PostSynthCheck = {
85
+ id: "WAW060",
86
+ description: "IAM policy attached to no principal — it grants nothing",
87
+
88
+ check(ctx: PostSynthContext): PostSynthDiagnostic[] {
89
+ return checkPolicyUnattached(ctx);
90
+ },
91
+ };