---
title: "Lab: Users, Policies and Temporary Credentials"
domain: cloud-computing
level: intermediate
duration: "75 min"
cost: "free"
environment: "containers (rootless Podman on Linux): a local AWS-compatible IAM emulator and the AWS CLI; no cloud account"
---

# Lab: Users, Policies and Temporary Credentials

## Goal
Build a small cloud IAM setup on your own computer: create users with a least-privilege policy, watch default deny and explicit deny at work, reuse a managed policy through a group, give a user temporary credentials by assuming a role, and rotate an access key. Everything runs against a local emulator, so you cannot break anything real or spend a cent.

## Objectives
- Authenticate as different principals and tell an authentication failure from an authorization failure.
- Write a least-privilege JSON policy and test an allowed and a denied request for each statement.
- Show that an explicit deny overrides an allow.
- Reuse permissions through a managed policy attached to a group.
- Assume a role to get temporary credentials (ASIA key and session token) and compare the identity and permissions before and after.
- Rotate an access key without interrupting access, and review keys with their last use.

## Prerequisites
- Podman 4 or later on Linux, rootless, no `sudo` (tested with Podman 5.8). Docker works if you replace `podman` with `docker` in the commands.
- Images pulled on first use (about 900 MB of disk in total): `docker.io/motoserver/moto:5.2.4` (the server) and `docker.io/amazon/aws-cli:2.38.0` (the client).
- Free TCP port `9100` on `127.0.0.1`.
- No cloud account, no credit card, and no Internet access after the images are pulled.
- [The Cloud IAM lesson](lesson.md) of this module.

> [!WARNING]
> The lab is free and local. The server listens on `127.0.0.1` only. The "keys" you create are random strings for an emulator and mean nothing anywhere else; the lab saves them in plain files to keep the steps short, which you must **never** do with real credentials. Changes stay inside one folder (`~/iam-lab`), one container and, optionally, two images, all removed at the end.

> [!NOTE]
> **Why AWS-compatible APIs?** The lab speaks the AWS IAM, STS and S3 APIs because they are the de facto standard: most tutorials, tools, Terraform modules and S3-compatible storage services at other providers understand them, and open-source emulators let you practise for free. Other providers differ in syntax and vocabulary (OpenStack Keystone with users, projects and tokens; Azure role assignments at a scope; Google Cloud roles bound to members on a resource) but share the concepts you practise here: principals, default deny, least privilege and temporary credentials.

> [!NOTE]
> **Emulator limits.** [Moto](https://docs.getmoto.org/) is an emulator, not the real cloud, and it implements only part of IAM. In this setup (Moto 5.2.4), `Allow` and `Deny` on actions and resources are enforced for IAM, STS and S3, which is what the lab needs. These real-cloud behaviours are **not** reproduced, so don't expect them and don't rely on them: `Condition` blocks are ignored (an MFA or IP condition always "passes"); deactivating an access key doesn't block it; the expiry of temporary credentials is not verified; `iam simulate-principal-policy` fails with a server error; and presigned URLs and anonymous requests fail with a server error when authentication is enforced. On a real cloud, all of these work.

## Architecture
![Lab architecture. On your Linux computer with rootless Podman, a terminal runs shell functions from lab.sh in the folder ~/iam-lab, which also holds the policy JSON files and a keys folder with lab-only keys. Each aws command runs the AWS CLI v2 container, image amazon/aws-cli:2.38.0, started with run --rm, with ~/iam-lab mounted at /work. The CLI sends signed HTTP requests to 127.0.0.1 port 9100, mapped to port 5000 of the container lab-iam-moto running Moto 5.2.4, an AWS API emulator that enforces authentication after the first 3 calls. Moto keeps its state in memory: the users admin, bob, carol and dave, the group analysts, the role reader, the managed policy reports-reader and the bucket lab-data](../../../assets/diagrams/iam-lab-architecture.svg)

*Figure 1. Each `aws` command is a short-lived client container that sends signed requests to the emulator on `127.0.0.1:9100`; the emulator keeps users, policies and data in memory.*

## Steps

### Step 1 — Create the working folder and start the emulator
All files go in one folder, so cleanup is easy. The server container has a name starting with `lab-iam-`, and `INITIAL_NO_AUTH_ACTION_COUNT=3` tells Moto to accept its first three API calls without authentication. You need exactly that to bootstrap the first administrator, because nobody can sign a request until a user and a key exist. After the third call, every request must be signed by a known key and is checked against policies.

```bash
mkdir -p ~/iam-lab && cd ~/iam-lab
podman run -d --name lab-iam-moto -p 127.0.0.1:9100:5000 \
  -e INITIAL_NO_AUTH_ACTION_COUNT=3 docker.io/motoserver/moto:5.2.4
```

Expected output (a container ID; yours differs):
```text
f97527afd13808739cf9b751e2d21b95469f2837c6cbb991e688d8f806244295
```

> [!IMPORTANT]
> The three free calls are a counter on the server: do exactly Steps 3 to 5 in order and don't run other `aws` commands before them. If you mix up the order, remove the container and start again: `podman rm -f lab-iam-moto`, then repeat this step. (A command that fails on your side before reaching the server, for example a typo in a file name, doesn't use a call.)

### Step 2 — Define the helper functions
Create a small file with three shell functions and load it. It is the only "tooling" in the lab. Read it once: it is short.

- `aws` runs the AWS CLI v2 container and points it at the emulator. It passes your credentials from environment variables, mounts the current folder at `/work` so `file://policy.json` works (`:Z` relabels the folder for SELinux hosts such as Fedora), and uses a fixed Region.
- `use <name>` switches your terminal to the identity whose key is saved in `keys/<name>`.
- `newkey <user>` creates an access key for a user and saves it in `keys/<user>`.

```bash
cat > lab.sh <<'SCRIPT'
# Lab helpers: source this file in every terminal you use for the lab.
aws() { podman run --rm --network host -v "$PWD:/work:Z" -w /work -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_SESSION_TOKEN -e AWS_DEFAULT_REGION=us-east-1 -e AWS_PAGER= docker.io/amazon/aws-cli:2.38.0 --endpoint-url http://127.0.0.1:9100 "$@"; }
# use <name>: act as the user whose key is saved in ~/iam-lab/keys/<name>
use() { read -r AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY < "$HOME/iam-lab/keys/$1"; export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY; unset AWS_SESSION_TOKEN; }
# newkey <user>: create an access key for <user> and save it (lab only: never store real keys in plain files)
newkey() { aws iam create-access-key --user-name "$1" --query 'AccessKey.[AccessKeyId,SecretAccessKey]' --output text > "$HOME/iam-lab/keys/$1"; }
SCRIPT
mkdir -p keys && chmod 700 keys
source lab.sh
```

The first `aws` command pulls the CLI image (about 470 MB), so it takes a moment once. Run `source ~/iam-lab/lab.sh` in every new terminal, from `~/iam-lab`.

### Step 3 — Bootstrap the administrator (free calls 1 to 3)
The emulator doesn't check the credentials of the first three calls, but the CLI still wants some, so you use the dummy pair `test` / `test`. You create a user `admin`, give it a policy that allows everything, and create its access key. The policy file is the shape you saw in the lesson: a version and one statement.

```bash
export AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test

cat > admin-policy.json <<'JSON'
{
  "Version": "2012-10-17",
  "Statement": [
    { "Effect": "Allow", "Action": "*", "Resource": "*" }
  ]
}
JSON

aws iam create-user --user-name admin
aws iam put-user-policy --user-name admin --policy-name admin-all --policy-document file://admin-policy.json
newkey admin
```

Expected output (the user ID and date differ; `put-user-policy` and `newkey` print nothing):
```text
{
    "User": {
        "Path": "/",
        "UserName": "admin",
        "UserId": "c2ndbofy683n3gu2ii3r",
        "Arn": "arn:aws:iam::123456789012:user/admin",
        "CreateDate": "2026-11-07T18:58:03.515092+00:00"
    }
}
```

Account `123456789012` is the fixed account ID that Moto uses. That broad policy is for this single lab administrator only: you saw in the lesson why `*` on `*` is dangerous in real life.

### Step 4 — Sign in as admin and see authentication fail
Switch to the key you just saved. From now on, every request is signed and checked.

```bash
use admin
aws sts get-caller-identity
aws iam list-users --query 'Users[].UserName'
```

Expected output (the user ID differs):
```text
{
    "UserId": "c2ndbofy683n3gu2ii3r",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:user/admin"
}
[
    "admin"
]
```

`get-caller-identity` is the cloud's answer to "who am I?" and works for any valid identity without extra permissions. Run it whenever you wonder which identity your terminal uses. Now try the dummy key again, which is no longer a known identity:

```bash
AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test aws iam list-users
```

Expected output:
```text
aws: [ERROR]: An error occurred (InvalidClientTokenId) when calling the ListUsers operation: The security token included in the request is invalid.
```

This is an **authentication** failure: the server doesn't know who you are. Keep it in mind: in the next steps you will see `AccessDenied`, which is a different problem.

### Step 5 — Create a bucket with two folders
You need something to protect. As admin, create the bucket `lab-data` and upload one harmless "report" and one "secret". Both are fake text.

```bash
aws s3api create-bucket --bucket lab-data
echo "Q3 revenue: 42 (fake)" > q3.txt
echo "admin password: not-a-real-secret" > passwords.txt
aws s3 cp q3.txt s3://lab-data/reports/q3.txt --only-show-errors
aws s3 cp passwords.txt s3://lab-data/secret/passwords.txt --only-show-errors
aws s3 ls s3://lab-data --recursive
```

Expected output (timestamps differ):
```text
{
    "Location": "/lab-data"
}
2026-11-07 18:58:18         22 reports/q3.txt
2026-11-07 18:58:19         34 secret/passwords.txt
```

### Step 6 — Create bob with a least-privilege policy
Bob is an analyst who must read and write reports and nothing else. The policy has two statements, written as in the lesson: `ListBucket` applies to the bucket ARN, while `GetObject` and `PutObject` apply to the objects under `reports/`.

```bash
cat > bob-policy.json <<'JSON'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ListTheBucket",
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::lab-data"
    },
    {
      "Sid": "ReadWriteReports",
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:PutObject"],
      "Resource": "arn:aws:s3:::lab-data/reports/*"
    }
  ]
}
JSON

aws iam create-user --user-name bob --query User.Arn
aws iam put-user-policy --user-name bob --policy-name reports-rw --policy-document file://bob-policy.json
newkey bob
```

Expected output:
```text
"arn:aws:iam::123456789012:user/bob"
```

`put-user-policy` creates an **inline policy**: it lives inside the user and has a name (`reports-rw`). You will meet the other kind, a managed policy, in Step 9.

### Step 7 — Test what Bob can and cannot do
Act as Bob and try eight requests. For each one, predict the answer before you run it: the policy decides, not luck.

```bash
use bob
aws sts get-caller-identity --query Arn --output text
echo "Q4 draft (fake)" > q4.txt

# 1. List the reports
aws s3api list-objects-v2 --bucket lab-data --prefix reports/ --query 'Contents[].Key'
# 2. Read a report
aws s3api get-object --bucket lab-data --key reports/q3.txt q3-bob.txt --query ContentLength
cat q3-bob.txt
# 3. Write a report
aws s3api put-object --bucket lab-data --key reports/q4.txt --body q4.txt --query ETag
# 4. Write outside reports/
aws s3api put-object --bucket lab-data --key secret/q4.txt --body q4.txt
# 5. Read the secret
aws s3api get-object --bucket lab-data --key secret/passwords.txt x.txt
# 6. List all buckets
aws s3api list-buckets
# 7. Delete a report
aws s3api delete-object --bucket lab-data --key reports/q4.txt
# 8. Use IAM
aws iam list-users
```

Expected output (the ETag differs):
```text
arn:aws:iam::123456789012:user/bob
[
    "reports/q3.txt"
]
22
Q3 revenue: 42 (fake)
"\"c32c8500d318ac0878b49cc441b6b837\""

aws: [ERROR]: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

aws: [ERROR]: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied

aws: [ERROR]: An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied

aws: [ERROR]: An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied

aws: [ERROR]: An error occurred (AccessDenied) when calling the ListUsers operation: User: arn:aws:iam::123456789012:user/bob is not authorized to perform: iam:ListUsers
```

Requests 1 to 3 match an `Allow`. Requests 4 and 5 target `secret/`, which no statement allows. Request 6 needs `s3:ListAllMyBuckets`, which Bob doesn't have. Request 7, `DeleteObject`, is not in the list of allowed actions. All of these are the **default deny**: no policy said "no", there is simply no "yes". Note that every denial is `AccessDenied`, not `InvalidClientTokenId`: Bob authenticated fine.

### Step 8 — Make the policy too broad, then add an explicit deny
Suppose someone "simplifies" Bob's policy with `s3:*` on `reports/*`. Then you cap the damage with an explicit deny on deletion. Policy changes are an admin job, so switch to admin and back.

```bash
use admin
cat > bob-policy-broad.json <<'JSON'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ListTheBucket",
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::lab-data"
    },
    {
      "Sid": "EverythingInReports",
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": "arn:aws:s3:::lab-data/reports/*"
    }
  ]
}
JSON
aws iam put-user-policy --user-name bob --policy-name reports-rw --policy-document file://bob-policy-broad.json

use bob
aws s3api delete-object --bucket lab-data --key reports/q4.txt && echo "delete succeeded"
aws s3api put-object --bucket lab-data --key reports/q4.txt --body q4.txt --query ETag
```

Expected output:
```text
delete succeeded
"\"c32c8500d318ac0878b49cc441b6b837\""
```

Putting a policy with the same name replaces the old one. Bob can now delete: the wider allow covers `DeleteObject`. You re-uploaded `q4.txt` so you can test the next step. Now add a third statement, an explicit deny, to the policy:

```bash
use admin
cat > bob-policy-deny.json <<'JSON'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ListTheBucket",
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::lab-data"
    },
    {
      "Sid": "EverythingInReports",
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": "arn:aws:s3:::lab-data/reports/*"
    },
    {
      "Sid": "NeverDelete",
      "Effect": "Deny",
      "Action": "s3:DeleteObject",
      "Resource": "*"
    }
  ]
}
JSON
aws iam put-user-policy --user-name bob --policy-name reports-rw --policy-document file://bob-policy-deny.json

use bob
aws s3api delete-object --bucket lab-data --key reports/q4.txt
aws s3api get-object --bucket lab-data --key reports/q4.txt q4-back.txt --query ContentLength
aws s3api list-objects-v2 --bucket lab-data --query 'Contents[].Key'
```

Expected output:
```text

aws: [ERROR]: An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied
16
[
    "reports/q3.txt",
    "reports/q4.txt",
    "secret/passwords.txt"
]
```

The `s3:*` allow still matches `DeleteObject`, but the explicit `Deny` wins: delete fails and the object is still there (16 bytes). Notice the last result as well: Bob can *list* the whole bucket, including the name `secret/passwords.txt`, because `ListBucket` was allowed on the bucket ARN with no prefix limit. He can't read the file, but he learns it exists. On a real cloud you narrow this with a `Condition` on the key prefix; the emulator ignores conditions, so you can't try it here.

### Step 9 — Reuse permissions with a managed policy and a group
Inline policies are copied per user. A **managed policy** is a named, reusable document that you create once and attach to many users, groups or roles. Create a read-only policy, attach it to a group `analysts`, and add a new user, dave, to the group. Dave gets his permissions from the group and has no policy of his own.

```bash
use admin
cat > reports-reader.json <<'JSON'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::lab-data"
    },
    {
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::lab-data/reports/*"
    }
  ]
}
JSON

aws iam create-policy --policy-name reports-reader --policy-document file://reports-reader.json --query Policy.Arn
aws iam create-group --group-name analysts --query Group.Arn
aws iam attach-group-policy --group-name analysts --policy-arn arn:aws:iam::123456789012:policy/reports-reader
aws iam create-user --user-name dave --query User.Arn
aws iam add-user-to-group --group-name analysts --user-name dave
aws iam list-groups-for-user --user-name dave --query 'Groups[].GroupName'
newkey dave
```

Expected output:
```text
"arn:aws:iam::123456789012:policy/reports-reader"
"arn:aws:iam::123456789012:group/analysts"
"arn:aws:iam::123456789012:user/dave"
[
    "analysts"
]
```

Test Dave:

```bash
use dave
aws s3api get-object --bucket lab-data --key reports/q3.txt q3-dave.txt --query ContentLength
aws s3api put-object --bucket lab-data --key reports/dave.txt --body q4.txt
aws s3api get-object --bucket lab-data --key secret/passwords.txt x.txt
```

Expected output:
```text
22

aws: [ERROR]: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

aws: [ERROR]: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied
```

Dave can read reports because his group has the managed policy; he can't write or read the secret. Adding the next analyst is one `add-user-to-group` call, and changing what analysts may do means editing one policy. That is RBAC in practice.

### Step 10 — Assume a role to get temporary credentials
Carol needs read access to the reports only now and then. Instead of a permanent permission, you create a **role** `reader` that she may assume. The role has a **trust policy** (who may assume it) and a **permissions policy** (what it may do; you reuse `reports-reader.json`).

```bash
use admin
aws iam create-user --user-name carol --query User.Arn
newkey carol

cat > reader-trust.json <<'JSON'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::123456789012:user/carol" },
      "Action": "sts:AssumeRole"
    }
  ]
}
JSON

aws iam create-role --role-name reader --assume-role-policy-document file://reader-trust.json --query Role.Arn
aws iam put-role-policy --role-name reader --policy-name read-reports --policy-document file://reports-reader.json

cat > carol-assume.json <<'JSON'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "sts:AssumeRole",
      "Resource": "arn:aws:iam::123456789012:role/reader"
    }
  ]
}
JSON
aws iam put-user-policy --user-name carol --policy-name may-assume-reader --policy-document file://carol-assume.json
```

Expected output:
```text
"arn:aws:iam::123456789012:user/carol"
"arn:aws:iam::123456789012:role/reader"
```

> [!NOTE]
> The last policy lets Carol call `sts:AssumeRole` on this one role. Real AWS accepts a trust policy that names a user in the same account by itself, without it; the emulator requires both, so you add it here. Many teams add it anyway so the permission is visible on the user.

Now act as Carol. First try to read a report directly: she has no permission of her own. Then assume the role. The `read` line takes the three temporary values (key ID, secret, session token) from the response and puts them in environment variables.

```bash
use carol
aws sts get-caller-identity
aws s3api get-object --bucket lab-data --key reports/q3.txt x.txt

read -r AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN < <(
  aws sts assume-role --role-arn arn:aws:iam::123456789012:role/reader \
    --role-session-name carol-lab --duration-seconds 900 \
    --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' --output text)
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
echo "key id starts with: ${AWS_ACCESS_KEY_ID:0:4}   session token length: ${#AWS_SESSION_TOKEN}"
```

Expected output (the user ID and the token length differ):
```text
{
    "UserId": "2lahxwq9nou7k0ox8yzp",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:user/carol"
}

aws: [ERROR]: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied
key id starts with: ASIA   session token length: 356
```

The key now starts with `ASIA`, the prefix of temporary credentials (long-lived keys start with `AKIA`), and the session token is part of every request. Compare identities and permissions:

```bash
aws sts get-caller-identity
aws s3api get-object --bucket lab-data --key reports/q3.txt q3-role.txt --query ContentLength
aws s3api put-object --bucket lab-data --key reports/carol.txt --body q4.txt
aws s3api get-object --bucket lab-data --key secret/passwords.txt x.txt
```

Expected output:
```text
{
    "UserId": "AROARZPUZDIKOPOZ53WR2:carol-lab",
    "Account": "123456789012",
    "Arn": "arn:aws:sts::123456789012:assumed-role/reader/carol-lab"
}
22

aws: [ERROR]: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

aws: [ERROR]: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied
```

Carol is now `assumed-role/reader/carol-lab`: the role's permissions apply (read reports, nothing else), and her own are suspended. The session name `carol-lab` would show up in audit logs, so you can still tell who acted. These credentials were requested for 900 seconds (15 minutes) and would stop working then; the emulator doesn't enforce the expiry (see the emulator note), but a real cloud does. Return to Carol's own identity: `use` clears the session token.

```bash
use carol
aws sts get-caller-identity --query Arn --output text
```

Expected output:
```text
arn:aws:iam::123456789012:user/carol
```

### Step 11 — Rotate an access key
Long-lived keys should be replaced regularly, without an outage. The safe order is: create the second key, switch the application to it, confirm the old key is no longer used, and delete the old one. A user can have two keys at a time, which is what makes this possible. Rotate Bob's key.

```bash
use admin
cp keys/bob keys/bob.old
read -r OLDKEY _ < keys/bob.old
aws iam list-access-keys --user-name bob --query 'AccessKeyMetadata[].[AccessKeyId,Status]' --output text
newkey bob
aws iam list-access-keys --user-name bob --query 'length(AccessKeyMetadata)'
```

Expected output (the key IDs differ; each ID is 20 characters):
```text
AKIAIOSFODNN7EXAMPLE	Active
2
```

Bob now has two active keys. Both work, so you can move his applications to the new one (`keys/bob`) at your own pace:

```bash
use bob;     aws sts get-caller-identity --query Arn --output text
use bob.old; aws sts get-caller-identity --query Arn --output text
```

Expected output:
```text
arn:aws:iam::123456789012:user/bob
arn:aws:iam::123456789012:user/bob
```

When nothing uses the old key any more, delete it and confirm that only the new one works:

```bash
use admin
aws iam delete-access-key --user-name bob --access-key-id "$OLDKEY"
aws iam list-access-keys --user-name bob --query 'length(AccessKeyMetadata)'
use bob.old; aws sts get-caller-identity
use bob;     aws sts get-caller-identity --query Arn --output text
```

Expected output:
```text
1

aws: [ERROR]: An error occurred (InvalidClientTokenId) when calling the GetCallerIdentity operation: The security token included in the request is invalid.
arn:aws:iam::123456789012:user/bob
```

The old key fails at **authentication**, exactly like the dummy key in Step 4.

> [!NOTE]
> On a real cloud you can also set a key to `Inactive` first (`aws iam update-access-key --status Inactive`) and wait a few days to see what breaks before deleting it. Moto doesn't enforce deactivation, so the lab goes straight to deleting.

### Step 12 — Review: who exists and when were keys used?
A regular access review starts with an inventory. List the users, count their keys and check when a key was last used and for which service. Keys that nobody has used for months are candidates for deletion.

```bash
use admin
aws iam list-users --query 'Users[].UserName' --output text
for u in admin bob carol dave; do echo -n "$u keys: "; aws iam list-access-keys --user-name $u --query 'length(AccessKeyMetadata)'; done
aws iam get-access-key-last-used --access-key-id "$(cut -f1 keys/bob)"
```

Expected output (the date and order differ):
```text
admin	bob	dave	carol
admin keys: 1
bob keys: 1
carol keys: 1
dave keys: 1
{
    "UserName": "bob",
    "AccessKeyLastUsed": {
        "LastUsedDate": "2026-11-07T18:59:40.119388+00:00",
        "ServiceName": "sts",
        "Region": "us-east-1"
    }
}
```

On a real cloud this is where you would also open the audit log (for example CloudTrail) and look at the calls made with each identity.

## Verification
Run this check. It tries each request and compares the result (`allowed` or `denied`) with what the policies should produce. Each line must start with `PASS`.

```bash
check() { local want=$1 label=$2; shift 2; if "$@" >/dev/null 2>&1; then got=allowed; else got=denied; fi; if [ "$got" = "$want" ]; then echo "PASS  $label"; else echo "FAIL  $label (got $got)"; fi; }
use bob
check allowed "bob: read reports/q3.txt"   aws s3api get-object --bucket lab-data --key reports/q3.txt /dev/null
check allowed "bob: write reports/q5.txt"  aws s3api put-object --bucket lab-data --key reports/q5.txt --body q4.txt
check denied  "bob: write secret/q5.txt"   aws s3api put-object --bucket lab-data --key secret/q5.txt --body q4.txt
check denied  "bob: delete reports/q5.txt" aws s3api delete-object --bucket lab-data --key reports/q5.txt
check denied  "bob: list all buckets"      aws s3api list-buckets
use dave
check allowed "dave: read reports/q3.txt"  aws s3api get-object --bucket lab-data --key reports/q3.txt /dev/null
check denied  "dave: write reports/d.txt"  aws s3api put-object --bucket lab-data --key reports/d.txt --body q4.txt
use carol
check denied  "carol: read reports/q3.txt directly" aws s3api get-object --bucket lab-data --key reports/q3.txt /dev/null
read -r AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN < <(aws sts assume-role --role-arn arn:aws:iam::123456789012:role/reader --role-session-name carol-verify --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' --output text)
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
check allowed "carol as reader: read reports/q3.txt" aws s3api get-object --bucket lab-data --key reports/q3.txt /dev/null
check denied  "carol as reader: write reports/c.txt" aws s3api put-object --bucket lab-data --key reports/c.txt --body q4.txt
use bob.old
check denied  "bob's old key: any call" aws sts get-caller-identity
```

Expected output:
```text
PASS  bob: read reports/q3.txt
PASS  bob: write reports/q5.txt
PASS  bob: write secret/q5.txt
PASS  bob: delete reports/q5.txt
PASS  bob: list all buckets
PASS  dave: read reports/q3.txt
PASS  dave: write reports/d.txt
PASS  carol: read reports/q3.txt directly
PASS  carol as reader: read reports/q3.txt
PASS  carol as reader: write reports/c.txt
PASS  bob's old key: any call
```

A `denied` check passes for any failure, so also look at one denial by hand (Step 7) and confirm it says `AccessDenied`, not a connection error.

## Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| `Could not connect to the endpoint URL: "http://127.0.0.1:9100/"` | The server container isn't running, or port 9100 is taken by something else. | `podman ps -a --filter name=lab-iam-` and `podman logs lab-iam-moto`. If the port is busy, stop the other program. If you had to start over, redo Steps 3 to 12. |
| `InvalidClientTokenId` on a command that should work | The terminal uses the wrong key: the dummy `test` key after the three free calls, a deleted key, or a shell that never ran `use`. | Run `use <name>` and check with `aws sts get-caller-identity`. If the bootstrap order went wrong, run `podman rm -f lab-iam-moto`, repeat Step 1 and do Steps 3 to 5 in order. |
| `Unable to locate credentials` (`NoCredentials`) | A new terminal without the helpers or credentials. | `cd ~/iam-lab && source lab.sh && use admin`. |
| `Unable to load paramfile file://...: Permission denied` | SELinux blocks the mounted folder, or the `aws` function was copied without `:Z`. | Check that the `-v "$PWD:/work:Z"` option is intact, and that you run from `~/iam-lab`. |
| `AccessDenied` for a request you expected to work | The policy doesn't match the action or the resource, usually the bucket versus object ARN, or an old inline policy. | `aws iam get-user-policy --user-name bob --policy-name reports-rw` as admin, and compare the action and ARN with the request. |
| `MalformedPolicyDocument: Syntax errors in policy` | Invalid JSON in the policy file: a missing comma, quote or brace. | Check the file, for example with `python3 -m json.tool bob-policy.json`. |
| `Unknown options` or a parse error with `--query` and `--output text` | A `--query` that returns an object, not a list or a string, can fail in text mode. | Use `--output json`, or a query that returns a list (`[...]`) or a single value. |

## Challenge (optional)
Create a user `erin` who can *only* read objects under `reports/2026/` and has no way to list or read anything else. Then write the policy that would also require MFA for her, and explain why you can write it but not test it in this lab. Finally, create a role `uploader` that carol can assume to put objects into `reports/` but never to delete them, and prove it with the commands from Step 10.

## Cleanup
Stop and remove the server container, and delete the lab folder. The folder holds the lab keys, policies and downloaded files; the emulator keeps its data in memory only, so removing the container removes every user, policy and object.

```bash
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
podman rm -f lab-iam-moto
cd ~ && rm -r ~/iam-lab
```

Expected output:
```text
lab-iam-moto
```

The two images stay in your local storage so a second run starts instantly. To free the disk space (about 900 MB), remove them too. If you plan to do the storage lab that uses the same emulator image, keep the Moto image:

```bash
podman rmi docker.io/amazon/aws-cli:2.38.0 docker.io/motoserver/moto:5.2.4
```

Check that nothing is left:

```bash
podman ps -a --filter name=lab-iam-
ls ~/iam-lab
```

The first command should print only its header line, and the second should say that the folder doesn't exist. The `aws` and `use` functions disappear when you close the terminal.

## What you learned
- Authentication and authorization fail differently: an unknown or deleted key gives `InvalidClientTokenId`, a known identity without a matching `Allow` gives `AccessDenied`.
- Everything is denied unless a policy allows it (default deny), and `ListBucket` (bucket ARN) and `GetObject` (object ARN) need different resources.
- A broad allow can be capped by an explicit `Deny`, and the deny always wins.
- A managed policy attached to a group gives every member the same permissions from one place.
- `AssumeRole` swaps a user's identity for a role's: `ASIA` keys with a session token, the role's permissions only, and a session name that stays in the audit trail.
- Key rotation is safe because a user can hold two keys: create, switch, check, delete.
- An emulator is a good way to learn the model, but it doesn't reproduce everything (conditions, deactivation and expiry), so test those on a real cloud.
