Skip to content

Commit 2f289f9

Browse files
committed
fix(cli): address PR review on lambda policies
One blocker + four importants from Vai's review: - REQUIRED_ACTIONS was missing `s3:ListAllMyBuckets` (called by `sam deploy --resolve-s3` on first run to discover/create the `aws-sam-cli-managed-default-*` artifact bucket) and `cloudformation:ValidateTemplate` (CFN template validation during change-set creation). Without these, a first-deploy adopter with the generated policy hits AccessDenied on the very call the PR was meant to unblock. Added both. - `policies role --principal=lambda` was a footgun — it produced a `lambda.amazonaws.com` trust paired with the full deploy superset, i.e. a confusingly-overscoped Lambda execution role no human should attach (the SAM template creates its own scoped execution role automatically). Dropped `lambda` as a principal option; `policies role` now always emits a CloudFormation service-role doc. - `validatePolicy` silently misreported NotAction/NotResource statements (treating them as zero grants), producing false negatives. Detect both shapes and surface them via a new `warnings: string[]` field; NotAction statements are skipped (rather than producing a false negative), NotResource is treated as full action grant + a warning. - Mid-string wildcards (`s3:Get*Object`, `?`) silently failed the matcher. End-anchored wildcards still work; mid-string patterns now warn so users know the validator can't expand them. - Dropped the dead `samArtifactBucket` action group (fully subsumed by `s3Bucket` + `s3Object`). - `validate --json` now wraps errors in a friendly envelope (`{ ok: false, error: "..." }`) so CI consumers have one parse shape regardless of failure mode. - lambda.ts subcommand description and examples updated to include `policies`. Tests: 5 new negative-path tests cover NotAction warning, NotResource warning, mid-string wildcard warning, missing file (ENOENT), malformed JSON (SyntaxError), and absent Statement field. All 21 policies tests pass.
1 parent 5cc9291 commit 2f289f9

3 files changed

Lines changed: 164 additions & 40 deletions

File tree

‎packages/cli/src/commands/lambda.ts‎

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ export const examples: Example[] = [
2828
"hyperframes lambda sites create ./my-project",
2929
],
3030
["Tear the stack down", "hyperframes lambda destroy"],
31+
["Print the IAM policy the CLI needs", "hyperframes lambda policies user"],
32+
[
33+
"Validate a checked-in IAM policy still covers the CLI",
34+
"hyperframes lambda policies validate ./infra/iam/hyperframes.json",
35+
],
3136
];
3237

3338
const HELP = `
@@ -59,17 +64,18 @@ export default defineCommand({
5964
subcommand: {
6065
type: "positional",
6166
required: false,
62-
description: "deploy | sites | render | progress | destroy",
67+
description: "deploy | sites | render | progress | destroy | policies",
6368
},
6469
target: {
6570
type: "positional",
6671
required: false,
67-
description: "Subcommand-specific positional (project dir, render id, etc.)",
72+
description: "Subcommand-specific positional (project dir, render id, policies verb, etc.)",
6873
},
6974
extra: {
7075
type: "positional",
7176
required: false,
72-
description: "Extra positional (e.g. `sites create <projectDir>`)",
77+
description:
78+
"Extra positional (e.g. `sites create <projectDir>` or `policies validate <policy.json>`)",
7379
},
7480

7581
// Stack identity
@@ -113,13 +119,6 @@ export default defineCommand({
113119
description: "Poll cadence in ms when --wait is set (default: 5000)",
114120
},
115121

116-
// policies
117-
principal: {
118-
type: "string",
119-
description:
120-
"Trust principal for `policies role` (lambda | cloudformation; default cloudformation)",
121-
},
122-
123122
// shared
124123
json: { type: "boolean", description: "Emit machine-readable JSON" },
125124
},
@@ -277,7 +276,6 @@ export default defineCommand({
277276
await runPolicies({
278277
verb,
279278
inputPath: args.extra as string | undefined,
280-
principal: parsePrincipal(args.principal),
281279
json: Boolean(args.json),
282280
});
283281
return;
@@ -331,7 +329,6 @@ const FORMATS = ["mp4", "mov", "png-sequence"] as const;
331329
const CODECS = ["h264", "h265"] as const;
332330
const QUALITIES = ["draft", "standard", "high"] as const;
333331
const CHROME_SOURCES = ["sparticuz", "chrome-headless-shell"] as const;
334-
const PRINCIPALS = ["lambda", "cloudformation"] as const;
335332

336333
const parseFormat = (raw: unknown): (typeof FORMATS)[number] =>
337334
parseEnum(raw, FORMATS, "[lambda render] --format", "mp4")!;
@@ -341,5 +338,3 @@ const parseQuality = (raw: unknown): (typeof QUALITIES)[number] | undefined =>
341338
parseEnum(raw, QUALITIES, "[lambda render] --quality", undefined);
342339
const parseChromeSource = (raw: unknown): (typeof CHROME_SOURCES)[number] =>
343340
parseEnum(raw, CHROME_SOURCES, "[lambda deploy] --chrome-source", "sparticuz")!;
344-
const parsePrincipal = (raw: unknown): (typeof PRINCIPALS)[number] =>
345-
parseEnum(raw, PRINCIPALS, "[lambda policies role] --principal", "cloudformation")!;

‎packages/cli/src/commands/lambda/policies.test.ts‎

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,10 @@ describe("policies — buildPolicyDocument", () => {
5454
});
5555

5656
describe("policies — buildRoleTrustPolicy", () => {
57-
it("returns a sts:AssumeRole statement scoped to the requested service", () => {
58-
const trust = buildRoleTrustPolicy("cloudformation");
57+
it("returns a sts:AssumeRole statement for the CloudFormation service principal", () => {
58+
const trust = buildRoleTrustPolicy();
5959
expect(trust.Statement[0]!.Action).toBe("sts:AssumeRole");
6060
expect(trust.Statement[0]!.Principal.Service).toBe("cloudformation.amazonaws.com");
61-
const lambdaTrust = buildRoleTrustPolicy("lambda");
62-
expect(lambdaTrust.Statement[0]!.Principal.Service).toBe("lambda.amazonaws.com");
6361
});
6462
});
6563

@@ -167,6 +165,59 @@ describe("policies — validatePolicy", () => {
167165
// Allow set covers required actions.
168166
expect(result.missing).toEqual([]);
169167
});
168+
169+
it("warns on NotAction shapes instead of producing a false negative", () => {
170+
const path = writePolicy({
171+
Version: "2012-10-17",
172+
Statement: [{ Effect: "Allow", NotAction: ["iam:DeleteUser"], Resource: "*" }],
173+
} as unknown as Parameters<typeof writePolicy>[0]);
174+
const result = validatePolicy(path);
175+
expect(result.warnings.some((w) => /NotAction/.test(w))).toBe(true);
176+
// Without the warning, the validator would silently report everything
177+
// as missing. With it, the validator skips the statement and reports
178+
// honestly.
179+
expect(result.missing.length).toBeGreaterThan(0);
180+
});
181+
182+
it("warns on NotResource shapes but still grants the listed actions", () => {
183+
const path = writePolicy({
184+
Version: "2012-10-17",
185+
Statement: [
186+
{ Effect: "Allow", Action: ["*"], NotResource: ["arn:aws:s3:::secret-bucket/*"] },
187+
],
188+
} as unknown as Parameters<typeof writePolicy>[0]);
189+
const result = validatePolicy(path);
190+
expect(result.warnings.some((w) => /NotResource/.test(w))).toBe(true);
191+
expect(result.missing).toEqual([]);
192+
});
193+
194+
it("warns on mid-string wildcard patterns (`s3:Get*Object`)", () => {
195+
const path = writePolicy({
196+
Version: "2012-10-17",
197+
Statement: [{ Effect: "Allow", Action: ["s3:Get*Object"], Resource: "*" }],
198+
});
199+
const result = validatePolicy(path);
200+
expect(result.warnings.some((w) => /mid-string wildcard/.test(w))).toBe(true);
201+
});
202+
203+
it("throws ENOENT for a missing file (caller decides UX)", () => {
204+
expect(() => validatePolicy(join(workdir, "does-not-exist.json"))).toThrow();
205+
});
206+
207+
it("throws SyntaxError for malformed JSON (caller decides UX)", () => {
208+
const path = join(workdir, "bad.json");
209+
writeFileSync(path, "{ not json");
210+
expect(() => validatePolicy(path)).toThrow();
211+
});
212+
213+
it("treats an absent Statement field as zero grants", () => {
214+
const path = writePolicy({ Version: "2012-10-17" } as unknown as Parameters<
215+
typeof writePolicy
216+
>[0]);
217+
const result = validatePolicy(path);
218+
expect(result.granted).toEqual([]);
219+
expect(result.missing).toEqual(allRequiredActions());
220+
});
170221
});
171222

172223
function writePolicy(doc: { Version: string; Statement: unknown }): string {

‎packages/cli/src/commands/lambda/policies.ts‎

Lines changed: 100 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ export const REQUIRED_ACTIONS = {
7272
"cloudformation:GetTemplateSummary",
7373
"cloudformation:ListStacks",
7474
"cloudformation:UpdateStack",
75+
"cloudformation:ValidateTemplate",
7576
],
7677
cloudwatchAlarms: [
7778
"cloudwatch:DeleteAlarms",
@@ -122,6 +123,7 @@ export const REQUIRED_ACTIONS = {
122123
"s3:GetBucketTagging",
123124
"s3:GetBucketVersioning",
124125
"s3:GetLifecycleConfiguration",
126+
"s3:ListAllMyBuckets",
125127
"s3:ListBucket",
126128
"s3:PutBucketPolicy",
127129
"s3:PutBucketTagging",
@@ -144,10 +146,6 @@ export const REQUIRED_ACTIONS = {
144146
"states:UntagResource",
145147
"states:UpdateStateMachine",
146148
],
147-
// The artifact bucket SAM auto-creates via --resolve-s3 needs a few
148-
// permissions on the `aws-sam-cli-*` bucket. Adopters who set
149-
// --s3-bucket explicitly can drop these.
150-
samArtifactBucket: ["s3:CreateBucket", "s3:GetObject", "s3:ListBucket", "s3:PutObject"],
151149
};
152150

153151
/** All required actions flattened, deduped, sorted. */
@@ -182,15 +180,20 @@ export function buildPolicyDocument(): PolicyDocument {
182180
};
183181
}
184182

185-
/** Trust policy a service-linked IAM role consumes (used by `policies role`). */
186-
export function buildRoleTrustPolicy(principal: "lambda" | "cloudformation"): TrustPolicyDocument {
187-
const Service = principal === "lambda" ? "lambda.amazonaws.com" : "cloudformation.amazonaws.com";
183+
/**
184+
* Trust policy for a CloudFormation service role (used by `policies role`).
185+
* Lambda execution roles are out of scope here: the SAM template creates
186+
* its own scoped execution role, and emitting a `lambda.amazonaws.com`
187+
* trust paired with the full deploy-superset inline policy below would
188+
* be a confusingly-overscoped runtime role no human should attach.
189+
*/
190+
export function buildRoleTrustPolicy(): TrustPolicyDocument {
188191
return {
189192
Version: "2012-10-17",
190193
Statement: [
191194
{
192195
Effect: "Allow",
193-
Principal: { Service },
196+
Principal: { Service: "cloudformation.amazonaws.com" },
194197
Action: "sts:AssumeRole",
195198
},
196199
],
@@ -201,8 +204,6 @@ export interface PoliciesArgs {
201204
verb: PoliciesVerb;
202205
/** For `validate`: path to an IAM policy JSON file. */
203206
inputPath?: string;
204-
/** For `role`: which service the role trusts. */
205-
principal: "lambda" | "cloudformation";
206207
/** Print JSON only. Default true for `role`/`user` (output is JSON by definition); ignored for `validate`. */
207208
json: boolean;
208209
}
@@ -222,7 +223,7 @@ export async function runPolicies(args: PoliciesArgs): Promise<void> {
222223
return;
223224
}
224225
case "role": {
225-
const trust = buildRoleTrustPolicy(args.principal);
226+
const trust = buildRoleTrustPolicy();
226227
const inline = buildPolicyDocument();
227228
const wrapped = {
228229
TrustRelationship: trust,
@@ -233,16 +234,37 @@ export async function runPolicies(args: PoliciesArgs): Promise<void> {
233234
}
234235
case "validate": {
235236
if (!args.inputPath) {
236-
throw new Error(
237-
"[lambda policies validate] usage: hyperframes lambda policies validate <policy.json>",
238-
);
237+
const msg =
238+
"[lambda policies validate] usage: hyperframes lambda policies validate <policy.json>";
239+
if (args.json) {
240+
console.log(JSON.stringify({ ok: false, error: msg }, null, 2));
241+
process.exitCode = 1;
242+
return;
243+
}
244+
throw new Error(msg);
245+
}
246+
let result: ValidateResult;
247+
try {
248+
result = validatePolicy(args.inputPath);
249+
} catch (err) {
250+
const msg = err instanceof Error ? err.message : String(err);
251+
if (args.json) {
252+
console.log(JSON.stringify({ ok: false, error: msg }, null, 2));
253+
process.exitCode = 1;
254+
return;
255+
}
256+
console.error(c.error(`Failed to validate ${args.inputPath}: ${msg}`));
257+
process.exitCode = 1;
258+
return;
239259
}
240-
const result = validatePolicy(args.inputPath);
241260
if (args.json) {
242-
console.log(JSON.stringify(result, null, 2));
261+
console.log(JSON.stringify({ ok: result.missing.length === 0, ...result }, null, 2));
243262
if (result.missing.length > 0) process.exitCode = 1;
244263
return;
245264
}
265+
for (const warning of result.warnings) {
266+
console.warn(c.dim(`Warning: ${warning}`));
267+
}
246268
if (result.missing.length === 0) {
247269
console.log(c.success(`Policy covers all ${result.required.length} required actions.`));
248270
return;
@@ -265,28 +287,67 @@ export interface ValidateResult {
265287
required: string[];
266288
granted: string[];
267289
missing: string[];
290+
/** Non-fatal warnings about policy shapes we couldn't fully evaluate. */
291+
warnings: string[];
268292
}
269293

270294
/**
271295
* Parse an IAM policy doc + flatten its Allow statements into a set of
272296
* "granted" actions. Returns the difference vs {@link allRequiredActions}.
273297
*
274298
* Supports the common shapes: `Action` as a string or array; `Statement`
275-
* as a single object or an array; wildcards (`s3:*`, `*`) expand to
276-
* match anything in the required list.
299+
* as a single object or an array; wildcards (`s3:*`, `s3:Get*`, `*`)
300+
* expand to match anything in the required list.
301+
*
302+
* Limitations surfaced as `warnings`:
303+
* - `NotAction` / `NotResource` shapes — IAM grants the complement of
304+
* the listed actions, but a sound check would need to model the
305+
* full IAM action namespace. We flag the statement instead of
306+
* producing a false negative.
307+
* - Mid-string wildcards (`s3:Get*Object`, `?`) — supported by IAM,
308+
* not by our matcher. We end-anchor only.
277309
*/
278310
export function validatePolicy(policyPath: string): ValidateResult {
279311
const raw = readFileSync(policyPath, "utf-8");
280312
const parsed = JSON.parse(raw) as { Statement?: unknown };
281-
const statements: Array<{ Effect?: string; Action?: unknown }> = Array.isArray(parsed.Statement)
282-
? (parsed.Statement as { Effect?: string; Action?: unknown }[])
313+
const statements: Array<{
314+
Effect?: string;
315+
Action?: unknown;
316+
NotAction?: unknown;
317+
NotResource?: unknown;
318+
}> = Array.isArray(parsed.Statement)
319+
? (parsed.Statement as {
320+
Effect?: string;
321+
Action?: unknown;
322+
NotAction?: unknown;
323+
NotResource?: unknown;
324+
}[])
283325
: parsed.Statement
284-
? [parsed.Statement as { Effect?: string; Action?: unknown }]
326+
? [
327+
parsed.Statement as {
328+
Effect?: string;
329+
Action?: unknown;
330+
NotAction?: unknown;
331+
NotResource?: unknown;
332+
},
333+
]
285334
: [];
286335

287336
const grantedPatterns: string[] = [];
337+
const warnings: string[] = [];
288338
for (const stmt of statements) {
289339
if (stmt.Effect !== "Allow") continue;
340+
if (stmt.NotAction !== undefined) {
341+
warnings.push(
342+
"Allow statement uses NotAction; the validator only checks positive Action grants, so this statement is being ignored. Convert to an explicit Action list to validate it.",
343+
);
344+
continue;
345+
}
346+
if (stmt.NotResource !== undefined) {
347+
warnings.push(
348+
"Allow statement uses NotResource; resource-scoping is not modelled by this validator. Treating the statement as fully granted on its Action set.",
349+
);
350+
}
290351
const actions = stmt.Action;
291352
if (typeof actions === "string") {
292353
grantedPatterns.push(actions);
@@ -295,6 +356,14 @@ export function validatePolicy(policyPath: string): ValidateResult {
295356
}
296357
}
297358

359+
for (const pattern of grantedPatterns) {
360+
if (hasMidStringWildcard(pattern)) {
361+
warnings.push(
362+
`Action pattern ${JSON.stringify(pattern)} contains a mid-string wildcard the validator can't expand; only end-anchored wildcards (\`*\`, \`service:*\`, \`prefix*\`) are honoured.`,
363+
);
364+
}
365+
}
366+
298367
const required = allRequiredActions();
299368
const granted: string[] = [];
300369
const missing: string[] = [];
@@ -305,7 +374,16 @@ export function validatePolicy(policyPath: string): ValidateResult {
305374
missing.push(action);
306375
}
307376
}
308-
return { required, granted, missing };
377+
return { required, granted, missing, warnings };
378+
}
379+
380+
function hasMidStringWildcard(pattern: string): boolean {
381+
// Wildcards we DO support: bare `*`, `service:*`, `prefix*` (single
382+
// trailing `*`). Anything else (mid-string `*` or `?`) is mid-string.
383+
if (pattern === "*") return false;
384+
if (pattern.endsWith(":*")) return false;
385+
if (pattern.endsWith("*") && !pattern.slice(0, -1).includes("*")) return false;
386+
return pattern.includes("*") || pattern.includes("?");
309387
}
310388

311389
function actionMatches(pattern: string, action: string): boolean {

0 commit comments

Comments
 (0)