Lesson 2 of 30Core services
IAM
Write least-privilege IAM policies, use roles instead of keys, and predict whether a request is allowed or denied.
IAM (Identity and Access Management) decides who can do what to which resource in your AWS account. Every single API call, from s3:GetObject to ec2:TerminateInstances, goes through it. Most real AWS security incidents are IAM mistakes, and "AccessDenied" is the error you will debug most often, so this is the lesson that pays back every day.
The cast: users, groups, roles, policies
IAM has four building blocks.
- A user is a long-term identity for one person or program, with a password and/or access keys (a key ID plus a secret). Access keys never expire on their own, which is exactly why they leak and cause trouble.
- A group is a set of users that share permissions, like
developers. You attach permissions to the group, not to each person. - A role is an identity with permissions but no long-term credentials. Something assumes the role and gets temporary credentials that expire (15 minutes to 12 hours). EC2 instances, Lambda functions, GitHub Actions and people can all assume roles.
- A policy is a JSON document that lists permissions. You attach policies to users, groups and roles (identity-based policies) or to resources like an S3 bucket (resource-based policies).
People go into groups. Ada and Sam get whatever the developers group allows.
Anatomy of a policy
Here is a real identity-based policy that lets an app read and write objects in one bucket, but only over HTTPS:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadWriteUploads",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::acme-uploads/*",
"Condition": {
"Bool": { "aws:SecureTransport": "true" }
}
}
]
}- Version is always
"2012-10-17"(it is the policy language version, not today's date). - Effect is
AlloworDeny. - Action names API calls as
service:Operation. Wildcards work:s3:Get*,s3:*. - Resource is an ARN (Amazon Resource Name), the unique ID of a thing in AWS:
arn:aws:s3:::acme-uploads/*means every object in theacme-uploadsbucket. - Condition (optional) adds rules about the request: source IP, MFA used, HTTPS, tags, time.
s3:GetObject on arn:aws:s3:::acme-uploads. The app calls GetObject on photos/cat.jpg in that bucket and gets AccessDenied. Why?"Action": "s3:GetObject", "Resource": "arn:aws:s3:::acme-uploads"
Least privilege
Least privilege means granting only the actions and resources a job actually needs. "Action": "*", "Resource": "*" is easy and works on the first try, which is why it ends up in production and why a leaked key from that app can delete your whole account.
In practice:
- Start from AWS managed policies only for humans exploring, then tighten.
- For apps, write narrow policies: specific actions, specific ARNs.
- Use IAM Access Analyzer to generate a policy from what a role actually used in CloudTrail logs, and to flag resources shared publicly or with other accounts.
Roles for services: no keys in code
Never put access keys in your code, your .env file or your Docker image. Instead, give the compute a role:
- EC2: attach an instance profile (a wrapper that holds a role). The SDK on the instance fetches temporary credentials from the instance metadata service automatically.
- Lambda: every function has an execution role. The function's code gets that role's permissions.
- ECS tasks: a task role.
The SDK finds these credentials on its own. Your code just does boto3.client("s3") with no keys anywhere.
A role has two policies. The permissions policy says what the role can do. The trust policy says who may assume it:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "lambda.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}Temporary credentials with STS
STS (Security Token Service) hands out the temporary credentials behind every role. When something assumes a role, STS returns an access key ID, a secret key and a session token, all of which expire.
The app asks STS to become app-role.
aws sts assume-role \ --role-arn arn:aws:iam::123456789012:role/app-role \ --role-session-name debug-ada# returns AccessKeyId, SecretAccessKey, SessionToken, ExpirationIAM Identity Center: how humans should sign in
For people, the modern answer is IAM Identity Center (formerly AWS SSO). You create users there (or connect Google Workspace, Okta or Microsoft Entra ID), assign them permission sets per account, and they sign in through a portal. Behind the scenes they assume roles and get temporary credentials. On the CLI it is aws configure sso then aws sso login.
That means: no IAM users with long-lived access keys for humans. If a laptop is stolen, the credentials on it expire within hours.
How AWS decides: allow or deny
When a request arrives, IAM gathers every policy that applies and follows three rules:
- Start at deny. Everything is denied by default (an implicit deny).
- An explicit
Denyalways wins. If any applying statement says Deny, the answer is no. Nothing can override it. - Otherwise, an
Allowlets it through. If no Deny matched and at least one Allow did, the request is allowed.
(The full logic also includes organization SCPs, permission boundaries and session policies, which can only narrow access. The three rules above are the core.)
Press Run (⌘ Enter) to see what happens.Change the order of the two statements and run it again. The answers do not change, because order never matters in IAM. A Deny anywhere wins.
Using the evaluator above, what does this print?
policy = [
{"Effect": "Allow", "Action": ["ec2:Describe*"], "Resource": ["*"]},
{"Effect": "Deny", "Action": ["ec2:*"], "Resource": ["*"]},
]
print(evaluate(policy, "ec2:DescribeInstances", "*"))Order the questions IAM effectively asks about a request.
- Tap the steps below in the right order.
Debugging AccessDenied, step by step
It is 4 p.m., a deploy just went out, and the report Lambda logs AccessDenied on s3:GetObject. The tempting fix is to widen the policy to s3:* on * and move on. That fix ships a security hole and often does not even work, because the problem may not be the identity policy at all. Work through it in order instead.
1. Read the whole message. Many services now say who was denied, for which action on which resource, and which kind of policy caused it:
User: arn:aws:sts::111111111111:assumed-role/report-lambda/fn is not authorized
to perform: s3:GetObject on resource: arn:aws:s3:::reports-b/q3.csv
because no identity-based policy allows the s3:GetObject action"because no ... policy allows" means an Allow is missing in that layer. "with an explicit deny in a ... policy" means you must find a Deny, and adding Allows will never help. This small parser pulls the parts out, which is also how you should read the message yourself:
Press Run (⌘ Enter) to see what happens.2. Confirm who you really are. A surprising share of AccessDenied errors are the right policy on the wrong principal: an old access key in environment variables overriding your SSO profile, a CI job assuming a different role than you think, a Lambda deployed with last month's role.
aws sts get-caller-identityaws sts get-caller-identity --profile payments-devIt returns the account, the ARN and the user or role ID. In code, call the same API once at startup and log it (boto3.client("sts").get_caller_identity()["Arn"]). Check the account too: a correct role in the staging account still cannot read a bucket in prod. Multiple Accounts, Organizations and SSO explains the credential provider chain that causes most of these mix-ups.
3. Check the resource ARN character by character. arn:aws:s3:::reports-b is the bucket, arn:aws:s3:::reports-b/* is its objects; ListBucket needs the first, GetObject the second. A typo in a bucket name, the wrong Region in a DynamoDB ARN, or a missing /index/* for a table's indexes all produce a clean AccessDenied.
4. Walk the layers the message did not name. If the caller is right and the identity policy looks right, the block is elsewhere: a resource policy (bucket, KMS key, SQS queue), a KMS key policy when the object is encrypted with a customer managed key (the error then mentions kms:Decrypt), a permissions boundary, a session policy, or an SCP from the organization. Messages name only one layer even when several deny.
5. Find the event in CloudTrail. CloudTrail records denied calls with an errorCode such as AccessDenied, AccessDeniedException or Client.UnauthorizedOperation, along with the exact principal ARN, source IP and request parameters. If your organization sends the trail to CloudWatch Logs, this Logs Insights query finds recent denials:
filter errorCode like /AccessDenied|UnauthorizedOperation/
| fields eventTime, eventSource, eventName, userIdentity.arn, errorMessage
| sort eventTime desc
| limit 50One catch: Event history and default trails hold management events only. Object-level S3 calls like GetObject are data events, which are recorded only if a trail is configured for them. If you cannot find an S3 or DynamoDB item-level denial, that is usually why.
6. Decode EC2's encoded messages. Some EC2 errors return an opaque "encoded authorization failure message". It contains the full evaluation context, and you decode it with STS (which needs sts:DecodeAuthorizationMessage):
aws sts decode-authorization-message --encoded-message <the-long-string> --query DecodedMessage --output text7. Prove the fix, narrowly. Use the policy simulator or IAM Access Analyzer to check the exact action and resource, change the smallest thing that is wrong, and retest. If you widened anything temporarily, set a reminder to tighten it, or better, never widen in the first place.
A service gets AccessDenied after a deploy. Put the debugging steps in order.
- Tap the steps below in the right order.
aws sts get-caller-identity prints arn:aws:iam::111111111111:user/old-ci-bot. What is going on?Going further: IAM Policies in Depth
This lesson gives you the core: the cast, policy anatomy, roles, STS and the basic allow and deny rules. IAM Policies in Depth, in the Identity and security unit, picks up from here. It covers all seven policy types and the full evaluation flow, why cross-account access needs an Allow on both sides, the confused deputy problem and external IDs, the condition keys that matter in practice, ABAC with tags, permission boundaries for letting developers create roles safely, the dangerous patterns to catch in review (such as iam:PassRole on *), and how IAM Access Analyzer checks policies in CI. If step 4 above felt vague, that lesson is where each layer is explained properly.
Evaluate an IAM policy
Write a tiny IAM policy evaluator. You get a list of statements, an action and a resource. Each statement is an object with Effect ("Allow" or "Deny"), Action (a list of patterns) and Resource (a list of patterns).
A pattern matches a value when it is exactly equal, or when it ends in * and the value starts with everything before the *. So "s3:*" matches "s3:GetObject", and "*" matches anything.
A statement applies when at least one Action pattern matches the action and at least one Resource pattern matches the resource. Then:
- If any applying statement is a
Deny, return"explicit-deny". - Otherwise, if any applying statement is an
Allow, return"allow". - Otherwise return
"implicit-deny"(nothing said yes).
statements = [{"Effect": "Allow", "Action": ["s3:*"], "Resource": ["*"]},
{"Effect": "Deny", "Action": ["s3:DeleteObject"], "Resource": ["*"]}]
evaluate(statements, "s3:GetObject", "arn:aws:s3:::photos/a.jpg") → "allow"
evaluate(statements, "s3:DeleteObject", "arn:aws:s3:::photos/a.jpg") → "explicit-deny"
evaluate(statements, "ec2:StartInstances", "*") → "implicit-deny"- IAM role
- An identity with permissions but no long-term keys. Assumed by services or people for temporary credentials.
- policy
- JSON listing Effect, Action, Resource and optional Condition. Attached to identities or resources.
- trust policy
- The part of a role that says who is allowed to assume it, like
lambda.amazonaws.com. - STS
- Security Token Service. Issues temporary credentials (key, secret, session token) when a role is assumed.
- explicit deny
- A matching
Denystatement. Always wins over any Allow. - least privilege
- Grant only the specific actions and resources a job needs, nothing more.
- get-caller-identity
- The STS call that returns the account and ARN your credentials actually resolve to. The first step in any AccessDenied.
- data event
- A CloudTrail record of a data-plane call such as S3
GetObject. Recorded only when a trail is configured for it.