AWSBeginner
IAM AccessDenied with the right action: S3 ARNs, explicit Deny and roles
Key results
- A policy allowing s3:GetObject on arn:aws:s3:::reports still gets AccessDenied; changing Resource to reports/* makes read and write work at once.
- Grant s3:*, then add one Deny s3:DeleteObject statement: delete is blocked, read still works. An explicit Deny beats every Allow.
- Assuming role report-reader: STS returns an ASIA… temporary key that expires after 1 hour; reading works, writing is denied because the role is read-only.
- Role ops-admin trusts only user ops: dev is refused even though its own policy allows sts:AssumeRole.
What you need
- No prior knowledge of IAM, STS or S3 needed: the guide explains everything from the start.
- A Linux machine with Docker, AWS CLI v2 and jq. See the "Cloud and network lab setup" guide.
- No AWS account needed: Moto emulates the AWS APIs with IAM authorization turned on; every key in this guide is a fake key generated by Moto.
- Time
- 35 minutes
- Cost
- Free as written (emulated). On real AWS: IAM and STS have no charge; S3 charges for storage and requests
- AWS IAM
- AWS STS
- Amazon S3
- Moto
Watch the lab video

🎬 Goes live 02 Jan 2027, 20:00 (UTC+7)
You write an IAM policy that allows s3:GetObject, attach it to a user, try it: AccessDenied. The action name is right and spelled correctly, and AWS still says no. This happens all the time, and the cause usually sits in the line people look at least: Resource.
In this guide you run an emulated AWS with real authorization on your own machine, then break and fix one mistake at a time: a bucket ARN where an object ARN belongs, a Deny statement that beats every Allow, a temporary STS role key instead of a long-term access key, and a trust policy that does not trust you. Every result shown is real output.
Concepts you need first
- IAM identity (principal)
- Who is sending the request to AWS: an IAM user (a person or program with its own keys) or a role (an identity with no long-term keys that permitted callers borrow).Example: user/dev, role/report-reader.
- IAM policy
- A JSON document of Allow and Deny statements. Each statement names which actions (Action) on which resources (Resource).Example: Allow s3:GetObject on arn:aws:s3:::reports/*.
- ARN (Amazon Resource Name)
- The unique address of an AWS resource, like a street address. S3 has two kinds: the bucket ARN and the ARN of objects inside the bucket.Example: arn:aws:s3:::reports (bucket), arn:aws:s3:::reports/* (every object).
- Implicit deny and explicit deny
- If no Allow statement matches, the request is denied by default (implicit). If a Deny statement matches, it is denied outright (explicit), and no Allow can rescue it.Example: Deny s3:DeleteObject blocks deletes even with s3:*.
- STS temporary credentials
- The keys STS issues when you assume a role. They expire, and the AccessKeyId starts with ASIA (an IAM user long-term key starts with AKIA).Example: ASIA… expiring after 1 hour.
- Role trust policy
- The policy on a role that says who may assume it. If you are not in it, you cannot assume the role.Example: Role report-reader trusts only user/dev.
That order is the core of the IAM policy evaluation logic. Real AWS adds more layers to the same decision (AWS Organizations SCPs, permissions boundaries, bucket policies), but the base rule never changes: if any Deny matches, the request is denied; if no Allow matches, it is denied too.
Architecture on real AWS
The scenario: an S3 bucket named reports holds a report, q4-report.txt. User dev must read and write reports but never delete them. A read-only role, report-reader, can be assumed when needed, so nobody has to carry a key that can write.
| Component | Name in this guide | Why it is needed |
|---|---|---|
| S3 bucket | reports |
Holds the reports. The bucket and its objects have different ARNs, which is the root of the first error. |
| IAM user | dev |
An identity with long-term access keys, standing in for the person or program hitting AccessDenied. |
Inline policies on dev |
read-write-reports, no-delete, assume-roles |
Read and write; a guardrail against deletes; permission to request roles. |
| IAM role | report-reader |
Read-only, trusts only dev. Assumed through STS for temporary keys. |
| IAM role | ops-admin |
Trusts only user ops. Shows a trust policy turning away a stranger. |
| AWS STS | AssumeRole |
Issues temporary keys when the role’s trust policy allows it. |
The lab model and how it runs
The lab rebuilds that scenario inside one Moto container on a Linux machine with Docker. The difference from a typical Moto lab: this container has IAM authorization turned on, so the key and its policies decide the result, just like real AWS. No lab machine yet? Follow the Cloud and network lab setup guide. For another least-privilege role (for Lambda), see Security Hub and GuardDuty alerts to Teams or Slack.
What is in the lab
| Component | What it is | What it plays on real AWS | Created by / file |
|---|---|---|---|
Container l06-moto, 127.0.0.1:4567 |
Moto, an open-source server that answers AWS APIs, started with INITIAL_NO_AUTH_ACTION_COUNT=5 |
The IAM, STS and S3 APIs of one AWS account | dung.sh (step 1) |
User admin |
IAM user with an Allow * on * policy |
The administrator who creates users, roles and policies | Commands 3–5 of dung.sh |
User dev |
IAM user with an access key | The person or program getting AccessDenied |
dung.sh, created by admin |
Roles report-reader, ops-admin |
IAM roles with trust policies | Roles assumed through STS | dung.sh, created by admin |
Bucket reports, file q4-report.txt |
S3 bucket inside Moto, content Q4 revenue report (sample data) |
The data to protect | First 2 commands of dung.sh |
chinh-sach/*.json |
9 policy files | Permission policies and trust policies | You (step 1) |
lab.sh |
Short shell functions: l06, ai-day, doc, ghi, xoa, dat-policy, nhan-role |
The AWS CLI with different profiles | You (step 1), loaded with source |
~/.l06/credentials |
Credentials file with one profile per identity: admin, dev, and each assumed role |
~/.aws/credentials |
Written by dung.sh and nhan-role |
How the pieces connect
Everything runs on one machine. The AWS CLI calls http://127.0.0.1:4567 (port 4567 on the host, mapped to port 5000 in the container). It listens on 127.0.0.1 only, so nothing else on the network can reach it. The lab uses its own port 4567 to stay clear of the shared Moto container on 4566 used by other guides.
A request such as doc dev (read the report as dev) goes through 5 stages:
- The AWS CLI signs the request with the access key of profile
devfrom~/.l06/credentials. For a role there is also a session token. - AWS identifies the caller from the key: it belongs to
arn:aws:iam::123456789012:user/dev.ai-day dev(which callssts get-caller-identity) prints exactly that line. - AWS collects every policy that applies to that identity. In the lab these are the inline policies of
dev. Real AWS adds bucket policies, SCPs, permissions boundaries and session policies. - AWS evaluates them as in the first diagram: a matching Deny denies; no Allow matching both Action and Resource denies; anything else is allowed.
- The result: if allowed, S3 returns the file content or an ETag; if denied, it returns
AccessDenied(HTTP 403) and the AWS CLI printsaws: [ERROR]: An error occurred (AccessDenied) ....
What you prepare
After step 1 the lab folder holds exactly these files:
06-iam-access-denied/├── chinh-sach/│ ├── admin.json Allow * on *: admin permissions│ ├── dev-sai.json Get/Put on the bucket ARN → error in step 2│ ├── dev-dung.json Get/Put on the object ARN reports/* → fix in step 3│ ├── dev-rong.json s3:* on reports/* (too wide) → step 4│ ├── chan-xoa.json Deny s3:DeleteObject → guardrail, step 4│ ├── dev-assume.json Allow sts:AssumeRole on role/*│ ├── trust-dev.json trust policy: trusts only user/dev → role report-reader│ ├── trust-ops.json trust policy: trusts only user/ops → role ops-admin│ └── reader.json report-reader permissions: GetObject only├── lab.sh functions l06, ai-day, doc, ghi, xoa, dat-policy, nhan-role├── dung.sh starts Moto with authorization + sample data└── don.sh removes the container + fake keysThe names are Vietnamese without accents, kept as they appear in the screenshots: chinh-sach means “policies”, sai wrong, dung correct, rong wide, chan-xoa block delete. In lab.sh, ai-day means “who is this”, doc read, ghi write, xoa delete, dat-policy set policy, nhan-role assume role; dung.sh builds the lab and don.sh cleans it up.
What is real and what is emulated:
| In the lab | Real or emulated | On real AWS |
|---|---|---|
APIs on 127.0.0.1:4567 |
Emulated (Moto 5.2.6) | iam.amazonaws.com, sts.amazonaws.com, s3.<region>.amazonaws.com |
| IAM authorization | Real in Moto’s own way: matches Action, Resource and Effect of identity-based policies | The full evaluation logic over many policy types |
| Access keys, temporary keys | Fake, generated by Moto, not secrets | Real keys that must stay private |
Account 123456789012 |
Moto’s default sample account | Your account ID |
| Error messages | Short: Access Denied |
Extra context: which policy type denied and why (see step 2) |
The whole run at a glance
- Create the files and start Moto (step 1). Expect:
dung.shprintsLab 06 san sang: ...(“Lab 06 ready”);ai-day devprintsarn:aws:iam::123456789012:user/dev. - Break it: Get/Put on the bucket ARN (step 2). Expect:
doc devfails withAccessDeniedonGetObject. - Fix it: the object ARN
reports/*(step 3). Expect:doc devprintsQ4 revenue report (sample data),ghi devprints an ETag. - Too-wide permissions plus a Deny guardrail (step 4). Expect:
xoa devfails withAccessDeniedonDeleteObject,doc devstill reads. - Assume a read-only role (step 5). Expect: an
ASIA…key expiring in 1 hour; reading works, writing getsAccessDenied. - Request a role that does not trust you (step 6). Expect:
AccessDeniedonAssumeRole. - Clean up. Expect:
don.shprintsDa don Lab 06(“Lab 06 cleaned”), and containerl06-motois gone.
Step 1: Create the policies and scripts, start Moto with authorization
What you are doing: writing 9 policy files and two scripts, then starting an emulated AWS where every call must pass authorization.
mkdir -p 06-iam-access-denied/chinh-sach && cd 06-iam-access-deniedThe admin policy (one line, full access) and the dev policy in its broken state:
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"*","Resource":"*"}]}{ "Version": "2012-10-17", "Statement": [ { "Sid": "ReadWriteReports", "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject"], "Resource": "arn:aws:s3:::reports" } ]}| Line | Meaning | Why it is set this way |
|---|---|---|
"Version": "2012-10-17" |
Policy language version | The current one. Without it AWS falls back to the old 2008-10-17, which has no policy variables. |
"Sid": "ReadWriteReports" |
A label for the statement | Optional, but it makes errors and later reviews faster to read. |
"Effect": "Allow" |
An allow statement | Everything is denied by default; nothing works without an Allow. |
"Action": ["s3:GetObject", "s3:PutObject"] |
Read and write objects | The right action names. The bug is not here. |
"Resource": "arn:aws:s3:::reports" |
The bucket ARN | This is the bug: GetObject and PutObject act on objects and only match an object ARN. Step 2 shows the result. |
The remaining permission policies, one statement each:
"Resource": "arn:aws:s3:::reports/*"{ "Version": "2012-10-17", "Statement": [ { "Sid": "EverythingOnReports", "Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::reports/*" } ]}{ "Version": "2012-10-17", "Statement": [ { "Sid": "NobodyDeletesReports", "Effect": "Deny", "Action": "s3:DeleteObject", "Resource": "arn:aws:s3:::reports/*" } ]}{ "Version": "2012-10-17", "Statement": [ { "Sid": "ReadReportsOnly", "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::reports/*" } ]}The permission for dev to request roles, and the trust policies of both roles:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "sts:AssumeRole", "Resource": "arn:aws:iam::123456789012:role/*" } ]}{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::123456789012:user/dev"}, "Action": "sts:AssumeRole" } ]}trust-ops.json is identical except user/dev becomes user/ops.
| Line | Meaning | Why it is set this way |
|---|---|---|
"Principal" (in a trust policy) |
Who may assume the role | A permission policy has no such line because it is attached to an identity already. A trust policy sits on the role, so it must name who is trusted. |
"AWS": "arn:...:user/dev" |
Trust user dev by name |
arn:aws:iam::123456789012:root would trust the whole account and leave it to that account’s own policies; naming the user is narrower and clearer. |
"Action": "sts:AssumeRole" |
The action allowed on the role | Assuming a role is a call to sts:AssumeRole. |
"Resource": "...:role/*" (dev-assume) |
dev may request any role in the account |
Deliberately wide, so step 6 shows that the trust policy is what blocks. On real AWS, name the exact role ARNs. |
Next is lab.sh, which wraps long AWS CLI commands in short names:
# Lab 06: load with `source lab.sh`. Private Moto on 127.0.0.1:4567 WITH IAM AUTHORIZATION (not the shared Moto on 4566).# Keys in ~/.l06/credentials are Moto fake keys, not secrets.export L06_DIR=~/.l06l06(){ # l06 <profile> <aws command...> run an AWS CLI command as identity <profile> local p=$1; shift AWS_SHARED_CREDENTIALS_FILE=$L06_DIR/credentials AWS_CONFIG_FILE=/dev/null AWS_PROFILE=$p \ AWS_ACCESS_KEY_ID= AWS_SECRET_ACCESS_KEY= AWS_SESSION_TOKEN= \ aws --endpoint-url http://127.0.0.1:4567 --region us-east-1 "$@"}ai-day(){ l06 "$1" sts get-caller-identity --query Arn --output text; } # who is calling?doc(){ l06 "$1" s3api get-object --bucket reports --key q4-report.txt /dev/stderr >/dev/null; } # print the filedat-policy(){ # dat-policy <policy-name> <file in chinh-sach/>: admin attaches an inline policy to dev l06 admin iam put-user-policy --user-name dev --policy-name "$1" --policy-document "file://chinh-sach/$2.json" && echo "policy $1 <- $2.json"; }ghi(){ l06 "$1" s3api put-object --bucket reports --key "${2:-note.txt}" --body /etc/hostname --query 'ETag' --output text; }xoa(){ l06 "$1" s3api delete-object --bucket reports --key q4-report.txt && echo "da xoa"; }nhan-role(){ # nhan-role <role>: dev gets temporary keys for the role, saved as profile <role> local c; c=$(l06 dev sts assume-role --role-arn arn:aws:iam::123456789012:role/$1 --role-session-name dev-$1 \ --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken,Expiration]' --output text) || return 1 set -- "$1" $c printf '[%s]\naws_access_key_id = %s\naws_secret_access_key = %s\naws_session_token = %s\n' "$1" "$2" "$3" "$4" >> $L06_DIR/credentials echo "AccessKeyId: $2"; echo "Expiration: $5"}| Line | Meaning | Why it is set this way |
|---|---|---|
AWS_SHARED_CREDENTIALS_FILE=$L06_DIR/credentials |
Read keys from the lab’s own file | Your real ~/.aws/credentials is never touched. |
AWS_CONFIG_FILE=/dev/null |
Ignore the machine’s AWS config file | Keeps existing SSO profiles or default Regions out of the lab. |
AWS_ACCESS_KEY_ID= ... AWS_SESSION_TOKEN= |
Blank out keys in environment variables | The AWS CLI prefers environment variables over profiles; without this, every command runs with the same key whether you type dev or admin. |
--endpoint-url http://127.0.0.1:4567 |
Call the lab’s own Moto | Never reaches real AWS by accident. |
doc writes to /dev/stderr |
Print the file straight to the screen | get-object requires an output file; stderr shows the content without creating one. |
ghi returns the ETag |
Print the ETag of the new object | An ETag is proof the write succeeded. |
nhan-role writes a new profile |
Save the temporary keys as a profile named after the role | You can then run doc report-reader like any other identity. |
Finally dung.sh (build) and don.sh (clean up):
#!/usr/bin/env bash# Lab 06: start Moto with IAM authorization + sample data.# INITIAL_NO_AUTH_ACTION_COUNT=5: the first 5 calls skip authorization (enough to create admin); from the 6th, every call needs permission.set -euo pipefailsource "$(dirname "$0")/lab.sh"cd "$(dirname "$0")"docker rm -f l06-moto >/dev/null 2>&1 || truedocker run -d --name l06-moto -e INITIAL_NO_AUTH_ACTION_COUNT=5 -p 127.0.0.1:4567:5000 motoserver/moto:latest >/dev/nulluntil curl -s -o /dev/null http://127.0.0.1:4567/moto-api/; do sleep 0.5; donemkdir -p $L06_DIR; : > $L06_DIR/credentialsA="aws --endpoint-url http://127.0.0.1:4567 --region us-east-1"export AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test# 5 calls without authorization$A s3api create-bucket --bucket reports >/dev/null # 1printf 'Q4 revenue report (sample data)\n' > /tmp/q4-report.txt$A s3api put-object --bucket reports --key q4-report.txt --body /tmp/q4-report.txt >/dev/null # 2$A iam create-user --user-name admin >/dev/null # 3$A iam put-user-policy --user-name admin --policy-name admin --policy-document file://chinh-sach/admin.json # 4$A iam create-access-key --user-name admin --query 'AccessKey.[AccessKeyId,SecretAccessKey]' --output text \ | awk '{printf "[admin]\naws_access_key_id = %s\naws_secret_access_key = %s\n",$1,$2}' >> $L06_DIR/credentials # 5# from here on: admin does the work, Moto authorizes for reall06 admin iam create-user --user-name dev >/dev/nulll06 admin iam put-user-policy --user-name dev --policy-name read-write-reports --policy-document file://chinh-sach/dev-sai.jsonl06 admin iam put-user-policy --user-name dev --policy-name assume-roles --policy-document file://chinh-sach/dev-assume.jsonl06 admin iam create-access-key --user-name dev --query 'AccessKey.[AccessKeyId,SecretAccessKey]' --output text \ | awk '{printf "[dev]\naws_access_key_id = %s\naws_secret_access_key = %s\n",$1,$2}' >> $L06_DIR/credentialsl06 admin iam create-role --role-name report-reader --assume-role-policy-document file://chinh-sach/trust-dev.json >/dev/nulll06 admin iam put-role-policy --role-name report-reader --policy-name read-only --policy-document file://chinh-sach/reader.jsonl06 admin iam create-role --role-name ops-admin --assume-role-policy-document file://chinh-sach/trust-ops.json >/dev/nullecho "Lab 06 san sang: bucket reports, user admin + dev, role report-reader (tin dev) + ops-admin (chi tin ops)"#!/usr/bin/env bash# Lab 06: remove the private Moto (all data lives in the container) + the fake keys file.docker rm -f l06-moto >/dev/null 2>&1; rm -f ~/.l06/credentials; echo "Da don Lab 06"| Line | Meaning | Why it is set this way |
|---|---|---|
-e INITIAL_NO_AUTH_ACTION_COUNT=5 |
The first 5 calls skip authorization | With no users yet, nobody has permission to create the first one. Exactly 5: create bucket, upload file, create admin, attach policy, create admin key. Set it higher than the calls you make and authorization is still off when you test, so everything “works”. |
-p 127.0.0.1:4567:5000 |
Port 4567 on 127.0.0.1 only |
Not exposed to the network; separate from the shared Moto on 4566. |
until curl ... /moto-api/ |
Wait for Moto to be ready | Calling too early fails the first command with a connection error, and set -e aborts the script. |
AWS_ACCESS_KEY_ID=test |
Fake key for the first 5 calls | The AWS CLI requires a key; these calls are not checked, so any key works. |
l06 admin ... |
From the 6th call on, use admin’s key | Moto now authorizes for real; admin succeeds because of Allow *. |
--assume-role-policy-document |
The role’s trust policy | Every role needs one at creation. |
The two echo lines print in Vietnamese: “Lab 06 ready: …” and “Lab 06 cleaned”.
Run it:
chmod +x dung.sh don.sh && ./dung.sh && source lab.shai-day devLab 06 san sang: bucket reports, user admin + dev, role report-reader (tin dev) + ops-admin (chi tin ops)arn:aws:iam::123456789012:user/devHow to read the output: the first line means dung.sh finished without errors (with set -e it stops at the first failure). The second line confirms that profile dev uses the key of user dev. If you see InvalidClientTokenId instead, ~/.l06/credentials has no dev profile: run ./dung.sh again.
Step 2: Break it: right action, wrong ARN
What you are doing: reading the report as dev with the dev-sai.json policy that dung.sh attached. The policy clearly says s3:GetObject.
ai-day devjq -c '.Statement[]' chinh-sach/dev-sai.jsondoc dev![Terminal: ai-day dev prints arn:aws:iam::123456789012:user/dev; jq prints the statement Sid ReadWriteReports, Effect Allow, Action s3:GetObject and s3:PutObject, Resource arn:aws:s3:::reports; doc dev fails with aws: [ERROR]: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied](/_astro/canh-1-sai-arn.fdefuG6f_1ppJgQ.webp)
How to read the output: arn:aws:iam::123456789012:user/dev confirms the caller is dev, not a mixed-up key. The statement has "Action":["s3:GetObject",...]. The error says when calling the GetObject operation: the blocked action is indeed GetObject. So the Action is fine, which leaves Resource: arn:aws:s3:::reports is the address of the bucket, while the file q4-report.txt lives at arn:aws:s3:::reports/q4-report.txt. The Allow does not match the resource, so no Allow applies: an implicit deny.
Step 3: Fix it with the object ARN reports/*
What you are doing: changing the single Resource line to the object ARN, re-attaching the policy under the same name, then reading and writing.
diff chinh-sach/dev-sai.json chinh-sach/dev-dung.jsondat-policy read-write-reports dev-dungdoc devghi dev| Command | Meaning | Why |
|---|---|---|
dat-policy read-write-reports dev-dung |
admin calls put-user-policy on dev with the name read-write-reports |
An inline policy with the same name replaces the old one instead of adding a statement. dev now has only the fixed version. |
arn:aws:s3:::reports/* |
Every object in bucket reports |
The / after the bucket name and * for any key. For less, use a prefix: reports/q4/*. |

How to read the output: diff prints 8c8: line 8 differs between the files, and only that line. doc dev prints the file, so GetObject is now allowed. ghi dev prints a quoted string, the ETag of the new object note.txt: PutObject is allowed too.
Step 4: Too-wide permissions, and a Deny as a guardrail
What you are doing: giving dev s3:* (every S3 action) on objects, then adding a separate policy with a single Deny s3:DeleteObject statement. Try a delete, try a read.
jq -c '.Statement[]' chinh-sach/dev-rong.json chinh-sach/chan-xoa.jsondat-policy read-write-reports dev-rong; dat-policy no-delete chan-xoaxoa devdoc dev
How to read the output: the two policy ... <- lines show that dev now has two policies. The s3:* Allow includes s3:DeleteObject, yet xoa dev gets AccessDenied on DeleteObject: that is an explicit deny, evaluated first, and it wins. doc dev still prints the content because the Deny only names s3:DeleteObject.
| Line | Meaning | Why it is set this way |
|---|---|---|
"Action": "s3:*" |
Every S3 action | The common “just make it work” grant. Kept here to prove the guardrail still holds. On real AWS, list the actions you need. |
"Effect": "Deny" in a separate policy |
Block deletes, kept apart from the grant | Someone can edit or replace the grant (as you just did with read-write-reports) and the guardrail stays. |
"Resource": "arn:aws:s3:::reports/*" |
Applies to every object | A Deny must also match the resource. Put the bucket ARN here by mistake and the guardrail silently does nothing. |
Step 5: Drop long-term keys: assume a read-only role
What you are doing: instead of carrying a key that can write all day, dev assumes role report-reader (read-only) when it needs to read reports. STS issues a set of temporary keys.
jq -c '.Statement[0].Principal' chinh-sach/trust-dev.jsonnhan-role report-readerai-day report-readerdoc report-readerghi report-reader
How to read the output:
AccessKeyId: ASIA…: theASIAprefix marks temporary credentials from STS; IAM user keys start withAKIA. SeeingASIAin a log tells you the caller is using a role.Expiration: the expiry time in UTC, exactly 1 hour after the request because no--duration-secondswas passed (default 3600 seconds). After that the key is useless.assumed-role/report-reader/dev-report-reader: the identity is now the role; the last part is the session name (--role-session-name) set bynhan-role. It shows up in logs, so you can tell who assumed the role.ghi report-readergetsAccessDeniedonPutObjecteven thoughdevcurrently hass3:*. While using a role you have only the role’s permissions; the user’s permissions are not added.
| Parameter | Meaning | Why |
|---|---|---|
--role-arn arn:aws:iam::123456789012:role/report-reader |
The role to assume | Roles are assumed by ARN, so a role in another account works too if its trust policy allows it. |
--role-session-name dev-report-reader |
Session name | Required. Appears in the identity ARN and in CloudTrail, so you can trace who assumed the role. |
(no) --duration-seconds |
Key lifetime | Defaults to 3600 seconds. The maximum is the role’s maximum session duration, from 1 to 12 hours; assuming a role from another role (role chaining) caps it at 1 hour. |
Step 6: A trust policy that does not trust you
What you are doing: having dev request role ops-admin. The dev policy allows sts:AssumeRole on every role, but the ops-admin trust policy trusts only user/ops.
jq -c '.Statement[0].Principal' chinh-sach/trust-ops.jsonnhan-role ops-admin![Terminal: trust-ops.json has Principal AWS arn:aws:iam::123456789012:user/ops; nhan-role ops-admin fails with aws: [ERROR]: An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::123456789012:user/dev is not authorized to perform: sts:AssumeRole](/_astro/canh-5-trust.BIbukuZO_Z1D2fKC.webp)
How to read the output: the error comes from AssumeRole, so no temporary key was issued (nhan-role stops there and writes no profile). The message names user/dev and the action sts:AssumeRole. The dev policy already allows that action (step 1), so the block is on the role side: its trust policy lists only user/ops. To let dev in, change the role’s trust policy (aws iam update-assume-role-policy), not the dev policy.
On real AWS
- Read the error before you fix anything. For requests within the same account or organization, S3’s 403 says which policy type denied:
because no identity-based policy allows(missing Allow, usually a wrong Action or Resource) orwith an explicit deny in ...(a Deny, with the policy ARN). Requests from accounts outside your organization get a plainAccess Denied. - Write S3 policies in pairs:
s3:ListBucketonarn:aws:s3:::<bucket>, object actions onarn:aws:s3:::<bucket>/*. Writing both statements by habit avoids the step 2 bug. - Use Deny as a guardrail for things that must never happen (deleting reports, turning off CloudTrail). Keep it in its own policy; across many accounts, use SCPs.
- Replace long-term access keys with roles. Applications on EC2, ECS and Lambda get temporary keys from an attached role, with no key file. People sign in through IAM Identity Center and assume roles. A leaked
ASIA…key only lives until it expires. - Test before you attach: the IAM policy simulator takes an identity, an action and an ARN, and tells you whether it is allowed, along with the deciding statement.
- Find the trail: CloudTrail records
errorCode: AccessDeniedfor denied calls. S3 object operations (GetObject, PutObject) are data events, which you must enable to see them.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
An error occurred (AccessDenied) when calling the GetObject operation although the policy has s3:GetObject |
Resource is the bucket ARN arn:aws:s3:::reports |
Use the object ARN arn:aws:s3:::reports/* (step 3) |
aws s3 ls s3://reports fails with AccessDenied on ListObjectsV2, reading files works |
s3:ListBucket is missing, or granted on reports/* |
Add an s3:ListBucket statement on the bucket ARN, without /* |
AccessDenied on DeleteObject despite s3:* |
A matching Deny in another policy (identity, bucket policy or SCP) |
Find the Deny; on real AWS read with an explicit deny in ... in the error |
AccessDenied when calling the AssumeRole operation |
The role’s trust policy does not include you, or (cross-account, or a trust policy that names only :root) your policy lacks sts:AssumeRole |
Fix the role’s trust policy; check the caller’s policy too |
| After assuming a role you cannot do what the user could | A role session has only the role’s permissions | Grant the permission to the role, or go back to the user’s keys |
Error code ExpiredToken (S3: The provided token has expired; STS, IAM: The security token included in the request is expired) |
The temporary key is past its Expiration |
Assume the role again; for longer sessions raise the role’s maximum session duration and pass --duration-seconds |
| On Moto every command succeeds, even with a broken policy | Authorization is not on yet: INITIAL_NO_AUTH_ACTION_COUNT is larger than the calls made so far |
Set it to exactly the number of setup calls (5 in this guide) |
doc dev runs as someone else |
AWS_ACCESS_KEY_ID is set in the environment and wins over the profile |
Clear the environment variables, as the l06 function does |
Clean up
./don.shDa don Lab 06All users, roles and buckets live in the memory of container l06-moto, so removing the container removes everything. don.sh also deletes the fake keys file ~/.l06/credentials.
FAQ
Why not grant s3:* on * and be done?
It works, but that user can delete every bucket, change bucket policies and expose data to the internet. Leak the key and you leak everything. Granting the right actions on the right ARNs means a leaked key costs little.
There is a Deny in place. How do I let one person through? You cannot out-vote a Deny with an Allow. Change the Deny itself, for example with a condition that excludes that person or role.
How is a role different from an IAM user?
A user has long-term keys (AKIA…) that live until they are deleted or rotated. A role has no long-term keys; whoever its trust policy allows can assume it and get temporary keys (ASIA…) that expire.
Does trusting arn:aws:iam::123456789012:root mean trusting the root user?
No. It means trusting the whole account; users and roles in that account then need a policy that allows sts:AssumeRole before they can assume the role.
Can I do this on real AWS? IAM and STS have no charge. A separate test account is enough; S3 costs next to nothing for a few small files.
References
- AWS: Policy evaluation logic and explicit vs implicit deny
- AWS: How AWS processes Deny and Allow
- AWS: How Amazon S3 works with IAM (bucket and object ARNs)
- AWS: Troubleshoot access denied (403) errors in Amazon S3, message examples
- AWS: Grant a user permissions to switch roles and cross-account policy evaluation logic
- AWS STS: AssumeRole (DurationSeconds) and GetAccessKeyInfo (AKIA, ASIA prefixes)
- AWS Security Blog: Writing IAM Policies: How to Grant Access to an Amazon S3 Bucket
- AWS: IAM policy simulator
- AWS: Logging S3 data events with CloudTrail
- Moto: IAM-like Access Control

Cloud & Network Engineer · TrungCLN
Designs and runs AWS infrastructure, hybrid networking (VPN, BGP) and cloud security. Every guide on this site is built and run for real before it is written.
Related guides

AWSBeginner30 min
ALB 502 or 503? Every target is unhealthy, yet the site still returns 200
A real lab with Envoy playing an ALB: all targets unhealthy still returns 200 (fail open), a closed app port gives 502, only an empty target group gives 503.
AWSBeginner45 min
Private subnet can't reach the Internet: route tables, NAT Gateway and VPC endpoints
A host in a private subnet cannot reach the Internet? Build a real lab with route tables, NAT and internet gateways, an S3 gateway endpoint, and price NAT at real rates.