CL·89
Cloud Identity
Identity as the cloud's security perimeter: principals, authentication and authorisation; users, groups and roles; service identities (instance profiles, execution roles, managed identities, service accounts); how IAM policies are written and evaluated (identity and resource policies, conditions, permission boundaries, organisation guardrails, explicit deny); least privilege in practice; federation with SAML and OIDC; short-lived credentials via STS; workload identity for VMs, Kubernetes, CI and other clouds; and why to eliminate long-lived static keys, with AWS in depth and Azure and GCP equivalents.
Start here: who may do what to which resource
Identity replaced the network perimeter
In a data centre, "inside the firewall" meant trusted. In the cloud, every action (reading an object, starting a VM, deleting a database) is an API call, and every call is checked against who is calling and what policies allow. A leaked credential with broad permissions is the most common route to a cloud breach, so identity design is security design. Three ideas carry most of it:
- Principals: users (people), roles (identities anyone trusted can temporarily assume) and service identities (for workloads).
- Policies: JSON documents of
Effect(Allow/Deny),Action(s3:GetObject),Resource(an ARN) and optionalCondition. - Evaluation: everything is denied by default; an Allow is needed; any matching explicit Deny wins.
A policy, tested
User ravi gets one policy: read anything in tiffin-menus, but never anything under internal/:
{"Version": "2012-10-17", "Statement": [
{"Sid": "ReadMenus", "Effect": "Allow", "Action": ["s3:GetObject", "s3:ListBucket"],
"Resource": ["arn:aws:s3:::tiffin-menus", "arn:aws:s3:::tiffin-menus/*"]},
{"Sid": "NeverInternal", "Effect": "Deny", "Action": "s3:*",
"Resource": "arn:aws:s3:::tiffin-menus/internal/*"}]}
1) user ravi, with the menus-reader policy (allow read on the bucket, deny internal/*):
GET public/menu.json: allowed
GET internal/costs.json (explicit deny wins over the allow): AccessDenied
PUT public/menu.json (nothing allows it: implicit deny): AccessDenied
DeleteBucket: AccessDenied
Note the two kinds of "no": internal/costs.json matched the Allow and the Deny, and the explicit Deny won; PUT and DeleteBucket were never allowed, so they fell to the implicit deny. Also note the two resource forms: ListBucket applies to the bucket ARN, GetObject to object ARNs (bucket/*); forgetting one of them is a classic mistake.
Roles and temporary credentials
Long-lived access keys are the riskiest credentials there are: they work from anywhere until someone revokes them. Roles give out short-lived credentials instead. A role has a trust policy (who may assume it) and permission policies (what it may do). Ravi is allowed to assume menu-editor for 15 minutes:
2) ravi assumes role menu-editor: temporary key ASIARZPU…, session token 356 chars, expires in 15 min
as menu-editor: PUT public/menu.json: allowed
as menu-editor: GET internal/costs.json: AccessDenied
The role's credentials (an ASIA… key, a secret and a session token) could edit public menus and nothing else, and they expire by themselves. In practice people don't have IAM users at all: they sign in through the organisation's identity provider (single sign-on) and receive role sessions, and workloads get role credentials automatically: EC2 instance profiles, ECS task roles, EKS Pod Identity, Lambda execution roles, or OIDC federation from CI systems (the lab).
| Principal | How it authenticates | Credential lifetime |
|---|---|---|
| Person (workforce) | SSO (IAM Identity Center, Entra ID, Google Workspace) → role session | Hours |
| Workload on the cloud | Instance profile, task role, pod identity, managed identity | Minutes to hours, auto-rotated |
| Workload elsewhere (CI, other clouds) | OIDC/SAML federation → AssumeRoleWithWebIdentity |
Minutes to an hour |
| Legacy integration | Access keys | Until rotated (avoid) |
How deep to go in cloud identity
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain principals, roles, policies, allow/deny and temporary credentials |
| L2 | Write least-privilege policies; use roles for people (SSO) and workloads |
| L3 | Explain full policy evaluation (SCPs, boundaries, resource and session policies, conditions) and federation |
| L4 | Diagnose AccessDenied errors, over-broad permissions and credential leaks from logs |
| L5 | Design account structure, guard rails, workload identity and break-glass access |
| L6 | Run identity governance: access reviews, policy-as-code, detection and response at scale |
Identity is the perimeter
In a data centre, the network edge was the main security boundary. In the cloud, every action is an API call, and every API call is authenticated and authorised by IAM. Whoever holds valid credentials with sufficient permissions can read your data, delete your backups or launch crypto-miners, from anywhere on the internet. So:
Identity and access management is the primary security perimeter in the cloud.
Industry incident data consistently ranks leaked credentials (access keys in Git repositories, CI logs, laptops, container images) and over-permissive policies among the top causes of cloud breaches. The roadmap's rule for this chapter: avoid long-lived static credentials wherever possible.
The vocabulary
| Term | Meaning |
|---|---|
| Principal | An entity that can make requests: a human user, a role session, a service, a workload, a federated identity |
| Authentication (AuthN) | Proving who you are: passwords + MFA, SSO tokens, signed requests with keys, OIDC tokens |
| Authorisation (AuthZ) | Deciding whether this principal may perform this action on this resource under these conditions |
| Credential | What proves identity: long-term (passwords, access keys) or temporary (session tokens) |
| Policy | A document granting or denying permissions |
| Role | An identity with permissions that is assumed temporarily by trusted principals; it has no long-term credentials |
Users, groups and roles
AWS IAM building blocks
- Root user: the email address that created the account; unrestricted. Enable MFA (hardware key), never create access keys for it, use it only for the few tasks that require it, and in AWS Organizations, centrally manage root access (root credentials can be removed from member accounts).
- IAM users: long-term identities with passwords and/or access keys (
AKIA…). Modern guidance: don't create IAM users for humans (use federation through IAM Identity Center); avoid them for workloads (use roles). - IAM groups: collections of users for attaching policies (only relevant if you still have IAM users).
- IAM roles: identities assumed by trusted principals, delivering temporary credentials (
ASIA…keys + session token, valid from 15 minutes to 12 hours). A role has: - a trust policy (who may assume it: an AWS service, another account, a federated identity provider, a specific GitHub repository);
- permission policies (what the session may do).
Humans log in through IAM Identity Center (formerly AWS SSO), backed by an identity provider (Entra ID, Okta, Google Workspace), and receive role sessions in the accounts they're entitled to (permission sets). Developers get CLI credentials with aws sso login, which caches short-lived tokens: no access keys on laptops.
Azure and GCP equivalents
| Concept | AWS | Azure | GCP |
|---|---|---|---|
| Directory of humans | IAM Identity Center + external IdP | Microsoft Entra ID (formerly Azure AD) | Cloud Identity / Google Workspace, or workforce identity federation |
| Grant model | Policies attached to identities and resources | Azure RBAC: role definitions assigned to principals at a scope (management group, subscription, resource group, resource) | IAM policies on resources: bindings of principals → roles, inherited down org → folder → project → resource |
| Workload identity | IAM roles (instance profiles, execution roles) | Managed identities (system- or user-assigned), service principals | Service accounts (attached to resources), with workload identity federation |
| Guardrails | SCPs, RCPs, permission boundaries | Azure Policy, deny assignments, management-group RBAC | Organization policies, IAM deny policies, principal access boundaries |
| Temporary credentials | STS | Entra tokens (OAuth 2.0) | Short-lived OAuth tokens, service account impersonation |
Azure has two permission planes: Entra ID roles (managing the directory: users, apps) and Azure RBAC (managing Azure resources). GCP roles are basic (Owner/Editor/Viewer: too broad, avoid), predefined (per service, e.g. roles/storage.objectViewer) and custom.
Service identities
Workloads need identities just like humans, and they should never use a human's credentials or embedded keys:
| Workload | AWS | Azure | GCP |
|---|---|---|---|
| VM | Instance profile (role delivered via IMDS) | System/user-assigned managed identity | Attached service account (metadata server) |
| Container service | ECS task role | Container Apps managed identity | Cloud Run service account |
| Function | Lambda execution role | Functions managed identity | Cloud Run functions service account |
| Kubernetes pod | EKS Pod Identity or IRSA (OIDC) | Azure Workload Identity (federated credentials) | GKE Workload Identity Federation |
| AWS service acting for you | Service-linked roles, service principals in trust policies | Resource provider identities | Service agents |
How workloads get credentials: SDKs use a default credential provider chain that checks, in order, environment variables, shared config/SSO profiles, web-identity token files (Kubernetes), container credential endpoints (ECS, EKS Pod Identity), and the instance metadata service. Code should just create a client and let the chain find credentials, never hard-code keys:
// Java: default chain + assuming a role in another account with automatic refresh
S3Client local = S3Client.create(); // credentials from the environment's chain
StsClient sts = StsClient.create();
S3Client crossAccount = S3Client.builder()
.credentialsProvider(StsAssumeRoleCredentialsProvider.builder()
.stsClient(sts)
.refreshRequest(r -> r.roleArn("arn:aws:iam::222233334444:role/reporting-reader")
.roleSessionName("orders-report")
.durationSeconds(3600))
.build()) // refreshes before expiry
.build();
// Go: default config, then an assume-role credentials cache
cfg, _ := config.LoadDefaultConfig(ctx) // env, SSO, web identity, IMDS…
stsClient := sts.NewFromConfig(cfg)
cfg.Credentials = aws.NewCredentialsCache(stscreds.NewAssumeRoleProvider(stsClient,
"arn:aws:iam::222233334444:role/reporting-reader",
func(o *stscreds.AssumeRoleOptions) { o.RoleSessionName = "orders-report" }))
s3c := s3.NewFromConfig(cfg)
# Python: boto3 session per role (botocore refreshes credentials when using a profile with role_arn)
import boto3
sts = boto3.client("sts")
creds = sts.assume_role(RoleArn="arn:aws:iam::222233334444:role/reporting-reader",
RoleSessionName="orders-report", DurationSeconds=3600)["Credentials"]
s3 = boto3.client("s3", aws_access_key_id=creds["AccessKeyId"],
aws_secret_access_key=creds["SecretAccessKey"], aws_session_token=creds["SessionToken"])
// C#: Azure, DefaultAzureCredential picks up managed identity, workload identity, CLI login…
var credential = new DefaultAzureCredential();
var blobs = new BlobServiceClient(new Uri("https://acmeinvoices.blob.core.windows.net"), credential);
var secrets = new SecretClient(new Uri("https://acme-kv.vault.azure.net"), credential);
// TypeScript: Google Cloud, Application Default Credentials (service account attached to Cloud Run)
import { Storage } from "@google-cloud/storage";
const storage = new Storage(); // no key file: ADC uses the metadata server
const [files] = await storage.bucket("acme-lake").getFiles({ prefix: "events/2026/10/" });
Policies and how they're evaluated
Anatomy of an AWS policy
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadOwnTeamInvoices",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:ListBucket"],
"Resource": [
"arn:aws:s3:::acme-invoices",
"arn:aws:s3:::acme-invoices/${aws:PrincipalTag/team}/*"
],
"Condition": {
"StringEquals": { "aws:PrincipalOrgID": "o-a1b2c3d4e5" },
"Bool": { "aws:SecureTransport": "true" }
}
},
{
"Sid": "NeverDeleteInvoices",
"Effect": "Deny",
"Action": ["s3:DeleteObject", "s3:DeleteObjectVersion"],
"Resource": "arn:aws:s3:::acme-invoices/*"
}
]
}
- Effect:
AlloworDeny. - Action:
service:Operation(wildcards likes3:Get*exist, but use them sparingly). - Resource: ARNs (Amazon Resource Names:
arn:partition:service:region:account:resource). - Condition: global and service-specific keys: source VPC endpoint, IP, MFA present, time, tags on principal and resource, organisation ID, requested region.
- Principal: appears only in resource-based policies (bucket policies, KMS key policies, role trust policies, SQS queue policies), naming who the statement applies to.
Policy types
| Type | Attached to | Effect |
|---|---|---|
| Identity-based | Users, groups, roles | Grants (or denies) permissions to that principal |
| Resource-based | Buckets, keys, queues, topics, functions, roles (trust policy) | Grants (or denies) access to that resource, including to other accounts |
| Permission boundary | A user or role | Maximum permissions an identity can have; doesn't grant anything by itself. Used to let teams create roles safely |
| Service control policies (SCPs) | Organisation, OU, account | Maximum permissions for all principals in member accounts (except the management account), e.g. deny leaving the organisation, deny regions outside the approved list, deny disabling CloudTrail |
| Resource control policies (RCPs) | Organisation, OU, account | Maximum permissions on resources in those accounts, regardless of who calls (e.g. "no principal outside our organisation may access our buckets") |
| Session policies | Passed when assuming a role | Further restrict one session |
| VPC endpoint policies | Endpoints | Restrict what's reachable through that endpoint |
Evaluation logic
For a request within one account, AWS evaluates all applicable policies:
Rules to remember:
- Default deny: nothing is allowed unless something allows it.
- An explicit
Denyalways wins over anyAllow. - Guardrails (SCPs, RCPs, boundaries, session policies) only limit; they never grant.
- Cross-account access needs both sides: the caller's identity policy must allow the action and the resource's policy (or a role trust policy in the target account) must allow the caller. (Within one account, either an identity or a resource policy is enough for most services.)
- KMS keys are special: the key policy must allow access (optionally delegating to IAM policies), so a forgotten key policy can lock everyone out.
Tools: the IAM policy simulator, aws iam simulate-principal-policy, CloudTrail errorCode: AccessDenied events (which now often include the policy type that denied), and IAM Access Analyzer (finds resources shared externally, unused access, and validates policies).
Azure RBAC evaluates role assignments at the scope and above, with deny assignments overriding and conditions (ABAC) on some actions; GCP evaluates deny policies first, then allow policies on the resource and its ancestors.
Least privilege in practice
Least privilege: each principal gets only the permissions it needs, on only the resources it needs, for only as long as it needs them. It's easy to state and hard to sustain. Techniques:
- Start narrow, expand on evidence: use Access Analyzer policy generation from CloudTrail activity; review last-accessed information and remove unused services and roles; Azure and GCP provide similar recommenders (GCP IAM Recommender, Entra access reviews).
- Scope resources: specific ARNs or name prefixes, not
*. - Separate roles per workload: one role per service, not a shared "app role".
- Attribute-based access control (ABAC): grant by matching tags (
aws:PrincipalTag/team=aws:ResourceTag/team), so new resources are covered without policy edits, scaling better than one policy per resource. - Guardrails at the organisation level: SCPs denying dangerous actions (disabling CloudTrail/GuardDuty, leaving the org, using unapproved regions, creating IAM users with access keys); RCPs enforcing data perimeters ("only identities from our organisation, from our networks, may access our data").
- Just-in-time elevation for humans: request time-bound admin access with approval (Entra Privileged Identity Management, AWS temporary elevated access solutions, GCP Privileged Access Manager), rather than standing admin rights.
- Break-glass accounts: emergency credentials stored securely, monitored, rarely used, and tested.
- Avoid wildcards on sensitive actions:
iam:PassRole(passing a powerful role to a service is privilege escalation),iam:*,kms:*,sts:AssumeRoleon*.
# Terraform: a narrowly scoped role for one ECS service, with ABAC on the team tag
data "aws_iam_policy_document" "orders_task" {
statement {
actions = ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Query", "dynamodb:UpdateItem"]
resources = [aws_dynamodb_table.orders.arn, "${aws_dynamodb_table.orders.arn}/index/*"]
}
statement {
actions = ["sqs:SendMessage"]
resources = [aws_sqs_queue.order_events.arn]
}
statement {
actions = ["secretsmanager:GetSecretValue"]
resources = ["*"]
condition {
test = "StringEquals"
variable = "aws:ResourceTag/team"
values = ["checkout"]
}
}
}
resource "aws_iam_role" "orders_task" {
name = "orders-task"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = { Service = "ecs-tasks.amazonaws.com" }
Action = "sts:AssumeRole"
Condition = { StringEquals = { "aws:SourceAccount" = data.aws_caller_identity.current.account_id } }
}]
})
}
resource "aws_iam_role_policy" "orders_task" {
role = aws_iam_role.orders_task.id
policy = data.aws_iam_policy_document.orders_task.json
}
The aws:SourceAccount condition in the trust policy prevents the confused deputy problem (another account tricking the service into assuming your role on its behalf).
Federation
Federation lets identities from an external identity provider (IdP) access cloud resources without separate cloud users:
- SAML 2.0: XML-based assertions; the classic enterprise SSO standard (Entra ID, Okta, ADFS → AWS IAM Identity Center or IAM SAML providers).
- OpenID Connect (OIDC): JSON Web Tokens over OAuth 2.0; used for humans and, increasingly, workloads (any system that can obtain a signed OIDC token from a trusted issuer can exchange it for cloud credentials).
- SCIM provisions users and groups from the IdP into the cloud's directory automatically, and deprovisions them when people leave (the single most important joiner/mover/leaver control).
Benefits: one place to enforce MFA, conditional access (device posture, location) and offboarding; no cloud passwords to leak; group-based entitlements mapped to roles or permission sets.
Short-lived credentials
AWS STS (Security Token Service) issues temporary credentials:
AssumeRole: from another principal (cross-account access, privilege separation).AssumeRoleWithWebIdentity: in exchange for an OIDC token (Kubernetes service account tokens, GitHub Actions tokens, Google or Azure identity tokens).AssumeRoleWithSAML: in exchange for a SAML assertion.GetSessionToken: MFA-protected sessions for IAM users.
Why temporary credentials matter:
| Long-lived access key | Temporary session credentials |
|---|---|
| Valid until someone rotates or deletes it (often years) | Expire automatically (15 min – 12 h) |
| Must be stored somewhere: env vars, files, CI secrets, images | Obtained on demand from a trusted source |
| Leaks are exploitable indefinitely | A leak is useful only briefly |
| Hard to attribute (shared keys) | Each session has a name in CloudTrail (role/session-name) |
Azure and GCP issue short-lived OAuth 2.0 access tokens (typically about an hour) for managed identities and service accounts; GCP service account impersonation replaces downloading service-account key files (which you should disable with the organisation policy iam.disableServiceAccountKeyCreation).
Workload identity
Workload identity federation is the modern answer to "how does a workload outside (or inside) the cloud get credentials without a stored secret?": the workload proves its identity with a token issued by its platform, and the cloud exchanges it for short-lived credentials based on a trust configuration.
Where it applies:
- CI/CD: GitHub Actions, GitLab CI, Azure DevOps, CircleCI, Buildkite and others issue OIDC tokens; trust them in AWS (IAM OIDC provider + role), Azure (federated credentials on an app registration or managed identity) and GCP (workload identity pools). Scope the trust tightly: the
subclaim should pin repository and branch or environment, or any repository's workflow could assume the role. - Kubernetes: EKS Pod Identity / IRSA, GKE Workload Identity Federation, Azure Workload Identity map Kubernetes service accounts to cloud identities; pods get credentials via projected tokens, with no secrets in the cluster.
- Cross-cloud and on-premises: a GCP workload can assume an AWS role with its Google-issued identity token; AWS workloads can access GCP via workload identity pools; IAM Roles Anywhere issues AWS credentials to on-premises servers presenting X.509 certificates from your CA.
- SPIFFE/SPIRE provides platform-neutral workload identities (SVIDs) for service-to-service mTLS and can federate into clouds.
# GitHub Actions: deploy to AWS with OIDC, no stored access keys
permissions:
id-token: write # allow the job to request an OIDC token
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::111122223333:role/gha-orders-deploy
aws-region: ap-south-1
- run: aws ecs update-service --cluster prod --service orders --force-new-deployment
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com" },
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:acme/orders:environment:production"
}
}
}]
}
Eliminating static credentials
A practical programme:
- Inventory: list IAM users and access keys (credential report), Azure service principals with client secrets, GCP service account keys; find keys in code with secret scanning (GitHub push protection, gitleaks, TruffleHog).
- Replace humans' keys with SSO (
aws sso login,az login,gcloud auth login) and short-lived sessions. - Replace workloads' keys with instance/task/execution roles, managed identities, attached service accounts, and workload identity federation for anything outside the cloud (CI, other clouds, on-premises).
- Prevent new keys: SCPs denying
iam:CreateAccessKeyoriam:CreateUseroutside break-glass paths; GCP organisation policy disabling key creation; Azure policies requiring managed identities. - Where a static secret is unavoidable (a third-party API key, a database password for a legacy system): keep it in a secrets manager (AWS Secrets Manager, Azure Key Vault, GCP Secret Manager, HashiCorp Vault), fetch it at runtime with workload identity, rotate automatically, and audit access. Better still, use dynamic, short-lived secrets (Vault database credentials, RDS IAM authentication, Entra authentication for Azure SQL, Cloud SQL IAM database authentication).
- Detect and respond: alert on root logins, new access keys, policy changes granting
*, and API calls from unusual places (GuardDuty, Defender for Cloud, Security Command Center); have a runbook for leaked keys (deactivate, assess CloudTrail activity, rotate, clean up).
Lab: evaluating policies the way the cloud does
Two tools: moto's IAM enforcement (from the on-ramp) for real allow/deny on API calls, and a compact policy evaluator written for this lab that follows AWS's documented evaluation order (explicit deny → organisation policies → permissions boundary → identity policies → implicit deny) and supports StringEquals, StringNotEquals, StringLike, Bool and IpAddress conditions. It isn't AWS's engine; it reproduces its logic so you can test cases. JWTs are signed and verified with PyJWT and RSA keys.
Experiment 1: layered decisions
A developer's identity policy allows s3:* on tiffin-* buckets and ec2:Describe*, and denies s3:DeleteBucket. Two optional layers: an organisation guard rail (SCP) that denies every action outside the two Indian regions, and a permissions boundary that allows only s3:Get*, s3:List* and ec2:Describe*:
s3:GetObject tiffin-menus/menu.json ap-south-1 identity only → ALLOW
s3:PutObject tiffin-menus/menu.json ap-south-1 identity only → ALLOW
s3:DeleteBucket tiffin-menus ap-south-1 identity only → DENY (explicit)
s3:GetObject payroll/salaries.csv ap-south-1 identity only → DENY (implicit)
ec2:RunInstances * ap-south-1 identity only → DENY (implicit)
s3:PutObject tiffin-menus/menu.json ap-south-1 + boundary → DENY (implicit)
s3:GetObject tiffin-menus/menu.json ap-south-1 + scp → ALLOW
s3:GetObject tiffin-menus/menu.json us-east-1 + scp → DENY (explicit)
The identity policy allowed PutObject, but the boundary didn't, so it was denied: boundaries and SCPs never grant anything; they cap what identity policies can grant. That's how platform teams let developers create their own roles safely ("any role you create must carry this boundary") and enforce organisation rules (data residency, no disabling CloudTrail) that no account administrator can override. Resource policies (bucket policies, KMS key policies) add one more layer, and for cross-account access both sides must allow.
Experiment 2: the NotAction trap
A policy written to mean "everything except IAM":
'Allow NotAction iam:*' (meant as 'no IAM'):
iam:CreateUser → DENY (implicit)
s3:DeleteBucket → ALLOW
ec2:TerminateInstances → ALLOW
kms:ScheduleKeyDeletion → ALLOW
Allow + NotAction grants every action in every service except the listed ones, including deleting buckets, terminating instances and scheduling key deletion. NotAction is safe with Deny (deny everything except a list) and dangerous with Allow. Tools like IAM Access Analyzer's policy checks, checkov and cfn-lint flag it.
Experiment 3: workload identity from CI
A deploy role trusts tokens from GitHub Actions' OIDC provider, but only for the main branch of asha/tiffin. Three jobs present tokens (each RS256-signed, valid 300 s, verified for signature, expiry and audience before the conditions are checked):
sub=repo:asha/tiffin:ref:refs/heads/main token 594 bytes, valid 300 s → ALLOW
sub=repo:asha/tiffin:pull_request token 584 bytes, valid 300 s → DENY (implicit)
sub=repo:someone/fork:ref:refs/heads/main token 592 bytes, valid 300 s → DENY (implicit)
The sub claim names the repository and ref, so the trust policy's condition decided who could deploy: pull requests (which can contain anyone's code) and other repositories were refused. Without the sub condition, any repository on GitHub could have assumed the role, a misconfiguration that has been found in the wild many times. The same pattern serves GitLab, Azure DevOps, Kubernetes service accounts (EKS IRSA, Azure workload identity, GKE workload identity) and cross-cloud access.
Experiment 4: how long a leaked credential works
static access key, rotated every 90 days : if leaked at a random moment, usable for 45 days on average
STS session, 1 hour : if leaked at a random moment, usable for 30.0 minutes on average
OIDC token, 5 minutes : if leaked at a random moment, usable for 2.5 minutes on average
Credentials leak through logs, public repositories, laptops and CI output. A short lifetime turns a leak from a weeks-long open door into a short window, and session credentials are tied to an identity and visible in audit logs (CloudTrail's AssumeRole events). The remaining static keys should be inventoried (IAM credential report), scoped to IP ranges or VPC endpoints with conditions, and replaced over time.
Try it yourself
- Add a resource policy layer to the evaluator (a bucket policy) and test cross-account access where only one side allows.
- Use IAM Access Analyzer (in a real account) to generate a least-privilege policy from a week of CloudTrail activity for a role.
- Configure GitHub Actions OIDC to a real AWS role and print
aws sts get-caller-identityin a workflow; then try it from a fork. - Write an SCP that prevents leaving the organisation, disabling CloudTrail and creating IAM users, and test it in a sandbox account.
Revision sheet: cloud identity
Key ideas
- Identity as the perimeter: every cloud action is an authenticated, authorised API call; credential compromise is the main threat.
- Principals: root/account owner, users, groups, roles, service-linked roles, federated identities, workload identities; Azure (Entra ID users, service principals, managed identities, RBAC role assignments at scopes) and GCP (principals, service accounts, roles bound in IAM policies on the resource hierarchy).
- Policies: identity-based, resource-based, SCPs/RCPs, permissions boundaries, session policies, ACLs; conditions and global condition keys; ARNs and wildcards.
- Evaluation: default deny → explicit deny wins → allow needed from every applicable layer; cross-account needs both sides.
- Least privilege: start from zero, access analysis from logs, separate roles per job, break-glass access, regular reviews.
- Federation: SAML/OIDC SSO for people; OIDC for workloads outside the cloud; trust-policy conditions on
audandsub. - Short-lived credentials: STS sessions, instance metadata (IMDSv2), task/pod identities, managed identities; eliminate static keys.
Numbers to remember
- STS sessions: 15 minutes to 12 hours (role setting); GitHub OIDC tokens valid ~5 minutes.
- Lab: explicit deny beat allow; a boundary turned an allowed PutObject into a deny; an SCP denied the same GET in us-east-1;
Allow NotAction iam:*allowed deleting buckets; a pinnedsubrefused PRs and forks; leaked static keys live 45 days on average vs 30 minutes for 1-hour sessions.
Pitfalls
- IAM users with access keys for people or CI.
*actions or resources "for now".AllowwithNotActionorNotResource.- OIDC trust policies without
subconditions. - Using the root user; no MFA on human sign-in.
- Forgetting the bucket ARN vs object ARN distinction.
Glossary
- ARN: Amazon Resource Name, the unique ID of a resource.
- Trust policy: who may assume a role.
- Permissions boundary: maximum permissions an identity policy can grant.
- SCP: organisation-level guard rail on accounts.
- STS: Security Token Service issuing temporary credentials.
- Workload identity: credentials issued to software from its platform identity.