Let Your AI Agent Write Least-Privilege IAM Policies

We gave Claude Code the LocalStack MCP server and a serverless app whose Lambda role could do anything on any resource. The agent used the IAM Policy Analyzer to find the permissions the app really needs, and proved the app still worked with IAM enforcement turned on.

Let Your AI Agent Write Least-Privilege IAM Policies

Introduction

IAM policies often start out too broad. A Lambda function needs to read a table, but the first deployment fails with AccessDenied. Someone adds dynamodb:* with Resource: "*" to fix it. The policy works, so no one revisits it. Soon, the function can access far more than it needs.

Writing a narrow policy by hand takes time. You must find every API call, map it to an IAM action, and identify the right resource ARN. If you miss one, the app fails only when that code path runs.

We wanted to see whether an AI agent could do this work. We gave Claude Code access to the LocalStack MCP server and an intentionally insecure serverless app. Its Lambda role allowed every action in nine AWS services. We asked the agent to replace that policy with a least-privilege policy.

The agent used the IAM Policy Analyzer to find the required permissions. It reviewed the generated policy against the code, enabled IAM enforcement, and verified that the app still worked. It also proved that the role could no longer access unrelated resources.

The tools: IAM enforcement and the IAM Policy Analyzer

By default, LocalStack accepts AWS requests without checking IAM. This keeps local development fast, but it also hides broken or overly broad policies.

IAM policy enforcement makes LocalStack evaluate the policies that apply to each request. These include identity and resource policies, permission boundaries, and service control policies. If no policy allows a request, LocalStack returns AccessDenied.

This check also applies to Lambda functions. LocalStack gives each function temporary credentials for its execution role. Its SDK calls arrive as assumed-role/<role-name>/<function-name> and are checked against the role’s policy.

Enforcement has three modes:

  • DISABLED is the default. LocalStack allows every request.
  • SOFT_MODE evaluates every request and logs the ones that would be denied, but still lets them through.
  • ENFORCED denies requests that the policies do not allow.

Each denial is written to the LocalStack logs with the principal, the action, and the resource:

Terminal window
User: arn:aws:sts::000000000000:assumed-role/blog_app_lambda_data/blog-application-data
is not authorized to perform: dynamodb:Scan on resource:
arn:aws:dynamodb:us-east-1:000000000000:table/blog-posts
because no identity-based policy allows the dynamodb:Scan action

The LocalStack MCP server provides a localstack-iam-policy-analyzer tool with three actions:

  • set-mode changes the mode without restarting LocalStack.
  • get-status returns the current mode.
  • analyze-policies reads recent logs, removes duplicate denials, and creates a policy that would allow those requests. It groups actions by resource.

The agent also uses localstack-management to start LocalStack, localstack-deployer to apply the Terraform stack, and localstack-aws-client to run AWS CLI commands.

Prerequisites

  • Docker installed and running.
  • A LOCALSTACK_AUTH_TOKEN from a LocalStack account. IAM policy enforcement is included in the Base and Ultimate plans.
  • Node.js 22+ to run the MCP server with npx.
  • Terraform and tflocal (pip install terraform-local). The deployer tool uses them to apply the stack.
  • Python 3 and curl for the sample app’s test script.
  • Claude Code or another MCP client.

The Lambda layer uses x86_64. Docker Desktop runs it through emulation on Apple Silicon without extra setup.

Step 1: Set up the MCP server

The MCP server comes with a wizard that writes the client configuration for you:

Terminal window
npx -y @localstack/localstack-mcp-server init

The wizard checks Docker and reads LOCALSTACK_AUTH_TOKEN from your environment. If the token is missing, it asks for one. It then finds installed MCP clients, such as Claude Code, Cursor, VS Code, and Codex, and configures the clients you select. Restart your agent to load the LocalStack tools.

You do not need to configure anything for IAM enforcement. The agent switches modes with the analyzer tool after LocalStack starts.

Step 2: Get the sample app

The sample app is a smaller version of the serverless blog module from AWSGoat, an intentionally vulnerable AWS project from INE.

A Python Lambda function behind API Gateway provides the blog backend. Users can register, log in, write posts, and upload images. Two DynamoDB tables store the data, and an S3 bucket stores the images.

Architecture of the sample app

Clone the repository:

Terminal window
git clone https://github.com/localstack-samples/sample-iam-policy-analyzer-awsgoat.git
cd sample-iam-policy-analyzer-awsgoat

We removed the parts that need EC2 but kept the serverless app and its IAM policy. The function’s execution role, blog_app_lambda_data, has this policy:

{
"Sid": "Pol1",
"Effect": "Allow",
"Action": [
"s3:*", "s3-object-lambda:*", "autoscaling:Describe*", "cloudwatch:*",
"logs:*", "sns:*", "dynamodb:*", "dax:*", "lambda:*"
],
"Resource": "*"
}

The function only needs two tables and one bucket. However, this policy allows any action in nine services on every resource in the account. An attacker who exploits the function would also gain those permissions.

Terraform loads the policy from resources/iam/data-lambda-policy.json. To change the role, edit this file and apply the stack again. The repository also includes exercise-api.sh. It registers a user, logs in, and tests the main routes. It fails if a route returns an unexpected status.

Step 3: Give the agent the task

Open Claude Code in the repository folder. We used Claude Opus 5.5. This prompt gives the agent a goal and a clear sequence:

Terminal window
This repository deploys a blog API whose Lambda execution role has a wildcard IAM
policy. Replace it with a least-privilege policy and prove the app still works.
Do everything on LocalStack through the LocalStack MCP server.
1. Start LocalStack and deploy the Terraform stack in this directory.
2. Read the policy attached to the role blog_app_lambda_data and note what it grants.
3. Run ./exercise-api.sh to record which routes work today.
4. Cut resources/iam/data-lambda-policy.json down to CloudWatch Logs only, redeploy,
switch IAM enforcement to SOFT_MODE, and run the routes again. IAM changes take
a few seconds to apply.
5. Generate a policy from the logged denials with the IAM Policy Analyzer. Review it,
fix anything that is too narrow or too broad, write it to the policy file, and
redeploy.
6. Switch enforcement to ENFORCED and run the routes again. All of them must pass.
7. Show what the old policy allowed that the new one blocks: run a small probe under
the same role against a resource the app never uses, before and after.
8. Leave the app on the new policy and summarize what changed.

Step 4 is important for two reasons. First, a policy that allows everything produces no denials, so the analyzer has nothing to inspect. Second, SOFT_MODE lets the whole request finish while logging every missing permission. With ENFORCED, the first denial stops the request, so each run might reveal only one missing permission.

Step 4: Deploy and record a baseline

The agent found LocalStack stopped, started it, and deployed the stack:

Terminal window
● localstack-management(action: "start")
⎿ 🚀 LocalStack started successfully!
Edition: pro, Version: 2026.9.0
● localstack-deployer(action: "deploy", projectType: "terraform")
⎿ Apply complete! Resources: 280 added, 0 changed, 0 destroyed.

The deployment output was long, so the agent checked the result and searched for errors. It then read the role’s policy, checked the enforcement mode, and tested the routes:

Terminal window
● localstack-aws-client(command: "iam get-policy-version --policy-arn
arn:aws:iam::000000000000:policy/lambda-data-policies --version-id v1")
⎿ "Action": ["s3:*", "s3-object-lambda:*", "autoscaling:Describe*", "cloudwatch:*",
"logs:*", "sns:*", "dynamodb:*", "dax:*", "lambda:*"],
"Resource": "*"
● localstack-iam-policy-analyzer(action: "get-status")
⎿ 🔓 Current Mode: DISABLED
IAM enforcement is disabled. All actions are permitted.
● Bash(./exercise-api.sh)
⎿ list-posts POST /list-posts HTTP 200 ok
register POST /register HTTP 200 ok
login-wrong-pw POST /login HTTP 401 ok
login POST /login HTTP 200 ok
save-post POST /save-post HTTP 200 ok
get-dashboard POST /get-dashboard HTTP 200 ok
save-content POST /save-content HTTP 200 ok
list-my-posts POST /list-posts HTTP 200 ok

All eight checks passed. However, this baseline does not validate the policy because IAM enforcement was disabled.

Step 5: Discover the permissions in soft mode

5.1: Cut the policy down to logs only

The agent reduced the policy to two statements. They only allowed the function to create and write to its own log group, /aws/lambda/blog-application-data. It then redeployed, enabled soft mode, and tested the routes again:

Terminal window
● localstack-deployer(action: "deploy", projectType: "terraform")
⎿ Apply complete! Resources: 0 added, 2 changed, 0 destroyed.
● localstack-iam-policy-analyzer(action: "set-mode", mode: "SOFT_MODE")
⎿ 📝 IAM enforcement mode has been set to SOFT_MODE.
● Bash(sleep 8 && ./exercise-api.sh)
⎿ list-posts POST /list-posts HTTP 200 ok
...
list-my-posts POST /list-posts HTTP 200 ok

The routes still passed because soft mode logs denials without blocking requests. LocalStack checked every DynamoDB and S3 call and logged each missing permission. The command waits eight seconds because a running function can briefly keep the old permissions after a policy update.

5.2: Generate the policy

Next, the agent called the analyzer:

Terminal window
● localstack-iam-policy-analyzer(action: "analyze-policies")
⎿ # 🔍 IAM Policy Analysis Report
- Found 12 IAM permission errors.
- Identified 6 unique missing permissions.
- This affects 1 principal(s):
arn:aws:sts::000000000000:assumed-role/blog_app_lambda_data/blog-application-data

The analyzer reduced 12 denials to six unique permissions. All came from the function’s execution role. It generated one policy statement for each resource:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GeneratedStatement1",
"Effect": "Allow",
"Action": ["dynamodb:PutItem", "dynamodb:Scan"],
"Resource": "arn:aws:dynamodb:us-east-1:000000000000:table/blog-posts"
},
{
"Sid": "GeneratedStatement2",
"Effect": "Allow",
"Action": ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Scan"],
"Resource": "arn:aws:dynamodb:us-east-1:000000000000:table/blog-users"
},
{
"Sid": "GeneratedStatement3",
"Effect": "Allow",
"Action": ["s3:PutObject"],
"Resource": "arn:aws:s3:::production-blog-awsgoat-bucket-000000000000/images/20261006084009665853.png"
}
]
}

This is much narrower than the original policy. However, it only covers the requests that the test script made.

Step 6: Review the generated policy

The agent reviewed the generated policy and found three gaps.

First, the S3 statement allowed only one exact object: images/20261006084009665853.png. Each upload gets a new timestamped key, so the next upload would fail. The agent changed the resource to images/*.

Second, the upload sets ACL="public-read". AWS requires both s3:PutObject and s3:PutObjectAcl for this request. The analyzer did not report the ACL action, so the agent added it.

Third, the script tests eight routes, but the function has about twenty. The agent reviewed every DynamoDB call in the code. It found untested routes that use UpdateItem, DeleteItem, and PartiQLSelect, then added each action to the correct table.

The final policy:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CreateLogGroup",
"Effect": "Allow",
"Action": "logs:CreateLogGroup",
"Resource": "arn:aws:logs:us-east-1:000000000000:log-group:/aws/lambda/blog-application-data"
},
{
"Sid": "WriteLogs",
"Effect": "Allow",
"Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
"Resource": "arn:aws:logs:us-east-1:000000000000:log-group:/aws/lambda/blog-application-data:*"
},
{
"Sid": "UsersTable",
"Effect": "Allow",
"Action": ["dynamodb:Scan", "dynamodb:GetItem", "dynamodb:PutItem",
"dynamodb:UpdateItem", "dynamodb:DeleteItem", "dynamodb:PartiQLSelect"],
"Resource": "arn:aws:dynamodb:us-east-1:000000000000:table/blog-users"
},
{
"Sid": "PostsTable",
"Effect": "Allow",
"Action": ["dynamodb:Scan", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:UpdateItem"],
"Resource": "arn:aws:dynamodb:us-east-1:000000000000:table/blog-posts"
},
{
"Sid": "UploadImages",
"Effect": "Allow",
"Action": ["s3:PutObject", "s3:PutObjectAcl"],
"Resource": "arn:aws:s3:::production-blog-awsgoat-bucket-000000000000/images/*"
}
]
}

Each statement is limited to one table, one bucket prefix, or one log group. The permissions for untested routes came from code review, so those routes still need tests.

Step 7: Turn on enforcement

The agent applied the reviewed policy, switched to ENFORCED, and ran the routes again:

Terminal window
● localstack-deployer(action: "deploy", projectType: "terraform")
⎿ Apply complete! Resources: 0 added, 2 changed, 0 destroyed.
● localstack-iam-policy-analyzer(action: "set-mode", mode: "ENFORCED")
⎿ 🔒 IAM enforcement mode has been set to ENFORCED.
● Bash(sleep 8; count images/ objects; ./exercise-api.sh; count again)
⎿ list-posts POST /list-posts HTTP 200 ok
...
list-my-posts POST /list-posts HTTP 200 ok
exit=0
images/ objects before=12 after=13
● localstack-logs-analysis(analysisType: "logs", filter: "is not authorized")
⎿ Filter: "is not authorized" → 0/400 lines
No matching logs found.

All eight checks passed with enforcement enabled. However, status codes were not enough. The upload helper catches S3 errors and still returns 200 with the message “Please try with another image.” A failed upload could therefore look successful. The agent confirmed that the object count increased and checked the logs for denials. It found none.

Step 8: Measure the blast radius

Passing routes show that the policy allows the app to work. They do not prove that it blocks unrelated access. To test that, the agent created a small Lambda function with the same blog_app_lambda_data role. It tried three actions that the blog app never uses:

results = [
run("s3:GetObject finance-reports-probe/payroll.csv",
lambda: s3.get_object(Bucket="finance-reports-probe", Key="payroll.csv")["Body"].read()),
run("dynamodb:Scan billing-records-probe",
lambda: ddb.scan(TableName="billing-records-probe")),
run("lambda:ListFunctions",
lambda: lam.list_functions()),
]

The agent deployed the probe with a test bucket, a fake payroll file, and a test table. It temporarily restored the original wildcard policy, kept enforcement enabled, and invoked the probe:

Terminal window
● localstack-aws-client(command: "lambda invoke --function-name iam-probe /dev/stdout")
⎿ ["s3:GetObject finance-reports-probe/payroll.csv: ALLOWED",
"dynamodb:Scan billing-records-probe: ALLOWED",
"lambda:ListFunctions: ALLOWED"]

It restored the least-privilege policy and ran the same probe again:

Terminal window
● localstack-aws-client(command: "lambda invoke --function-name iam-probe /dev/stdout")
⎿ ["s3:GetObject finance-reports-probe/payroll.csv: DENIED (AccessDenied)",
"dynamodb:Scan billing-records-probe: DENIED (AccessDeniedException)",
"lambda:ListFunctions: DENIED (AccessDeniedException)"]

The old policy allowed all three unrelated actions. The new policy blocked them while still allowing the blog routes. The agent ran the route tests once more, then destroyed the probe stack.

Conclusion

The full process took less than eight minutes and did not need an AWS account:

Metric Value
Model Claude Opus 5.5
Cost $1.91
Time 7m 39s
Turns 44
Tool calls 43

The IAM Policy Analyzer found the actions and resources used by the app. Soft mode captured the missing permissions in one pass without stopping requests. The agent then fixed the S3 resource, added the ACL permission, covered untested code paths, and verified the result with enforcement enabled.

You can use the same process for your own stacks:

  1. Deploy the stack to LocalStack.
  2. Reduce the policy.
  3. Run your tests in soft mode.
  4. Generate and review a policy.
  5. Verify it with enforcement enabled.

Review is essential. A generated policy only reflects the traffic you ran. You must still test or inspect any code paths that were not exercised.

Learn More

About the Author

Harsh Mishra
Harsh Mishra
Engineer at LocalStack

Harsh Mishra is an Engineer at LocalStack and AWS Community Builder. Harsh has previously worked at HackerRank, Red Hat, and Quansight, and specialized in DevOps, Platform Engineering, and CI/CD pipelines.

Launch yourself in the world of local cloud development

Start a free trial