Skip to content
Tech Interview Prep
Technical interview guide

IAM & Security Fundamentals

The principle of least privilege, and how roles/policies enforce it instead of relying on long-lived credentials.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Vendor-neutral IAM fundamentals with AWS IAM, STS, Access Analyzer, CloudTrail, and KMS references accessed 2026-08-30..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain authentication and authorization using a request to delete one production resource.

Answer

The 90-second answer

Authentication answers "who is calling"; authorization answers "may this principal do this to this resource, right now". They fail differently and they log differently, so keep them separate when you debug a delete.

Assume an on-call engineer federated through IAM Identity Center into production account 111122223333, running aws s3api delete-object --bucket prod-customer-exports --key 2024/q3/ledger.csv from a laptop on the corporate VPN. The bucket is versioned and carries a bucket policy.

Authentication is mechanical and comes first. The CLI signs the request with SigV4 using temporary credentials from sts:AssumeRole; the session token carries the role ARN, the role session name, and an expiry (Identity Center defaults to 1 hour, configurable up to 12). S3 verifies the signature against the role's current keys and checks the token has not expired. Success yields a principal, arn:aws:iam::111122223333:assumed-role/AWSReservedSSO_ProdOps_.../alice, and nothing more. A valid signature says the caller holds those credentials; it says nothing about the ledger.

Authorization is a separate evaluation over that principal, the action s3:DeleteObject, the resource ARN, and the request context.

Worked trace

  1. Explicit deny sweep. SCPs on the OU, the permissions boundary on the role, the bucket policy, the VPC endpoint policy, and any session policy are all checked for a Deny. One match anywhere ends it: deny beats every allow.
  2. Filter check. SCPs and boundaries never grant; they only cap. If the SCP allows s3:* but the identity policy has no s3:DeleteObject, the answer is still deny.
  3. Allow check. Same account, so an allow from either the identity policy or the bucket policy is enough. Say the identity policy allows s3:DeleteObject on arn:aws:s3:::prod-customer-exports/* when aws:PrincipalTag/team is payments and aws:SourceVpce is the corporate endpoint. Both conditions hold → Allow.
  4. S3's own controls. IAM said yes; the service can still say no. If the object sits under Object Lock retention or a legal hold, the delete returns 403 AccessDenied. And because the bucket is versioned, this call without a version ID writes a delete marker: the bytes are still there. Destroying them needs s3:DeleteObjectVersion on each version.

Failure modes

  • Expired session. A job that outlives the 1-hour token gets ExpiredToken (HTTP 400), not AccessDenied. CloudTrail records the error code; alerting only on "AccessDenied" misses it.
  • Over-broad role. A role holding s3:* on * makes step 3 trivially true. Detect with IAM Access Analyzer unused-permission findings and CloudTrail-driven policy generation; the cost is blast radius if the session token leaks.
  • Audit gap. CloudTrail management events are on by default; S3 object-level data events are not, and are billed separately (list price around $0.10 per 100,000 events). Without them you can answer "who called the S3 API" but not "who deleted this key".

Trade-offs

Identity policy vs bucket policy: identity policies centralize and travel with the principal; bucket policies let the data owner grant without IAM write access, and are mandatory for cross-account. Cross an account boundary and both must allow.

SCP/boundary vs per-role policy: filters cap an entire OU in one edit, but cannot grant, so they never replace a real allow.

Coarse s3:* vs per-action with conditions: coarse is faster to operate and wider to lose. Per-action with aws:SourceVpce and principal tags costs more upkeep and shrinks what a stolen token can do.

Soft delete vs hard delete: versioning plus delete markers is recoverable and costs storage; DeleteObjectVersion is irreversible and belongs behind a narrower role.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Walk through an IAM policy statement and explain how action, resource, effect, and condition interact.

Answer

Core answer

A statement is a predicate over a request. Effect is the verdict it returns when the predicate matches: Allow or Deny. Action, Resource, and (for resource-based policies) Principal are the match terms; Condition is an extra filter on request context. If every term matches, the statement fires. If any term fails, the statement is silent and contributes nothing.

The interaction that decides most real requests: explicit Deny beats every Allow. Evaluation is not "last statement wins": AWS collects all applicable statements, and a single matching Deny anywhere (identity, resource, SCP, boundary, session) denies the request. Absent any Allow, the default is deny.

A statement and a trace

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "TenantRead",
    "Effect": "Allow",
    "Action": ["s3:GetObject"],
    "Resource": "arn:aws:s3:::tenant-logs/acme/*",
    "Condition": {
      "StringEquals": {"aws:PrincipalOrgID": "o-a1b2c3d4e5"},
      "IpAddress": {"aws:SourceIp": "203.0.113.0/24"},
      "Bool": {"aws:SecureTransport": "true"}
    }
  }]
}

Request: GetObject on arn:aws:s3:::tenant-logs/acme/2024-06-01.log, caller in org o-a1b2c3d4e5, source IP 203.0.113.7, TLS on. Action matches, resource matches, all three condition operators true → statement applies → Allow (assuming no Deny elsewhere). Same request from 198.51.100.9: the IpAddress operator is false, the statement is silent, and the request falls to default deny.

How conditions evaluate

Operators are ANDed: every operator block must be true. Within one operator, multiple keys are ANDed too. Within one key, multiple values are ORed by default: "aws:SourceIp": ["203.0.113.0/24","198.51.100.0/24"] passes if either matches. ForAllValues:/ForAnyValue: set qualifiers change that. Evaluation short-circuits: the first false operator makes the statement not apply, so a condition is a narrowing filter, never a grant.

NotAction and wildcards

Allow + NotAction grants everything except the listed actions: it widens the blast radius, because new actions added to the service are allowed by default. Deny + NotAction is the opposite and is the standard guardrail: deny everything except a small allowlist. That asymmetry is the deciding criterion: use NotAction with Deny to fence a boundary, avoid it with Allow.

When broad grants are right

Wildcards are correct for read-only discovery (s3:ListAllMyBuckets, ec2:Describe*) where the action set is stable and non-mutating, and for Deny guardrails. They are wrong for anything that writes or reads data, where you can enumerate the actions.

Failure modes and detection

  • Action/resource mismatch: s3:ListBucket needs the bucket ARN arn:aws:s3:::tenant-logs, not the object ARN. The policy looks right and silently never matches. Detect with IAM Access Analyzer policy validation and CloudTrail AccessDenied events.
  • aws:SourceIp behind a VPC endpoint is the private IP, so an IP condition fails or over-matches; use aws:SourceVpce for endpoint-scoped access.
  • Unsupported condition key for the action: the key is ignored or the statement never matches. Verify against the service's condition-key list.
  • One document is not the effective permission: identity, resource, SCP, permissions boundary, session, and KMS key policies all apply. Use iam:SimulatePrincipalPolicy or Access Analyzer to see the effective result.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Explain implicit deny and explicit deny, and give a safe use for each.

Answer

The 90-second answer. Implicit deny is the absence of an allow: if no policy in the chain grants the action, the request fails. Explicit deny is a statement with "Effect": "Deny" that matches the request, and it wins over every allow in every layer: identity policy, resource policy, or SCP. AWS evaluates in this order: any explicit deny → denied; otherwise every SCP on the org path must allow; otherwise an identity or resource policy must allow. SCPs never grant, so an SCP allow is necessary but not sufficient.

Safe use for implicit deny: the default posture. An SCP attached to an OU that allows only the services you have approved means a newly launched service is unusable until someone adds it: fail-closed, and it cannot break a path that already works.

Safe use for explicit deny: a narrow guardrail that must survive any future allow. Two that hold up in production.

Protect the audit trail from member accounts:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "ProtectOrgTrail",
    "Effect": "Deny",
    "Action": ["cloudtrail:StopLogging", "cloudtrail:DeleteTrail"],
    "Resource": "*"
  }]
}

No legitimate member-account workflow stops the org trail, so the deny has no false positives. SCPs apply to every principal in a member account, including its root user; the management account is exempt, which is why the trail lives there.

Keep the account-level S3 Block Public Access setting from being switched off:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "LockPublicAccessBlock",
    "Effect": "Deny",
    "Action": ["s3:PutBucketPublicAccessBlock", "s3:DeletePublicAccessBlock", "s3:PutAccountPublicAccessBlock"],
    "Resource": "*"
  }]
}

With Block Public Access on, PutBucketAcl with a public ACL and PutBucketPolicy with a public policy return AccessDenied; the deny above stops a member account from disabling the setting. Since April 2023 new buckets ship with Block Public Access on and ACLs disabled (Object Ownership = BucketOwnerEnforced), so this mainly defends older buckets.

Region guardrail with a break-glass exception:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "DenyOutsideApprovedRegions",
    "Effect": "Deny",
    "Action": "*",
    "Resource": "*",
    "Condition": {
      "StringNotEquals": {"aws:RequestedRegion": ["eu-west-1", "eu-central-1"]},
      "StringNotEqualsIfExists": {"aws:PrincipalArn": "arn:aws:iam::111122223333:role/BreakGlassAdmin"}
    }
  }]
}

Both conditions must hold, so the break-glass role is exempt and everything else is pinned to two regions.

Failure modes. A region deny breaks global services: IAM, CloudFront, Route 53, STS and Organizations calls report aws:RequestedRegion as us-east-1, so the statement above locks them out unless you add us-east-1 or a NotAction list. A break-glass written as an allow in the same SCP silently nullifies the guardrail; scope the exception with aws:PrincipalArn and require MFA via aws:MultiFactorAuthPresent. And an unattributable explicit deny is the worst outage: CloudTrail shows AccessDenied with "with an explicit deny in a service control policy", and the SCP's Sid names the statement. Read that before widening any allow, because no allow can override it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Compare temporary credentials with long-lived access keys, including remaining risks.

Answer

What a strong candidate says first

Assume AWS unless told otherwise. A long-lived access key is a static pair (key ID starting AKIA) that stays valid until someone deletes it. Temporary credentials are a short-lived triple (key ID starting ASIA, secret, session token) that STS mints only after an identity proves itself: a role assumption, a web-identity or SAML federation, or an instance/task role. The security difference is not "temporary is safe": it is that the window in which a stolen credential is useful collapses from months to minutes, and every issuance is an authenticated, logged event tied to a named principal.

Mechanism and defaults

AssumeRole returns credentials with DurationSeconds defaulting to 3600 s and capped at 43200 s (12 h); if those credentials are used to assume another role (role chaining), the chained session is capped at 3600 s. GetSessionToken, used for MFA-protected IAM user sessions, defaults to 43200 s and allows up to 129600 s (36 h), but only 3600 s when the caller is the account root user. EC2 instance profiles and ECS/EKS task roles refresh automatically before expiry, so no human ever handles the secret. Outside AWS: GCP service account keys never expire, while Workload Identity Federation and impersonation tokens default to 1 hour (max 12 h); an Azure storage user-delegation SAS is capped at 7 days, whereas an account-key-signed SAS can be set to expire years out.

Long-lived access keySTS temporary credentials
LifetimeUntil deleted; rotation is a human process900 s–12 h (AssumeRole), auto-expiring
Issued byCreateAccessKeyAssumeRole, federation, instance/task role
RevocationDelete the key; immediateNo per-session revoke; role-wide or TokenIssueTime deny
AttributionKey ID onlyAssuming principal + session name in CloudTrail
Leak signalSecret scanning, quarantine policyShorter window, but still exfiltratable

Failure modes

  1. Revocation gap. STS has no API to revoke a single session. Deleting the role or its policies kills every session at once; the surgical option is a deny policy conditioned on aws:TokenIssueTime being before a cutoff. Until that propagates, a stolen session keeps working for its remaining lifetime: up to 12 h.
  2. Broad temporary admin. A 12-hour AdministratorAccess session is worse than a scoped long-lived key. Duration is not a substitute for least privilege.
  3. Leaking the session itself. Session credentials sit in environment variables as roughly 1.5 KB of base64 and get printed into CI logs and crash dumps. A compromised process can exfiltrate them exactly like a static key.
  4. Key baked into an image. A key in a container layer or a committed .env is valid until someone notices. AWS scans public repositories and attaches the AWSCompromisedKeyQuarantineV2 managed policy to keys it finds: a backstop, not a control.

Detection

CloudTrail AssumeRole events name the assuming principal and the session name, so actions attribute to a person or workload; long-lived key usage names only the key ID. GuardDuty's UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS fires when instance-role credentials are used from outside AWS. IAM Access Analyzer unused-access findings flag keys and roles untouched for 90 days.

Arithmetic

A 90-day rotation policy on a long-lived key leaves an attacker up to 2160 hours of use after theft. A 1-hour AssumeRole session leaves 1 hour, 2160× smaller, and the credential is dead after expiry even if it is still sitting in a log file.

When long-lived is unavoidable

A third-party SaaS that only accepts a static key, or an on-prem appliance with no OIDC path. Then: one key per integration, a recorded owner, permissions scoped to the specific API calls, CloudTrail alarms on use from unexpected addresses, and a removal date. Prefer temporary sessions everywhere else.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

How should a production workload obtain cloud credentials without storing access keys?

Answer

Short answer. Don't ship a key. Give the compute identity a role the platform can assume, and let the SDK fetch short-lived credentials from the platform's metadata or identity endpoint. On AWS that's an instance profile read through IMDSv2, an ECS task role, or IRSA on EKS; on GCP an attached service account read from the metadata server; on Azure a managed identity. Off-cloud (GitHub Actions, GitLab CI, on-prem Kubernetes) federate instead: the workload presents an OIDC token to STS and gets back a session.

Where it runsMechanismCredential sourceSession bounds
EC2instance profile roleIMDSv2 at 169.254.169.254role creds rotate; AssumeRole default 1 h, max 12 h
ECS / Fargatetask role169.254.170.2 via AWS_CONTAINER_CREDENTIALS_RELATIVE_URIsame STS bounds
EKSIRSA or EKS Pod Identityprojected SA token → AssumeRoleWithWebIdentity15 min–12 h, default 1 h
GCPattached service accountmetadata.google.internal, header Metadata-Flavor: Googleaccess token 1 h
Azuremanaged identity169.254.169.254/metadata/identity, header Metadata: trueshort-lived, SDK-refreshed
GitHub ActionsOIDC → STSid-token: write permission, role-to-assume15 min–12 h

What the fetch actually looks like. IMDSv2 is two calls: a PUT for a session token, then GETs carrying it:

Shell
TOKEN=$(curl -sS -X PUT http://169.254.169.254/latest/api/token \
  -H 'X-aws-ec2-metadata-token-ttl-seconds: 21600')   # 1–21600 s

curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/iam/security-credentials/
# -> app-prod-api

curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/iam/security-credentials/app-prod-api
# -> {"Code":"Success","AccessKeyId":"ASIA...","SecretAccessKey":"...",
#     "Token":"...","Expiration":"2025-..."}

The SDK does this for you and refreshes ahead of Expiration; you curl it only when debugging. For GitHub Actions the trust policy pins the subject, e.g. token.actions.githubusercontent.com:sub equals repo:acme/api:ref:refs/heads/main: a fork or a different branch cannot assume the role.

Constraints that matter. Scope the role to specific actions and resource ARNs, and set MaxSessionDuration to the shortest value your longest job tolerates: 1 h default, 12 h ceiling. On EKS, bind the Kubernetes service account to the IAM role with a trust policy whose sub is system:serviceaccount:ns:sa; without that condition any pod in the cluster can assume it.

Failure modes and how you see them.

  • SSRF against IMDSv1. This is the Capital One path. Fix with aws ec2 modify-instance-metadata-options --http-tokens required --http-put-response-hop-limit 1. Hop limit 1 also stops containers on the host from reaching IMDS, which is exactly why ECS and EKS need their own credential path.
  • Pod silently using the node role. Run aws sts get-caller-identity inside the pod. If it returns the node's instance role ARN, IRSA isn't wired: missing annotation or missing trust-policy condition.
  • Stale env vars. AWS_ACCESS_KEY_ID sits first in the SDK's provider chain and is read once, so a leftover value shadows the role and never refreshes. Unset it in the task definition.
  • Clock skew. RequestTimeTooSkewed on SigV4 means node NTP drift, not a bad key.
  • Refresh path broken. A burst of ExpiredTokenException means the metadata endpoint is blocked by a network policy or the projected token isn't rotating.
  • Over-broad role. IAM Access Analyzer unused-permissions findings plus CloudTrail last-accessed data.

When not to use this. A third-party SaaS that only accepts a static key, or a legacy host with no OIDC issuer, has no federation path. Put that key in a secrets manager with rotation and a broker that hands out short-lived downstream credentials, rather than on the box.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Design human access to 30 cloud accounts for employees, contractors, and administrators.

Answer

Assumptions I'd state first: the 30 accounts sit under one cloud organization (AWS Organizations or equivalent), there is one authoritative directory (Entra ID, Okta, Google Workspace), and the three populations differ in who approves access and how long it lasts.

The answer: federate the directory into a central access plane (AWS IAM Identity Center, or Entra ID with PIM if the estate is multi-cloud) and never create per-account IAM users for humans. The directory owns identity; the access plane owns authorization. Directory groups map to permission sets, permission sets are assigned to accounts, and no human holds a credential that outlives their session.

Mechanism. SCIM 2.0 pushes users and groups from the directory into Identity Center; SAML 2.0 or OIDC carries the login. When someone picks an account and role in the access portal, Identity Center calls STS AssumeRole and returns temporary credentials. Permission-set session duration defaults to 1 hour and is configurable from 1 to 12 hours: keep admins at 1, go longer only for read-only. Set the STS SourceIdentity at assume time: it survives role chaining and lands in CloudTrail, which is what makes "who did this" answerable when the role itself is shared.

Worked trace: contractor joins, then leaves.

  1. A directory admin adds dana to grp-contractors-payments. SCIM pushes it; Entra ID's provisioning cycle runs roughly every 40 minutes, Okta's is near-real-time.
  2. Dana signs in to the access portal with MFA, sees only the accounts her groups grant, picks payments-prod / PaymentsReadOnly, and receives STS credentials valid for 1 hour.
  3. CloudTrail records the assumed-role ARN, the role session name, and sourceIdentity=dana@example.com.
  4. On exit, the admin removes the group membership. New sessions stop after the next provisioning cycle; the session already issued runs to its 1-hour expiry. Worst-case revocation latency ≈ 40 min + 60 min ≈ 100 minutes. That number is why session duration is a security control, not a convenience setting.

Trade-offs.

optionwhat it buyswhat it costs
Per-account IAM usersno central dependency30 credential sets, manual per-account revocation, no single audit identity
Direct SAML federation into each account's rolesno Identity Center dependency30 trust configs and role mappings to keep in sync
Identity Center (or Entra ID + PIM)one group→permission-set mapping, one audit trail, SCIM-driven lifecyclethe access plane becomes a hard dependency and needs a break-glass path

Deciding criterion: account count and churn rate. At 30 accounts with contractors cycling, the per-account option's revocation cost dominates.

Admins. No standing privilege. Give them an eligible assignment they activate for a bounded window, Entra ID PIM's default maximum activation is 8 hours, with an MFA re-prompt and a justification field. Daily work happens under a read-only permission set.

Failure modes and detection.

  • IdP outage: nobody can start a new session. Break-glass is one IAM user per account with a hardware MFA device, credentials in a sealed offline store, a CloudTrail alarm on any use, tested quarterly.
  • SCIM deprovisioning lag: alert when a disabled directory account still holds an active assignment.
  • Group sprawl: IAM Access Analyzer's unused-access findings flag permissions unused for 90 days; review on a schedule.
  • Root: no daily use, hardware MFA, credentials offline.
  • Audit retention: CloudTrail event history keeps 90 days of management events; a trail to S3 keeps them indefinitely. That trail is the retention you actually rely on.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Compare identity policies, resource policies, permissions boundaries, session policies, and organization guardrails.

Answer

The 60-second answer. These five split into two jobs: two can grant, three can only cap.

  • Identity policies (attached to a user, group, or role) and resource policies (attached to an S3 bucket, KMS key, SQS queue, SNS topic, Lambda function, etc.) are grants. Same-account access usually needs only an identity allow; cross-account access on most services needs an allow on both sides.
  • Permissions boundaries, session policies, and SCPs are ceilings. They never grant. Effective permission = (identity allow ∪ resource allow, per service) ∩ boundary ∩ session policy ∩ SCP, and any explicit deny anywhere wins.
ControlAttaches toGrants?ScopeUse it for
Identity policyuser / group / roleyesthat principalday-to-day access
Resource policybucket / key / queue / topic / functionyesthat resourcecross-account, service principals, public access
Permissions boundaryuser or rolenothat principalcap roles other people create
Session policyone AssumeRole / federation sessionnothat sessionnarrow a shared role per caller
SCPorg root, OU, or accountnoall principals in member accountsorg-wide guardrails

When to reach for which. Use a boundary when you delegate role creation: a platform team lets developers make roles, but every role must carry a boundary that caps it, so a developer cannot mint an admin role. Use an SCP for guardrails that must hold across many accounts: deny regions you do not operate in, deny cloudtrail:StopLogging, deny leaving the org. Use a resource policy when the principal is outside your account, is a service (cloudtrail.amazonaws.com writing to a bucket), or is anonymous: identity policies cannot express those. Use a session policy when one role serves many callers and you want to hand each a narrower slice for the life of the session.

Do not use a boundary as your primary access control: it is a ceiling, not a grant, and a role with a boundary but no identity allow has no access. Do not use an SCP to grant; it cannot. Do not use a resource policy to manage hundreds of in-account principals: identity policies are easier to audit.

What actually breaks.

  • Boundary silently revokes access. Attach a boundary that allows only s3:* to a role that had AdministratorAccess and the role loses EC2, IAM, everything else, immediately. Detect with CloudTrail AccessDenied events and IAM Access Analyzer; confirm with the IAM policy simulator before rollout.
  • SCP locks out the root user. SCPs apply to the root user of member accounts, so an SCP denying iam:* can strand root. SCPs also do not apply to the management account, so a guardrail you verified in a member account is not enforced where you tested it. Test in a sandbox account, watch CloudTrail.
  • Confused deputy. A trust policy with "Principal": {"Service": "..."} and no aws:SourceArn / aws:SourceAccount condition lets that service assume the role on behalf of another account. Detect via CloudTrail AssumeRole with an unexpected source and Access Analyzer findings.
  • KMS key policy gap. A key policy that does not delegate to IAM makes identity-policy kms:Decrypt grants inert. Detect with AccessDenied on decrypt despite a matching identity policy.

Worked trace. Developer in account A reads an object in account B's bucket via an assumed role.

  1. Role trust policy in B must allow A's principal, else AssumeRole fails.
  2. If AssumeRole passed a session policy, effective session permissions = role identity policy ∩ session policy.
  3. SCPs in B must allow s3:GetObject; an SCP deny kills it even though the role policy allows.
  4. Bucket policy in B must allow the role: cross-account S3 needs both sides.
  5. Any explicit deny at any step wins.

Numbers to remember. Managed policy and boundary: 6,144 characters. Inline role policy: 10,240; inline user policy: 2,048. Session policy: 2,048. SCP document: 5,120, with at most 5 SCPs attached per root, OU, or account.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Troubleshoot an access-denied response when the role's attached policy appears to allow the action.

Answer

The attached policy is one of six layers that decide a request: explicit deny, SCP, resource-based policy, permissions boundary, session policy, identity-based policy. The deny is usually in a layer the IAM Policy Simulator does not evaluate (SCPs, permissions boundaries, session policies, or resource-based policies) so a green simulator result proves nothing about the real request.

Get the encoded authorization failure message. Most services return it in the API error response; CloudTrail logs it in errorMessage for services that include it (EC2 returns Client.UnauthorizedOperation, most others AccessDenied). Decode it:

aws sts decode-authorization-message --encoded-message <base64> --query DecodedMessage --output text

Worked trace (hypothetical). A CI job calls ec2:RunInstances in eu-west-1 and gets 403. CloudTrail event:

JSON
{
  "eventTime": "2025-03-11T09:14:22Z",
  "eventSource": "ec2.amazonaws.com",
  "eventName": "RunInstances",
  "awsRegion": "eu-west-1",
  "errorCode": "Client.UnauthorizedOperation",
  "errorMessage": "You are not authorized to perform this operation. Encoded authorization failure message: <base64>",
  "userIdentity": {
    "type": "AssumedRole",
    "arn": "arn:aws:sts::111122223333:assumed-role/DeployRole/ci-42",
    "sessionContext": {
      "sessionIssuer": { "type": "Role", "arn": "arn:aws:iam::111122223333:role/DeployRole" },
      "attributes": { "creationDate": "2025-03-11T09:10:00Z", "mfaAuthenticated": "false" }
    }
  },
  "requestParameters": { "instancesSet": { "items": [ { "imageId": "ami-0abc123" } ] }, "instanceType": "m5.large" },
  "requestID": "A1B2C3D4E5F6"
}

Decoded message:

JSON
{
  "allowed": false,
  "explicitDeny": true,
  "matchedStatements": {
    "items": [
      {
        "statement": {
          "effect": "Deny",
          "action": "ec2:RunInstances",
          "resource": "*",
          "condition": { "StringNotEquals": { "aws:RequestedRegion": "eu-west-1" } }
        },
        "sourcePolicyId": "arn:aws:organizations::111122223333:policy/o-example/service_control_policy/p-region",
        "sourcePolicyType": "Service Control Policy"
      }
    ]
  }
}

The role's identity policy allows ec2:RunInstances; the SCP denies it outside eu-west-1. The fix is not to widen the role policy: it is to change the request region or, if the region is genuinely needed, change the SCP. explicitDeny: true plus sourcePolicyType names the layer.

If explicitDeny is false, the allow never matched. Compare the request's condition keys against the policy's Condition block. Common keys: aws:PrincipalTag, aws:SourceVpce, aws:RequestedRegion, aws:MultiFactorAuthPresent, aws:PrincipalOrgID, aws:SourceAccount, aws:SourceArn. A missing session tag or a request through the wrong VPC endpoint produces an implicit deny with no deny statement anywhere.

Decision table for remediation:

Decoded sourcePolicyTypeLayerNarrowest fixBlast radius
Service Control PolicyOrg guardrailChange the SCP, or change the request to satisfy itEvery account in the OU
Permissions boundaryRole guardrailEdit the boundaryEvery principal using that boundary
Session policyPer-session scopeRe-issue the session with a corrected policyThat session only
Identity-based policyRole's own policyAdd the missing action/resourceEvery session of that role
Resource-based policyResource ownerEdit the bucket/key/queue policyThat resource
No matched statement, allowed: falseImplicit denyAdd an allow at the layer that should grant itDepends on layer

Criteria for choosing: fix the layer that actually denied, prefer the narrowest scope, and prefer fixing the request context over widening a policy when the policy is correct by design. A session-policy fix is cheapest when the role is shared; a boundary fix needs security review because it affects every principal using it. Do not fix it by attaching AdministratorAccess.

Failure modes to name:

  • Simulator green, request denied: the IAM Policy Simulator evaluates identity-based policies; it does not evaluate SCPs, permissions boundaries, session policies, or resource-based policies.
  • Wrong role: check userIdentity.sessionContext.sessionIssuer.arn against the intended role ARN. A similarly named role with a different policy is a common cause.
  • Dependent permission: ec2:RunInstances needs iam:PassRole for the instance profile; s3:GetObject on an SSE-KMS object needs kms:Decrypt on the key. The deny is on the dependent action, not the one you are looking at.
  • S3 returns 403 instead of 404 when the caller lacks s3:ListBucket, so a missing object looks like an access-denied.
  • IAM policy changes take a few seconds to propagate; a fix that "didn't work" may just be timing.

CloudTrail is the source of the event; IAM Access Analyzer's policy-validation and unused-access findings flag policies that are too broad or unused, but they do not explain a single deny: the decoded message does.

Reproduce one allowed and one denied request, change the narrowest incorrect layer, keep the decoded message and CloudTrail event as evidence, and add a regression test that asserts the denied request still fails and the allowed one still succeeds.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Review a role design by separating its trust policy from its permissions policies.

Answer

What a strong candidate says first (60–120 s). A role carries two policies that fail independently. The trust policy is a resource-based policy on the role; STS evaluates it once, at AssumeRole, and it answers who may obtain a session. The permissions policy is an identity-based policy attached to the role; every service evaluates it on every API call, and it answers what that session may do. Two consequences follow. First, assuming a role is two-sided: the caller's own identity policy must allow sts:AssumeRole on the role ARN and the role's trust policy must allow the caller. Either one denying kills the call. Second, because trust is checked once and permissions per call, tightening trust does nothing to sessions already issued; you revoke those separately. Reviewing a role design means reading both documents and the two verbs that rewrite them.

Trust policy. Read it as (principal, action, condition) triples. Action must match the API the caller actually uses: sts:AssumeRole, sts:AssumeRoleWithSAML, sts:AssumeRoleWithWebIdentity, or sts:AssumeRoleWithCertificate. A trust policy that allows only AssumeRoleWithWebIdentity silently denies an IAM user calling AssumeRole.

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com"},
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"},
      "StringLike":   {"token.actions.githubusercontent.com:sub": "repo:acme/deploy:ref:refs/heads/main"}
    }
  }]
}

Check the principal type: a concrete ARN, an account root (arn:aws:iam::444455556666:root, which delegates the decision to that account's identity policies), or *. Then the conditions that pin it: sts:ExternalId for third parties, aws:PrincipalOrgID, aws:PrincipalArn, aws:SourceIp, aws:MultiFactorAuthPresent, sts:SourceIdentity, sts:RoleSessionName, sts:DurationSeconds, and session tags via aws:RequestTag/aws:TagKeys.

Permissions policy. Actions, resources, and the escalation verbs that matter more than the rest: iam:PassRole, sts:AssumeRole (chaining), kms:Decrypt, cloudtrail:StopLogging, organizations:LeaveOrganization, iam:CreateAccessKey. Then the ceilings that intersect it: permissions boundary, session policy, SCPs, and the role's maximum session duration (default 1 hour, up to 12).

Trace: one call, and which policies are consulted. Session S was issued to the GitHub workflow above. S now calls s3:GetObject on arn:aws:s3:::acme-artifacts/*. STS is not involved. S3 evaluates, in order: the account SCP → the role's permissions boundary → the role's identity policy → any session policy → the bucket policy. The trust policy is not in that list. So editing the trust policy to drop the workflow changes nothing for S; S keeps its permissions until it expires.

The asymmetry that matters. Trust is evaluated once, at session creation; permissions are evaluated per call. To cut live sessions you attach an inline policy that denies when aws:TokenIssueTime is earlier than a fixed timestamp, the AWS sample AWSRevokeOlderSessions hardcodes that date, or you wait out the max duration. Role chaining caps the chained session at 1 hour regardless of the target role's setting.

Trust policyPermissions policy
Attached tothe role (resource-based)the role (identity-based)
Evaluated bySTS, at AssumeRoleeach service, per API call
Answerswho may obtain a sessionwhat the session may do
A change takes effectnext assumptionnext call

Both documents are themselves resources: iam:UpdateAssumeRolePolicy rewrites trust, iam:PutRolePolicy/iam:AttachRolePolicy rewrites permissions. Whoever holds those can undo the design, so review them too.

Failure modes.

  • Principal: "*" or an account root with no condition → any principal in the account (or anyone) can assume. Detect with IAM Access Analyzer external-access findings.
  • A third-party service principal without sts:ExternalId → confused deputy; another customer's tenant points its integration at your role. Access Analyzer flags the external access.
  • OIDC sub too broad (repo:acme/deploy:* instead of :ref:refs/heads/main) → any PR-triggered workflow, which anyone who can open a PR can edit, assumes the role and exfiltrates credentials.
  • iam:PassRole on * → the session hands a more privileged role to a service and escalates past its own policy.

Verification. Run IAM Access Analyzer policy checks, then a real allowed assumption and a real denied one (wrong branch, wrong audience), and read sts:SourceIdentity/aws:PrincipalArn in the resulting CloudTrail events to confirm the session's audit identity is what you expect.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

What should an organization-level service control policy do, and what should it avoid?

Answer

The 90-second answer

An SCP is a guardrail, not a grant. It caps what principals in a member account can do; the identity-based or resource-based policy still has to allow the action. Two rules decide almost every design: SCPs at every level from the root down to the account must allow the action (they intersect), and an explicit Deny at any level wins. So use SCPs for a handful of invariants you want true for every account, and put everything else in IAM.

Assumptions worth stating up front: AWS Organizations with SCPs enabled, you are not relying on the management account (SCPs do not apply there), and you know service-linked roles are exempt from SCPs.

What it should do

Protect the audit and detection plane so a compromised workload account cannot blind you:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "ProtectAuditTrail",
    "Effect": "Deny",
    "Action": [
      "cloudtrail:StopLogging",
      "cloudtrail:DeleteTrail",
      "config:DeleteConfigurationRecorder",
      "guardduty:DeleteDetector"
    ],
    "Resource": "*"
  }]
}

Constrain regions with aws:RequestedRegion:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "DenyOutsideApprovedRegions",
    "Effect": "Deny",
    "Action": "*",
    "Resource": "*",
    "Condition": {
      "StringNotEquals": {
        "aws:RequestedRegion": ["us-east-1", "us-west-2", "eu-west-1"]
      }
    }
  }]
}

us-east-1 is in that list on purpose: global services such as IAM and STS report us-east-1 as the requested region, so a region deny that omits it breaks identity and token calls everywhere. Also worth denying: removing S3 public-access blocks, creating public RDS snapshots, and organizations:LeaveOrganization on accounts you do not want leaving.

What it should avoid

  • Treating an SCP Allow as access. The default FullAWSAccess policy is attached to the root, every OU and every account; it grants nothing on its own, it just stops the SCP layer from blocking.
  • Being the primary permission system. Per-team permissions belong in IAM identity policies or permission boundaries.
  • One giant deny document. Keep each SCP small and single-purpose; the document limit is 5,120 characters, and a 4,000-character policy nobody can review is worse than three focused ones.
  • Forgetting the exemptions: the management account, service-linked roles, and AWS service principals acting on your behalf (autoscaling, ECS, backup). A blanket deny that ignores these breaks services silently.
  • Assuming SCPs reach everything. They do not cap a resource-based policy that grants access to a principal outside your organization.

Failure modes and how you catch them

  • Lockout: an SCP that denies iam:* stops anyone creating roles. Recovery is the management account, where SCPs do not apply, so you can detach the policy there. Test in a canary account first.
  • Region deny breaking global services: the symptom is IAM and STS failures in every account at once. The canary account catches it before rollout.
  • Deny blocking service principals: the symptom is autoscaling or ECS tasks failing to launch. Exempt them with aws:PrincipalIsAWSService or aws:ViaAWSService.

What would change the decision

If the requirement is per-team least privilege, that is IAM, not SCPs. If it is restricting cross-account resource access to your org, that is aws:PrincipalOrgID in the resource policy. SCPs only earn their place for invariants that must hold for every account, each with a named owner, a reason, and a rollback path.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How would you use a permissions boundary to delegate IAM role creation to a development team?

Answer

Assumptions. One account, 123456789012. Boundary policy arn:aws:iam::123456789012:policy/DevWorkloadBoundary. Every delegated role lives under the path /dev-team/, so its ARN matches arn:aws:iam::123456789012:role/dev-team/*. The team's own role is arn:aws:iam::123456789012:role/dev-team/developer.

The 90-second answer. A permissions boundary is a managed policy that caps what a role's identity-based policies can grant. Effective permissions are the intersection: an action has to be allowed by both the role policy and the boundary. It grants nothing on its own.

So you write one boundary that is the maximum any workload the team creates may ever do, then make every role-administration action conditional on that exact boundary ARN being attached. The condition key is iam:PermissionsBoundary, and it is only evaluated on iam:CreateRole, iam:CreateUser, iam:PutRolePermissionsBoundary and iam:PutUserPermissionsBoundary: it does not exist on iam:AttachRolePolicy, so you cannot use it there. Pair it with an explicit deny on iam:DeleteRolePermissionsBoundary, scope iam:AttachRolePolicy by iam:PolicyARN, and scope iam:PassRole by iam:PassedToService.

The policy you attach to the team's role.

JSON
{
  "Version": "2012-10-17",
  "Statement": [
    { "Sid": "CreateOnlyWithBoundary", "Effect": "Allow",
      "Action": "iam:CreateRole",
      "Resource": "arn:aws:iam::123456789012:role/dev-team/*",
      "Condition": { "StringEquals": {
        "iam:PermissionsBoundary": "arn:aws:iam::123456789012:policy/DevWorkloadBoundary" } } },

    { "Sid": "ReattachOnlyApprovedBoundary", "Effect": "Allow",
      "Action": "iam:PutRolePermissionsBoundary",
      "Resource": "arn:aws:iam::123456789012:role/dev-team/*",
      "Condition": { "StringEquals": {
        "iam:PermissionsBoundary": "arn:aws:iam::123456789012:policy/DevWorkloadBoundary" } } },

    { "Sid": "NeverRemoveBoundary", "Effect": "Deny",
      "Action": "iam:DeleteRolePermissionsBoundary", "Resource": "*" },

    { "Sid": "AttachOnlyApprovedPolicies", "Effect": "Allow",
      "Action": "iam:AttachRolePolicy",
      "Resource": "arn:aws:iam::123456789012:role/dev-team/*",
      "Condition": { "ArnEquals": { "iam:PolicyARN": [
        "arn:aws:iam::123456789012:policy/dev-team/*",
        "arn:aws:iam::aws:policy/ReadOnlyAccess" ] } } },

    { "Sid": "PassOnlyOwnRolesToTwoServices", "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "arn:aws:iam::123456789012:role/dev-team/*",
      "Condition": { "StringEquals": {
        "iam:PassedToService": ["lambda.amazonaws.com", "ecs-tasks.amazonaws.com"] } } },

    { "Sid": "NoTrustRewrites", "Effect": "Deny",
      "Action": "iam:UpdateAssumeRolePolicy", "Resource": "*" },

    { "Sid": "NoServiceLinkedRoles", "Effect": "Deny",
      "Action": "iam:CreateServiceLinkedRole", "Resource": "*" },

    { "Sid": "NoPolicyVersionEscalation", "Effect": "Deny",
      "Action": "iam:CreatePolicyVersion",
      "Resource": "arn:aws:iam::123456789012:policy/*",
      "Condition": { "Bool": { "iam:SetAsDefault": "true" } } }
  ]
}

Trace it. Developer calls CreateRole with no PermissionsBoundary → the StringEquals key is absent, the condition fails, implicit deny. Same call with the boundary attached → allowed. AttachRolePolicy with arn:aws:iam::aws:policy/AdministratorAccess → iam:PolicyARN is not in the ArnEquals list → denied. DeleteRolePermissionsBoundary → explicit deny beats any allow. PassRole to ec2.amazonaws.com → not in iam:PassedToService → denied. And if the role's own policy says s3:* on * while the boundary says only s3:GetObject on arn:aws:s3:::dev-artifacts/*, the effective grant is GetObject on that prefix.

Failure modes worth naming. The boundary is a managed policy, so it is capped at 6,144 characters, and it counts against the 10-managed-policies-per-role limit. A boundary broad enough to cover every future workload tends to grow s3:*-shaped holes. Boundaries cap identity-based grants only: a bucket or KMS key policy that names the role's principal is a separate grant path, so audit resource policies for the role ARNs you hand out. Service-linked roles cannot carry a boundary, which is why CreateServiceLinkedRole is denied. And iam:PermissionsBoundary is an exact-ARN match: if the platform team ever creates a v2 boundary, every create call starts failing until the condition is updated.

Detect drift with CloudTrail plus an EventBridge rule on eventName in DeleteRolePermissionsBoundary, PutRolePermissionsBoundary, CreatePolicyVersion and UpdateAssumeRolePolicy, routed to the platform on-call.

Alternatives, and when to pick them. An SCP gives the same ceiling but applies account-wide and cannot be delegated: the team cannot self-serve, and it also constrains roles that have nothing to do with them. Pre-provisioned role templates (CloudFormation StackSets or Service Catalog) remove delegation entirely: the team picks from a catalog, the platform team owns the definitions. That is the right call when the workload permission set changes quarterly, not weekly. Choose the boundary when the team needs to create roles faster than a ticket queue allows and you can enumerate their maximum capability inside 6 KB.

What would change the decision. If the team cannot state the maximum capability up front, or if the boundary keeps needing wildcards to stay under the size limit, move to catalog templates. If the risk is account-wide rather than team-specific, add an SCP underneath the boundary rather than widening it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Explain the confused-deputy problem for a multi-tenant SaaS provider that assumes customer roles.

Answer

The confused deputy is when a trusted service with broad permissions is tricked into using them for an attacker. In a multi-tenant SaaS provider that assumes roles in customer accounts, the provider is the deputy. Customer A asks the provider to assume a role in customer B's account. If the trust relationship only checks that the caller is the provider's AWS account, and the provider doesn't bind the request to the tenant that made it, the provider assumes B's role and hands A the credentials. The role ARN and account ID are not secrets (they appear in error messages, docs, and logs) so they can't be the only gate.

The fix is a tenant-bound condition in the trust policy. The standard AWS mechanism is sts:ExternalId: a unique, unpredictable string per tenant that the provider generates and includes in the AssumeRole call, and the customer puts in the role's trust policy. The provider also keeps a server-side mapping from tenant to allowed role ARN and external ID, so a customer can't supply an arbitrary pair.

Trust policy on the customer role:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"AWS": "arn:aws:iam::111122223333:root"},
    "Action": "sts:AssumeRole",
    "Condition": {
      "StringEquals": {"sts:ExternalId": "tenant-7f3a9c2e-4b1d-4e8a-9c6f-2a1b3c4d5e6f"}
    }
  }]
}

Provider calls sts:AssumeRole with RoleArn and ExternalId. AWS does not treat the external ID as a secret, but it must be unique per tenant and not guessable so another customer cannot replay it.

Alternatives and trade-offs:

MechanismHow it bindsWhen to useCost
sts:ExternalIdTrust policy condition on a per-tenant stringDefault for third-party SaaS assuming roles in customer accountsMust store and rotate per tenant; rotation requires coordinated trust-policy update
Session tags (sts:TagSession)Trust policy condition on aws:PrincipalTag/tenant; tags set by providerWhen you also need ABAC inside the customer accountCustomer must write policies using tags; tags are not a substitute for provider-side tenant binding
OIDC / web identityTrust policy condition on sub or aud claim from a per-tenant issuerCI/CD, Kubernetes, or when you already have an OIDC providerRequires OIDC setup; less common for generic SaaS
Separate AWS account per tenantNo cross-account assumptionHigh-isolation customersOperational overhead; not always possible

Deciding criteria: if the customer can't change their IAM beyond a trust policy, external ID is the least-friction. If you need per-request authorization inside the account, add session tags. If you control the identity provider, OIDC with a bound subject claim is stronger because the claim is signed.

Failure modes and detection:

  • Missing external ID condition: Attacker A supplies B's role ARN. Provider assumes it. Detection: CloudTrail AssumeRole events where the roleArn doesn't match the provider's tenant mapping, or where the external ID is absent. Alert on any AssumeRole from the provider account to a role not in the mapping.
  • External ID reused across tenants: One leak compromises all. Detection: periodic audit for duplicate external IDs in the provider's database.
  • Provider doesn't bind tenant to role ARN: Even with external ID, if A can supply B's role ARN and B's external ID (e.g., from a leaked config), A wins. Detection: provider-side authorization check that the authenticated tenant owns the requested role ARN; log and reject mismatches.
  • External ID logged in plaintext: Leak. Detection: log scanning for the external ID pattern; store hashed if possible.
  • Rotation without coordination: AssumeRole fails with AccessDenied. Detection: error-rate spike on AssumeRole; runbook for two-phase rotation (add new ID to trust policy, switch provider, remove old).

Worked trace:

  1. Attacker (tenant A) calls provider API: POST /assume {roleArn: "arn:aws:iam::999988887777:role/SaaSAdmin"}.
  2. Provider without binding: calls sts:AssumeRole with its own credentials and that ARN. Trust policy on SaaSAdmin allows arn:aws:iam::111122223333:root (provider). No external ID condition. STS returns credentials. Attacker now has B's admin role.
  3. With fix: provider looks up tenant A's record. Allowed role ARN is arn:aws:iam::111122223333:role/TenantAReadOnly, external ID tenant-A-.... Request for B's role is rejected before STS is called. If attacker somehow gets B's external ID, trust policy still requires it; provider never sends it for A.

The condition complements authentication and least privilege: it doesn't replace validating the caller's identity or scoping the role's permissions.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design least-privilege cross-account access for a central security team.

Answer

First 90 seconds. Assume AWS Organizations, a central security account (111122223333), member accounts, IAM Identity Center as the human entry point, and one CloudTrail organization trail. The design is three roles per target account, each trusted by exactly one central role ARN, each with its own session ceiling and its own alarm. Nothing is trusted at account granularity.

The trust policy is where least privilege actually lives:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"AWS": "arn:aws:iam::111122223333:role/security-ir-analyst"},
    "Action": "sts:AssumeRole",
    "Condition": {
      "StringEquals": {"aws:PrincipalOrgID": "o-example1234"},
      "Bool": {"aws:MultiFactorAuthPresent": "true"},
      "NumericLessThan": {"aws:MultiFactorAuthAge": "900"},
      "Null": {"sts:SourceIdentity": "false"}
    }
  }]
}

Principal is a role ARN, not the account root: that is the difference between "the security team" and "anyone who ever gets a principal in that account." aws:PrincipalOrgID is belt-and-braces against someone re-pointing the ARN. Null: false requires the caller to set a source identity; without it the request is denied.

One trap: aws:MultiFactorAuthPresent is absent on federated sessions, including IAM Identity Center permission sets. For those callers the MFA gate lives at the IdP sign-in and the trust policy drops that key: a condition that never matches is worse than no condition, because it reads as a control.

Role in target accountMaxSessionDurationGrantsExtra trust condition
SecurityAuditReadOnly14400 (4 h)SecurityAudit managed policy plus scoped Describe*/List*MFA age < 4 h
SecurityContainment3600 (1 h)ec2:StopInstances, ec2:RevokeSecurityGroupIngress, iam:UpdateAssumeRolePolicy, s3:PutBucketPolicy on tagged resourcesMFA age < 15 min, session tag ticket required
SecurityBreakGlass3600, callers request 900AdministratorAccess under a permission boundaryalarm on every AssumeRole

MaxSessionDuration is the ceiling, not the session: the containment role's callers pass DurationSeconds=900 so a leaked token dies in 15 minutes. Role chaining caps at 1 hour regardless of that setting, so the central role assumes the target directly and never through an intermediate.

Session identity is the audit spine. sts:RoleSessionName is mandatory on AssumeRole and lands in CloudTrail; sts:SourceIdentity is set by the caller (which needs sts:SetSourceIdentity in its own policy) and cannot be changed by the assumed role, so it survives into userIdentity.sessionContext.sourceIdentity on every downstream call. Session tags need sts:TagSession on the caller, and the target's permissions gate on aws:PrincipalTag/ticket: a session without the tag fails closed.

Audit: organization trail with log file validation, bucket policy denying any principal outside aws:PrincipalOrgID, KMS CMK, and an EventBridge rule matching AssumeRole on the containment role ARN that pages. SCPs deny cloudtrail:StopLogging, iam:CreateUser, and iam:CreateAccessKey in member accounts so a compromised target admin cannot blind the trail or mint a standing credential.

Break-glass is a separate role with credentials in a sealed store, AdministratorAccess under a permission boundary, and an alarm on every use. It is tested on a schedule, not during the incident.

Verification: IAM Access Analyzer unused-access findings (90 days by default, configurable to 365) drive role cleanup, external-access findings catch a trust policy that got widened, and a quarterly diff of role assignments against the current responder roster catches people who left. A scheduled test asserts the read-only role can describe and that the containment role is denied iam:CreateUser.

Failure modes worth naming: Principal: "*" with only an org condition (valid, but any principal in any member account can assume); session tags silently unenforced because the caller lacks sts:TagSession; and a break-glass role that has never been exercised, which is discovered to be broken at 3 a.m.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design MFA enrollment, enforcement, and recovery for privileged administrators.

Answer

Assumptions: privileged admins have a separate admin account from their daily user account, and the IdP is Entra ID, Okta, or AWS IAM Identity Center. If not, map the controls to the equivalent.

Core answer. Enroll two phishing-resistant hardware authenticators per admin, bind them to the admin identity, require attestation, and never allow SMS or TOTP for privileged access. Enforce with conditional access that requires phishing-resistant MFA, a compliant device, a short sign-in frequency, and no persistent browser session. Recovery uses the second key; if both are lost, use an offline break-glass account with dual control. No helpdesk reset to a weaker factor.

Mechanism. FIDO2/WebAuthn credentials are public-key pairs. The private key stays in the hardware secure element and cannot be exported. The browser signs a challenge only when the origin matches the credential's RP ID. A phishing site at evil.com cannot request a signature for login.microsoftonline.com; the browser refuses. TOTP and SMS are shared secrets, so a real-time proxy can relay the code within its 30-second window. That is why hardware-backed keys resist remote phishing and OTP does not.

Enrollment. Verify identity in person or by video with government ID. Issue two keys: one primary, one stored offline. In Entra ID, enable FIDO2 security key in Authentication methods, target the privileged admin group, require attestation, and allowlist AAGUIDs so only approved hardware models enroll. In Okta, use the WebAuthn authenticator. In AWS IAM Identity Center, require MFA and use FIDO2 security keys. Require user verification (PIN or biometric) on each key.

Enforcement. Entra ID Conditional Access: require authentication strength Phishing-resistant MFA, require compliant device, block legacy auth, set sign-in frequency to 4 hours, and disable persistent browser sessions. AWS IAM Identity Center: cap admin permission set session duration at 1 hour. Okta: sign-on policy with WebAuthn and re-authentication every 4 hours. Use just-in-time elevation (Entra PIM or equivalent) so admin rights are not always on.

Recovery. Pre-register two recovery methods: the second hardware key and the offline break-glass account. Break-glass credentials are split, stored in a safe, and require two approvers. A temporary bypass is valid for 1 hour, single-use, dual-approved, and alerts the SIEM. Post-event review within 24 hours. Log enrollment, removal, bypass, failed challenges, and privileged session issuance.

PhaseControlNamed specifics
EnrollmentVerify identity, issue two FIDO2 keysEntra ID Authentication methods > FIDO2 security key, require attestation, allowlist AAGUIDs; Okta WebAuthn; AWS IAM Identity Center MFA
EnforcementPhishing-resistant MFA, short sessionsEntra ID Conditional Access authentication strength Phishing-resistant MFA, sign-in frequency 4h, no persistent browser; AWS permission set session 1h
RecoveryDual control, time-bound bypassTwo approvers, bypass 1h single-use, break-glass offline, SIEM alert

Failure modes. Helpdesk social engineering: attacker impersonates an admin and asks for a factor reset. Detection is a factor reset without a user-initiated ticket, from a new ASN, outside the change window. Cost is full admin takeover. Mitigation: no helpdesk reset for privileged accounts; require in-person or dual control. Bypass window: a temporary bypass left enabled. Detection is a bypass token used after 1 hour, used twice, or from a new ASN. Exploit path is a stolen session enrolling a new key. Mitigation: expire in 1 hour, single-use, alert. Stale admin: offboarded admin still has an active key. Detection is no privileged sign-in for 90 days and no HR feed match. Exploit is a former employee using the key. Mitigation: inventory and disable after 30 days of no privileged sign-in. Shared factor: one SMS for the operations team. Detection is the same phone number across multiple accounts. Exploit is one compromise unlocking all. Mitigation: unique factors per admin.

Worked trace: phishing attempt. Against FIDO2: admin visits evil.com; the site proxies the login page; the browser calls WebAuthn with RP ID evil.com; the credential is bound to login.microsoftonline.com, so no signature is produced; the attacker gets no credential. Against TOTP: admin visits evil.com; the site proxies the login page; admin enters the TOTP; the attacker relays the code to the real site within 30 seconds; the attacker gets a session. That difference is the reason privileged enrollment must be hardware-backed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Define a secure root-account and break-glass operating model.

Answer

Assumptions first: AWS Organizations, one dedicated management account that runs no workloads, IAM Identity Center as the daily sign-in path. Root is not an identity anyone uses: it is a recovery credential with a documented, tested path. If your estate is Azure or GCP the shape is the same; the control names differ.

The four controls that matter

  1. No root access keys, anywhere. Delete them in every account. AWS Config managed rule iam-root-access-key-check and Security Hub control IAM.1 flag any that reappear. Root API calls are the single highest-blast-radius credential in the account.
  2. Hardware MFA on every root user: a FIDO2 security key, not a virtual TOTP app on a phone. The key lives under dual control (safe, or a sealed envelope in a second location), not on an engineer's keyring.
  3. Root email is a monitored group mailbox (cloud-root@…), and the recovery phone is a dedicated number. Losing the mailbox is losing the account; a departed employee's address is an account-takeover path.
  4. Alert on any root use. CloudTrail management events feed EventBridge; the sign-in rule is:
JSON
{
  "source": ["aws.signin"],
  "detail-type": ["AWS Console Sign In via CloudTrail"],
  "detail": { "userIdentity": { "type": ["Root"] } }
}

Route it to SNS → pager. For root API calls, GuardDuty's Policy:IAMUser/RootCredentialUsage finding covers it without a second hand-written rule.

Break-glass, separate from root

Identity Center is the daily path; break-glass exists for when it is down. Create a dedicated emergency IAM user with a long random password and its own hardware MFA device, credentials stored offline, and have it assume a role whose max session duration is set to 1 hour (IAM roles allow 1–12 hours; the default is 1). Activation requires: an incident declared, two named approvers, a time-boxed session, and a screen-share into the incident channel. After use, rotate the password and MFA device and review the CloudTrail trail for the session. AWS Organizations multi-party approval can require N-of-M approver sign-off for selected privileged operations, which is the closest thing to enforced dual control in the console.

Root-only tasks and who executes them

Root-only taskGuardrail
Change account name, email, or root passwordTicket, two engineers on the call, hardware MFA
Close the accountTwo approvers, 24 h cooling-off
Change or cancel the Support planTwo approvers
Restore a deleted admin IAM userTwo approvers; prefer a break-glass admin role instead
Enable S3 MFA Delete; edit a bucket policy that denies s3:PutBucketPolicyTwo approvers
Enable IAM access to billingTwo approvers
Sign up for GovCloudTwo approvers

Failure modes worth naming

  • Circular dependency: break-glass credentials in a password manager behind the same IdP that just failed. Store them offline.
  • Standing privilege with a nicer name: if break-glass is used weekly, the real gap is your Identity Center setup. Count activations; more than one a quarter means fix the cause.
  • False comfort from SCPs: SCPs do not apply to the management account, so a "deny root" SCP protects member accounts and does nothing for the account that matters most.
  • Untested envelope: the MFA battery is dead, the password was rotated and never re-sealed, or the role no longer has the permission it needs.

Test it quarterly. Open the envelope, sign in, perform one read-only root action, rotate, re-seal, and record time-to-recover. Target under 30 minutes from page to root console. Break-glass that has never been tested is documentation; break-glass used daily is standing privilege.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design a break-glass process that remains usable but cannot become a quiet bypass.

Answer

Clarify: break-glass is for when your primary identity provider (IdP) is unavailable or compromised, and you need emergency access to production. Assumptions: you have an IdP (Okta, Azure AD), you need to recover from an IdP outage or a compromised admin account, and you have a regulatory requirement to audit all privileged actions.

Answer directly: build a separate emergency identity path that does not depend on the IdP. Use a dedicated AWS account (the "break-glass account") with IAM users that have hardware MFA (e.g., YubiKey) and a 32-character random password stored in a physical safe. The IAM policy allows only sts:AssumeRole into a break-glass role in the production account. That role has a maximum session duration of 1 hour (the AWS STS default) and requires MFA. Activation requires two approvers (one from security, one from operations) to approve a ticket in Jira. The credentials are retrieved from the safe, and the user assumes the role. An EventBridge rule on CloudTrail's AssumeRole event triggers an SNS alert to the security team within 5 seconds. CloudTrail logs every action, and the session expires after 1 hour.

Why this works: it is independent of the IdP, so an IdP outage does not block you. It is not a quiet bypass because activation is loud: two approvals, physical retrieval, and immediate alerts. The scope is narrow: the role's policy allows only s3:GetObject on the incident bucket and ec2:DescribeInstances. After use, you revoke the STS session, rotate the IAM user password and MFA, review CloudTrail logs, and run AWS Config to check that the break-glass IAM policy and role have not changed from the approved baseline. Conduct a post-incident review within 48 hours and update the runbook.

Trade-offs: compare three approaches.

ApproachAvailability when IdP downStanding riskAuditabilityDeciding criteria
Standing admin roleHighHigh (credential theft)Good if loggedOnly if RTO < 5 min and you accept risk
JIT via IdP (e.g., Azure PIM)None (depends on IdP)LowExcellentUse for routine privileged access, not break-glass
Sealed vault (separate account, hardware MFA)HighLow (credentials offline)Good if you log activationUse when IdP RTO > 15 min or regulatory requirement

Deciding criteria: if your IdP's recovery time objective (RTO) is under 15 minutes, a JIT approach may suffice. If RTO is longer, or you have a regulatory requirement for independent access, use a sealed vault. Standing access is rarely justified.

Failure modes with detection and cost:

  1. Credentials stored in the same IdP: if IdP is down, you cannot retrieve them. Detection: synthetic login test every 5 minutes from an external monitor. Cost: MTTR increases by the IdP outage duration (e.g., 30–60 minutes).
  2. Emergency role exempt from guardrails: an attacker with break-glass can delete CloudTrail logs. Detection: AWS Config rule cloudtrail-enabled and CloudWatch alarm on StopLogging API calls. Cost: loss of audit trail, potential fines.
  3. No dual control: a single person can activate without approval. Detection: CloudTrail logs show AssumeRole without a corresponding Jira ticket. Cost: insider threat, no accountability.
  4. Credentials not rotated after use: if leaked, permanent access. Detection: AWS Config rule access-keys-rotated and iam-user-mfa-enabled. Cost: persistent backdoor.

Do not normalize routine use. Alert on any failed MFA attempt for the break-glass IAM user: CloudTrail logs ConsoleLogin with errorMessage: "Failed authentication", and an EventBridge rule triggers PagerDuty. Keep credentials out of the system they protect. Exercise the process quarterly with a tabletop and a live test in a non-production account.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Describe a practical process for reaching and maintaining least privilege for an existing application.

Answer

The 90-second answer

Least privilege on an existing app is a loop, not a project: inventory every identity, baseline from what the workload actually did, cut in small reversible steps, verify with tests and a canary, then re-review on a schedule. You don't get there by reading the policy: you get there by watching traffic and deleting what never showed up.

1. Inventory the identities, not the policies

List every principal the app uses: IAM roles, GCP service accounts, Kubernetes ServiceAccounts, CI/CD deploy roles, Lambda execution roles, and human break-glass roles. For each, record an owner, the resource set it touches, and how it authenticates. AWS: iam:GenerateServiceLastAccessedDetails (IAM Access Advisor) gives service-level last-accessed. GCP: the IAM Recommender. Azure: Entra Permissions Management. Kubernetes: kubectl auth can-i --list --as=system:serviceaccount:prod:checkout prints the effective rules for that SA.

2. Baseline from evidence, not vendor templates

Vendor job-function policies (AmazonS3ReadOnlyAccess and friends) are a bootstrap only: they're broad by design. Replace them with a generated policy: AWS IAM Access Analyzer policy generation consumes up to 90 days of CloudTrail management events for a role and emits only the actions seen. GCP's IAM Recommender does the same from 90 days of activity. Then widen deliberately for paths that don't run often.

3. Find the rare paths before you cut

Exercise the boring stuff: deploy, scale out and in, backup and restore, failover, credential rotation, break-glass. Denied events in CloudTrail (errorCode: AccessDenied) and Kubernetes audit logs are your list of things you'd break. A policy that passes a smoke test but fails a restore at 3 a.m. is not least privilege, it's a latent outage.

4. Reduce incrementally, with a rollback

LayerConcrete controlSignal you watch
AWS IAMValidatePolicy and CheckNoNewAccess in CI before merge; permissions boundary on the roleAccess Analyzer findings, AccessDenied rate
AWS orgSCP as a ceiling (5,120 chars, max 5 per target): SCPs never grantCloudTrail AccessDenied by principal
GCPIAM Recommender diffs + deny policiesRecommender "apply" diff
AzureEntra PIM time-bound activation for human rolesActivation audit log
KubernetesRBAC has no deny rules: remove verbs, don't try to subtractkubectl auth can-i --list diff, audit log

Ship one change per PR, watch for one full business cycle (a week, or a month if the path is monthly), then delete the old grant. Keep the previous policy in git so rollback is a revert.

5. Maintain

  • Re-review dates on every role; a role with no owner gets deleted, not kept.
  • Separate iam:PassRole from everything else and constrain it with iam:PassedToService: role-passing is privilege escalation.
  • Protect the policy-write path itself: who can call PutRolePolicy? That's the real crown jewel.
  • A wildcard-free policy isn't automatically least privileged. s3:GetObject on arn:aws:s3:::bucket/* is fine; s3:* on a bucket whose name doesn't match its contents is not. Conditions like aws:SourceArn may be unsupported by the service you're calling.

Worked example (illustrative numbers)

A checkout service runs as an IAM role. Access Advisor shows 3 services touched in 90 days; Access Analyzer policy generation emits 14 actions. The existing policy has 61. You cut to 14, plus 6 for a monthly reconciliation job found via denied events during a staging restore, deploy behind a permissions boundary, and watch AccessDenied for a week: 0 new denials. Two months later the reconciliation job is retired and its 6 actions are removed. Net: 61 → 20 → 14.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How do you detect, safely remove, and continuously enforce least privilege against unused IAM permissions at scale without breaking production services?

Answer

Before I answer, two things I'd pin down: is this one account or an AWS Organization, and are CloudTrail data events on? Both change the answer, because you can't safely remove a permission you have no evidence anyone used.

The short version: measure real usage over a window long enough to cover your slowest job, prove the cut on a canary with an automatic revert, then make the tightened state the only state CI will deploy.

Measuring. CloudTrail management events give you the principal ARN, the eventName, and the resources touched. IAM Access Analyzer's policy generation reads the last 90 days of CloudTrail for a role and emits a policy containing only the actions it actually saw: that's a candidate, not a final answer. IAM service last accessed and action last accessed fill in the services that report them. The trap is data events: S3 object-level reads, DynamoDB, Lambda invokes are off by default and billed separately. A role that only reads objects looks completely unused in management events, so you'd cut it and break the service on the next request.

Ninety days is the default because it covers quarterly batch jobs and DR drills. If you have an annual close, 90 days is not enough: either extend the window or, better, move that job onto its own role so the operational role isn't held broad all year.

Cutting. Never edit the live policy. Generate the candidate, attach it to a canary (5% of ECS tasks, or one EKS deployment) and watch two signals: AccessDenied in CloudTrail and the service's own error rate. Keep the previous policy version and wire an alarm: if AccessDenied or UnauthorizedOperation crosses a threshold within the first hour, the pipeline reverts. That hour matters because the failure mode is a code path that runs monthly, not the request path you're testing.

Enforcing. Permissions boundaries on whatever role can create roles, so a developer can't grant themselves past the perimeter. SCPs at the org root denying the things that would blind you: stopping CloudTrail, editing the boundary, touching the KMS key policy. And a CI check that fails a PR containing Action: "*" with Resource: "*".

SignalWhat it provesWhere it lies
CloudTrail management eventswhich API calls a principal madedata-plane reads invisible unless data events are on
Access Analyzer policy generationa policy covering 90 days of observed callssilent on anything that runs less often
AccessDenied rate after attachwhether the cut broke a live pathonly fires when that path is exercised

One more failure mode worth naming: when a role is assumed by another role, the identity in CloudTrail is the session, not the human, so you have to trace the chain before you decide a permission is unused. And leave break-glass roles broad: alarm on their use instead of trimming them, because the day you need one is the day you can't wait for a policy change.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How would you review a deployment role for privilege-escalation paths?

Answer

Assume an AWS IAM role that a CI/CD pipeline assumes (GitHub Actions over OIDC, say) deploying into one or more accounts.

A deployment role's own policy is the wrong document to read. Read the closure: every identity it can hand to something else, every policy it can rewrite, and every workload it can start under a more privileged role. A role with no * in its policy is routinely administrative through delegation: that's the finding worth writing up.

Three passes.

Direct actions. What the role can call itself: usually the least interesting, since deploy roles are scoped to a service's write APIs. Note anything touching IAM, KMS, Secrets Manager or CloudTrail: those feed the next two passes.

Delegation. iam:PassRole is the one that matters. For every role ARN the policy allows, resolve that target's effective permissions (attached policies, inline policies, permissions boundary) and ask whether the deploy role can also modify the target (UpdateAssumeRolePolicy, PutRolePolicy, AttachRolePolicy). If both hold, you have a self-escalation loop: the role widens its own delegation target, then uses it. Same pass covers SetDefaultPolicyVersion (a dormant admin version on a reachable policy), DeleteRolePermissionsBoundary, and trust-policy edits on privileged roles.

Execution. Anything that starts code under another role: lambda:UpdateFunctionCode, ecs:RegisterTaskDefinition, codebuild:UpdateProject, CloudFormation stack updates, SSM automation documents. The deploy role doesn't need the privileged permission; it needs permission to change what runs with it.

PrimitiveAPIWhat to resolve
PassRoleiam:PassRoletarget role's effective permissions, not the ARN pattern
Trust editiam:UpdateAssumeRolePolicycan it add itself or * to a privileged role's trust policy
Policy versioniam:SetDefaultPolicyVersiondormant admin versions on reachable policies
Boundaryiam:DeleteRolePermissionsBoundarycan it strip its own or another role's boundary
Compute updatelambda:UpdateFunctionCode, ecs:RegisterTaskDefinitionthe execution role of the updated resource
Secretssecretsmanager:GetSecretValue, kms:Decryptwhat the secret unlocks downstream
Auditcloudtrail:StopLogging, DeleteTrail, PutEventSelectorscan it blind the trail before escalating

Worked chain. ci-deploy has iam:PassRole on app-exec, plus lambda:CreateFunction and lambda:InvokeFunction. app-exec carries AdministratorAccess.

  1. aws lambda create-function --function-name pwn --runtime python3.12 --role arn:aws:iam::111122223333:role/app-exec --handler index.handler --zip-file fileb://x.zip: allowed, because iam:PassRole on app-exec is granted.
  2. aws lambda invoke --function-name pwn out.json: the function body runs with app-exec's credentials.

ci-deploy never called an admin API. It is admin. The finding is the pair (PassRole on app-exec) + (lambda:CreateFunction); the fix is dropping one of them, not a boundary on ci-deploy, which wouldn't help.

Trade-offs. An allow-list on PassRole is the default recommendation, but it costs you every time a pipeline adds a service; a condition on the target role's tags keeps the list short without going back to *. A permissions boundary is cheaper than a separate account, but it only caps the role it's attached to, unless you also deny iam:CreateRole or force the boundary via a condition, the role creates an unbounded role and passes to it. Separate accounts give a hard blast-radius wall at the cost of cross-account plumbing. OIDC short sessions beat static keys, but the trust policy condition is the entire boundary: a sub of repo:org/* is a public role.

When a lighter touch is enough: a deploy role that only calls one service's deploy API (ecs:UpdateService on a named service, s3:PutObject into a release bucket) with no IAM write and no PassRole has no escalation path worth a boundary. Resource-scoped policy plus a CloudTrail alert on the escalation primitives is proportionate.

Failure modes and detection. Self-escalation loop: resolve the transitive closure of PassRole targets against the roles the deploy role can edit; alert on UpdateAssumeRolePolicy and PutRolePolicy by the deploy role. Dormant policy version: alert on SetDefaultPolicyVersion. Boundary removal: alert on DeleteRolePermissionsBoundary. Compute update to a privileged execution role: alert on UpdateFunctionCode and RegisterTaskDefinition where the target's execution role is privileged. Trail tampering: alert on StopLogging, DeleteTrail, PutEventSelectors. Then encode the known chains as denied cases in a sandbox account and assert AccessDenied: a chain you've only reasoned about is a chain you haven't tested.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Compare RBAC and ABAC for a platform with hundreds of teams and projects.

Answer

Core answer (first 90 seconds)

Assume projects are the tenant boundary, one platform team owns the policy repo, and both humans and workloads need access.

Split the problem. RBAC owns the capability layer: what a role can do: deploy, read logs, rotate a secret. ABAC owns the scoping layer, which project, environment and region that capability applies to. A role per (team, project, environment) is the failure mode; a condition comparing principal.project to resource.project is the fix.

Pure ABAC is not strictly better. It moves the work from role review to attribute issuance: who may set team=payments, what the allowed values are, and what happens when the attribute is missing. That governance is the real cost, and it is the part teams skip.

Why RBAC explodes at this size

300 teams × 3 environments × 2 regions = 1,800 roles before a single project is scoped. Add 500 projects and the (team, project, env) triples reach 450,000. AWS IAM's default quota is 1,000 roles per account, so you exceed the default before projects enter the picture. Raising the quota doesn't reduce review cost: every role is an object someone has to read.

What ABAC replaces it with

One policy, two attributes. On AWS, aws:PrincipalTag/team comes from session tags passed at sts:AssumeRole (requires sts:TagSession; up to 50 session tags, key ≤128 chars, value ≤256 chars). The resource side is aws:ResourceTag/team, or s3:ExistingObjectTag/team for object reads. ABAC has its own ceiling: a managed policy caps at 6,144 characters, so "one policy to rule them all" hits a wall too.

RBACABAC
Unit of grantrole → permission setpolicy over attributes
Grows withroles × scoping dimensionspolicies + attribute keys
Main riskrole sprawl, stale grantsattribute issuance and mutation
Audit questionwho holds role X?what can team=payments reach? (needs decision logs)
Native exampleKubernetes Role/RoleBindingAWS IAM condition keys, Cedar, GCP IAM Conditions
Deny semanticsKubernetes RBAC has no deny rulesIAM: explicit deny wins

Worked trace

Principal: role session with session tag team=payments. Policy condition: StringEquals: {"s3:ExistingObjectTag/team": "${aws:PrincipalTag/team}"}.

  1. GetObject on acme-artifacts/payments/2024/report.csv, object tagged team=payments. IAM resolves the variable to payments, S3 supplies payments, equal → statement applies → allow.
  2. Same principal, acme-artifacts/billing/2024/report.csv, object tagged team=billing. Condition false → no statement allows → implicit deny.
  3. Object with no team tag. The condition key is absent, StringEquals is false → implicit deny. Fail-closed, which is the property you want.

Failure modes and how to catch them

  • Self-assigned privilege tags. If a team can call iam:TagRole or CreateTags on its own resources, it can widen its own access. Deny tag-mutating actions outside the platform role (SCP or identity policy), and require aws:RequestTag/team to equal aws:PrincipalTag/team on create. Detect with CloudTrail TagResource/CreateTags events where the caller isn't the platform role.
  • Fail-open on missing attributes. In Rego, referencing an undefined attribute makes the rule undefined → deny. But a rule that denies only when the two attributes differ (not (principal.project != resource.project)) allows a resource with no project at all. Catch it with a CI test that evaluates every policy against an attribute-less resource and asserts deny.
  • Tag key sprawl. project, Project, proj means three policies and silent gaps. Nightly GetTagKeys from the Resource Groups Tagging API; alert on any key outside the allowlist.
  • Cross-tenant leakage. For 20 canary teams, assert all 400 ordered (principal, resource) pairs deny off-diagonal. Run it in CI against the real policy bundle.

Making "comprehensibility" a number

Track three: policy count, distinct attribute keys referenced, and the share of policies that produced zero allow decisions in 90 days of decision logs (OPA decision logs, or IAM Access Analyzer unused-access findings). A high third number means dead policy, not a scalable model.

When neither fits

If the question is "can this principal reach this object" through a chain of relationships, folder → project → resource, ReBAC models it directly and avoids both role explosion and tag governance (Zanzibar, USENIX ATC 2019; OpenFGA, SpiceDB). Kubernetes has no native ABAC and no deny rules, so attribute decisions there need an admission webhook (OPA Gatekeeper, Kyverno) or an external authorizer; audit with kubectl auth can-i --list --as=system:serviceaccount:ns:sa.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design OIDC federation from a CI/CD platform into a production deployment role.

Answer

Core answer (first 90 seconds). Assume GitHub Actions as the CI platform and AWS as the deploy target; GCP Workload Identity Federation and Azure federated credentials have the same shape. Do not create an IAM user with an access key. Register token.actions.githubusercontent.com as an IAM OIDC provider, then make the deploy role's trust policy accept only sts:AssumeRoleWithWebIdentity from that provider when the token's aud and sub match exact values. The job gets a 15-minute session; nothing long-lived is stored.

Why the conditions stop replay. The OIDC token is a signed JWT with a 5-minute exp. AWS fetches the issuer's JWKS, verifies the signature, then evaluates the trust policy conditions against the claims. aud pins the token to the intended recipient: a token minted for sts.amazonaws.com is useless against another cloud's STS. sub pins it to the exact workflow context: repo:acme/deploy:environment:production only matches a job that ran in that repo's production environment. A token lifted from a different repo, branch, or fork fails the string match, so replay across contexts is denied at the trust policy rather than by a secret being absent.

Concrete trust policy.

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"},
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {
        "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
        "token.actions.githubusercontent.com:sub": "repo:acme/deploy:environment:production"
      }
    }
  }]
}

The workflow calls aws-actions/configure-aws-credentials with role-to-assume and role-session-name, and passes --source-identity (or session tags) so CloudTrail records which run assumed the role. sts:SourceIdentity can be required in the condition block; session tags need sts:TagSession in the trust policy. Set DurationSeconds to 900 rather than the 3600 default.

Trade-offs. Federation removes the long-lived secret but adds a hard dependency on the issuer being reachable, if GitHub's OIDC endpoint is down, deploys stop. Static keys in a secrets manager with rotation keep working during an issuer outage but are a standing credential to leak. One org-wide role with a sub condition on repo is fewer objects to manage but a single policy edit widens every repo; per-repo roles isolate blast radius at the cost of role sprawl. If you deploy from one self-hosted runner in a locked VPC with no external contributors, federation is more machinery than the threat justifies.

Failure modes. Fork PRs get a pull_request subject: never match on it; match environment: or ref:refs/heads/main. Reusable workflows: the sub is the caller's repo, so also pin job_workflow_ref to the called workflow, otherwise any repo can call an arbitrary workflow. The IAM OIDC provider stores a TLS thumbprint of the issuer's certificate chain; if the issuer rotates its CA, validation fails until the thumbprint is updated: alert on it. Environment protection rules are what make environment:production meaningful: the claim only appears after required reviewers approve.

Denied-case tests. Assume-role attempts with a token from another repo, another branch, a fork PR, a wrong aud, and a job outside the protected environment must all fail. Run them in CI as a negative test suite.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design the lifecycle for a database password used by multiple application instances.

Answer

Assumptions I'd state first. Postgres 14+ primary (password_encryption has defaulted to scram-sha-256 since PG 14, so the server holds one verifier per role); about 40 app instances each with a HikariCP pool (maxLifetime default 1,800,000 ms); no ability to restart every instance at once; secret material in AWS Secrets Manager or Vault. If those don't hold, say what changes.

The answer: make the credential expire rather than rotate a shared password. Vault's database secrets engine, dynamic path: an instance reads database/creds/app-ro and gets its own database user and password with a lease (default_ttl 1h, max_ttl 24h is a normal starting point). Lifecycle is then creation on first read, renewal while the process is healthy, revocation when the lease expires or the client disappears. Nothing is shared, so there is no coordinated cutover and no rollback to plan: the worst case is one instance losing only its own credential.

Static rotation is the fallback when per-instance role creation is unacceptable (DBA process, role-count limits, licensed engine). Then design against one deciding question: can the engine keep two valid passwords for the same login?

Vault dynamic, user per leaseManaged rotation, two roles app_a/app_bManaged rotation, one role
Two passwords valid at onceYes, leases overlap by constructionYesPostgres: no. MySQL 8.0.14+ only: ALTER USER ... IDENTIFIED BY 'new' RETAIN CURRENT PASSWORD keeps one retained password, released with DISCARD OLD PASSWORD
What changes at rotationNothingWhich role name config points at: needs config that reaches pods without a restartNothing; every reconnect during the cutover fails until the new value lands
Added cost or riskOne CREATE ROLE per instance per hour: pg_auth churn, role growth, no transaction-mode pooler in the auth pathTwo names to keep in sync; a config flip mid-deploySeconds to minutes of failed auth, no rollback
Choose whenEngine creates roles cheaply, no auth-rewriting proxy in frontManager supports staged versions (AWSCURRENT / AWPENDING / AWPREVIOUS) and the engine tolerates two rolesYou accept an atomic cutover

Timing, because overlap is what makes this safe. With AWS Secrets Manager rotation every 30 days at 03:00 UTC (four-step Lambda: createSecret, setSecret, testSecret, finishSecret) give a 6-hour overlap. If the app caches the fetched value for at most 5 minutes, the oldest usable copy of the old password is 6h05m old when you revoke, so revoke at 7 hours, not 6. Fetch volume: 1440/5 = 288 reads per instance per day, so 40 * 288 = 11,520/day, about 345,600/month. At Secrets Manager list price (us-east-1, $0.40 per secret per month plus $0.05 per 10,000 GetSecretValue calls) that is roughly $1.73/month of API calls; a 30-minute TTL drops it to 57,600 calls and about $0.29. Note which way the constraint points: the TTL is bounded by the overlap, and the overlap by how long you want rollback to stay possible. Cost is noise next to those.

Failure modes, and what each looks like on a dashboard.

  • App cache TTL longer than the overlap: after revoke, instances still holding the old value log FATAL: password authentication failed for user "app_a" (SQLSTATE 28P01; MySQL is error 1045). Alert on the rate of 28P01 in the server log and on HikariCP hikaricp.connections.pending, not on single failures.
  • Herd: 40 instances fail at once, each opening a fresh connection. At pool size 10 that is 400 sockets against Postgres max_connections default 100, producing FATAL: sorry, too many clients already, which reads like a database outage rather than a secrets bug. Jitter the refresh, keep the pool small, make the overlap much wider than the refresh interval.
  • Revoking a password in Postgres does not terminate sessions that are already authenticated. Verify the revoke with a new connection; a long batch job can stay connected on a password you believe is dead.
  • PgBouncer in transaction pooling mode does not compose with per-lease users: authentication happens once per client connection, so you need an auth_query SECURITY DEFINER lookup rather than a role per lease. Without it every instance authenticates as the pooler's user and dynamic credentials buy nothing.
  • Password in an environment variable or ConfigMap is visible in /proc/<pid>/environ, in crash dumps, and in kubectl describe pod. Read it into process memory at startup (or from a tmpfs file written by a CSI driver), never through env.

Access boundary. The app role gets exactly secretsmanager:GetSecretValue on the one secret ARN plus DescribeSecret; the operator gets PutResourcePolicy/DescribeSecret but no GetSecretValue; the rotation role gets GetSecretValue and the database ALTER ROLE grant, and nothing else the app can do. Send GetSecretValue to CloudTrail data events and alert when a principal reads a secret it has never read before.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Explain envelope encryption and the authorization boundaries around decrypting application data.

Answer

What a strong candidate says first

Envelope encryption means you never encrypt data with the long-lived key. You ask a key service for a data key, use its plaintext once to encrypt the payload with an AEAD cipher, store the encrypted data key beside the ciphertext, and discard the plaintext. Reading reverses it: one call to the key service to unwrap the data key, then local decryption. The expensive, audited, centrally-controlled operation happens once per object, not once per byte.

On AWS: GenerateDataKey(KeySpec="AES_256") returns a 32-byte plaintext key plus its ciphertext blob; you encrypt the payload locally with AES-256-GCM and persist {encrypted_dk, nonce, ciphertext, encryption_context}. KMS itself refuses payloads over 4 KB, which is exactly why you don't call it per record.

Authorization boundaries

Three roles, kept apart:

  • key admin: kms:CreateKey, PutKeyPolicy, ScheduleKeyDeletion
  • key user: kms:GenerateDataKey, kms:Decrypt
  • data reader: application-level access to the object

The key policy is the root of trust; IAM only works where the key policy delegates to the account. Scope kms:Decrypt with a condition on the encryption context so a grant for tenant A cannot unwrap tenant B's data key:

JSON
{"Effect":"Allow","Action":"kms:Decrypt","Resource":"*",
 "Condition":{"StringEquals":{"kms:EncryptionContext:tenant":"acme"}}}

Encryption context is authenticated but not secret: bind tenant, object id, purpose. A decrypt with the wrong context fails with InvalidCiphertextException. That is the confused-deputy defense: a service acting for one caller cannot be tricked into unwrapping another's key.

Failure modes and detection

  • Over-broad decrypt: kms:Decrypt on Resource:"*" with no context condition. Any principal in the account can unwrap any object's data key. Detect with CloudTrail Decrypt events whose encryptionContext is empty or whose principal is unexpected; IAM Access Analyzer flags public or cross-account key policies.
  • Missing encryption context: the same confused-deputy hole, silently. Detect by asserting context presence in the decrypt path and alerting on context-less Decrypt calls.
  • Key-service dependency: every read now needs a KMS round trip. At the default 5,500 symmetric requests/second per account per Region, a hot read path throttles (ThrottlingException), and a KMS regional outage blocks all reads. Detect via KMS 5xx/throttle metrics and read-path p99. Mitigate by caching plaintext data keys in memory with a short TTL, the AWS Encryption SDK's data key cache does this, accepting that a cached key outlives revocation by the TTL.

Trade-offs

approachper-byte costcontrolwhen it's wrong
envelope (KMS + local AEAD)one KMS call per objectcentralized, auditedyou need the key service to never see the data key
direct KMS Encrypt/Decryptone call per payload, ≤4 KBsimplestpayloads over 4 KB, high volume
CloudHSM / self-managed rootyou run itdedicated HSM, regulatorysmall teams without HSM ops

Rotation is cheap here: rotating the KMS key does not re-encrypt payloads, and old backing keys stay available for decrypt, so you re-wrap the small data keys on your own schedule instead of rewriting the data.

Once plaintext is in the workload, envelope encryption stops helping: that is application authorization, not key policy.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What IAM and STS audit events should be centralized, and how would you detect abuse?

Answer

Assume AWS, a multi-account organization, and CloudTrail as the source of truth. The answer: run an organization trail that delivers all management events to a log-archive account, keep STS session context intact, and split detection into high-signal EventBridge rules and baselined anomaly detection.

Centralize

An organization trail created in the management account covers every account, including new ones, and member accounts cannot stop or modify it. The first copy of management events is free; additional trails cost $2.00 per 100,000 events. Data events (S3 object-level, Lambda Invoke) are off by default and cost $0.10 per 100,000 events, so enable them only on buckets and functions that hold credentials or PII.

Events that must be in the archive:

GroupEventsWhy
Sign-inConsoleLogin, GetSessionToken, GetFederationTokenConsole and long-lived credential issuance; ConsoleLogin carries additionalEventData.MFAUsed
Role assumptionAssumeRole, AssumeRoleWithSAML, AssumeRoleWithWebIdentitySession issuance; requestParameters has roleArn and roleSessionName
CredentialsCreateAccessKey, UpdateAccessKey, DeleteAccessKey, CreateServiceSpecificCredential, UploadSSHPublicKey, CreateLoginProfile, UpdateLoginProfileNew durable credentials
MFADeactivateMFADevice, DeleteVirtualMFADeviceMFA removal precedes takeover
Identity/policyCreateUser, CreateRole, AttachRolePolicy, PutRolePolicy, CreatePolicyVersion, SetDefaultPolicyVersion, UpdateAssumeRolePolicy, AddUserToGroupPrivilege and trust changes
Logging/orgStopLogging, DeleteTrail, UpdateTrail, PutEventSelectors, DeleteDetector, LeaveOrganization, PutOrganizationPolicyAnti-forensics

Keep the full userIdentity block: type, arn, principalId, accessKeyId, sessionContext.sessionIssuer.arn, sessionContext.attributes.mfaAuthenticated, and sourceIdentity. Without sessionIssuer you cannot tie a downstream DeleteObject back to the role session that made it.

Detect

SignalDetectionThreshold
Root useAny event with userIdentity.type = Root1
New access keyCreateAccessKey where actor is not a known automation role1
Trust broadeningUpdateAssumeRolePolicy diff adds Principal "*" or a new external account1
Wildcard adminCreatePolicyVersion/SetDefaultPolicyVersion with Action "" Resource "" and no Condition1
PassRole anomalyRunInstances, CreateFunction, CreateServiceLinkedRole where the named role has not been passed by this principal in 30 days1
Failed assumption burstAssumeRole errorCode AccessDenied>20 in 5 min per principal
Logging disablementStopLogging, DeleteTrail, PutEventSelectors1
Console without MFAConsoleLogin with additionalEventData.MFAUsed = "No" for privileged users1

Route these through EventBridge to a Lambda that enriches with GuardDuty findings (PrivilegeEscalation:IAMUser/AdministrativePermissions, Stealth:IAMUser/CloudTrailLoggingDisabled) and IAM Access Analyzer unused-access findings.

Trade-offs

Event-only alerting is cheap and low-latency but blind to what a session did after it was issued. Session attribution: joining AssumeRole to downstream calls on sessionIssuer.arn + principalId: is what makes an alert actionable, but role chaining breaks the chain: a session that assumes a second role gets a new sessionIssuer. Set sourceIdentity at the first AssumeRole; it propagates through chaining and survives into the second session's userIdentity. Role chaining also caps the session at 1 hour, versus 12 hours for a direct assumption.

Full data events on every bucket is the other cost cliff: at $0.10 per 100,000 events, a bucket serving 50M requests/day is ~$50/day. Scope data events to credential-bearing buckets.

Burst detection on AssumeRole has a real false-positive cost: CI/CD and autoscaling assume roles on a schedule. Baseline per role per hour-of-day and alert on deviation, not on absolute count.

Failure modes

  • LookupEvents is capped at 2 requests/second and 50 events per page: fine for investigation, not for real-time detection. Use EventBridge or CloudTrail Lake (7-year default retention) for queries.
  • CloudTrail typically delivers within 5 minutes, up to 15. Validate with a canary call and measure; a detection that fires 15 minutes late is a different control.
  • GetCallerIdentity is not recorded by CloudTrail, so it cannot serve as a heartbeat.
  • Protect the archive: S3 Object Lock in compliance mode, versioning, a bucket policy denying deletion, and log file integrity validation (SHA-256 digest files).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Respond to a leaked production access key discovered in a public repository.

Answer

The first 90 seconds

Assume the key is compromised the moment it is public. Public repositories are scraped continuously, so the working assumption is that the credential has already been used: do not spend the first hour deciding whether it was.

Record the access key ID, the commit SHA, and the push timestamp. Then deactivate the key rather than delete it:

Shell
aws iam update-access-key --user-name ci-deployer \
  --access-key-id AKIAEXAMPLE123456789 --status Inactive

Deactivate first because it is reversible if the alert turns out to be a false positive, and the key ID stays valid for log correlation. Delete (aws iam delete-access-key) only once you have confirmed no legitimate workload still holds a copy: a CI job, a Lambda environment variable, an AMI, a Terraform state file. Deleting before you have found those copies converts a security incident into an outage.

Then hunt with the key ID as the pivot:

Shell
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=AccessKeyId,AttributeValue=AKIAEXAMPLE123456789 \
  --start-time 2024-05-01T00:00:00Z

CloudTrail Event history holds 90 days of management events and returns up to 50 per page. If the commit is older than that, or you need data events, query the trail's S3 bucket with Athena instead.

What to look for

EventMeansAction
GetCallerIdentity from an unknown ASNRecon; the key is live and being testedTreat as active compromise
CreateAccessKey, CreateUser, CreateLoginProfilePersistence independent of the leaked keyDelete the new principal, rotate again
AssumeRole with the key as sourceAttacker moved to a role with wider scopeEnumerate the role's sessions; attach an inline policy denying actions when aws:TokenIssueTime predates now
StopLogging, DeleteTrail, UpdateTrailAnti-forensicsRestore the trail, check log file validation digests for gaps
PutBucketPolicy, PutRolePolicy, AttachUserPolicyPrivilege escalation or an exfiltration pathRevert, diff against IaC

GuardDuty covers much of this without you writing queries: UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS, CredentialAccess:IAMUser/AnomalousBehavior, Persistence:IAMUser/AnomalousBehavior.

Trade-offs

Revoke versus preserve: revoke. The credential is a bearer token; every minute it lives widens the blast radius, and evidence is preserved through logs, not by keeping it usable. The only reason to delay is if you cannot yet identify the owner, and even then, deactivate.

Rotate everything versus rotate what was touched: scope by the log window. Rotating every secret in the account is a multi-hour outage; rotating the secrets the principal actually read (GetSecretValue, GetParameter, s3:GetObject on config buckets) is proportionate. If the logs are missing, assume the worst and rotate broadly.

Rewrite git history versus just rotate: rotate. Rewriting does not retract clones, forks, or cached blobs, and it breaks every collaborator's checkout. The key is already burned; history rewriting buys nothing.

Failure modes

The common miss is rotating the key but not the secrets it could reach. The key was in a repository, so it was probably also in a CI variable, a .env baked into an image layer, or a Terraform state file. Search by key ID across those stores, not by filename.

Second: the attacker's persistence outlives the rotation. A new access key created at 02:14 survives your 02:30 rotation. Re-run the CloudTrail query after rotation and confirm no new principals or keys exist.

Third: detection never fired. If the key sat public for six days, ask why: GitHub secret scanning with push protection blocks the commit before it lands, and IAM Access Analyzer's unused-access findings flag a key the workload never used. Measure the gap between push and revocation; that number is the control you are actually fixing.

Curated: · Written: · Reviewed:

Difficulty: Hard