You can write an AWS IAM policy with an LLM in seconds, and the JSON will look right: a Version, a few Statement blocks, actions that sound like AWS, ARNs in roughly the right shape. That is the problem. In our lab, a draft with three made-up action names drew only LOW findings from one linter and nothing at all from another. A draft whose S3 read permission could never match the files it was meant to read passed every linter we ran. A draft that allowed every action except IAM's was rated LOW. An LLM IAM policy JSON draft is a draft until every action exists, every ARN can match a real resource, and a replay of the requests your workload makes, and the ones it must never make, comes out exactly as planned.
This guide runs that loop on one small workload. Every message and result below came from our lab: parliament 1.6.4, policy_sentry 0.15.2, cloudsplaining 0.9.1 and cfn-lint 1.57.0, all installed from PyPI, plus two small scripts of our own that read AWS's machine-readable service reference. We checked every action, resource type and condition key against the Service Authorization Reference before writing the drafts. The broken drafts were written for this guide to reproduce mistakes models commonly make when asked for an AI least privilege IAM policy. They are not a captured model transcript, and no model was called in the lab. The tools' output is the evidence.
Updated: we re-ran the CloudFormation step on cfn-lint 1.61.0 and re-checked every action name and wildcard count against AWS's current service reference. Every pass and fail matched; the action counts below come from that re-check.
Your own accounts only. Everything here is for AWS accounts you own or are engaged to secure. The lab never touches an account: policies are checked as files, and the account ID 111122223333 and the key ARN are the placeholder values AWS uses in its own docs. Keep real account IDs, role names and bucket names out of prompts.
What we ran, and what we didn't
- One workload, a report exporter that runs as a Lambda function. It reads CSV files from
incoming/in one bucket, writes results toprocessed/in the same bucket, uses one customer managed KMS key through S3, and writes to its own log group. - Eight drafts plus a final policy, all identity-based policy JSON for that function's role.
- Four existing tools: parliament (with
--include-community-auditors), cloudsplainingscan-policy-file, cfn-lint on a CloudFormation template that wraps each policy in anAWS::IAM::ManagedPolicy, and policy_sentry'swrite-policyas a comparison. - Two scripts of ours:
verify_actions.py, which looks up every action, wildcard, resource ARN and condition key in the service reference JSON, andevaluate.py, a tiny evaluator that replays 22 requests against one policy.
We did not call IAM Access Analyzer or the IAM policy simulator, because both run in an AWS account and this lab has none. The section before the FAQ covers what they add. Our evaluator models only one identity-based policy; it ignores KMS key policies, bucket policies, SCPs, RCPs and permission boundaries, so a 22/22 here means "this policy says what we meant," not "the function will work in production." In the output below we trimmed long action lists with "..." and dropped Python deprecation warnings. Nothing else was changed.
How to write an AWS IAM policy with an LLM
Treat every draft as untrusted and ask three questions, in order:
- Does every action exist, and can every Resource ARN match the resource type that action needs? Check against the service reference, not against what sounds plausible. Linters disagree here, and one of the worst mistakes in this post passed all of them.
- What does each wildcard actually grant on these resources? Expand
s3:Get*,kms:*and friends against the current action list, and look for permissions-management actions such askms:PutKeyPolicyands3:PutObjectAcl. - Do the requests the workload makes get allowed, and do the ones it must never make get denied? Write that table before you prompt, then replay it. This is the only gate that caught a condition that never matches and a missing KMS permission.
# 1 and 2: actions, ARNs, wildcards, condition keys (our script, AWS's data)
python3 verify_actions.py policy.json
# second opinions
parliament --include-community-auditors --string "$(cat policy.json)"
cloudsplaining scan-policy-file -i policy.json
# 3: replay allowed and denied requests (our evaluator)
python3 evaluate.py requests.json policy.json
Step 1: Write down the job, and the requests that must fail
Least privilege is a statement about a specific workload, so write it down first. Ours:
| Must be allowed | Must be denied | |
|---|---|---|
| S3 list | s3:ListBucket on the bucket with prefix incoming/ | listing the bucket root, listing processed/ |
| S3 read | s3:GetObject on incoming/* | reading processed/*, reading another bucket |
| S3 write | s3:PutObject on processed/* | writing to incoming/, s3:DeleteObject, s3:PutObjectAcl, s3:PutBucketPolicy |
| KMS | kms:Decrypt and kms:GenerateDataKey on the key, through S3 | calling kms:Decrypt directly, kms:PutKeyPolicy, kms:ScheduleKeyDeletion |
| Logs | logs:CreateLogStream, logs:PutLogEvents in its own log group | logs:DeleteLogStream, writing to another function's log group |
| Other | nothing | iam:PassRole, secretsmanager:GetSecretValue |
That is 7 requests that must be allowed and 15 that must be denied. Each becomes one line in requests.json, with the context keys IAM would see:
{"id":"R01","want":"ALLOW","action":"s3:ListBucket",
"resource":"arn:aws:s3:::lab-reports-111122223333",
"context":{"s3:prefix":"incoming/"}},
{"id":"R14","want":"DENY","action":"kms:Decrypt",
"resource":"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
"context":{}}
Two rows need a reason. kms:GenerateDataKey is on the allow side because the S3 SSE-KMS docs say a PutObject that encrypts with a KMS key needs kms:GenerateDataKey on the key, and a download needs kms:Decrypt. R14 is on the deny side because the function should only use the key through S3, which is what the kms:ViaService condition key expresses.
Step 2: Prompt with the real policy language
Models fill gaps with names that sound right. Close the gaps in the prompt: the exact resources, the API calls the code makes, the policy grammar, and what to leave out.
Write an AWS IAM identity-based policy (JSON only) for a Lambda role.
Version must be "2012-10-17". One Sid per statement.
The code calls: s3 ListObjectsV2 (Prefix="incoming/"), GetObject on incoming/*,
PutObject on processed/* in bucket lab-reports-111122223333. Objects use SSE-KMS with
key arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab.
Logs go to log group /aws/lambda/report-exporter (already exists).
Use IAM action names from the Service Authorization Reference, not API names.
Use key ARNs, not aliases. No wildcards in Action. No Resource "*".
Restrict ListBucket with s3:prefix, and KMS with kms:ViaService.
We didn't send this to a model for the post. The drafts below are what the gates are for. Note the trap the prompt has to name explicitly: the code calls ListObjectsV2, but no IAM action has that name.
Step 3: Actions that don't exist
Draft 1 is the most common failure: an API name used as an action, a plural that isn't real, and a verb that sounds right.
{"Effect": "Allow", "Action": ["s3:ListObjectsV2", "s3:GetObject"], "Resource": [...]},
{"Effect": "Allow", "Action": ["kms:Decrypt", "kms:GenerateDataKeys"], "Resource": "..."},
{"Effect": "Allow", "Action": ["logs:CreateLogStream", "logs:WriteLogEvents"], "Resource": "..."}
Three tools, three opinions:
$ parliament --include-community-auditors --string "$(cat d1-invented.json)"
LOW - Unknown action - - Unknown action s3:ListObjectsV2 - {'string': 's3:ListObjectsV2', 'line': 4, ...}
LOW - Unknown action - - Unknown action kms:GenerateDataKeys - {...}
LOW - Unknown action - - Unknown action logs:WriteLogEvents - {...}
exit=1
$ cfn-lint -t cfn/d1-invented.json
W3037 'listobjectsv2' is not one of ['abortmultipartupload', 'allowvendedlogdeliveryforresource', ...]
W3037 'generatedatakeys' is not one of ['cancelkeydeletion', 'connectcustomkeystore', ...]
W3037 'writelogevents' is not one of ['associatekmskey', ...]
exit=4
$ cloudsplaining scan-policy-file -i d1-invented.json
There were no results found.
parliament and cfn-lint both found all three, at LOW and warning level. cloudsplaining looks for risky permissions, not invalid ones, so it had nothing to say. AWS rates this differently: the Access Analyzer policy check reference lists "Invalid action" as an ERROR. Treat any unknown action as a hard failure, whatever severity your linter prints.
Our script adds the fix, because the service reference JSON maps API operations to the actions that authorize them:
$ python3 verify_actions.py d1-invented.json
REJECT #1: s3:ListObjectsV2 is not an action in the service reference (ListObjectsV2 is an API operation; it is authorized by s3:GetObjectAcl, s3:ListBucket)
REJECT #3: kms:GenerateDataKeys is not an action in the service reference
REJECT #4: logs:WriteLogEvents is not an action in the service reference
The functional cost shows up in the replay: listing incoming/, generating a data key and writing logs were all denied (18/22). Nothing else in the policy reveals that the function can't do its job. And because the draft had no kms:ViaService condition, a direct kms:Decrypt call was allowed.
One more thing about action lists: they age. parliament 1.6.4 shipped in April 2025 with its own copy of the action list. Against the current service reference it doesn't know 20 S3 actions, 3 KMS actions and 34 CloudWatch Logs actions, so a valid newer action such as kms:GetKeyLastUsage comes back as "Unknown action" too. cfn-lint updates its list with each release. After the November 19 update, between 1.57.0 and 1.61.0 the KMS list in its W3037 message gained decapsulate. When a linter and the service reference disagree, the service reference wins.
Step 4: Real actions, wrong resource ARNs
Draft 2 uses only real actions. Its ARNs are the problem:
{"Effect": "Allow", "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::lab-reports-111122223333/*"},
{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::lab-reports-111122223333/incoming"},
{"Effect": "Allow", "Action": "s3:PutObject", "Resource": "arn:aws:s3:us-west-2:111122223333:lab-reports-111122223333/processed/*"},
{"Effect": "Allow", "Action": ["kms:Decrypt", "kms:GenerateDataKey"], "Resource": "arn:aws:kms:us-west-2:111122223333:alias/reports"}
$ parliament --include-community-auditors --string "$(cat d2-wrong-arns.json)"
MEDIUM - No resources match for the given action - - [{'action': 's3:ListBucket', 'required_format': 'arn:*:s3:::*'}] - ...
MEDIUM - No resources match for the given action - - [{'action': 's3:PutObject', 'required_format': 'arn:*:s3:::*/*'}] - ...
MEDIUM - No resources match for the given action - - [{'action': 'kms:Decrypt', 'required_format': 'arn:*:kms:*:*:key/*'}, {'action': 'kms:GenerateDataKey', ...}] - ...
exit=1
Three of the four mistakes caught: ListBucket takes the bucket ARN, not the object ARN; S3 bucket and object ARNs have no Region or account; and KMS key operations need a key ARN. The KMS one is spelled out in the KMS IAM policy docs: "You cannot use a key id, alias name, or alias ARN to identify a KMS key in an IAM policy statement." To control access by alias, use the kms:RequestAlias or kms:ResourceAliases condition keys instead.
The fourth mistake got past every linter in the lab. arn:aws:s3:::lab-reports-111122223333/incoming is a perfectly valid object ARN. It names one object whose key is literally incoming, not the files under that prefix. parliament, cfn-lint, cloudsplaining and our own verify_actions.py all accepted it, because nothing about its shape is wrong. Only the replay caught it:
$ python3 evaluate.py requests.json d2-wrong-arns.json
d2-wrong-arns.json: 17/22 as expected
R01 BROKEN: s3:ListBucket lab-reports-111122223333 {'s3:prefix': 'incoming/'} -> DENY, want ALLOW
R04 BROKEN: s3:GetObject lab-reports-111122223333/incoming/batch-17.csv -> DENY, want ALLOW
R06 BROKEN: s3:PutObject lab-reports-111122223333/processed/batch-17.json -> DENY, want ALLOW
R12 BROKEN: kms:Decrypt key/1234abcd-... {'kms:ViaService': 's3.us-west-2.amazonaws.com'} -> DENY, want ALLOW
R13 BROKEN: kms:GenerateDataKey key/1234abcd-... {'kms:ViaService': 's3.us-west-2.amazonaws.com'} -> DENY, want ALLOW
A missing /* doesn't break the policy file. It breaks the job, and only a test with a real object key shows it.
Step 5: Wildcards that look scoped
The opposite failure is a policy that works because it allows far too much. We wrote three versions: the blunt one (s3:*, kms:*, logs:* on "*"), one that looks careful (s3:Get* and s3:Put* on the bucket's objects, kms:* on the one key, logs:* on the one log group), and one that uses NotAction to allow "everything except IAM and Organizations."
verify_actions.py expands each wildcard against the current action list and keeps only the actions whose resource types can match the ARN in the statement:
| Draft | Wildcard | Expands to | Usable on that Resource | Notable extras |
|---|---|---|---|---|
| d3 | s3:*, kms:*, logs:* on * | 183 + 58 + 133 | all 374 | s3:PutBucketPolicy, kms:PutKeyPolicy, kms:ScheduleKeyDeletion |
| d4 | s3:List* on the bucket | 18 | 4 | s3:ListBucketVersions, no prefix limit |
| d4 | s3:Get* on bucket/* | 65 | 17 | s3:GetObjectVersion, s3:GetObjectAcl |
| d4 | s3:Put* on bucket/* | 41 | 9 | s3:PutObjectAcl, s3:PutObjectRetention |
| d4 | kms:* on the key ARN | 58 | 47 | kms:PutKeyPolicy, kms:CreateGrant, kms:ScheduleKeyDeletion |
| d4 | logs:* on the log group | 133 | 4 | logs:DeleteLogStream, logs:GetLogEvents |
The resource ARN does real work here: s3:Put* on bucket/* can't grant s3:PutBucketPolicy, because that action needs the bucket ARN. But "scoped to one key" still meant 47 KMS actions, including the ones that change who can use the key and the one that schedules it for deletion. "Scoped to one log group" still let the function delete its own log streams, which is exactly what an attacker who lands in that function would want.
How the tools rated them:
=== d3-star.json
parliament: MEDIUM - Permissions management actions; LOW - Unnecessary use of Resource *
cloudsplaining: Data Exfiltration; Resource Exposure; ALL Actions from a service; Unrestricted Infrastructure Modification
=== d4-scoped-wildcards.json
parliament: MEDIUM - Permissions management actions; 4 x MEDIUM - No resources match for the given action
cloudsplaining: Policy allows ALL Actions from a service (like service:*) [kms, logs]
=== d6-notaction.json
parliament: LOW - Unnecessary use of Resource * - ['iam:AddClientIDToOpenIDConnectProvider', 'iam:AddRoleToInstanceProfile', ...]
cloudsplaining: Privilege Escalation; Data Exfiltration; Resource Exposure; actions that return credentials; Unrestricted Infrastructure Modification
Two results stand out. cloudsplaining by default didn't mention d4's s3:PutObjectAcl at all; it only listed it, with the KMS key-policy actions, when we added --flag-all-risky-actions. And parliament rated the NotAction draft, which allows every action in every AWS service except IAM and Organizations, as a single LOW finding. The action list in that finding contained only iam: and organizations: actions (131 and 24), the ones the statement excludes. cloudsplaining did much better here, listing privilege-escalation paths such as lambda:UpdateFunctionCode and secretsmanager:GetSecretValue among the data it could read. The NotAction docs are plain about it: with Allow, everything not listed is allowed. Our script rejects Allow with NotAction outright, and the replay scored it 8/22, allowing all 14 of the forbidden requests outside IAM.
Wildcards are not a severity question. Expand them, read the list, and keep only what the request table needs.
Step 6: Conditions that never match
Draft 5 has real actions and correct ARNs, and adds conditions the way a model often does:
{"Action": "s3:ListBucket", "Resource": "arn:aws:s3:::lab-reports-111122223333",
"Condition": {"StringEquals": {"s3:prefix": "incoming/*"}}},
{"Action": "s3:GetObject", "Resource": "arn:aws:s3:::lab-reports-111122223333/*",
"Condition": {"StringLike": {"s3:prefix": "incoming/*"}}},
{"Action": ["kms:Decrypt", "kms:GenerateDataKey"], "Resource": "arn:aws:kms:...:key/1234abcd-...",
"Condition": {"StringEquals": {"kms:ViaService": "s3.amazonaws.com"}}}
There are three bugs. parliament and verify_actions.py both found the same one, and cloudsplaining found none:
$ parliament --include-community-auditors --string "$(cat d5-conditions.json)"
MEDIUM - Unknown condition for action - - Unknown condition s3:prefix for action s3:GetObject - ...
$ python3 verify_actions.py d5-conditions.json
REJECT #2: condition key s3:prefix is not supported by s3:GetObject; the statement can never match
$ cloudsplaining scan-policy-file -i d5-conditions.json
There were no results found.
s3:prefix belongs to ListBucket, not GetObject. The condition operator docs explain what that means at runtime: if a key is not present in the request context, "the values do not match and the condition is false." The read statement never applies.
The other two bugs passed every offline tool. StringEquals doesn't treat * as a wildcard, so the list statement only matches a request whose prefix is literally incoming/*. Access Analyzer has a check for exactly this ("Wildcard without like operator," a general warning, per the check reference), but none of the tools we could run offline flagged it. And kms:ViaService values include the Region, in the form s3.us-west-2.amazonaws.com, as in the examples in the KMS condition key docs. With s3.amazonaws.com the KMS statement never matches. The replay showed all three:
d5-conditions.json: 18/22 as expected
R01 BROKEN: s3:ListBucket lab-reports-111122223333 {'s3:prefix': 'incoming/'} -> DENY, want ALLOW
R04 BROKEN: s3:GetObject lab-reports-111122223333/incoming/batch-17.csv -> DENY, want ALLOW
R12 BROKEN: kms:Decrypt key/1234abcd-... {'kms:ViaService': 's3.us-west-2.amazonaws.com'} -> DENY, want ALLOW
R13 BROKEN: kms:GenerateDataKey key/1234abcd-... {'kms:ViaService': 's3.us-west-2.amazonaws.com'} -> DENY, want ALLOW
Broken conditions fail closed, so they don't open anything. They do push people toward "just remove the condition," which is how a tight draft turns into d3.
Step 7: The least-privilege policy that passed
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ListIncomingPrefixOnly",
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::lab-reports-111122223333",
"Condition": {"StringLike": {"s3:prefix": ["incoming/", "incoming/*"]}}
},
{
"Sid": "ReadIncoming",
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::lab-reports-111122223333/incoming/*"
},
{
"Sid": "WriteProcessed",
"Effect": "Allow",
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::lab-reports-111122223333/processed/*"
},
{
"Sid": "UseReportsKeyThroughS3",
"Effect": "Allow",
"Action": ["kms:Decrypt", "kms:GenerateDataKey"],
"Resource": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
"Condition": {"StringEquals": {"kms:ViaService": "s3.us-west-2.amazonaws.com"}}
},
{
"Sid": "WriteOwnLogs",
"Effect": "Allow",
"Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
"Resource": "arn:aws:logs:us-west-2:111122223333:log-group:/aws/lambda/report-exporter:*"
}
]
}
$ parliament --include-community-auditors --string "$(cat final.json)"
exit=0
$ cloudsplaining scan-policy-file -i final.json
There were no results found.
$ cfn-lint -t cfn/final.json
exit=0
$ python3 verify_actions.py final.json
ListIncomingPrefixOnly: 1 effective actions
ReadIncoming: 1 effective actions
WriteProcessed: 1 effective actions
UseReportsKeyThroughS3: 2 effective actions
WriteOwnLogs: 2 effective actions
=> CLEAN
$ python3 evaluate.py requests.json final.json
final.json: 22/22 as expected
Seven actions, each on one resource pattern, and two conditions that match real request context. The log statement's log-group:NAME:* pattern covers the log-stream ARNs that CreateLogStream and PutLogEvents authorize against. We left out logs:CreateLogGroup because our log group already exists.
Now the warning. Draft 7 is this exact policy with kms:GenerateDataKey removed. parliament: exit 0. cloudsplaining: no results. cfn-lint: exit 0. verify_actions.py: CLEAN. Every static check in the lab passed it, and the function would fail on its first SSE-KMS upload. Only the request table caught it:
d7-no-generatedatakey.json: 21/22 as expected
R13 BROKEN: kms:GenerateDataKey key/1234abcd-... {'kms:ViaService': 's3.us-west-2.amazonaws.com'} -> DENY, want ALLOW
Linters tell you a policy is well formed and not obviously dangerous. Only a test tells you it is enough.
Results across all drafts
| Draft | parliament | cfn-lint 1.57.0 | cloudsplaining | verify_actions.py | Replay (22) |
|---|---|---|---|---|---|
| d1 invented actions | 3 x LOW | 3 x W3037 | no results | 3 REJECT | 18 |
| d2 wrong ARNs | 3 x MEDIUM | clean | no results | 4 REJECT | 17 |
d3 service:* on * | MEDIUM + LOW | clean | 4 issues | 5 WARN | 9 |
| d4 scoped wildcards | 5 x MEDIUM | clean | 1 issue | 7 WARN | 13 |
| d5 conditions | 1 x MEDIUM | clean | no results | 1 REJECT | 18 |
d6 NotAction | 1 x LOW | clean | 5 issues | REJECT | 8 |
| d7 no GenerateDataKey | clean | clean | no results | CLEAN | 21 |
d8 Version typo | MEDIUM | E3510 | no results | REJECT | n/a |
| final | clean | clean | no results | CLEAN | 22 |
After the November 19 update, cfn-lint 1.61.0 gave identical results. cloudsplaining exited 0 on every draft, including the ones it flagged, so gate on its output, not its exit code. Draft 8 is the final policy with "Version": "2012-10-18". cfn-lint (E3510 '2012-10-18' is not one of ['2008-10-17', '2012-10-17']) and parliament both caught it, and Access Analyzer lists "Invalid version" as an error. Our evaluator doesn't read Version, which is why it has no score.
Don't let a generator do the thinking either
policy_sentry is the usual answer to "write me a least-privilege policy," so we gave it the same three S3 ARNs as a CRUD template (read incoming/*, write processed/*, list the bucket):
$ policy_sentry write-policy --input-file sentry-crud.yml
"Sid": "S3ReadObject", "Action": ["s3:GetObject", "s3:GetObjectAcl", "s3:GetObjectAttributes", ... 13 actions]
"Sid": "S3WriteObject", "Action": ["s3:AbortMultipartUpload", "s3:DeleteObject", "s3:DeleteObjectVersion",
"s3:InitiateReplication", "s3:PutObject", "s3:PutObjectLegalHold",
"s3:PutObjectRetention", ... 11 actions]
"Sid": "S3ListBucket", "Action": ["s3:ListBucket", "s3:ListBucketMultipartUploads", "s3:ListBucketVersions",
"s3:ListTagsForResource"]
That is far better than s3:*, and every action is real and correctly scoped. But "write" means every write-level action, including s3:DeleteObject and Object Lock retention changes, and the list statement has no prefix limit. It grants access levels, not the job. The service reference's Operations section has the same trap: it lists s3:PutObject, s3:PutObjectAcl, s3:PutObjectTagging, s3:PutObjectRetention and s3:PutObjectLegalHold as actions that can authorize a PutObject call. AWS's required permissions for S3 API operations page marks the extras as conditionally required, for example s3:PutObjectAcl only "if you want to put the object access control list (ACL)". Our function sends no ACLs, tags or Object Lock settings, so it needs only the first. Use generators and maps as a starting list, then cut to the request table.
Common mistakes in LLM-written IAM policies
- API names as actions.
s3:ListObjectsV2is an API; the action iss3:ListBucket. Look up operations in the service reference. - Invented or pluralized actions.
kms:GenerateDataKeys,logs:WriteLogEvents. Some linters only rate this LOW; treat it as an error. - Object ARN for a bucket action, or the reverse.
ListBuckettakesarn:aws:s3:::bucket;GetObjecttakesarn:aws:s3:::bucket/key. - A prefix without
/*.bucket/incomingnames one object. No linter in our lab caught it. - Region or account in an S3 ARN, alias ARNs for KMS keys. Both make the statement match nothing.
- Wildcards on a "scoped" resource.
kms:*on one key still includeskms:PutKeyPolicyandkms:ScheduleKeyDeletion. AllowwithNotAction. It grants every unlisted action in every service.- Wildcards in
StringEquals, condition keys on the wrong action, condition values in the wrong format. All fail closed, silently. - Forgetting the encryption side. SSE-KMS uploads need
kms:GenerateDataKey; every linter passed the policy that left it out.
A small validator for the loop
evaluate.py is the piece that caught what the linters didn't. It is ours, it is short (below is a condensed copy; the version we ran gives the same scores and also prints the request context and shortened ARNs, as in the output above), and it is deliberately narrow: one identity-based policy, explicit Deny beats Allow beats the implicit deny, glob matching on actions (case-insensitive) and resources, and six string and ARN condition operators with AWS's missing-key rule. It doesn't model resource-based policies, SCPs, RCPs, permission boundaries, session policies or policy variables.
#!/usr/bin/env python3
import json, re, sys
def L(v): return v if isinstance(v, list) else [v]
def glob(pattern, value, ci=False):
rx = "^" + re.escape(pattern).replace(r"\*", ".*").replace(r"\?", ".") + "$"
return re.match(rx, value, re.I if ci else 0) is not None
OPS = {
"StringEquals": lambda p, v: p == v,
"StringNotEquals": lambda p, v: p != v,
"StringLike": lambda p, v: glob(p, v),
"StringNotLike": lambda p, v: not glob(p, v),
"ArnEquals": lambda p, v: p == v,
"ArnLike": lambda p, v: glob(p, v),
}
def cond_ok(cond, ctx):
ctx = {k.lower(): v for k, v in ctx.items()}
for op, kv in (cond or {}).items():
base = op[:-8] if op.endswith("IfExists") else op
if base not in OPS:
raise SystemExit(f"unsupported operator {op}")
for key, vals in kv.items():
have = ctx.get(key.lower())
if have is None: # missing key: false, except Not... and ...IfExists
if op.endswith("IfExists") or "Not" in base:
continue
return False
hits = [OPS[base](p, have) for p in L(vals)]
if not (all(hits) if "Not" in base else any(hits)):
return False
return True
def matches(st, req):
if "Action" in st:
if not any(glob(a, req["action"], ci=True) for a in L(st["Action"])): return False
elif any(glob(a, req["action"], ci=True) for a in L(st["NotAction"])): return False
if "Resource" in st:
if not any(glob(r, req["resource"]) for r in L(st["Resource"])): return False
elif any(glob(r, req["resource"]) for r in L(st["NotResource"])): return False
return cond_ok(st.get("Condition"), req.get("context", {}))
def decide(policy, req):
hit = [s for s in L(policy["Statement"]) if matches(s, req)]
if any(s["Effect"] == "Deny" for s in hit): return "DENY"
return "ALLOW" if any(s["Effect"] == "Allow" for s in hit) else "DENY"
reqs = json.load(open(sys.argv[1]))
failed = False
for path in sys.argv[2:]:
pol = json.load(open(path))
bad = [r for r in reqs if decide(pol, r) != r["want"]]
print(f"{path}: {len(reqs) - len(bad)}/{len(reqs)} as expected")
for r in bad:
print(f" {r['id']} {'OVER-GRANT' if r['want'] == 'DENY' else 'BROKEN'}: {r['action']} {r['resource']}")
failed = failed or bool(bad)
sys.exit(1 if failed else 0)
verify_actions.py is longer, so we won't paste it. It downloads https://servicereference.us-east-1.amazonaws.com/v1/<service>/<service>.json for each service prefix, then checks action names (suggesting the authorized action when the name is an API operation), expands wildcards, tests whether each Resource pattern can overlap the action's ARN formats, and checks condition keys against the action's supported keys. One install note: parliament 1.6.4 imports pkg_resources, so on a fresh Python 3.13 virtual environment it failed with ModuleNotFoundError: No module named 'pkg_resources' until we installed setuptools<81.
To close the loop with a model, send the REJECT, WARN, BROKEN and OVER-GRANT lines back and ask for a corrected policy. This sketch does that with the OpenAI Python SDK and RedRouter's https://redrouter.org/v1 base URL from the quickstart. We did not run it against the API for this post; the validation half is the scripts above.
import os, subprocess
from openai import OpenAI
client = OpenAI(base_url="https://redrouter.org/v1", api_key=os.environ["REDROUTER_API_KEY"])
prompt = open("prompt.txt").read()
messages = [{"role": "user", "content": prompt}]
for attempt in range(4):
reply = client.chat.completions.create(model="glm-5.3-flash-red", messages=messages)
policy = reply.choices[0].message.content.strip().removeprefix("```json").removesuffix("```")
open("policy.json", "w").write(policy)
checks = [["python3", "verify_actions.py", "policy.json"],
["python3", "evaluate.py", "requests.json", "policy.json"]]
out = [subprocess.run(c, capture_output=True, text=True) for c in checks]
if all(o.returncode == 0 for o in out):
break
feedback = "\n".join(o.stdout for o in out)
messages += [{"role": "assistant", "content": policy},
{"role": "user", "content": "Fix these findings. Return the JSON only.\n" + feedback}]
Keep a human review at the end even when both scripts pass. The request table is only as good as the requests you thought to write down.
Before you attach it: Access Analyzer and the simulator
Run these in an account you own before the policy goes anywhere real. Access Analyzer policy validation runs AWS's own checks, including the "Wildcard without like operator" warning our offline tools missed. The IAM policy simulator can include SCPs and resource-based policies you supply, which our evaluator can't. The simulator's docs list how it differs from a live request: it makes no service call and doesn't use real context key values from production. For KMS in particular, remember that the key policy also has to allow the role; an identity policy alone is not enough. AWS's policy evaluation logic page covers how all of these combine.
Where this fits with other policy engines
IAM policies are AWS's own authorization language. If you're writing rules about JSON input or Kubernetes admission, OPA Rego policies with an LLM uses opa test as its first gate. If the rule is about Terraform before it is applied, for example "no role may have iam:*", Checkov policies with an LLM covers custom checks against fixtures you own. And when the permissions question lives in application code, LLM secure code review covers that side. The loop is the same in all of them: write the expected answers first, run the engine, diff.
What to send the model, and what not to
- Send the shape, not the estate. Resource names, API calls and the request table are enough. Don't paste
aws iam get-account-authorization-detailsoutput, real account IDs, or role trust policies from production. - Send the reference data. Pasting the relevant actions and ARN formats from the service reference into the prompt removes most of the guessing behind Step 3 and Step 4.
- Check retention. On RedRouter, account zero data retention is an opt-in setting, off by default. The data handling docs explain what is stored and the controls, and what RedRouter keeps covers the defaults in plain terms.
Choosing a model for IAM policies
Any model that returns clean JSON and fixes a policy from a list of findings will do; the scripts do the judging. On RedRouter, GLM 5.3 Flash Red (glm-5.3-flash-red) is $0.25 per 1M input tokens, $0.13 per 1M cached input tokens and $1.00 per 1M output tokens. red-cyber-1 (Beta), the featured model for authorized penetration testing and red-team work, is $0.28 / $0.13 / $1.10 per 1M tokens. Current rates for every model are in the models docs, and plans are on /pricing.
IAM work means describing access plainly: who can delete which logs, which role could rewrite a key policy, which path leads to admin. RedRouter is built for that kind of authorized security work.
FAQ
Can I write an AWS IAM policy with an LLM?
Yes, as a first draft. In our lab, every broken draft looked plausible, and the static tools disagreed: three invented actions drew LOW findings from parliament and nothing from cloudsplaining, and a GetObject statement missing /* passed every linter. Only the final policy passed the action, ARN and condition checks and matched all 22 expected allow and deny results.
How do I check that LLM IAM policy JSON is valid?
Check every action, resource ARN and condition key against the Service Authorization Reference or its JSON version. parliament and cfn-lint catch invented actions and some ARN mismatches offline; Access Analyzer policy validation runs AWS's checks in your account. Treat any unknown action as an error, whatever severity a tool prints.
What makes an AI least privilege IAM policy actually least privilege?
A written list of the requests the workload makes and the ones it must never make, and a replay that matches it exactly. Expand every wildcard, avoid Resource: "*" and Allow with NotAction, and scope with conditions such as s3:prefix and kms:ViaService. Least privilege is about a specific job, not an access level.
Why does my IAM policy pass the linter but still deny the request?
In our runs: a resource ARN that is valid but names the wrong thing (bucket/incoming instead of bucket/incoming/*), a condition key that the action doesn't support, StringEquals with a wildcard, a kms:ViaService value without the Region, or a missing companion permission such as kms:GenerateDataKey for SSE-KMS uploads. None of these are syntax errors.
Which IAM actions does an S3 ListObjectsV2 call need?
s3:ListBucket on the bucket ARN. ListObjectsV2 is an API operation, not an action. AWS also lists s3:GetObjectAcl for that call, but only as conditionally required, "if you want to display object owner information." Use s3:prefix in a StringLike condition to limit which prefixes can be listed.
Is it safe to paste IAM policies into an LLM?
Paste the structure, not your account. Replace account IDs, role names and bucket names with placeholders, and never paste credentials or full account authorization dumps. On RedRouter, account zero data retention is opt-in and off by default; see the data handling docs.
Sources
- AWS IAM User Guide: Policies and permissions, Access Analyzer policy validation, Access Analyzer policy check reference, Policy evaluation logic, Condition operators, NotAction, Version, Resource, Testing policies with the simulator, Security best practices.
- Service Authorization Reference: overview, Amazon S3, AWS KMS, CloudWatch Logs, service reference JSON and its index.
- Service docs: Required permissions for S3 API operations, S3 condition key examples, S3 SSE-KMS, KMS condition keys, KMS keys in IAM policies, Controlling access to aliases, Lambda execution role.
- Tools: parliament (1.6.4 on PyPI), policy_sentry (0.15.2), cloudsplaining (0.9.1), cfn-lint (1.57.0, 1.61.0).
- Lab outputs: the tools above from PyPI on Python 3.13, our
verify_actions.pyandevaluate.py, eight drafts and one final policy for a lab workload. No AWS account and no model were used. - OpenAI Python SDK.
- RedRouter Docs: Quickstart, Models and pricing, Data handling.