feat(cli): add hyperframes lambda policies role/user/validate (#912)

* feat(cli): add hyperframes lambda policies role/user/validate

IAM bootstrap subcommand for the lambda CLI. Closes the "first run hits
'User is not authorized to perform iam:CreateRole'" gap that adopters
otherwise have to figure out by hand.

  hyperframes lambda policies user
    → prints an inline-policy doc to attach to the IAM user that runs
      the CLI

  hyperframes lambda policies role --principal=cloudformation
    → prints { TrustRelationship, InlinePolicy } for a service role
      cloudformation can assume

  hyperframes lambda policies validate ./infra/policy.json
    → diffs a checked-in policy against the CLI's required action set,
      expanding s3:* / s3:Get* / * wildcards, exits non-zero on missing
      actions (wire it into CI to catch drift before deploys fail)

The required-actions list is derived from what the SAM template at
examples/aws-lambda/template.yaml needs to create plus what
renderToLambda/getRenderProgress call against S3 + Step Functions at
runtime. Sorted alphabetically per-service so diffs stay readable.

Resource is "*" by design — CloudFormation creates new function /
state-machine / bucket ARNs on every adopter's first deploy. The
generated policy is documented as a starting point; adopters with
stricter postures narrow Resource to the deployed ARNs after the
first successful run.

Tests: 10 unit tests covering the action set, doc shape, trust policy
service principal, and validate() against valid / missing / wildcard /
single-Statement / Deny-statement inputs.

* refactor(cli): /simplify pass on lambda policies

Adds a typed TrustPolicyDocument / TrustPolicyStatement pair so
buildRoleTrustPolicy can return a real type instead of unknown. The
trust-policy shape has a Principal field that the generic
PolicyStatement doesn't model, but it was previously punted via a
return unknown rather than a parallel type.

Test cleanup: drop the `as {...}` casts that the previous return-
unknown signature forced.

* 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.
This commit is contained in:
James Russo
2026-05-17 13:15:01 -04:00
committed by GitHub
parent e90ad2da61
commit 62ddd29b74
4 changed files with 674 additions and 3 deletions
+26 -3
View File
@@ -28,6 +28,11 @@ export const examples: Example[] = [
"hyperframes lambda sites create ./my-project",
],
["Tear the stack down", "hyperframes lambda destroy"],
["Print the IAM policy the CLI needs", "hyperframes lambda policies user"],
[
"Validate a checked-in IAM policy still covers the CLI",
"hyperframes lambda policies validate ./infra/iam/hyperframes.json",
],
];
const HELP = `
@@ -41,6 +46,7 @@ ${c.bold("SUBCOMMANDS:")}
${c.accent("render")} ${c.dim("Start a distributed render (returns a renderId)")}
${c.accent("progress")} ${c.dim("Print progress + cost for an in-flight or finished render")}
${c.accent("destroy")} ${c.dim("Tear the stack down (S3 bucket is retained)")}
${c.accent("policies")} ${c.dim("Print or validate the IAM permissions the CLI needs")}
${c.bold("FIRST RUN:")}
${c.accent("hyperframes lambda deploy")}
@@ -58,17 +64,18 @@ export default defineCommand({
subcommand: {
type: "positional",
required: false,
description: "deploy | sites | render | progress | destroy",
description: "deploy | sites | render | progress | destroy | policies",
},
target: {
type: "positional",
required: false,
description: "Subcommand-specific positional (project dir, render id, etc.)",
description: "Subcommand-specific positional (project dir, render id, policies verb, etc.)",
},
extra: {
type: "positional",
required: false,
description: "Extra positional (e.g. `sites create <projectDir>`)",
description:
"Extra positional (e.g. `sites create <projectDir>` or `policies validate <policy.json>`)",
},
// Stack identity
@@ -257,6 +264,22 @@ export default defineCommand({
await runDestroy({ stackName, awsProfile: args.profile as string | undefined });
return;
}
case "policies": {
const verb = args.target as string | undefined;
if (verb !== "role" && verb !== "user" && verb !== "validate") {
console.error(
`[lambda policies] usage: hyperframes lambda policies <role|user|validate> [args]`,
);
process.exit(1);
}
const { runPolicies } = await import("./lambda/policies.js");
await runPolicies({
verb,
inputPath: args.extra as string | undefined,
json: Boolean(args.json),
});
return;
}
default:
console.error(`${c.error("Unknown subcommand:")} ${subcommand}\n${HELP}`);
process.exit(1);