Skip to content
Tech Interview Prep
Technical interview guide

Cloud IAM Policy Design

Writing least-privilege access policies for cloud resources, and avoiding the common over-permissioning failure modes.

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

Scope: AWS IAM, Google Cloud IAM, Azure RBAC/managed identity, and NIST SP 800-207 guidance current 2026-08-31.

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 why an AWS request is denied despite an identity allow.

Answer

The short answer

An identity-based Allow is necessary but not sufficient. AWS allows a request only if every policy layer that applies to it allows and none of them denies. So the denial is coming from a different layer: most often a permissions boundary, a session policy, an SCP, or a cross-account resource policy that doesn't grant this principal.

How the layers combine

  • Identity-based policy: grants, but is capped by the boundary and any session policy.
  • Permissions boundary: intersects with the identity policy. It never grants; it only removes.
  • Session policy (only when a role is assumed with one): another intersection.
  • SCP (org): caps every principal in the account; never grants.
  • RCP: caps resource-based permissions for resources in member accounts.
  • Resource-based policy: cross-account, both the identity side and the resource side must allow. Same-account, a resource-policy allow is often sufficient on its own, except IAM role trust policies, where the trust policy and the identity policy must both allow sts:AssumeRole.
  • Explicit deny: wins over every allow, anywhere.

Effective permission is roughly the intersection of identity policy, boundary, session policy and SCP, combined with the resource policy per the same/cross-account rule, minus any explicit deny.

Worked trace

Role arn:aws:iam::111122223333:role/AppRole, assumed as arn:aws:sts::111122223333:assumed-role/AppRole/session-1, calls s3:PutObject on arn:aws:s3:::reports-prod/2024/q4.csv in account 444455556666.

LayerStatementEffect
Identity policyAllow s3:PutObject on arn:aws:s3:::reports-prod/*allow
Permissions boundaryAllow s3:GetObject, s3:ListBucketPutObject not allowed
Bucket policy (444455556666)Allow principal arn:aws:iam::111122223333:role/AppRole s3:PutObjectallow
SCPFullAWSAccessallow

Result: AccessDenied. The boundary caps the identity policy, so the effective identity-side set has no s3:PutObject. Cross-account access needs the identity side to allow too, so the bucket-policy allow can't rescue it. The controlling layer is the boundary.

Debugging trade-offs

CloudTrail is ground truth: the AccessDenied event carries principal, action and resource, and for boundary or SCP denials the error text names the layer. It's after the fact and delivery lags by minutes. IAM Policy Simulator (aws iam simulate-principal-policy) lets you test a candidate fix before applying it, but it evaluates the policies you hand it against the context you supply: miss a condition key like aws:SourceIp or aws:PrincipalOrgID and it will tell you the call is allowed. IAM Access Analyzer finds external access and unused permissions, but won't explain one specific denial. Use CloudTrail to find the layer, the simulator to test the fix.

Failure modes to check

  • Boundary strips the action (above). Detected by the boundary named in the error and by simulating with the boundary attached.
  • SCP written with NotAction: a deny-everything-except list that omits the action. The error names the SCP.
  • Cross-account bucket policy whose Principal is the assumed-role session ARN instead of the role ARN. Session ARNs never match a Principal, so the grant silently doesn't apply.
  • Session policy on AssumeRole that omits the action: the intersection drops it.
  • Identity allow with a condition that fails (aws:SourceVpce, aws:MultiFactorAuthAge) so the statement never matches the request.

Fix the one controlling layer, then re-run the call and a negative case (an action that should still be denied) to confirm you didn't widen access.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Use attributes and conditions to scope cloud access.

Answer

What I'd say first. Take AWS IAM as the concrete case, with Azure ABAC and GCP IAM Conditions as the variants. Attributes scope access only when three things hold at once: the attribute is present in the request context, the operator fails closed when it isn't, and the attribute's value is writable by someone other than the principal being granted access. Miss the third and you've built a self-service privilege escalation.

Mechanism. IAM assembles a request context (principal tags, resource tags, request tags, source VPC/IP, time, MFA age) then evaluates each condition key against it. For a single-valued operator like StringEquals, a key that isn't in the context makes the condition false. That's the fail-closed default you want:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::app-data/*",
    "Condition": {
      "StringEquals": { "aws:ResourceTag/env": "prod" },
      "Null": { "aws:PrincipalTag/team": "false" }
    }
  }]
}

Null: false asserts the key exists. Without it, a principal with no team tag still passes the StringEquals on the resource side and gets in.

The trap is ForAllValues. AWS documents that it returns true when the request context contains no value for the key: vacuous truth. So ForAllValues:StringEquals on aws:PrincipalTag/team grants access to every untagged principal. Pair it with a Null check, or use ForAnyValue.

Trace. Principal alice, no team tag, requests s3:GetObject on app-data/report.csv, tagged env=prod. Context: aws:ResourceTag/env=prod, no aws:PrincipalTag/team. StringEquals → true. Null → key absent → false. Condition false → deny. Swap the Null line for ForAllValues:StringEquals and the same request is allowed: that is the whole difference between fail-closed and fail-open.

Trade-offs. RBAC encodes the mapping in role names; ABAC encodes it in attributes. For 40 teams × 12 environments, RBAC is 480 role bindings to keep in sync; ABAC is one policy plus two tags, but you've moved the complexity into tag governance, and you now depend on a second permission system (who may tag). When the set of teams and resources is small and fixed, RBAC is simpler and easier to audit; attribute scoping earns its cost when the matrix is large or changes often. GCP IAM Conditions can't reference principal attributes at all (conditions there are resource- and request-based (resource.name.startsWith(...), request.time < timestamp(...))) so cross-principal ABAC isn't available. Azure ABAC conditions attach to a role assignment and support a limited action set, so you can't blanket-apply them.

Failure modes. Tag drift denies legitimate traffic: a resource created before its tag lands fails the condition. Detect via CloudTrail AccessDenied entries naming the condition key, and alarm on the deny rate. An ungoverned tag write path is escalation: anyone with iam:TagRole or tag:TagResources can grant themselves access. Restrict tagging with SCPs and alert on TagResource/TagRole events. And a break-glass role with no conditions, MFA-gated and short-lived, is what keeps fail-closed from becoming an outage.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How would you design a permissions boundary for a team that creates and attaches its own roles, and how does it intersect with SCPs and identity policies when a single request is evaluated?

Answer

A permissions boundary is a cap, not a grant. It never adds permissions; it limits what identity-based policies can grant to a principal. For a team that creates and attaches its own roles, the boundary is the contract: every role they create must carry it, and the boundary itself must be tamper-proof so they cannot widen or remove it.

Design the boundary. Allow only what the workloads need (s3:GetObject on one prefix, sqs:SendMessage, logs:PutLogEvents) and explicitly deny the IAM actions that would let them escape the cap: iam:DeleteRolePermissionsBoundary, iam:PutRolePermissionsBoundary except to the boundary ARN, iam:CreateUser, iam:CreateAccessKey, and iam:PassRole except to a small set of role ARNs.

Enforce attachment. The team's identity policy allows iam:CreateRole, iam:AttachRolePolicy, iam:PutRolePolicy, but only under a condition:

JSON
{
  "Effect": "Allow",
  "Action": ["iam:CreateRole", "iam:PutRolePermissionsBoundary"],
  "Resource": "*",
  "Condition": {
    "StringEquals": {
      "iam:PermissionsBoundary": "arn:aws:iam::123456789012:policy/TeamBoundary"
    }
  }
}

Without that condition they create a role with no boundary and full admin. Put the same condition in an SCP at the OU so even an account admin cannot create a role without the boundary. The SCP also denies iam:DeleteRolePermissionsBoundary and iam:PutRolePermissionsBoundary for every principal except a break-glass role.

How a single request is evaluated. SCPs are guardrails, not grants. The default FullAWSAccess SCP allows every action, so it imposes no constraint; if you replace it with an allow-list SCP, the action must appear in that list. An explicit Deny in any SCP wins over everything else.

LayerWhat it does
SCPGuardrail. Default allows all; an allow-list restricts to listed actions; any explicit Deny wins.
Permissions boundaryCaps the principal. Must allow the action.
Identity-based policyGrants. Must allow the action.
Resource-based policyGrants on the resource. Same-account grants are still capped by the principal's boundary.

Explicit deny anywhere wins. Otherwise the action must survive the SCP (the default allows; an allow-list must include it), the boundary must allow it, and the identity policy must allow it. Effective permissions are the intersection.

Resource-based policies: a same-account bucket policy that grants s3:GetObject to a role does not let that role read the bucket if the role's boundary excludes s3:GetObject. The boundary caps the principal regardless of where the grant comes from. A resource policy in another account is outside your boundary's control, but it does not grant your principal anything on its own: your account's identity policy must still allow the action, and your boundary caps that.

What a boundary cannot do. It cannot grant permissions, cannot attach to service-linked roles, and does not apply to the root user. It also cannot stop a principal from creating a role without a boundary unless you enforce attachment with a condition or an SCP.

Failure modes and detection. A missing condition on CreateRole lets a role escape the cap. A boundary that allows iam:PutRolePermissionsBoundary lets the team swap in a wider boundary. An SCP not applied to the management account leaves a hole. Detect with CloudTrail events for CreateRole calls that omit iam:PermissionsBoundary, plus DeleteRolePermissionsBoundary and PutRolePermissionsBoundary, and an AWS Config rule that flags roles missing the boundary.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Write a KMS key policy that grants one role and one external principal use of the key without opening it to the whole account, and explain how the key policy, grants and the caller's identity policy combine at evaluation time.

Answer

Open with the two facts that decide the design: whether the caller is in the same account as the key, and whether the key policy names principals directly or delegates to the account root.

A KMS key policy is the gate, and it behaves differently from an S3 bucket policy. An IAM policy alone can never grant access to a key: the key policy must allow it, either by naming the principal or by granting kms:* to arn:aws:iam::111122223333:root. That root statement is the default, and it does not mean every principal in the account has access: it means IAM policies in that account can grant it. So "the key is private" is false the moment anyone in the account holds kms:*.

Here is a key policy that names principals instead:

{ "Version": "2012-10-17", "Statement": [ { "Sid": "AppRoleViaS3", "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::111122223333:role/payments-api"}, "Action": ["kms:Encrypt", "kms:Decrypt", "kms:GenerateDataKey"], "Resource": "", "Condition": {"StringEquals": {"kms:ViaService": "s3.us-east-1.amazonaws.com"}} }, { "Sid": "VendorAuditDecrypt", "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::444455556666:role/audit-reader"}, "Action": ["kms:Decrypt", "kms:DescribeKey"], "Resource": "", "Condition": {"StringEquals": {"kms:CallerAccount": "444455556666"}} }, { "Sid": "NoKeyDeletion", "Effect": "Deny", "Principal": "", "Action": ["kms:ScheduleKeyDeletion", "kms:DeleteImportedKeyMaterial"], "Resource": "" } ] }

No root statement, so IAM policies in account 111122223333 cannot widen this key. The cost is real: every new principal is a key policy edit, and that edit is a separate change from the IAM change that gives the role its permissions.

Evaluation combines three inputs. An explicit deny in any applicable policy wins, including against the account root and against grants. Otherwise the key policy, or a grant, must allow the call, and a cross-account caller additionally needs an identity-policy allow in their own account.

CallerKey policyIdentity policyGrantResult
payments-api (same account)Allow, namednone—Allowed: a direct key-policy grant is sufficient
other role in 111122223333no statementkms:Decrypt allow—Denied: no root delegation, so IAM cannot widen it
audit-reader (444455556666)Allow, namedkms:Decrypt allow—Allowed
audit-readerAllow, namedno allow—Denied: cross-account needs both sides
any principalDeny ScheduleKeyDeletionallow—Denied: explicit deny wins
service principalno statementnonekms:Decrypt grantAllowed: grants are evaluated with the key policy

Grants are the third input and the one people forget. A grant is evaluated as part of the key policy, so a grantee does not need an identity-policy allow for the granted operations: that is why AWS services use grants to act on your behalf. Constrain them with encryption context or grant tokens, and revoke with RevokeGrant. Grants never appear in the key policy, so ListGrants belongs in drift detection: a grant created last quarter still works after you tightened the policy.

Failure modes worth naming. Cross-account AccessDenied where the key policy looks correct is almost always the missing identity allow in the caller's account; the error names the key, not the missing half. kms:ViaService blocks direct KMS API calls, which is the point, but it also breaks a debugging script that calls Decrypt directly. And a key policy left on the default root statement, with a kms:* identity policy somewhere in the account, is a public key in all but name.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design least-privilege cloud access for an engineering team.

Answer

Assumptions I'd state up front: AWS Organizations, ~120 engineers, four accounts (dev, staging, prod, shared-services), workforce identity already in Okta or Entra ID. On GCP or Azure the shape is identical; only the names change. If your team is 8 people, skip half of this: the account boundary does the work for you.

The 90-second answer

No IAM users. Federate the workforce into IAM Identity Center, enforce MFA at the IdP, and hand out permission sets per job function, attached to groups synced from the IdP: never to individuals. Prod is read-only standing. Prod writes are just-in-time, time-boxed, and logged. Break-glass is a separate role that pages someone the moment it's assumed.

Job functionPermission setSessionScope
All engineersReadOnly8 hAll accounts
Service ownersDeployNonProd8 hdev, staging
On-callOperateProd (read + restart/scale)1 hprod
ElevatedProdWrite (JIT)60 minprod
Break-glassAdminBreakGlass1 hprod

Why groups, not per-user policies

A per-user policy is N policies to audit and N places to forget on offboarding. Group membership is one join/leave event driven by the IdP, so deprovisioning is a SCIM call, not a ticket. The 1-hour prod session is the other half: it caps how long a stolen laptop token is useful.

Why JIT beats a standing prod role

A standing prod-write role means a compromised session has prod write for its whole duration. JIT shrinks that to the approved interval and, more importantly, records intent, who asked, for what, approved by whom. The cost is real: an approval wait of 5-15 minutes per elevation. If a team deploys to prod 20 times a day, per-deploy JIT is friction that pushes people to share credentials. Decide by change frequency and blast radius: high-frequency, low-blast-radius deploys get a standing role with a short session; rare, high-blast-radius changes get JIT.

The two artefacts that matter

Standing prod read, region-bounded:

JSON
{
  "Version": "2012-10-17",
  "Statement": [
    { "Sid": "ReadProd", "Effect": "Allow",
      "Action": ["ec2:Describe*", "s3:GetObject", "s3:ListBucket", "logs:GetLogEvents"],
      "Resource": "*" },
    { "Sid": "DenyOutsideRegion", "Effect": "Deny",
      "Action": "*", "Resource": "*",
      "Condition": { "StringNotEquals": { "aws:RequestedRegion": "eu-west-1" } } }
  ]
}

The JIT role's trust policy: MFA required, and re-authenticated within the last 5 minutes:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "AWS": "arn:aws:iam::111122223333:root" },
    "Action": "sts:AssumeRole",
    "Condition": {
      "Bool": { "aws:MultiFactorAuthPresent": "true" },
      "NumericLessThan": { "aws:MultiFactorAuthAge": "300" }
    }
  }]
}

Failure modes and how you catch them

  • Permission creep: someone added to ProdWrite "temporarily" in March. Detect with IAM Access Analyzer unused-access findings (unused permissions over 90 days) plus a quarterly group-membership diff against the IdP.
  • Break-glass misuse: the role is assumed without an incident. Detect with an EventBridge rule on CloudTrail AssumeRole for that role ARN that pages on-call; credentials live in a sealed store and rotate after every use.
  • Wildcard drift: a mutating action lands on Resource: "*". Detect with Access Analyzer policy validation in CI, failing the build on "*" in any prod policy.
  • Stale federation: a user disabled in the IdP still holds a valid session. The session-duration cap bounds this; SCIM deprovisioning removes the group membership that would let them re-assume.

When not to do this

If you have fewer than ~15 engineers and one prod account, per-team accounts and a single admin group beat a permission-set matrix: the matrix is overhead you'd maintain for no one. And if a workload can't do OIDC or SAML, it gets an IAM role with a trust policy scoped to that workload's identity, not a shared user.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Create and maintain a custom cloud IAM role.

Answer

Assume AWS IAM. A Lambda function in account 123456789012 needs to read one bucket, my-bucket. The AWS-managed AmazonS3ReadOnlyAccess grants s3:GetObject on every bucket in the account, so you build a custom role instead.

Core answer

A role is two documents. The trust policy says who may assume it; the permissions policy says what the resulting session may do. Create the role with a trust policy that names the Lambda service principal and pins it to your function with aws:SourceArn and aws:SourceAccount, so no other account's Lambda can assume it. Attach a customer managed policy granting s3:GetObject on arn:aws:s3:::my-bucket/* and s3:ListBucket on arn:aws:s3:::my-bucket, and nothing else. Validate by generating a policy from a test run's CloudTrail activity with IAM Access Analyzer and confirming the role cannot delete objects or touch another bucket. Maintain it by reviewing last-accessed data and deleting actions that have gone unused for 90 days.

Trust policy: trust.json

JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {"Service": "lambda.amazonaws.com"},
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": {"aws:SourceAccount": "123456789012"},
        "ArnLike": {"aws:SourceArn": "arn:aws:lambda:us-east-1:123456789012:function:my-function"}
      }
    }
  ]
}

Permissions policy: perms.json

JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*"},
    {"Effect": "Allow", "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::my-bucket"}
  ]
}

s3:ListBucket applies to the bucket ARN; s3:GetObject applies to object ARNs. Swapping them is a common silent failure: the policy attaches cleanly and every call returns AccessDenied.

Create it

Shell
aws iam create-role --role-name my-function-s3-read \
  --assume-role-policy-document file://trust.json

aws iam create-policy --policy-name s3-read-my-bucket \
  --policy-document file://perms.json

aws iam attach-role-policy --role-name my-function-s3-read \
  --policy-arn arn:aws:iam::123456789012:policy/s3-read-my-bucket

Use a customer managed policy, not an inline one: inline policies on a role are capped at 2,048 characters, customer managed policies at 6,144. The trust policy is also capped at 2,048 characters, which is why the condition block has to stay tight. The function also needs to write logs: attach AWSLambdaBasicExecutionRole or add logs:CreateLogStream and logs:PutLogEvents on its log group.

The trust policy is where this goes wrong

Without aws:SourceArn, the trust policy grants sts:AssumeRole to the Lambda service principal globally. Any account that can create a Lambda function and knows the role ARN can point its function at that role and receive your credentials: the confused deputy. The condition binds the trust to one function ARN in one account.

Validation

The IAM policy simulator evaluates identity policies only. It ignores SCPs, permission boundaries, resource-based policies and KMS grants, so a green result there is not proof. Use it to check that s3:DeleteObject and s3:GetObject on another bucket are denied, then confirm in a nonproduction account. IAM Access Analyzer policy generation reads up to 90 days of CloudTrail for the role and emits a policy containing exactly the actions and resources observed: run the function through its real paths first, then diff that against what you wrote. In CloudTrail, an AccessDenied on an action you expected to allow means the policy is too tight (check it isn't an SCP or bucket policy denying instead); an API call that succeeds when you expected a denial means it's too broad.

Maintenance

Action-level last-accessed data covers a rolling 90-day window; service-level covers up to 400 days, and not every service reports it. Pull it with aws iam generate-service-last-accessed-details and remove actions with no activity. Watch CloudTrail for AccessDenied on the role to catch permissions removed too aggressively.

Trade-offs

AWS managed policyCustom policy
ScopeAll resourcesOne bucket, plus conditions
MaintenanceAWS updates itYou review it
ConditionsNoneaws:SourceArn, aws:SourceAccount
RiskSilently widensSilently goes stale

AWS managed policies are updated by AWS, which can change what your role can do without your involvement. Custom policies stay put, but you own the review. Use a managed policy when its scope matches exactly and you accept AWS's update cadence; use custom when you need to pin resources or add conditions.

When custom is wrong: if AWS ships a managed policy that matches the scope exactly, attaching it is less work and less risk than maintaining your own. In a multi-account setup, SCPs and permission boundaries are guardrails (they cap the maximum permissions, they don't grant any) so you still create a role per account; use IAM Identity Center permission sets to roll the same policy out everywhere rather than hand-editing each account.

Failure modes

  • "Action": "s3:*" on "Resource": "*": the function can delete buckets and read every object in the account. Detected by Access Analyzer policy validation and by unused-access findings. Cost: a compromised function destroys or exfiltrates data.
  • Trust policy with no source condition: any account's Lambda that knows the role ARN can assume it. Detected by an Access Analyzer external-access finding on the role. Cost: cross-account privilege escalation.
  • Stale permissions: s3:DeleteObject stays attached after the code stopped deleting. Detected by last-accessed showing no activity for 90 days. Cost: a wider blast radius than the function needs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Give a Kubernetes workload access to one cloud storage bucket.

Answer

What I'd say first

Assume EKS, bucket and cluster in the same AWS account, app uses the AWS SDK. The answer is workload identity, not keys: give the pod a projected OIDC token, let STS exchange it for short-lived credentials scoped to one role, and scope that role's trust policy to the exact namespace and service account.

Concretely: create an IAM role whose trust policy accepts sts:AssumeRoleWithWebIdentity only from the cluster's OIDC provider with sub equal to system:serviceaccount:payments:reporter and aud equal to sts.amazonaws.com. Attach an identity policy allowing s3:GetObject and s3:PutObject on arn:aws:s3:::acme-reports-prod/incoming/* and nothing else. Annotate the service account with the role ARN. No Secret, no key rotation.

Why it works

  1. Pod starts; the EKS pod-identity webhook injects AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE=/var/run/secrets/eks.amazonaws.com/serviceaccount/token.
  2. That file is a projected service account token: a JWT signed by the cluster's OIDC provider, default expirationSeconds 86400.
  3. The SDK calls sts:AssumeRoleWithWebIdentity. STS fetches the provider's JWKS, verifies the signature, and evaluates the trust-policy conditions.
  4. On match it returns temporary credentials, default lifetime 3600 s, which the SDK caches and refreshes before expiry.

The token is bound to the pod's identity, so a stolen token is useful only until it expires and only for that one role.

Trust policy

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {
      "Federated": "arn:aws:iam::111122223333:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE"
    },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {
        "oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE:sub": "system:serviceaccount:payments:reporter",
        "oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE:aud": "sts.amazonaws.com"
      }
    }
  }]
}
YAML
apiVersion: v1
kind: ServiceAccount
metadata:
  name: reporter
  namespace: payments
  annotations:
    eks.amazonaws.com/role-arn: arn:aws:iam::111122223333:role/acme-reports-writer

Alternatives

ApproachWhat the pod holdsBlast radius if the pod is compromisedWhen it's right
Static keys in a SecretLong-lived AKIA keyEverything the key can do, until someone rotates it; leaks via etcd, CI, logsNever for new work
Node instance profileNode role creds via IMDSEvery pod on the node, including ones you don't ownSingle-tenant nodes only
IRSAProjected OIDC token, exchanged for 1 h credsOne role, one namespace/SAEKS, per-workload
EKS Pod IdentityToken from the pod identity agentOne role, one SAEKS, avoids per-cluster OIDC trust edits
GKE Workload IdentityMetadata-server tokenOne GSAGKE

Failure modes

FailureHow it shows upDetection
Trust policy sub wildcarded to system:serviceaccount:*:*Any SA in the cluster can assume the roleaws iam get-role; CloudTrail AssumeRoleWithWebIdentity with an unexpected sub
Permissive bucket policy grants the same accessTightening IAM changes nothingaws s3api get-bucket-policy; test with a role that should be denied
OIDC provider deleted or recreated after a cluster rebuildPods fail with InvalidIdentityTokenSDK error in pod logs; aws iam list-open-id-connect-providers
SSRF in the app reads the token fileAttacker mints creds from outside the clusterCloudTrail AssumeRoleWithWebIdentity from an unexpected source IP; NetworkPolicy egress

On GKE the same shape applies with iam.gke.io/gcp-service-account and roles/iam.workloadIdentityUser; on EKS, Pod Identity does the same exchange through the pod identity agent and skips the per-cluster OIDC trust edits.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Decide between a stored secret and cloud IAM for service access.

Answer

Assumptions. The workload runs on a cloud with an identity provider (EKS, GKE, AKS, a VM, or a function) and the target is a cloud service or SaaS that validates a token the platform mints. If the target only accepts a static API key, the choice is already made and the question becomes how to store it.

The rule. Use workload identity when the target validates a platform-minted token. Otherwise store a secret in a managed secret store. The reason is blast radius: a federated credential is bounded by a trust policy and expires in an hour; a static key is valid until a human rotates it.

Federated identityStored secret
Credential lifetime1h STS session, 24h projected tokenuntil rotation (90d typical)
What bounds ittrust policy sub/aud conditionsIAM resource policy on the secret ARN
Lands on disknoyes, in the store and in process memory
Revocationremove the trust policy entryrotate; old value stays valid until upstream revokes
Works withOIDC-aware targetsanything with an API key

Worked trace: EKS pod → STS. Pod checkout-7d9f in namespace payments runs as service account checkout. kubelet projects a token at /var/run/secrets/eks.amazonaws.com/serviceaccount/token. Decoded claims:

JSON
{
  "aud": ["sts.amazonaws.com"],
  "iat": 1735603200,
  "exp": 1735689600,
  "sub": "system:serviceaccount:payments:checkout",
  "iss": "https://oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE"
}

exp - iat = 86400: 24 hours, refreshed by kubelet before expiry. The SDK posts those claims to sts:AssumeRoleWithWebIdentity with DurationSeconds=3600. STS checks the role's trust policy:

JSON
{
  "Effect": "Allow",
  "Principal": {"Federated": "arn:aws:iam::111122223333:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE"},
  "Action": "sts:AssumeRoleWithWebIdentity",
  "Condition": {
    "StringEquals": {
      "oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE:sub": "system:serviceaccount:payments:checkout",
      "oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE:aud": "sts.amazonaws.com"
    }
  }
}

Both conditions must match the token's sub and aud. On a match STS returns ASIA… credentials with Expiration = now + 3600. Nothing reusable is written to disk. Point the pod at service account billing instead and sub no longer matches: the call fails with AccessDenied, which is the whole point.

GCP maps the same projected token to a service account and issues 1-hour access tokens. Azure Managed Identity fetches from IMDS at 169.254.169.254 with roughly an 8-hour token and no secret at all.

When the target can't federate (a SaaS with a static API key, a legacy database) put the secret in Secrets Manager or Vault. One secret per workload per environment, an IAM resource policy on the secret ARN naming the task role, and a KMS key whose policy admits only that role and the rotation role. Secret storage is not authorization: the IAM policy on the secret ARN is what stops the billing service from reading the payments key.

Failure modes.

  1. Trust policy too loose. A sub condition of * or repo:org/* lets any pod in the cluster assume the role. Detect by diffing aws iam get-role in CI and alerting on CloudTrail AssumeRoleWithWebIdentity events whose sub isn't the expected service account. Cost: lateral movement across every workload sharing the cluster.

  2. Token captured at startup. The SDK's web-identity provider re-reads the token file on each refresh, so it rides through the 24h rotation. An app that reads the file once and calls STS itself does not: at t=24h the captured token is expired and every call returns ExpiredToken. Detect on the 403 rate in app logs; fix by re-reading the file per call.

  3. Rotation Lambda failing silently. Secrets Manager emits RotationFailed to EventBridge; with no alarm the secret sits at the old value and the app keeps working, until the upstream revokes the old credential and every instance fails at once. That's a hard outage, not a degraded one.

  4. Vault sealed after a restart. Every dynamic credential request returns 503. Detect on /v1/sys/health. Recovery needs 3 of 5 unseal shares, which is a pager rotation, not an automated fix.

What would change my answer. If the target's OIDC support doesn't actually validate aud or sub, federation is worse than a scoped secret: same blast radius, more moving parts. And for a batch job that runs once a day, a 90-day secret may cost less to operate than standing up an OIDC provider and its trust policy.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Migrate applications away from long-lived cloud access keys.

Answer

Core answer

Assume the workloads are a mix of AWS-hosted compute, on-prem or other-cloud services, and CI jobs, and that the goal is no static secret sitting in config, env vars, or a secret manager a human can read out.

The answer: replace the key with a short-lived credential minted from a workload identity the platform can verify, then prove the old key is unused before revoking it. Pick the mechanism by where the workload runs:

Workload runs onMechanismCredential TTL
EC2 / ECS / EKSInstance profile, task role, IRSASTS default 1 h, up to 12 h
On-prem or another cloudAWS IAM Roles Anywhere (X.509 cert from a trust anchor)1 h default, up to 12 h
GCPWorkload Identity Federation → service-account impersonationAccess token 1 h default
AzureManaged identity, or federated identity credential for GitHub/K8sToken ~1 h

For AWS compute the SDK credential chain already resolves IMDSv2 or container credentials, so the change is removing the static key, not rewriting auth code.

Why this removes the secret

A long-lived key is a bearer secret: whoever reads it authenticates as the workload, and it stays valid until someone rotates it. Federation inverts that. The workload proves identity with something bound to its runtime: an instance metadata document, a Kubernetes projected service-account token, a GitHub OIDC token, a client certificate. STS verifies that assertion against a trust anchor and returns credentials with a TTL. Nothing durable is stored, so there is nothing to exfiltrate from a config file or a leaked CI log.

Trade-offs

Federation is not always right. A vendor appliance that only accepts a static key, or a SaaS integration with no OIDC support, may force a long-lived key. Then keep the key but constrain it: one IAM user per integration, least-privilege policy, scheduled rotation. Managed identity is simpler than federation when the workload already lives inside the cloud, no trust anchor to maintain, but it does not cross cloud boundaries, which is exactly when Roles Anywhere or Workload Identity Federation earns its keep.

Failure modes

  • Trust anchor misconfigured: wrong OIDC audience or condition, so STS rejects the token. Shows up as 403s at first deploy; test in a non-prod account first.
  • Credential chain not updated: the SDK still reads the static key from env, so the new path is never exercised. Confirm by looking for the new role's AssumeRole events in CloudTrail.
  • Silent dependence on the old key: disabling an IAM access key makes it inactive but the key still exists. A workload still using it fails, which is the point of the observation window.

Observation window

Do not destroy on day one. Set the key to Inactive, then watch for 30 days: long enough to cover monthly batch jobs. Quarterly jobs need 90+ days. Use GetAccessKeyLastUsed and the credential report (regenerated every 4 hours) plus CloudTrail to confirm no calls. If a call appears, re-enable, fix the caller, restart the clock. Only after a clean window, delete the key and purge copies from secret managers, CI variables, and config repos.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design SAML or OIDC federation from your workforce IdP to cloud IAM roles so that IdP group membership determines scoped permissions. How do you handle a group change, and how do you scope a session down further at assume time?

Answer

Federate, don't sync users. The IdP stays authoritative for group membership; the cloud holds a small set of roles whose permission policies are static, reviewed and scoped. The assertion proves identity, the role carries authorization.

The trust policy cannot read SAML groups. AWS exposes only SAML:aud, SAML:iss, SAML:sub, SAML:sub_type, SAML:namequalifier and SAML:doc as condition keys on sts:AssumeRoleWithSAML. Group-to-role mapping therefore happens in the IdP: it emits the https://aws.amazon.com/SAML/Attributes/Role attribute listing the (role ARN, provider ARN) pairs the user's groups entitle them to. The trust policy's job is to reject assertions that aren't for this provider and this audience:

{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {"Federated": "arn:aws:iam::111122223333:saml-provider/Okta"}, "Action": "sts:AssumeRoleWithSAML", "Condition": {"StringEquals": {"SAML:aud": "https://signin.aws.amazon.com/saml"}} }] }

For OIDC the subject is a usable condition key, namespaced by the provider host: token.actions.githubusercontent.com:sub = repo:acme/deploy:environment:prod, together with aud = sts.amazonaws.com. A wildcard like repo:acme/* hands every repository in the org the role.

IdP groupRoleAssume-time scopeMax session
platform-oncallrole/ProdOncallsession policy: deny outside us-east-11 h
data-engineersrole/DataEngineersession policy: s3:GetObject on analytics/*8 h
contractorsrole/ContractorReadOnlypermission boundary + session policy1 h

Scoping down at assume time. Pass a session policy to AssumeRoleWithSAML/AssumeRoleWithWebIdentity (Policy, or PolicyArns for up to 10 managed policies). It intersects with the role's identity policies and can only subtract: a session policy can never grant. Permission boundaries are the second ceiling. Session tags are the other lever: the IdP emits PrincipalTag attributes, the trust policy grants sts:TagSession, and permission policies condition on aws:PrincipalTag/team. Tags are transitive through role chaining. If sts:TagSession is missing, the assume call fails with AccessDenied: fail closed, but the error is opaque.

Group changes. A session is immutable: its permissions are fixed at issuance. Removing a user from a group changes nothing until the session expires, so set DurationSeconds by sensitivity: 1 h for production admin, 8–12 h for read-only. The ceiling is 43200 s (12 h) for AssumeRoleWithSAML and AssumeRoleWithWebIdentity; role chaining caps at 1 h. For immediate revocation, attach an inline policy that denies when aws:TokenIssueTime is older than a cutoff (the AWSRevokeOlderSessions pattern), which invalidates every session issued before that timestamp.

The silent failure is group-name reuse: a renamed group drops its mapping (fail closed, users notice), but a recycled name grants its new members the old role. Treat group names as owned identifiers and audit them. Detect with CloudTrail AssumeRoleWithSAML/AssumeRoleWithWebIdentity events, requestParameters.principalTags and the assumed role ARN, alerting on first-seen group/role pairs and on assumptions by principals whose group should not map there.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design cross-account access for a multi-tenant SaaS vendor.

Answer

Assumptions before answering: the vendor runs in its own AWS account and calls APIs inside the customer's account; the customer will not hand over static credentials; AWS IAM/STS, trust policy Version 2012-10-17. If the integration touches one service that supports resource policies, there is a real alternative: see the last section.

Core (about 90 seconds). The customer owns the role, so the customer owns revocation. Its trust policy names the vendor's broker role ARN as principal and requires a per-customer sts:ExternalId that the vendor generated for that one account. The vendor keeps that ID in its tenant record and passes it on every AssumeRole. The role's permission policy carries only the actions and resource ARNs the integration needs, and sessions are short. Nothing long-lived leaves the customer account, and cutting access means deleting the role or editing its trust policy.

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"AWS": "arn:aws:iam::111122223333:role/vendor-broker-prod"},
    "Action": "sts:AssumeRole",
    "Condition": {"StringEquals": {"sts:ExternalId": "9f2c41d7ab8e4f0c9d3a6b1e5c7f802d"}}
  }]
}

Why each control is load-bearing. Naming the exact role rather than the account matters because Principal arn:aws:iam::111122223333:root means any principal in that account holding sts:AssumeRole. A leaked credential, or a role the vendor adds next quarter, inherits the trust. The external ID works only if the vendor reads it from the authenticated tenant's stored record, never from the role ARN in the request. Keyed off the request, an attacker who names Customer A's role makes the vendor pass A's ID and A's policy accepts. Keyed off the tenant, the same request carries B's ID and A's trust policy rejects it:

  1. Tenant B asks the vendor to operate on Customer A's role ARN.
  2. The vendor authenticates B, loads B's stored external ID, and calls sts:AssumeRole against A's role.
  3. A's trust policy requires sts:ExternalId to equal A's value, so STS returns AccessDenied and B never reaches A's account.

External IDs are identifiers, not secrets: 128 bits of random, never the account ID or the customer's domain.

Failure modes, and how they surface.

  • External ID derived from the account ID or domain: guessable, and the control collapses. Audit stored IDs for entropy at onboarding.
  • Trust widened later by a support engineer adding root or a second principal: IAM Access Analyzer external-access findings, plus an alert on UpdateAssumeRolePolicy.
  • Revocation lag: a session stays valid until it expires, so MaxSessionDuration is the worst-case revocation window. Default 3600 s, request DurationSeconds 900 for one-shot jobs, and role chaining caps any session at 1 hour regardless.
  • Static keys offered as a shortcut: no expiry, and one leak is a permanent cross-tenant compromise. Refuse it rather than compromise on it.

Operations. CloudTrail records sts:AssumeRole and every later call under the assumed-role session ARN. Alert on first-time (tenant, role) pairs, unexpected source IP or region, and sensitive actions outside the integration's normal shape. Vendor-side, log the (tenant, target role, external ID) triple and alert on mismatches. Put the revocation runbook and incident contact in the onboarding doc, and re-review trust and permissions when the integration's scope changes.

Alternatives and when they win.

designwins whencosts
customer-owned role + external IDthe vendor needs several services or a broad surface in the customer accountper-customer role setup; the vendor runs a broker and maps external IDs to tenants
resource-based policy on each targetone service, one or two resourcespolicy sprawl, every new resource needs one, no central revocation
customer-created IAM user with access keysnothing on modern AWSshared secret, no expiry, no per-tenant binding
VPC endpoint / PrivateLink between the partiespinning the network pathconstrains the path, not the identity; the confused deputy remains

Deciding rule: role plus external ID when the vendor needs a broad or multi-service surface in the customer account; resource policies when one service is involved and you would rather have no standing role.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Prevent accidental public or cross-organization data access.

Answer

Assumptions: AWS, resources spread across accounts inside one AWS Organization. "Cross-organization" means any principal whose account is not in your org ID. If you're on GCP or Azure the same shape holds with org policies and iam.allowedPolicyMemberDomains, but the specifics below are AWS.

Core answer (say this in the first 90 seconds): Two layers. Preventive: an SCP at the org root that denies the calls which create public access, aws:PrincipalOrgID in every resource policy so only your org can reach the resource, and S3 Block Public Access enabled at the account level. Detective: IAM Access Analyzer for external access, plus a CI gate that runs policy validation on every bucket, KMS, SQS and SNS policy change so a PR that widens access fails the build. Exceptions go through one break-glass role with an owner and an expiry tag.

Preventive: SCP at the org root. SCPs filter, they never grant, and they apply to principals in member accounts (not the management account, not service-linked roles). Deny the mutation calls outright except for the break-glass role:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "DenyPublicAccessMutation",
    "Effect": "Deny",
    "Action": [
      "s3:PutBucketPolicy",
      "s3:PutBucketAcl",
      "s3:DeletePublicAccessBlock",
      "s3:PutAccountPublicAccessBlock"
    ],
    "Resource": "*",
    "Condition": {
      "ArnNotLike": {"aws:PrincipalArn": "arn:aws:iam::*:role/BreakGlassAdmin"}
    }
  }]
}

Preventive: resource policy. Principal: "*" plus a PrincipalOrgID condition is the documented pattern: the policy is public-looking but only resolves for accounts in your org.

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": "*",
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::my-bucket/*",
    "Condition": {"StringEquals": {"aws:PrincipalOrgID": "o-abc123"}}
  }]
}

Detective: Access Analyzer. The external access analyzer is per-account, per-region (or org-wide via a delegated admin). It evaluates resource policies against a zone of trust (the account, or the whole org if you configure it) and reports any resource reachable from outside that zone: S3 buckets, IAM roles, KMS keys, SQS, SNS, Lambda, Secrets Manager, EFS. It reasons over policy, not traffic, so it flags reachability, not actual access. That distinction matters when you triage: a finding is a policy that could be reached, and you still need CloudTrail to know whether it was.

Trade-offs: pick per resource class:

ControlStrengthCost / limit
Org-root SCPCannot be overridden by account admins; one change covers all accountsCoarse; a bad SCP breaks every account at once; doesn't cover non-AWS or resources outside the org
Per-resource policy + PrincipalOrgIDPrecise, per-resourceMust be applied everywhere and drifts as resources are added
S3 Access PointsPer-application policy on one shared bucketExtra endpoint/naming layer; only S3

Use the SCP for the mutation calls, PrincipalOrgID for the data-plane policies, and access points when many teams share one bucket and you want per-team policy without one giant bucket policy.

Failure modes and how you catch them:

  • Confused deputy. A third-party service role assumes into your account; without aws:SourceArn/aws:SourceAccount conditions another customer can point that service at your resource. Access Analyzer flags the cross-account role trust.
  • Open KMS key policy. The bucket is private but the key grants kms:Decrypt to *, so the bucket policy is moot. Access Analyzer covers KMS keys; check them in the same review.
  • Preexisting exposure. Buckets created before AWS turned on Block Public Access by default for new buckets. Inventory with Access Analyzer plus the AWS Config rule s3-bucket-public-read-prohibited.
  • Break-glass abuse. The one role that can widen policy is the one to alert on: EventBridge rule on PutBucketPolicy/PutBucketAcl from that role, page on it.

Monitoring and response. CloudTrail to EventBridge for policy-mutation events, Config rules for drift, and a quarterly anonymous-request test against a known-private bucket to confirm the guardrails still hold. For a confirmed exposure: revoke by re-applying the SCP and the resource policy, rotate any credential the exposed path could reach, then run customer and incident response.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design IAM isolation for tenants in a shared cloud application.

Answer

Assume a multi-tenant SaaS on AWS, tenants are external customers, and we need to isolate data, compute, and control plane. The core answer: derive tenant identity from the authenticated session, enforce it at every layer with cloud-native primitives, and test cross-tenant paths. I'll walk through identity, authorization, data, compute, and operations, then trade-offs and failure modes.

Identity: Use a managed identity provider like Amazon Cognito. When a user logs in, Cognito issues a JWT with a custom claim tenant_id. The application validates the JWT signature and expiry, then extracts tenant_id. Never trust a client-supplied tenant header. For service-to-service calls, use AWS STS AssumeRole with session tags to pass the tenant ID, so the role's permissions are scoped to that tenant. This works because the identity provider is the single source of truth for tenant membership; if a user's membership is revoked, the next token refresh fails.

Authorization: Enforce at two levels. First, cloud IAM: use resource policies with conditions that match the principal's tenant tag to the resource's tenant tag. For example, an S3 bucket policy:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::tenant-data/${aws:PrincipalTag/TenantId}/*",
    "Condition": {
      "StringEquals": {
        "s3:ExistingObjectTag/TenantId": "${aws:PrincipalTag/TenantId}"
      }
    }
  }]
}

This policy allows a principal to read only objects whose TenantId tag matches the principal's TenantId tag. IAM evaluates this at the API call, so even if the application has a bug, the cloud enforces the boundary. IAM policies are deny by default, so any missing allow is a deny. Second, application-level authorization: every database query, cache access, and queue message must include the tenant ID. Use a shared library that injects the tenant ID from the request context into all data access calls. This prevents developers from forgetting.

Data: For the database, choose isolation based on blast radius and cost. A table:

| Strategy | Blast radius | Cost | Operational complexity | When to use | | Shared DB, row-level security | All tenants | Low | Medium | Many small tenants | | Separate schemas | One tenant | Medium | Medium | Moderate tenants | | Separate databases | One tenant | High | High | Compliance needs | | Separate cloud accounts | One tenant | Highest | Highest | Regulated tenants |

Row-level security (RLS) in PostgreSQL, for example, adds a WHERE tenant_id = current_setting('app.tenant_id') to every query. It works because the database enforces the filter, but it adds ~5-10% query overhead and requires careful session variable management. Separate accounts give the strongest isolation because IAM boundaries are at account level, but cross-account calls add latency (e.g., 10-20 ms per call) and account management overhead.

Compute: For workloads, use separate IAM roles per tenant if you have separate accounts, or a single role with tenant-scoped permissions if shared. Never let a workload assume a role that can access all tenants. For example, a Lambda function processing tenant A's data should have a role that can only read from tenant A's S3 prefix and write to tenant A's DynamoDB table. This prevents a compromised function from affecting other tenants.

Operations: Support and operators need elevation. Use just-in-time access with approval (e.g., AWS IAM Identity Center with approval workflows). Log every impersonation and cross-tenant access. Test cross-tenant paths: canary tenants, batch exports, search, backup/restore, replay, and support tools.

Failure modes: A cache key missing tenant ID. If the cache key is user:123:profile instead of tenant:456:user:123:profile, tenant A can read tenant B's cached profile. Detection: deploy a canary tenant that writes a unique value; if that value appears in another tenant's response, alert. Cost: data breach, GDPR fines up to 4% of global revenue. Another: a batch job that exports all tenants' data without filtering. Detection: audit logs show a single job reading across tenants. Cost: data leak, customer churn.

Trade-offs: Use separate accounts when tenants have regulatory requirements (HIPAA, FedRAMP) or when blast radius must be limited to one tenant. Avoid separate accounts when you have thousands of small tenants because account management and cross-account latency become prohibitive. Use RLS when cost-sensitive and tenants are small, but accept the shared blast radius.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Delegate IAM role creation to an application platform team.

Answer

Core answer (first 90 seconds)

Delegation means the platform team gets iam:CreateRole, iam:AttachRolePolicy, iam:TagRole and iam:PassRole scoped to their own path, and nothing that lets them move the ceiling. The ceiling is a permissions boundary: a managed policy attached to every role they create, which caps the role at the intersection of its policies and the boundary. A boundary never grants anything; it only subtracts.

Three things must hold before I'd sign off:

  1. Every role they create carries a named boundary, enforced by the iam:PermissionsBoundary condition key on iam:CreateRole, not by convention.
  2. They can attach only allow-listed managed policies (iam:PolicyARN) and pass roles only to allow-listed services (iam:PassedToService).
  3. They cannot edit the boundary, the SCP, or the roles that administer them.

Assumptions: one AWS Organization, SCPs applied at the OU, the platform team's role is not in the management account (SCPs don't apply there), and the data behind these roles is reachable by resource policies the team doesn't own.

The delegation policy

JSON
{
  "Version": "2012-10-17",
  "Statement": [
    { "Sid": "CreateWithBoundary", "Effect": "Allow",
      "Action": ["iam:CreateRole", "iam:TagRole"],
      "Resource": "arn:aws:iam::111122223333:role/app-platform/*",
      "Condition": {
        "StringEquals": { "iam:PermissionsBoundary": "arn:aws:iam::111122223333:policy/AppPlatformBoundary" },
        "ForAllValues:StringEquals": { "aws:TagKeys": ["env","owner","expires"] } } },
    { "Sid": "AttachApprovedOnly", "Effect": "Allow",
      "Action": "iam:AttachRolePolicy",
      "Resource": "arn:aws:iam::111122223333:role/app-platform/*",
      "Condition": { "StringEquals": { "iam:PolicyARN": [
        "arn:aws:iam::111122223333:policy/AppPlatformReadOnly",
        "arn:aws:iam::111122223333:policy/AppPlatformDeploy" ] } } },
    { "Sid": "PassToApprovedServices", "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "arn:aws:iam::111122223333:role/app-platform/*",
      "Condition": { "StringEquals": { "iam:PassedToService": ["lambda.amazonaws.com","ecs-tasks.amazonaws.com"] } } }
  ]
}

The caller also needs iam:PutRolePermissionsBoundary on the new role, or the boundary isn't set. Inline policies (iam:PutRolePolicy) have no ARN to condition on, so allow them on their own path and let the boundary cap them.

What actually breaks

  • Trust policy is unconstrained. No condition key inspects AssumeRolePolicyDocument. A team can create a role trusting arn:aws:iam::999988887777:root. The boundary caps what the role can do, not who can assume it. Mitigation: IAM Access Analyzer external-access findings on the account, alerted on, plus a CloudTrail metric filter on CreateRole/UpdateAssumeRolePolicy carrying a principal outside the org. If that window is unacceptable, don't grant iam:CreateRole at all: put creation behind a reviewed pipeline.
  • Resource policies bypass the boundary. A boundary caps identity-based permissions only. If the team can call s3:PutBucketPolicy, they can grant their role access the boundary denies. Cover the resource side or the cap is decorative.
  • Service-linked roles. They can't carry a permissions boundary, and SCPs don't restrict them. iam:CreateServiceLinkedRole is a separate permission: grant it per reviewed service.
  • Boundary edits. iam:CreatePolicyVersion on the boundary policy raises their own ceiling. Keep the boundary under a different admin role and deny CreatePolicyVersion/SetDefaultPolicyVersion on it.

Choosing the model

ModelWho writes the trust policyTime to first roleFails when
Central IAM team creates every roleCentraldays (ticket queue)role volume outgrows the queue
Delegated with boundary (above)Platform teamminutesyou can't tolerate the external-trust window
Self-service via reviewed pipelineTemplate, reviewed centrallyhoursteams need roles faster than review

The deciding criterion is the trust-policy question. If external trust is a real risk for the data behind the role, only the pipeline model closes it, because review happens before the role exists. SCPs are capped at 5,120 characters and apply per-OU, which is why the per-team cap belongs in a boundary rather than an SCP.

Verification

Run CheckNoNewAccess in IAM Access Analyzer in CI on every change to the boundary and the delegation policy; it fails the build if the new policy grants access the reference doesn't. Then a negative test: assume the platform team's role and try CreateRole without the boundary, AttachRolePolicy with AdministratorAccess, and PassRole to ec2.amazonaws.com. All three must return AccessDenied. If any succeeds, the guardrail is wrong, not the test.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design organization-wide IAM deny guardrails.

Answer

What I'd say first. Assume AWS Organizations with all features on, ~120 accounts in OUs by environment (sandbox, dev, prod, security). I'd ship four SCPs attached at the root and inherited by OUs, with every exception kept out of the policy body: a deny in an SCP cannot be overridden by any allow in an identity policy, permissions boundary or session policy. Effective permission is the intersection of SCP, identity policy, boundary and session policy: SCPs subtract, they never grant, so the default FullAWSAccess attachment is what keeps accounts usable. A deny anywhere from root to account short-circuits the request, including for the member account's root user and for account admins.

Holes to design around. The management account is never filtered by SCPs, so break-glass lives there and it holds no workloads. Service-linked roles are exempt too: denying ec2:TerminateInstances does not stop Auto Scaling's service-linked role from terminating an instance, so guardrails must bite human and CI principals, not the service path. And SCPs filter only principals inside your accounts, so an anonymous S3 GET isn't blocked by one, which is why the exposure guardrail denies the write path (s3:PutBucketPolicy, s3:PutBucketAcl), not reads.

GuardrailDenyFailure mode it stopsBlast radius
No escape from the orgorganizations:LeaveOrganizationan admin detaching itself from guardrailsnone
Audit trail append-onlycloudtrail:StopLogging, cloudtrail:DeleteTrail, cloudtrail:UpdateTrail, logs:DeleteLogGroupcovering tracks mid-incidentlegitimate trail edits must route through the security account
No public data or computes3:PutBucketPolicy, s3:PutBucketAcl, ec2:RunInstances when ec2:AssociatePublicIpAddress is truepublic bucket, exposed instancebreaks launch templates that set public IPs; the condition key is present only when the parameter is in the request, so subnet auto-assign must also be off
No long-lived keysiam:CreateAccessKey, iam:CreateUser, iam:CreateLoginProfileunrotatable credentialsbreaks legacy automation; exception per principal with expiry
No key destructionkms:ScheduleKeyDeletion, kms:DisableKeycrypto-deletion of backupsreal decommissioning needs a carve-out

Policy shape, one craftable file inside the 5,120-character limit:

{"Version":"2012-10-17","Statement":[
 {"Sid":"DenyOutsideApprovedRegions","Effect":"Deny","Action":"*","Resource":"*",
  "Condition":{"StringNotEquals":{"aws:RequestedRegion":["us-east-1","eu-west-1"]}}},
 {"Sid":"DenyOrgLeave","Effect":"Deny","Action":"organizations:LeaveOrganization","Resource":"*"},
 {"Sid":"DenyAuditTamper","Effect":"Deny","Resource":"*",
  "Action":["cloudtrail:StopLogging","cloudtrail:DeleteTrail","cloudtrail:UpdateTrail"]}]}

IAM, CloudFront, Route 53 and Organizations are global and evaluate as us-east-1, so that region stays in the list or all four break.

Trace of one blocked call. A prod admin calls cloudtrail:StopLogging. Identity policy: allow. Boundary: none. SCP chain: root FullAWSAccess allows, the OU's ProtectAudit denies. Result: AccessDenied ... with an explicit deny in a service control policy: arn:aws:organizations::111122223333:policy/o-abc/service_control_policy/p-xyz. The message names the SCP, so on-call doesn't hunt for it; CloudTrail records the same errorCode and an EventBridge rule matching errorMessage containing "explicit deny in a service control policy" pages the platform team. Unblocking requires organizations:UpdatePolicy from the management account.

Exceptions never take the form of a second allow statement, because the deny wins. Carve-outs go in the deny's own Condition (ArnNotLike on aws:PrincipalArn, or an exact aws:SourceArn) each with an owner and a 90-day expiry. Roll out to the sandbox OU first, wait a few minutes because propagation isn't instantaneous, then re-test the denial before promoting the policy up the OU tree; rollback is one DetachPolicy call.

Two failures I'd expect on day one: an action allowlist that blocks iam:CreateServiceLinkedRole stops RDS and ECS provisioning, and a deny keyed on a condition key absent from the request, such as MFA age, denies traffic you meant to allow.

Azure's equivalent is management-group-scoped Azure Policy with effect deny; RBAC deny assignments aren't user-creatable, they come from Deployment Stacks denySettings. GCP uses org policy constraints plus IAM deny policies with exceptionPrincipals.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Enforce separation of duties for production changes.

Answer

Core answer

Assume a cloud-hosted service with a CI/CD pipeline, humans and workload identities both acting as principals, and a break-glass path that has to exist. Separation of duties means no single principal can complete a high-impact production change end to end: the identity that authors a change cannot be the identity that approves and executes it. Enforce it at the control plane (IAM policies, SCPs, branch protection, admission controllers) not in a runbook, because a process control fails silently the first time someone is on call alone.

Why it works

SoD works by removing the single principal that holds every permission in a toxic combination. The classic AWS escalation is iam:PassRole plus lambda:CreateFunction plus lambda:InvokeFunction: a developer who can pass a role to Lambda can run code as that role. Splitting those permissions across a human role and a deploy role breaks the chain, because neither principal alone reaches the end state.

Toxic combinationWhy it escalatesControl that breaks it
iam:PassRole + lambda:CreateFunction + lambda:InvokeFunctionRun code as any passable roleDeploy role not passable by the developer role; SCP denies iam:PassRole outside CI
Code approval + deployAuthor approves own changeGitHub Environment required reviewers; CODEOWNERS on the deploy path
Role creation + permission-boundary removalCreate an admin role without a boundarySCP denies iam:DeleteRolePermissionsBoundary and iam:CreateUser outside the break-glass OU
Payment creation + payment approvalUnilateral money movementDistinct groups; approval quorum of 2

Worked trace

Developer session, prod deploy:

$ aws sts get-caller-identity
{ "Arn": "arn:aws:iam::111122223333:user/dev-alice" }
$ aws lambda update-function-code --function-name payments --zip-file fileb://x.zip
An error occurred (AccessDenied) when calling the UpdateFunctionCode operation:
User: arn:aws:iam::111122223333:user/dev-alice is not authorized to perform:
lambda:UpdateFunctionCode on resource: arn:aws:lambda:us-east-1:111122223333:function:payments

The CI role arn:aws:iam::111122223333:role/ci-deploy holds lambda:UpdateFunctionCode and is assumed only via GitHub OIDC with sub restricted to repo:org/payments:environment:prod. The developer role cannot sts:AssumeRole it and cannot iam:PassRole it.

Break-glass and logging

Emergency override is a role with MaxSessionDuration set to 1 hour (the default) and an SCP that denies everything except the incident path; activation posts to the incident channel and opens a ticket. Audit is CloudTrail with log file validation into an S3 bucket with Object Lock in compliance mode: no principal, including root, can shorten retention. CloudTrail event history alone is 90 days, so ship to the locked bucket for anything longer.

Trade-offs

SoD costs throughput and on-call speed. For a low-blast-radius change, a config flag behind a canary with automatic rollback, a single approver plus automated gates is usually enough; forcing a second human adds latency without reducing risk. The credible alternatives are a two-person rule (strong, slow), an automated policy gate such as OPA Gatekeeper or Kyverno (fast, only as good as the policy), and canary plus auto-rollback (fast, does not stop a determined insider). Pick per change class, not globally.

Failure modes

  • Collusion: two approvers who always approve each other. Detect by measuring approval latency and pair frequency; a median under a minute is rubber-stamping.
  • Indirect route: code execution on a privileged runner. A CI job that runs untrusted PR code on a runner holding prod credentials defeats the split. Detect by checking runner trust boundaries.
  • Break-glass never revoked: alert on any session longer than its window.
  • Membership drift: quarterly review of who is in the deploy group, because staffing changes silently collapse the separation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Introduce just-in-time production administration.

Answer

Just-in-time production administration means you don't hand out standing admin rights. Instead, an engineer requests elevation for a specific task, with a reason and a ticket, and the system grants a short-lived role that expires automatically. The core idea is to shrink the window of privilege. I'm assuming you have an identity provider that supports PIM or IAM Identity Center, and you can enforce MFA. You also need a ticketing system and a SIEM.

In AWS IAM Identity Center, you configure a permission set with a session duration: default 1 hour, max 12. The user requests it, an approver signs off, and they get temporary credentials. In Entra ID PIM, activation requires justification, MFA, and approval; default duration is 1 hour, max 24. Teleport issues short-lived certificates with a default TTL of 12 hours. The key is that the credential itself expires, so even if stolen, it's useless after the window.

Compare that to standing access. A standing admin role is always on. If an attacker steals a token or compromises a laptop, they have permanent admin. JIT shrinks that to the remaining session time. Here's a table:

DimensionStanding adminJIT admin
DurationPermanent until revoked1 hour default, max 12 hours (AWS)
ApprovalNone after initial grantTicket + MFA + approver
Blast radiusStolen token = permanent adminStolen token = admin for remaining session
AuditGrant/revoke eventsEvery activation, reason, actions

The trade-off is latency. If you're paged at 3 AM, waiting for approval is painful. You can pre-approve on-call engineers for specific roles, or use break-glass accounts with heavy monitoring. JIT is not for read-only observability: that can stay standing. It's for mutating privilege. Also, JIT can be bypassed if people create local admin accounts. So you need to detect and remove standing assignments.

Failure modes: Expiry mid-incident. Your session dies while you're debugging. Detection: alert on session expiry during an active incident. Mitigation: allow extension with re-approval, or set longer duration for on-call. Approval bottleneck: approver unavailable. Measure time from request to approval; if p95 > 5 minutes, you have a problem. Shadow admin: engineers create local users to avoid JIT. Detection: scan for local admin accounts, monitor IAM changes. Blast radius: if a JIT session is compromised, attacker has admin for the duration. Detection: anomalous API calls from that session. Mitigation: short duration, MFA, session recording.

Here's some arithmetic. Suppose 100 engineers hold standing admin. Each has a 1% annual compromise risk. You expect 1 compromise per year. With JIT, if each uses admin for 1 hour per week, total exposure is 100 * 52 = 5,200 hours vs 100 * 8,760 = 876,000 hours. That's a 168x reduction in the window an attacker can use a stolen token. (Hypothetical figures.)

What would change my decision? If you have a very small team with high trust and no compliance requirement, JIT might be overkill. If you have a 24/7 follow-the-sun on-call, you might need pre-approved JIT for on-call. If the cost of approval latency exceeds the risk reduction, consider a hybrid: standing read-only, JIT for write.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Design break-glass access for a cloud control-plane outage.

Answer

Assumptions. AWS control plane, workforce identity federated through Okta or Entra into IAM Identity Center. "Control-plane outage" means the IdP or the federation path is down, not that every AWS API is down. If IAM and STS themselves are unavailable, no credential works and you are waiting on AWS. Break-glass is for the former.

Core answer (first 90 seconds). Two IAM users in a dedicated AWS account, no access keys, console password plus a FIDO2 hardware key, each half stored in a separate physical safe. They can assume a BreakGlassAdmin role in production with DurationSeconds=3600. CloudTrail plus an EventBridge rule pages security on any ConsoleLogin or AssumeRole by those principals. Test quarterly by retrieving both halves and running a read-only call, then rotate. That is the design.

Why it works. Federation fails because sts:AssumeRoleWithSAML needs a signed assertion from the IdP and a working STS. A local IAM user with a password does not. Split custody gates login because the password and the hardware key sit in different safes; one person cannot authenticate alone. The role trust policy pins aws:PrincipalArn to the two users and requires aws:MultiFactorAuthAge under 3600. Permissions are not AdministratorAccess: allow only iam:UpdateSAMLProvider, iam:UpdateAssumeRolePolicy, organizations:Describe*, cloudtrail:StartLogging; deny iam:CreateUser and iam:DeleteTrail. TTL is 1 hour because the IAM role maximum is 12 hours (43200 seconds); 1 hour limits exposure.

Options and deciding criteria.

DesignWorks when IdP downStanding riskDeciding criteria
Separate IAM user + roleYesLong-term password existsYou need console access to fix federation
Break-glass role assumed via separate accountYes if that account has its own non-federated userCross-account trust to auditYou want no long-term creds in the prod account
AWS Support escape hatchNo: Support cannot issue IAM credentialsNoneBilling or account recovery only, not control plane
Azure emergency access accountsYesCloud-only accounts excluded from Conditional AccessEntra control plane
GCP super admin / Cloud IdentityYesSeparate identity outside federationGCP org policy recovery

Failure modes and detection.

  • An SCP denies sts:AssumeRole for the break-glass role. Detection: quarterly test fails with AccessDenied and CloudTrail shows no AssumeRole. Fix: exclude the break-glass account from the SCP or add an explicit allow.
  • Hardware key lost. Detection: physical safe audit. Second key lives in a separate safe; if both are lost you are locked out, which is why two keys and two safes exist.
  • Alert fatigue: test logins page security. Detection: if the test alert is not acknowledged within 5 minutes, the alarm is broken. Use a separate SNS topic with a distinct pager.
  • Break-glass role compromised. Detection: GuardDuty Stealth:IAMUser/CloudTrailLoggingDisabled or AWS Config cloudtrail-enabled noncompliant. Response: rotate password and revoke role sessions with a deny on aws:TokenIssueTime before the incident.

Worked trace.

  1. Okta SAML endpoint returns 503.
  2. Incident commander and security lead retrieve the password from safe A and the FIDO2 key from safe B.
  3. Sign in to https://123456789012.signin.aws.amazon.com/console as bg-1, MFA with the key.
  4. aws sts assume-role --role-arn arn:aws:iam::123456789012:role/BreakGlassAdmin --role-session-name bg-1 --duration-seconds 3600.
  5. CloudTrail records ConsoleLogin and AssumeRole; the EventBridge rule pages security.
  6. Operator runs aws iam update-saml-provider --saml-metadata-document file://okta.xml.
  7. Session expires at 1 hour; password rotated; CloudTrail reviewed within 24 hours.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Secure a CI/CD pipeline that deploys production infrastructure.

Answer

Use OIDC federation between your CI provider and cloud to get short-lived credentials. No long-lived keys. Restrict the trust policy to the exact repo, branch, and environment. For GitHub Actions to AWS, the trust policy condition looks like:

JSON
"Condition": {
  "StringEquals": {
    "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
  },
  "StringLike": {
    "token.actions.githubusercontent.com:sub": "repo:myorg/myrepo:ref:refs/heads/main"
  }
}

GitHub Actions OIDC tokens are valid for 5 minutes by default. Set the AWS role session duration to 15 minutes. Separate plan and apply: plan runs with read-only, apply requires approval via a protected environment. Grant least privilege: e.g., s3:PutObject on arn:aws:s3:::my-bucket/*, not s3:*. Constrain iam:PassRole to only the roles the pipeline needs, with condition iam:PassedToService restricted to specific services. Protect the pipeline definition: branch protection, required reviews, signed commits. Sign artifacts and verify before deploy if you have multiple consumers or regulatory requirements; if you have a single pipeline and trust the runner, you can skip signing but then you must harden the runner (ephemeral, network-restricted).

Failure modes

  1. Overly permissive OIDC trust policy: repo:myorg/* lets any repo assume the role. Detect via CloudTrail AssumeRoleWithWebIdentity events with unexpected sub values. Cost: monitoring and alerting.
  2. Artifact tampering: attacker modifies artifact after build. Detect via signature verification failure at deploy. Cost: signing infrastructure and key management.
  3. Runner compromise: attacker steals OIDC token. Detect via anomalous API calls from the role. Mitigate with ephemeral runners and network restrictions.
  4. Emergency path abuse: break-glass credentials used without audit. Detect via separate logging and alerting.

Tradeoffs

ApproachCredential lifetimeAttack surfaceWhen to use
OIDC federation5–15 minTrust policy misconfigurationCloud provider supports OIDC; standard for GitHub/GitLab
Static keys in secrets managerRotated every 90 daysKey leakage, rotation gapsLegacy systems without OIDC
Broker with mTLS1 hourBroker compromiseMulti-cloud, no native OIDC

OIDC eliminates long-lived secrets but requires cloud provider support and correct trust policy configuration. Static keys are simpler but risk leakage. Use OIDC when possible; if not, use a secrets manager with rotation and strict access. Artifact signing: use when you have multiple deployment targets or regulatory compliance; skip if you have a single trusted pipeline and no external consumers, but then you rely on runner integrity.

Validate plans and policies with OPA/Conftest before apply. Log all assumption and changes to a central account. Test rollback in staging. Keep a break-glass role that requires two-person approval and logs to a separate account; use it only when the normal pipeline is down.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Create a portable IAM model for a multi-cloud service.

Answer

Portable here means one intent model, three native encodings, one audit spine, not one policy language. Assume AWS, GCP and Azure, one workload identity per service per environment, and no shared long-lived credentials.

Intent model. Every grant is a tuple: principal (workload or human), action, resource, environment, conditions. Encode it natively; never translate policy JSON between providers.

IntentAWSGCPAzure
PrincipalIAM role + trust policy (OIDC/SAML)service account + Workload Identity Federation poolmanaged identity or app registration federated credential
Grantidentity policy ∧ resource policy ∧ permission boundary ∧ SCP ∧ session policy: all must allowIAM allow binding, unioned up the resource hierarchyRBAC role assignment, inherited down the hierarchy
Denyexplicit Deny in any policy winsIAM deny policy, evaluated before allowdeny assignment from Azure Policy overrides
ConditionCondition block (aws:PrincipalOrgID, aws:SourceVpce)CEL on the binding (resource.name.startsWith, request.time)role-assignment condition (ABAC) + Azure Policy
JITSTS AssumeRole, default 1 h, max 12 himpersonation, token 1 h, up to 12 hPIM eligible assignment, activation default 8 h
Boundarypermissions boundarynonenone (deny assignment is closest)

Federated sessions: AWS AssumeRoleWithWebIdentity defaults to 1 h, capped by the role's MaxSessionDuration (12 h); GCP STS token exchange defaults to 1 h, up to 12 h; an Azure federated credential yields a token with the default 1 h access-token lifetime.

The mechanism that bites: an AWS resource policy can grant cross-account directly. A bucket policy naming another account's role is a grant path GCP does not have, because GCP bucket IAM is the same binding model at a lower resource. GCP bindings are purely additive up the hierarchy, so roles/storage.objectViewer at project level silently covers every bucket; the only subtraction is a deny policy. Azure is additive down the hierarchy, and the only subtraction is a deny assignment, which the portal does not render next to the role assignment.

Trace one intent. svc-payments in prod reads ledger/*.

  • AWS: SCP filters → identity policy allows s3:GetObject → boundary allows → no explicit deny → allow. Same-account reads need no bucket policy.
  • GCP: bindings at bucket, project, folder and org are unioned; the project deny policy is evaluated first; the binding condition must evaluate true → allow.
  • Azure: Storage Blob Data Reader at storage-account scope inherits down; a deny assignment at management-group scope overrides → allow.

Failure modes.

  1. AWS role created by CI without a permission boundary. A principal holding iam:CreateRole + iam:AttachRolePolicy attaches AdministratorAccess. Detect: CloudTrail AttachRolePolicy where requestParameters.policyArn ends in AdministratorAccess and the role has no boundary; IAM Access Analyzer unused-permissions findings. Cost: account takeover.
  2. GCP condition resource.name.startsWith("projects/_/buckets/payments-prod"), no trailing slash, also matches payments-prod-backup. Detect: Policy Analyzer query on the binding; audit log google.iam.v1.IAMPolicy.SetIamPolicy. Cost: cross-bucket read.
  3. Azure PIM activation with no approval or MFA requirement is standing access in practice. Detect: Activity Log Microsoft.Authorization/roleAssignments/write showing eligible vs active; az role assignment list --all --assignee. Cost: audit finding, not a breach, until it is.

What to test. Per provider: positive (intent grants) and negative (adjacent resource denied, expired token denied, cross-tenant principal denied). One exception record per divergence, one audit correlation key, the intent ID, stamped into CloudTrail, Cloud Audit Logs and Azure Activity Log. Re-run the suite when a provider changes evaluation semantics: GCP deny policies and Azure ABAC conditions both landed after most multi-cloud designs were written.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Detect and remediate permission drift.

Answer

The 90-second answer

Drift is any gap between the permissions you reviewed and the permissions that are effective right now. Two assumptions decide the whole plan: humans get access through IAM Identity Center permission sets rather than IAM users, and intended state lives in Terraform, so "reviewed" means merged and applied. If either is false (a legacy account with hand-built IAM users, say) the detection plan changes, so say so up front.

The answer is three loops. Detect from two directions, because neither alone works: CloudTrail tells you what changed, a periodic full-state comparison tells you what is. Triage by blast radius, where external reachability and privilege escalation outrank "policy differs from code". Remediate on a ladder: auto-revert only changes covered by a tested invariant, quarantine the rest with an explicit deny, hand the remainder to an owner with a clock.

Detection: two directions

SignalSourceCadenceCatches
API-visible changesCloudTrail → EventBridgenear-real-time; CloudTrail delivery averages about 5 minconsole edits, new admin grants, trust-policy edits
Current state vs codeAWS Config managed rules + conformance packon configuration change, plus periodic (1 h minimum)policies attached outside code, public bucket policies
External reachabilityIAM Access Analyzer, external accesscontinuous, re-analyzed on policy changeresource policies granting cross-account or public access
Dormant identitiesIAM Access Analyzer, unused accesstrailing 90 days of CloudTrail activityunused roles, permissions, credentials
Full account snapshotaws iam get-account-authorization-detailsnightlyanything the event stream missed

The join key across all of them is the principal ARN. A minimal EventBridge pattern:

JSON
{"source":["aws.iam"],"detail-type":["AWS API Call via CloudTrail"],
 "detail":{"eventName":["AttachRolePolicy","PutRolePolicy","UpdateAssumeRolePolicy","CreatePolicyVersion","PutBucketPolicy"]}}

Worked trace

09:14:02 UTC. An engineer in account 111122223333 runs aws iam attach-role-policy --role-name SupportReadOnly --policy-arn arn:aws:iam::aws:policy/AdministratorAccess. IAM applies it immediately; the role is now admin.

09:14–09:19. CloudTrail delivers the AttachRolePolicy management event. AWS documents an average of about 5 minutes, so budget 5, not 5 seconds.

EventBridge matches, a Lambda fires. It reads the role's tags: managed-by=terraform, no breakglass tag. It reads Terraform state for that role: the allowlist is ReadOnlyAccess plus one inline policy. AdministratorAccess is not in it, so severity is critical. The Lambda calls DetachRolePolicy, confirms with ListAttachedRolePolicies, and opens a ticket carrying the CloudTrail event ID.

09:19:40. Detached. Time to revoke: about 5m38s.

If your policy says critical drift is revoked within 15 minutes, the 5-minute delivery budget leaves roughly 10 minutes for decision and action. Design against that bound. The median you measure in a lab will be under a minute and will make you overconfident.

Remediation ladder

  1. Auto-revert: only when the change is fully described by code, the revert is idempotent, and the invariant has been tested against a known-bad change in a staging account. Example invariant: no principal outside the organization has s3:GetObject on a bucket tagged data-class=restricted.
  2. Quarantine: attach an explicit deny rather than deleting. Deleting a role destroys both the evidence and the rollback; an SCP or a deny-all inline policy stops the access and is one API call to undo.
  3. Owner review: ticket with the diff, the CloudTrail event, and a clock. 24 hours for high, 7 days for low.

Failure modes

  • Auto-revert during an incident. Someone grants admin at 03:00 to end an outage and the Lambda detaches it five minutes later. Fix: a break-glass role with a time-boxed elevation path, tagged and excluded from auto-revert but alerted on every use.
  • Trust-policy edits. UpdateAssumeRolePolicy is the quietest escalation: the role keeps its own permissions, but an external account can now assume it. Put it in the EventBridge pattern and in the periodic comparison.
  • Terraform apply silently reverting the fix. If the console change was correct and the code is stale, terraform apply reverts it and you get a second outage. Run terraform plan -refresh-only first, or plan -detailed-exitcode where exit code 2 means drift, and treat drift as a signal to update code, not only to revert.
  • Dormant-identity cleanup breaking DR. A role used once a year for failover looks unused to a 90-day analyzer. Tag it, exclude it from deletion, review it on a calendar.
  • Alert fatigue. Four thousand findings a week means none get read. Dedupe by (principal, resource, action) and page only on external reachability and privilege escalation.

Metrics

Mean time to revoke, split by detection path; share of drift auto-remediated versus quarantined versus owner-reviewed; drift introduced per week by source: console, CI, or break-glass. That last one tells you which provisioning path to fix. If 80% of drift comes from one team's console habit, the fix is a permission set, not a better scanner.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Test IAM policy as infrastructure code before production.

Answer

The 90-second answer

Assume the policies are generated (Terraform, CDK or CloudFormation) so the artifact under test is the rendered JSON, not the source. Test in three layers, cheapest first, and only pay for the expensive layer when the change earns it.

  1. Static validation, every commit. cfn-lint for the template; aws accessanalyzer validate-policy --policy-type IDENTITY_POLICY --policy-document file://p.json for the policy document itself. Access Analyzer grades findings ERROR, SECURITY_WARNING, SUGGESTION and WARNING: ERROR means the policy is malformed, SECURITY_WARNING means it grants more than it needs. Add org rules in CloudFormation Guard or OPA/Conftest: no Action: "*", no Resource: "*", no iam:PassRole without an iam:PassedToService condition. Seconds per policy.

  2. Table-driven unit tests on the rendered policy. Each row is (principal, action, resource, context) → expected allow/deny, evaluated with iam:SimulatePrincipalPolicy. The rows that matter are the denies: a policy that grants everything passes every allow assertion.

  3. Live integration test in a sandbox account carrying the same SCPs and permission boundaries. Assume the role, call the real API, assert success or failure. Terratest or a script. Minutes per run.

Why layer 3 exists: the simulator answers exactly the question you hand it. It will not tell you that your Lambda calls dynamodb:PutItem on a table you never granted, and it does not reproduce every service's own authorization path. Live calls do.

The test table

actionresourceexpectedwhy
s3:GetObjectarn:aws:s3:::app-data/*allowin-scope prefix
s3:GetObjectarn:aws:s3:::other-team/*denycross-team
iam:PassRole...:role/deployallowPassedToService matches
iam:PassRole...:role/admindenycondition excludes it
sts:AssumeRolearn:aws:iam::999999999999:role/xdenycross-account
Python
import boto3
iam = boto3.client("iam")

def allowed(role_arn, action, resource):
    r = iam.simulate_principal_policy(
        PolicySourceArn=role_arn, ActionNames=[action], ResourceArns=[resource])
    return r["EvaluationResults"][0]["EvalDecision"] == "allowed"

for action, resource, expected in CASES:
    got = allowed(ROLE_ARN, action, resource)
    assert got == expected, f"{action} on {resource}: want {expected}, got {got}"

EvalDecision comes back allowed, explicitDeny or implicitDeny; assert on the exact value, not truthiness.

Where the bugs actually are

Effective permission is (identity policy ∪ resource policy) ∩ SCP ∩ permission boundary ∩ session policy, with explicit deny winning at every layer. Most defects live in the intersection: a statement that is fine alone and dead once the boundary is applied. Test the intersection, not the statement.

The second class is escalation. A role with iam:PassRole on *, lambda:CreateFunction and lambda:InvokeFunction is admin (create a function with the admin role, invoke it) even though no single statement looks wrong. Per-statement lint cannot see this; you need a graph check over the whole policy set.

Other failure modes: testing the source instead of the rendered document, so a for_each or variable silently changes what ships; allow-only suites; and simulator/live drift, where a call passes in simulation and fails because the service evaluates a resource policy or a condition key you never supplied. Detect all three by running the deny-tuple suite in CI, watching Access Analyzer external-access findings, and diffing the plan.

When to skip layer 3

An additive, single-service change with no PassRole is covered by layers 1 and 2. Pay for the sandbox when the policy crosses an account boundary, touches PassRole, or targets a service with its own resource-policy layer: S3, KMS, SQS. Static is seconds; live is minutes plus a sandbox account.

Rollout

Review the plan diff, require approval for any privilege expansion, roll out progressively, monitor denials and Access Analyzer findings, keep rollback ready.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Troubleshoot a conditional IAM policy that behaves inconsistently.

Answer

The first 90 seconds

"Inconsistent" almost always means one thing: the condition key was not in the request context. IAM evaluates every condition against the request, and a missing key is not the same as a wrong value:

expressionkey present, value "finance"key absent
StringEquals aws:PrincipalTag/team = analyticsfalsefalse
ForAllValues:StringEquals aws:PrincipalTag/team = analyticsfalsetrue
ForAnyValue:StringEquals aws:PrincipalTag/team = analyticsfalsefalse
StringEqualsIfExists aws:PrincipalTag/team = analyticsfalsetrue (check skipped)

So I pull the statement that decides the failing call, look at its operator, and ask whether the caller actually carried the key. The assumptions I state up front: same principal type and same policy version across the calls I am comparing. If the split is by caller, it is a tag problem. If the split is by clock, it is propagation or credential lifetime.

Where the key goes missing

  • Session tags are opt-in at assume time (aws sts assume-role --tags Key=team,Value=analytics), and the role's trust policy must allow sts:TagSession. Add tags without that and the AssumeRole call itself fails AccessDenied; a caller that retries untagged looks intermittent.
  • Identity Center maps identity-store attributes onto aws:PrincipalTag; a user whose source attribute is empty sends no tag.
  • Typos such as aws:PrincipalTags/team never match. IAM Access Analyzer policy validation flags unknown condition keys, so run it before debugging by hand.
  • aws:ResourceTag reads the resource, not the caller: it is absent on untagged resources and on actions with no resource-level permission, so the same policy passes for s3:GetObject and silently fails for s3:ListAllMyBuckets.
  • Through a VPC endpoint, aws:SourceIp holds a private address in the VPC, not the caller's public IP. In-VPC callers stop matching an office-NAT allowlist while internet callers keep matching.

The trace

JSON
{"Version":"2012-10-17","Statement":[
 {"Sid":"A","Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::reports-prod/*",
  "Condition":{"StringEquals":{"aws:PrincipalTag/team":"analytics"}}},
 {"Sid":"B","Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::reports-prod/*",
  "Condition":{"ForAllValues:StringEquals":{"aws:PrincipalTag/team":"analytics"}}}]}
request contextABdecision
session tagged team=analyticstruetrueAllow, intended
session tagged team=financefalsefalsedeny
session carrying no team tag at allfalsetrueAllow, the bug
assume-role with --tags and a trust policy lacking sts:TagSessionn/an/aAssumeRole fails; a retry without tags lands in the row above

B was probably written for roles carrying several team tags. On a single-valued key it behaves like StringEquals in every case except the missing one, where it allows.

Fix

Delete B. If the tag is genuinely optional, say so with a Deny, which beats any Allow:

JSON
{"Sid":"DenyUntagged","Effect":"Deny","Action":"s3:GetObject","Resource":"arn:aws:s3:::reports-prod/*",
 "Condition":{"Null":{"aws:PrincipalTag/team":"true"}}}

ForAllValues earns its place only on genuinely multivalued keys, aws:TagKeys in a deny-unless-tagged create rule being the classic one.

The competing fix is to repair the tag source: add sts:TagSession to the trust policy, fill the empty identity attribute, leave the policy strict. The deciding criterion is who owns the missing data. If the tag is supposed to be there, fix the pipeline and keep the policy strict. If it is optional by design, use the Null guard and do not paper over it by forcing the tag to exist. If the tags come from a system another team controls and can be empty, I would drop ABAC at that boundary and use one role per team: a policy per tenant, and no missing-key class of bug.

Reproduce

aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::111122223333:role/AnalyticsReader --action-names s3:GetObject --resource-arns arn:aws:s3:::reports-prod/q4.csv --context-entries ContextKeyName=aws:PrincipalTag/team,ContextKeyType=string,ContextKeyValues=analytics

Run it once more without --context-entries: the response lists aws:PrincipalTag/team under MissingContextValues, the simulator telling you the decision hangs on a key the request may not carry. That pair of runs is the regression test.

When the split is by clock: session tags are frozen at assume time, and DurationSeconds defaults to 3600 and goes up to 43200, so a wrong tag can ride a running session for 12 hours. Re-assume rather than wait. CloudTrail gives you the AssumeRole event with sessionIssuer and creationDate, a separate TagSession event when the session was tagged, and errorCode AccessDenied on the data call, which names no condition, so the context has to be reconstructed by hand.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Deprovision a departing administrator with cloud access.

Answer

Assume the admin has federated SSO plus at least one direct cloud credential: an AWS IAM user or access key, an Azure service principal secret, or a GCP service account key. The clock starts at the HR termination event, not at ticket approval. I run two tracks: freeze authority, then prove it's gone.

Track 1: freeze. For involuntary departure, HR event triggers emergency deprovision in the IdP (Okta, Entra ID). Disable the account and revoke refresh tokens. In Entra ID, "Revoke sessions" kills refresh tokens; access tokens live until expiry, default 1 hour. In AWS IAM Identity Center, remove the user from permission sets and groups. Active role sessions continue until STS expiry: default 1 hour, max 12 hours. Add an explicit deny with condition aws:TokenIssueTime less than the revocation timestamp in the role's identity policy or an SCP. That closes the window without waiting for expiry. For direct IAM users: aws iam delete-login-profile, aws iam update-access-key --status Inactive, then delete keys. For Azure, remove role assignments and disable the service principal. For GCP, suspend the Cloud Identity user and delete user-managed service account keys.

ProviderImmediate freezeSession/token killDirect credential kill
AWSSCP deny with aws:TokenIssueTimeSTS expiry 1h default, 12h maxaws iam update-access-key --status Inactive
Entra IDDisable accountRevoke sessions; access token 1hRemove app secrets/certs
GCPSuspend Cloud Identity userOAuth token 1hgcloud iam service-accounts keys delete

Track 2: remove indirect authority. Search for the principal's ARN/object ID in role trust policies, resource policies, KMS grants, Secrets Manager resource policies, ECR repo policies, S3 bucket policies, Lambda resource policies, SNS/SQS policies, CI/CD service accounts, break-glass accounts. AWS: aws iam get-account-authorization-details, aws accessanalyzer list-findings. Azure: az role assignment list --assignee, Get-AzRoleAssignment. GCP: gcloud asset search-all-iam-policies --query='policyBindings.members:...'. Transfer owned service identities: AWS roles, Azure managed identities, GCP service accounts. Managed identities can't be transferred; recreate and update the resource. That's a failure mode.

Rotate shared secrets they could have read. AWS Secrets Manager rotation, Azure Key Vault new secret version, GCP Secret Manager add version. Revoke certificates via CRL/OCSP. Remove SSH keys from authorized_keys. Rotate CI/CD tokens. Do not rely on KMS key rotation to revoke access: AWS KMS rotation creates new backing keys but retains old ones for decrypt, so change the key policy instead.

Validate. AWS aws iam simulate-principal-policy for each action; Azure az role assignment list; GCP Policy Analyzer. Check CloudTrail, Azure sign-in logs, GCP Admin Activity logs for AssumeRole, GetSessionToken, SignIn after revocation. Review recent privileged changes for persistence: new IAM users, access keys, role trust changes, KMS grants, secrets, VMs, firewall rules. Exfiltration: S3 GetObject, RDS snapshot share, KMS Decrypt, Secrets Manager GetSecretValue.

Trace: T+0 HR event. T+2 min IdP disable. T+5 min revoke sessions. T+10 min remove AWS permission sets. T+15 min SCP deny with TokenIssueTime. T+20 min rotate secrets. T+30 min simulate-principal-policy. T+60 min access tokens expire. Worst-case STS window 12h if no explicit deny.

Tradeoffs: disable vs delete. Disable first to preserve audit and ownership; delete after transfer and evidence. Voluntary vs involuntary: voluntary can schedule, but revoke at end of last day; involuntary immediate. Relying on SSO session expiry is wrong because access tokens live up to 1 hour and AWS STS up to 12 hours. Detection: CloudTrail userIdentity.type = IAMUser or accessKeyId present after deprovision; Azure sign-in logs with success after disable; GCP service account key usage after disable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Define observability and metrics for cloud IAM.

Answer

What I'd say first

I'd scope it before answering: observability for IAM isn't watching identities, it's watching the control plane's decisions. Every authentication, every authorization decision, and every change to the policy that produces them. Assume a multi-account AWS estate, Entra ID for the workforce, EKS workloads using IRSA, and one SIEM. Then I'd split the answer into two metric families: security-outcome metrics that tell you whether the estate is getting safer, and operational metrics that tell you whether your detection and response actually work.

Signals, and where they come from

QuestionSignalSource
Who authenticated?Console/API sign-in, MFA result, source IP/ASNCloudTrail ConsoleLogin, Entra ID interactive + non-interactive sign-in logs
What was allowed?AssumeRole, AssumeRoleWithWebIdentity, service API callsCloudTrail management events
What was denied?AccessDenied / UnauthorizedOperationCloudTrail, GCP Policy Denied logs
What changed?PutRolePolicy, CreateAccessKey, SetIamPolicyCloudTrail, Entra audit logs
What's exposed?External resource sharesIAM Access Analyzer findings

CloudTrail management events are on by default and free, with 90 days of event history in the console; data events (S3 object-level, Lambda Invoke) are off by default and billed. Entra ID keeps sign-in logs 30 days unless you export diagnostic settings to Log Analytics. GCP Admin Activity logs are always on with 400-day retention; Data Access logs are off by default except BigQuery.

Why correlation is the hard part

The same human appears as three different principals. A pod using IRSA calls AssumeRoleWithWebIdentity, so the CloudTrail principal is arn:aws:sts::...:assumed-role/..., not the pod. To tie it back you need the OIDC subject from the request parameters, joined to the deployment that shipped that image. Workforce, workload and deployment identity each land in a different log with a different schema and retention window, so the join key is usually the session-name convention you enforce at issuance, not something the logs give you for free.

Trade-off: volume vs risk alerting

Alerting on raw denial volume is cheap and catches broad probing, but one misconfigured CI job can emit thousands of AccessDenied per minute and bury the signal. Risk-based alerting enriches each event: is the principal privileged, is the resource externally reachable, is the source IP new, and costs you a baseline and enrichment pipeline, and it will miss a quiet, novel attack. The criterion I'd use: alert on absolute volume only for principals with no legitimate denial baseline; for everything else alert on a rate change against that principal's own trailing baseline.

Failure modes

  • Revocation lag. STS session tokens are bearer tokens validated without a call back to IAM, so changing a role's policy does not kill an issued session. Default session duration is 1 hour; you need the aws:TokenIssueTime condition to deny sessions issued before a revocation timestamp, or you're measuring intent, not effect.
  • Log gaps. Non-interactive Entra sign-ins and AWS data events are the two most commonly missing sources; both are off by default.
  • Sensitive context. requestParameters can carry secrets; restrict SIEM access to the raw event.

Worked check

Hypothetical break-glass exercise: detection fires at T+0, responder assumes the break-glass role at T+2 min, revokes the compromised role's policy at T+6 min, but the attacker's session token stays valid until T+58 min. Time-to-revoke measured as "policy changed" reads 6 minutes; measured as "session no longer usable" reads 58. Track the second number.

Curated: · Written: · Reviewed:

Difficulty: Medium