This lesson combines 2 topics: Secrets Management, IAM and Least Privilege.
Learning Objectives
- Understand why secrets (API keys, passwords, tokens, certificates) must NEVER be committed to source code
- Learn the
.env+.env.examplepattern and the common traps when managing environment variables - Know how to scrub an accidentally committed secret from git history with BFG/
git filter-repo, and why you rotate before scrubbing - Compare popular secret managers: HashiCorp Vault, AWS Secrets Manager, GCP Secret Manager, Doppler, 1Password
- Understand secret rotation and lease-based credentials
- Integrate gitleaks/truffleHog/GitHub secret scanning into CI
- Apply the 12-factor app: config separated from code
- Understand the core IAM concepts: identity, principal, role, policy
- Apply the principle of least privilege and recognize common over-privileged patterns
- Distinguish IAM User vs Role vs Group, identity-based vs resource-based policies, and trust policies
- Design cross-account access with
sts:AssumeRole - Use IAM Access Analyzer and the Last Accessed report to trim excess permissions
- Briefly compare AWS IAM with GCP IAM bindings and Azure RBAC
- Avoid IAM "traps":
NotAction, deny-by-default, allow vs explicit deny
Part 1: Secrets Management
1. Why secrets must never be committed
A real story
2019: A junior dev committed an AWS access key to a public GitHub repo.
4 minutes later, an automated bot scanning GitHub grabbed the key and spun up
100 p3.16xlarge EC2 instances to mine cryptocurrency.
The AWS bill the next morning: ~$28,000 USD in 12 hours.
A secret leaked through git is a problem you cannot undo:
- Once it has been pushed to a public repo, assume it is compromised, even if you delete it right away
- Bots scan GitHub within seconds of a push
- Git history is permanent:
git revertdoes not remove it, because the old commit still exists
Things that must NEVER be committed
- API keys (Stripe, OpenAI, Twilio, SendGrid, ...)
- Cloud credentials (AWS access key, GCP service account JSON, Azure SP secret)
- Database connection strings (with password)
- Private keys (SSH, TLS, GPG, JWT signing key)
- OAuth client secrets
- Session secrets / encryption keys
- Webhook signing secrets
- Third-party license keys
What can be committed?
- Code (logic)
- Public config (port number, region, default feature flags)
- The
.env.examplefile (a template, no real values) - Properly encrypted secrets (e.g.
sops,git-crypt, AWS KMS encrypted) — but still be careful
2. Common .env traps
The right pattern: .env + .env.example
.env.example — committed to the repo:
# .env.example — template, NO real values
DATABASE_URL=postgres://user:password@localhost:5432/mydb
STRIPE_SECRET_KEY=sk_test_xxxxxxxxxxxxx
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxx
JWT_SECRET=change_me_to_random_64_chars
.gitignore:
# Secrets
.env
.env.local
.env.*.local
*.pem
*.key
secrets/
credentials.json
Trap 1: .env committed before being added to .gitignore
# Adding .env to .gitignore AFTER it was committed has no effect
echo ".env" >> .gitignore
git add .gitignore
git commit -m "ignore .env"
# .env is still in the history of earlier commits! You must scrub history.
Trap 2: Committing .env.local, .env.production because the ignore does not cover them
.gitignore only has ".env"
but the project has:
.env.local ← GETS COMMITTED (not covered by ignore)
.env.production ← GETS COMMITTED
The safe approach: ignore every .env.* variant except .env.example:
.env*
!.env.example
Trap 3: Secrets in other config files
Don't assume .gitignore is enough — sometimes secrets live in:
config.json,application.yml,appsettings.jsonterraform.tfvars- Jupyter notebooks
.ipynb(may contain output with tokens) - README files with "examples" that use real keys
Trap 4: Frontend code "containing" secrets
// React/Next.js client code — ALL NEXT_PUBLIC_* values are bundled into the JS sent to the browser
const stripeKey = process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY; // ❌ LEAK
Rule: anything with the prefix NEXT_PUBLIC_, REACT_APP_, VITE_, PUBLIC_ is public, not a secret.
3. Scrubbing git history (after an accidental commit)
Step 0: Rotate the secret BEFORE scrubbing
PRIORITY ORDER (follow this order):
1. Rotate/revoke the leaked secret — this is the ONLY thing that actually stops the damage
- AWS: deactivate the access key in IAM
- Stripe: roll the API key in the dashboard
- OAuth: revoke the refresh token
2. Audit logs: check where and when the secret was used
- CloudTrail (AWS), Audit logs (Stripe), GitHub Security Log
3. SCRUB git history (only AFTER rotating)
- If you scrub before rotating, an attacker who already cloned the repo still has the key
Why: scrubbing git history cannot remove the secret from a clone the attacker already has. Only rotation stops the secret from being used.
BFG Repo-Cleaner
# 1. Back up the repo first
git clone --mirror git@github.com:org/repo.git repo-backup.git
# 2. Clone a mirror to clean
git clone --mirror git@github.com:org/repo.git
cd repo.git
# 3. Create a file listing the secrets to remove
cat > secrets.txt <<EOF
AKIA_EXAMPLE_KEY_ID
sk_live_51HtT5oJB6kF
EOF
# 4. Run BFG to replace them with "***REMOVED***"
bfg --replace-text secrets.txt
# 5. Or delete the file entirely
bfg --delete-files .env
# 6. Clean up reflog and GC
git reflog expire --expire=now --all
git gc --prune=now --aggressive
# 7. Force push (you MUST warn the team)
git push --force
git filter-repo (recommended by the Git project)
# Install (Python tool, replaces the deprecated git filter-branch)
pip install git-filter-repo
# Remove a file from every commit in history
git filter-repo --path .env --invert-paths
# Replace a string in every commit
echo 'AKIA_EXAMPLE_KEY_ID==>REMOVED' > replacements.txt
git filter-repo --replace-text replacements.txt
# Force push
git push --force --all
git push --force --tags
After the force push
- The team must re-clone or run
git fetch && git reset --hard origin/<branch> - Every existing PR/fork will break — they must rebase
- GitHub still caches old commits for a few weeks via direct URL — open a support ticket if you want them removed completely
4. Secret managers
Comparing the options
| Tool | Hosting | Auth model | Dynamic secrets | Best for |
|---|---|---|---|---|
| HashiCorp Vault | Self-host or HCP Cloud | Token, AppRole, JWT, K8s SA | Yes (DB creds, AWS STS) | Multi-cloud, enterprise |
| AWS Secrets Manager | AWS managed | IAM | Yes (RDS, native rotation Lambda) | AWS-only stack |
| AWS Parameter Store | AWS managed | IAM | No | Config + light secrets, cheap |
| GCP Secret Manager | GCP managed | GCP IAM | No | GCP-only stack |
| Azure Key Vault | Azure managed | Azure AD / Managed Identity | Yes (limited) | Azure-only stack |
| Doppler | SaaS | Service token, OIDC | No | Multi-env config sync, good team UX |
| 1Password Secrets | SaaS | Service Account | No | Small teams already using 1Password |
| Infisical | Open source / SaaS | Service token, OIDC | Limited | Free self-host, Doppler alternative |
Pattern using AWS Secrets Manager (Node.js)
import {
SecretsManagerClient,
GetSecretValueCommand,
} from "@aws-sdk/client-secrets-manager";
const client = new SecretsManagerClient({ region: "ap-southeast-1" });
async function getDbPassword() {
const cmd = new GetSecretValueCommand({ SecretId: "prod/myapp/db" });
const res = await client.send(cmd);
const secret = JSON.parse(res.SecretString);
return secret.password;
}
The app never stores the password in an env var or file. The app has an IAM Role (via EC2/ECS Task Role/IRSA) and calls the API at every startup — or caches it in memory with a TTL.
Pattern using Vault (Python)
import hvac
client = hvac.Client(url="https://vault.example.com")
# K8s service account JWT auth
client.auth.kubernetes.login(role="my-app", jwt=open("/var/run/secrets/kubernetes.io/serviceaccount/token").read())
# Read static secret
secret = client.secrets.kv.v2.read_secret_version(path="myapp/prod/db")
db_password = secret["data"]["data"]["password"]
# Dynamic DB credentials — Vault creates a PostgreSQL user on demand
creds = client.secrets.database.generate_credentials(name="readonly-role")
# creds["data"]["username"] and creds["data"]["password"] — valid for only a few hours
5. Secret rotation and lease-based credentials
Rotating a static secret
Week 1: DB password = "abc123"
App is using "abc123"
│
Week 2: Rotate → new password = "xyz789"
App is redeployed with the new password
Old password "abc123" is deactivated after a grace period
AWS Secrets Manager has automatic rotation via Lambda: it changes the password in RDS and then updates the secret. The app only needs to re-fetch.
Lease-based dynamic credentials (Vault)
App: "Give me a PostgreSQL credential"
Vault: "Here: user=v-app-abc123, password=xxx, TTL=1 hour"
→ Vault creates a new user in PostgreSQL with the appropriate GRANT
→ After 1 hour Vault DROPs that user automatically
App restarts within the next hour: it receives a DIFFERENT credential
Pros:
- Each instance has its own credential → audit logs can trace who did what
- A compromised credential only causes damage within the TTL
- No manual rotation needed — credentials are always short-lived
6. Detecting secrets in CI
gitleaks
# .github/workflows/gitleaks.yml
name: Secret scan
on: [push, pull_request]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # scan the full history
- uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Run locally:
# Install
brew install gitleaks
# Scan the full history
gitleaks detect --source . --verbose
# Scan staged changes (pre-commit hook)
gitleaks protect --staged --verbose
truffleHog
# truffleHog v3 — verifies whether the key actually works
trufflehog git https://github.com/org/repo --only-verified
The difference: truffleHog can call the real API to check whether a key is still valid — fewer false positives.
GitHub Secret Scanning
Enabled for free on public repos, and via GitHub Advanced Security for private ones. GitHub partners with providers (Stripe, AWS, Slack, ...) — when a key is detected, it can be revoked automatically through the provider.
Local pre-commit hook
# .pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks
pip install pre-commit
pre-commit install
# On every git commit, gitleaks runs on the staged files
7. 12-factor app: Config
From the 12factor.net methodology:
"Store config in the environment"
Principles:
- Config (including secrets) must not be hardcoded in code
- Config that differs between envs (dev/staging/prod) must not be stored in code
- Strict separation between code and config: the same codebase deploys to every env
// ❌ BAD — config in code
const dbUrl = "postgres://prod-user:secretpass@db.prod.com/app";
// ❌ BAD — config switch in code
const dbUrl = env === "prod"
? "postgres://prod-user:secret@db.prod.com/app"
: "postgres://dev-user:dev@localhost/app";
// ✅ GOOD — env var
const dbUrl = process.env.DATABASE_URL;
if (!dbUrl) throw new Error("DATABASE_URL is required");
Validate env vars at startup (fail fast):
import { z } from "zod";
const envSchema = z.object({
DATABASE_URL: z.string().url(),
STRIPE_SECRET_KEY: z.string().startsWith("sk_"),
JWT_SECRET: z.string().min(32),
NODE_ENV: z.enum(["development", "staging", "production"]),
});
export const env = envSchema.parse(process.env);
// The app crashes right at startup if an env var is missing/invalid
Part 2: IAM and Least Privilege
1. Core IAM concepts
IAM (Identity and Access Management) answers the question: "Who (principal) is allowed to do what (action) on which resource (resource), under which conditions (condition)?"
The four main components
| Concept | Meaning | Example |
|---|---|---|
| Identity | An entity that can authenticate | IAM User alice, Role lambda-exec |
| Principal | The identity requesting the action | User alice calls s3:GetObject |
| Action | An operation on a service | s3:PutObject, iam:PassRole |
| Resource | The resource being acted on (ARN) | arn:aws:s3:::my-bucket/* |
| Policy | A JSON document that grants permissions | Identity-based or resource-based |
| Condition | Additional constraints | aws:SourceIp, aws:MultiFactorAuthPresent |
2. Principle of Least Privilege
Least privilege: grant exactly the permissions needed to get the job done — no more, no less. It is a foundational principle of zero-trust security.
Common over-privileged patterns
Anti-pattern 1: Wildcard * in Action and Resource
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "*",
"Resource": "*"
}]
}
This is an implicit AdministratorAccess — whoever has this policy can delete the account, create new IAM users, turn off CloudTrail. Never attach it to a service workload.
Anti-pattern 2: AdministratorAccess for dev/CI roles in production
A CI runner only needs to deploy an ECS service but gets AdministratorAccess "for convenience". Consequence: a leaked credential = full control of the account.
Anti-pattern 3: s3:* on * instead of a specific bucket
// ❌ BAD
{ "Effect": "Allow", "Action": "s3:*", "Resource": "*" }
// ✅ GOOD
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::app-uploads-prod/*"
}
Anti-pattern 4: Overly broad iam:PassRole
iam:PassRole lets a service "wear" another role. If iam:PassRole is allowed on *, an attacker can escalate privileges by passing an AdministratorAccess role to a new Lambda.
// ✅ Restrict to a specific role
{
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "arn:aws:iam::123456789012:role/lambda-exec-prod",
"Condition": {
"StringEquals": { "iam:PassedToService": "lambda.amazonaws.com" }
}
}
3. User vs Role vs Group
| Criterion | User | Role |
|---|---|---|
| Credential | Long-lived (access key) | Temporary (STS, ~1h) |
| Used by | Humans | Services or trusted identities |
| Authentication | Password / Access key | AssumeRole API call |
| Best practice | Minimize, use SSO/IdC | Default for every workload |
2024 recommendation: Stop creating IAM Users for humans — use AWS IAM Identity Center (SSO) together with Okta/Google Workspace. IAM Users remain only for legacy cases or service accounts that cannot be role-based.
4. Identity-based vs Resource-based Policy
Identity-based policy
Attached to a User, Group, or Role. Answers: "What is this identity allowed to do?"
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::reports/*"
}]
}
Resource-based policy
Attached to a resource (S3 bucket, SQS queue, Lambda function, KMS key). Answers: "Who is allowed to access this resource?"
// S3 bucket policy — cross-account read
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::222222222222:role/analytics" },
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::shared-data/*"
}]
}
| Policy type | Has a Principal field? | Cross-account support |
|---|---|---|
| Identity-based | No (the principal is implicitly the attached identity) | Needs a resource-based policy or role assumption |
| Resource-based | Required | Yes (the principal just needs to be another account's ARN) |
5. Trust Policy and Cross-account Access
Trust policy — "Who is allowed to assume this role?"
Every role has 2 policies: the trust policy (who may assume it) and the permissions policy (what you can do once you have assumed it).
// Trust policy of the "data-reader" role in account A (111111111111)
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::222222222222:root" },
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": { "sts:ExternalId": "shared-secret-uuid" },
"Bool": { "aws:MultiFactorAuthPresent": "true" }
}
}]
}
Principal: root of account 222... = any identity in that account (that has the sts:AssumeRole permission) can assume it. It is usually tightened further with ExternalId to prevent the "confused deputy" problem.
Cross-account flow
# Account B user calls assume role
aws sts assume-role \
--role-arn arn:aws:iam::111111111111:role/data-reader \
--role-session-name alice-session \
--external-id shared-secret-uuid
# Output: AccessKeyId, SecretAccessKey, SessionToken (TTL ~1h)
Confused deputy problem: service B (e.g. a third-party SaaS) is trusted to assume a role in account A. If the trust policy only checks
Principal: B's account, another customer of B could also have B unknowingly impersonate them. ExternalId is a shared secret between A and B that proves the request really comes on behalf of customer A.
6. IAM Access Analyzer and Last Accessed
IAM Access Analyzer
Automatically detects resources shared outside your account/organization (public S3 buckets, roles with overly broad trust policies, KMS keys shared with external accounts).
# Enable an analyzer for the organization
aws accessanalyzer create-analyzer \
--analyzer-name org-analyzer \
--type ORGANIZATION
# List findings
aws accessanalyzer list-findings \
--analyzer-arn arn:aws:access-analyzer:us-east-1:...:analyzer/org-analyzer
Access Analyzer also offers policy validation — it checks an IAM policy for syntax errors and security warnings before you attach it.
Last Accessed report
See which identities/roles have not used which actions for a long time → trim excess permissions.
# Generate a report for a role
aws iam generate-service-last-accessed-details \
--arn arn:aws:iam::111111111111:role/ci-deploy
aws iam get-service-last-accessed-details \
--job-id <job-id-from-the-command-above>
The output shows which services the role has or has not used in the last N days. A common pattern: a role has AdministratorAccess but over 90 days only used s3:* and ecs:* → revoke admin and grant a minimal policy.
7. Brief comparison with GCP and Azure
| Concept | AWS IAM | GCP IAM | Azure |
|---|---|---|---|
| Identity | User, Role, Service | User, Service Account | User, Service Principal, Managed Identity |
| Permissions | Policy (JSON) | Role (predefined/custom) made of many permissions | Role Definition |
| Binding | Policy attached to identity | IAM Binding: (member, role, resource) | Role Assignment |
| Scope | Per-resource ARN | Project / Folder / Org hierarchy | Subscription / Resource Group / Resource |
| Cross-account | AssumeRole + STS | Workload Identity Federation | Cross-tenant access policy |
GCP IAM example
# Binding: alice@example.com has roles/storage.objectViewer on the "data" bucket
bindings:
- members:
- user:alice@example.com
role: roles/storage.objectViewer
Azure RBAC example
az role assignment create \
--assignee alice@contoso.com \
--role "Storage Blob Data Reader" \
--scope /subscriptions/<sub-id>/resourceGroups/<rg>
Common ground: all three follow the (who, what, where, when) model. The biggest difference is the scope hierarchy — GCP has clear inheritance along Org → Folder → Project, and AWS Organizations + SCP is the equivalent mechanism on AWS.
8. Common IAM traps
Trap 1: Deny-by-default, Explicit Deny always wins
Everything is denied by default. You need an explicit Allow. If there is an Explicit Deny in any policy (identity, resource, SCP, permission boundary) → DENY always wins.
Trap 2: NotAction is not Deny
{
"Effect": "Allow",
"NotAction": "iam:*",
"Resource": "*"
}
This statement is often misread as "deny all iam:*". In reality it Allows every action that is not iam:*. It is equivalent to an admin policy minus IAM. Using NotAction with Effect: Allow is very dangerous — it easily grants new permissions you did not anticipate (e.g. when AWS adds a new service).
Best practice: use
NotActiononly withEffect: Deny(deny everything except X). AvoidAllow + NotAction.
Trap 3: Permission boundary ≠ SCP ≠ Identity policy
Effective permissions =
Identity policy
∩ Permission boundary
∩ SCP (organization-level)
∩ Session policy (if any)
\ Explicit Deny (every layer)
- SCP (Service Control Policy): applies to the whole account in the Organization; even the root user is restricted. An SCP does not grant permissions, it only sets the maximum allowed.
- Permission boundary: attached to a User/Role, it caps the maximum permissions of that identity.
- Identity policy: the actual permissions granted to the identity.
If the identity policy grants s3:* but the SCP only allows s3:GetObject → effective = s3:GetObject.
Trap 4: Resource: "*" for actions that only apply to *
Some actions such as ec2:DescribeInstances are only valid with Resource: "*" (they do not support resource-level permissions). Don't mistake this for permissions being "too broad" — sometimes it is required. Check the IAM Authorization reference for each action.
Review Questions
-
You accidentally
git pusha.envfile containing an AWS access key to a public repo. What is the correct order to handle it?Show answer
Priority order: (1) Rotate/deactivate the access key in AWS IAM immediately, (2) Check CloudTrail to see whether the key has been used for any unusual activity, (3) Only then scrub history with
git filter-repoor BFG, (4) Force push and tell the team to re-clone.Why: scrubbing history does NOT remove the secret from clones/forks the attacker already has. Only rotation stops the secret from being used. Reversing the order (scrub first, rotate later) is a common mistake.
-
Why does adding
.envto.gitignoreafter it was committed not solve the problem?Show answer
.gitignoreonly stops Git from tracking new files. The already committed.envstill exists in every old commit of the history — cloning any earlier commit still gives you the.envfile. To remove it completely you must rewrite history withgit filter-repo/BFG and force push. More importantly: you still have to rotate the secret first, because the attacker may have cloned before you scrubbed. -
Compare AWS Parameter Store and AWS Secrets Manager — when should you use which?
Show answer
Parameter Store: cheap (standard tier is free), good for config that may not be sensitive (region, feature flags) and simple secrets. No automatic rotation. Limit 4 KB (standard) or 8 KB (advanced).
Secrets Manager: ~$0.40/secret/month, has automatic rotation via Lambda (changes the DB password and updates the secret automatically), supports cross-region replication and resource policies. Use it for DB passwords and API keys that need periodic rotation.
Common rule: config → Parameter Store, secrets that need rotation → Secrets Manager.
-
How does a Vault "dynamic secret" differ from Secrets Manager "static secret rotation"?
Show answer
Static rotation: the secret lives for a long time (weeks/months) and is rotated periodically. All apps share the same secret at any given moment. Compromise = damage until the next rotation.
Dynamic secret (Vault): the secret is created on demand for each app request, with a short TTL (minutes to hours). Each instance has its own credential. Vault creates a real DB user in PostgreSQL with the appropriate GRANT, and when the TTL expires Vault DROPs the user automatically. A compromise only causes damage within the TTL window. Audit logs can trace which instance did what.
-
Why is
NEXT_PUBLIC_STRIPE_SECRET_KEYin Next.js a dangerous anti-pattern?Show answer
Every env var with the
NEXT_PUBLIC_prefix is bundled by Next.js straight into the client (browser) JavaScript. Anyone who opens DevTools can read the value. Putting a secret key (meant only for server-side use) under this prefix = making the secret public to everyone. A Stripe secret key can create charges, issue refunds, and read customer data — leaking it is a disaster.Rule: use
NEXT_PUBLIC_*only for publishable keys (e.g.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEYstarting withpk_). Secret keys use a prefix withoutNEXT_PUBLIC_and are only accessed in API routes/Server Actions. -
How do the trust policy and the permissions policy of an IAM Role differ in function?
Show answer
The trust policy decides who is allowed to assume the role (which Principal may call
sts:AssumeRole). The permissions policy decides what can be done after assuming it (which actions/resources are Allowed).Both must line up: if the trust policy does not allow B to assume, B cannot get into the role; if the trust policy allows it but the permissions are empty, getting into the role is useless.
-
Why is granting
iam:PassRolewith Resource*dangerous?Show answer
iam:PassRolelets an identity "attach" a role to a service (Lambda, EC2, ECS). Ifiam:PassRoleis granted on*, the identity can attach any role in the account — including a role withAdministratorAccess— to their new Lambda, then invoke that Lambda to escalate.Fix: restrict Resource to the specific ARN of the role allowed to be passed, plus the Condition
iam:PassedToServicefor the right service. -
When there is both an Allow (identity policy) and a Deny (SCP) on the same action, what is the result?
Show answer
DENY. An Explicit Deny at any layer (identity policy, resource policy, SCP, permission boundary, session policy) always beats Allow. If the SCP has a Deny → the request is rejected even when the identity policy allows it. This is the core mechanism that lets a platform team enforce guardrails developers cannot bypass.
-
What problem does ExternalId in a trust policy solve?
Show answer
Confused deputy problem: when service B (a third-party SaaS) is trusted by many customers to assume roles, a malicious customer could trick B into assuming a role in another customer's account. ExternalId is a shared secret between customer A and service B — when B calls
sts:AssumeRoleinto account A, it must pass A's correct ExternalId. A malicious customer does not know the secret, so they cannot impersonate.ExternalId is only effective if each customer has a different ExternalId and the secret really does not leak.
-
Why is the
Effect: Allow + NotAction: iam:*pattern dangerous?
Show answer
It grants Allow for every action that is not iam:* — essentially admin minus IAM. When AWS adds a new service (e.g. bedrock:*), the identity automatically gets permissions you never reviewed. This differs from the usual pattern (Allow a list of specific actions), which grants only the actions listed.
Best practice: use NotAction only with Effect: Deny (e.g. deny everything except a few read-only actions). Avoid Allow + NotAction.
Hands-on Exercises
Part 1: Secrets Management
# 1. Create a demo project and set up the .env pattern
mkdir secrets-lab && cd secrets-lab
git init
cat > .env.example <<EOF
DATABASE_URL=postgres://user:password@localhost:5432/mydb
API_KEY=your_key_here
EOF
cat > .env <<EOF
DATABASE_URL=postgres://realuser:realpass@db.example.com:5432/prod
API_KEY=sk_live_FAKE_DO_NOT_COMMIT
EOF
cat > .gitignore <<EOF
.env
.env.*.local
EOF
git add .env.example .gitignore
git commit -m "chore: add env template"
# 2. Install gitleaks and scan
brew install gitleaks # or: docker run zricethezav/gitleaks
gitleaks detect --source . --verbose
# → detects .env (because .gitignore does not skip the working dir)
# 3. Try "accidentally" committing .env and scan the history
git add -f .env
git commit -m "oops: committed secret"
gitleaks detect --source . --log-opts="--all" --verbose
# → finds the secret in the commit history
# 4. Scrub with git filter-repo
pip install git-filter-repo
git filter-repo --path .env --invert-paths --force
git log --all # .env is gone from every commit
# 5. Set up a pre-commit hook
cat > .pre-commit-config.yaml <<EOF
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks
EOF
pip install pre-commit
pre-commit install
Part 2: IAM and Least Privilege
# 1. Create a role whose trust policy only allows Lambda to assume it
cat > trust-policy.json <<'EOF'
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "Service": "lambda.amazonaws.com" },
"Action": "sts:AssumeRole"
}]
}
EOF
aws iam create-role \
--role-name lab-lambda-exec \
--assume-role-policy-document file://trust-policy.json
# 2. Attach a minimal policy (logging only)
aws iam attach-role-policy \
--role-name lab-lambda-exec \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
# 3. Generate a Last Accessed report
aws iam generate-service-last-accessed-details \
--arn arn:aws:iam::$(aws sts get-caller-identity --query Account --output text):role/lab-lambda-exec
# 4. Enable Access Analyzer
aws accessanalyzer create-analyzer \
--analyzer-name lab-analyzer \
--type ACCOUNT
aws accessanalyzer list-findings \
--analyzer-arn $(aws accessanalyzer list-analyzers --query 'analyzers[0].arn' --output text)
# 5. Use the IAM Policy Simulator (UI: https://policysim.aws.amazon.com)
# Test whether an identity can perform an action on a specific resource.
# 6. Cleanup
aws iam detach-role-policy --role-name lab-lambda-exec \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
aws iam delete-role --role-name lab-lambda-exec
References
- The Twelve-Factor App — Config
- GitHub Secret Scanning
- AWS Secrets Manager User Guide
- HashiCorp Vault — Dynamic Secrets
- gitleaks
- git filter-repo
- IAM best practices
- How IAM policies evaluate
- IAM Access Analyzer
- GCP IAM overview
- Azure RBAC