Serverless Security Patterns: IAM, Cognito, Secrets and WAF
Serverless security is layered: Cognito (or JWT authorizers) at the door, WAF and throttles at the edge, least-privilege IAM on every Lambda role, secrets outside source code, and zero PII in logs. One checkbox is not a program.
What you'll learn in this chapter
- Map Cognito vs IAM vs Lambda authorizer
- Write least-privilege Lambda role habits
- Store secrets correctly
- Place WAF and throttles
- Link IAM and Cognito deep chapters
1. Everyday example: leaked key in a repo
Mei in Singapore (SGD) pasted a Stripe test key in Lambda env for a demo, committed the template, and forgot. Bots found it. Secrets Manager + rotation + git scan would have stopped the story.
Roles: IAM roles. Users: Cognito. Data IAM patterns: DynamoDB security. Edge: AWS WAF on API/CloudFront (console).
2. Why layered security?
Why do we need this?
Lambda is not a fortress by magic. Over-broad roles, public APIs, and secrets in env vars are the usual breach paths. Layers catch what one control misses.
What is it?
Cognito = user/app identity pools. IAM = who may call which AWS API. Secrets Manager/SSM = credentials at runtime. WAF = web ACL rules on API/CloudFront.
3. Vertical diagram
4. How: control checklist
How to do it (step by step)
| Layer | Do | Don't |
|---|---|---|
| AuthN/Z | Cognito JWT or custom authorizer | Open API with hope |
| IAM | Resource-scoped actions; condition keys | AdministratorAccess on Lambda |
| Secrets | Secrets Manager/SSM; IAM get on one secret | Plaintext in template or git |
| Edge | WAF managed rules + API throttle stages | Infinite burst for anonymous |
| Logs | Redact tokens and PII | Log Authorization headers |
5. Commands
Who am I / caller identity
aws sts get-caller-identity
Meaning: Confirm which principal your CLI uses before IAM edits.
Inspect a Lambda role trust + inline feel
aws iam get-role --role-name checkout-api-role --query 'Role.{Arn:Arn,Trust:AssumeRolePolicyDocument}'
aws iam list-attached-role-policies --role-name checkout-api-role
Meaning: Read before attach; prefer managed least-privilege.
List secrets (names only)
aws secretsmanager list-secrets --region ap-south-1 \
--query 'SecretList[].Name' --output text
Meaning: Inventory secrets; ensure Lambda roles map 1:1 where possible.
API stage throttle glance (REST example)
aws apigateway get-stages --rest-api-id APIID --region ap-south-1 \
--query 'item[].{S:stageName,T:throttleSettings}'
Meaning: HTTP APIs use different APIs — still set rate limits.
6. Industries
- Fintech (Aisha, Lagos, NGN): Cognito + tight IAM on ledger table; WAF on public.
- Healthcare (Mei, Singapore, SGD): PHI never in logs; secrets rotation.
- Ecommerce (Rohan, Pune, INR): WAF bot control on login/checkout.
- SaaS (Priya, Bengaluru, INR): per-tenant authorizer claims.
- Gov (Omar, Amman, JOD): approved IdP federation + audit.
7. Lab
8. Lab - read-only security pass
Do this in ap-south-1 (Mumbai) unless your org forbids it. Set a budget alert first.
How to do it (step by step)
- sts get-caller-identity; note account.
- List attached policies on one Lambda role (sandbox).
- Confirm no plaintext secret in a sample template you own.
- Sketch WAF + throttle for a public login route.
Cleanup (stop billing)
- Do not attach Admin for lab convenience.
- Revoke any temporary widen you made.
9. Same pattern across industries
- Fintech (Aisha, Lagos): payment webhooks → SQS → Lambda; never block the bank callback thread.
- Ecommerce (Rohan, Pune): checkout API on API Gateway+Lambda; inventory fan-out on SNS.
- Healthcare (Mei, Singapore): appointment SMS via SNS; PHI stays in DynamoDB with fine-grained IAM.
- EdTech (Diego, São Paulo): nightly cleanup EventBridge → Lambda on student drafts.
- Logistics (Fatima, Casablanca): package scan events on EventBridge bus; Step Functions for customs saga.
- Media (Kenji, Osaka): S3 upload → Lambda thumbnails; fan-out to moderation + CDN invalidate.
- SaaS multi-tenant (Priya, Bengaluru): Cognito groups + DynamoDB partition per tenant.
- Gov portal (Omar, Amman): strangler fig — peel one PDF form route per sprint to Lambda.
10. Troubleshooting checklist
- Confirm region (ap-south-1 vs us-east-1 for CloudFront/ACM quirks).
- Check CloudWatch Logs for the function name and request id.
- Verify IAM execution role allows the API you call.
- For async: check DLQ depth and SQS age of oldest message.
- For APIs: curl -v and compare status, CORS headers, body.
- For workflows: open Step Functions execution event history.
- Re-read the linked deep chapter before reinventing a service.
- If cost spikes: check concurrency, retries, and provisioned capacity.
11. Common errors and fixes
Each row is a real mistake students and juniors hit. Read the fix before you panic.
| Error / symptom | Fix |
|---|---|
| AdministratorAccess on Lambda | Replace with resource-scoped policy. |
| Secrets in environment plaintext | Move to Secrets Manager; grant GetSecretValue. |
| Public API no auth | Add Cognito/JWT authorizer or IAM. |
| WAF missing on login | Attach web ACL; rate limit. |
| PII in CloudWatch | Redact; structured allow-list. |
| Overly trusting authorizer claims | Validate issuer/audience; short TTL. |
| * resource on dynamodb:* | Table ARN + condition keys. |
| Long-lived access keys on users | Prefer roles/OIDC; rotate if must. |
| Ignoring confused deputy | Use aws:SourceArn conditions on resource policies. |
12. FAQ
Q. Cognito user pool vs identity pool?
User pool = users/passwords/tokens; identity pool = AWS credentials for users.
Q. Lambda authorizer vs Cognito?
Authorizer = custom logic; Cognito JWT authorizer = built-in JWT check.
Q. SSM vs Secrets Manager?
Secrets Manager for rotation-heavy secrets; SSM Parameter SecureString for simpler config.
Q. Is WAF enough alone?
No — still need IAM and authN.
Q. Link IAM chapter?
aws-iam-users-groups-roles-policies-explained-with-examples.
13. Interview Q&A (Beginner / Mid / Senior + MNC)
Q. Beginner: least privilege?
Only the actions and resources needed.
Q. Beginner: where secrets live?
Secrets Manager/SSM — not git.
Q. Mid: Cognito JWT on API?
Validate token on API authorizer; map claims.
Q. Mid: execution role vs invoke role?
Execution = what Lambda can call; invoke = who can call Lambda.
Q. Senior: defense in depth?
Auth + WAF + IAM + secrets + encryption + logging controls.
Q. MNC: evidence?
Access reviews, secret rotation logs, WAF metrics.
14. Tips in English, Marathi and Hindi
Ravindra Bagale's Tip (EN)
Layers: identity, edge, IAM, secrets, clean logs — review them every release.
Ravindra Bagale's Tip (MR)
Layers: identity, edge, IAM, secrets, clean logs — प्रत्येक release.
Tip (HI)
Layers: identity, edge, IAM, secrets, clean logs — हर release।
Try at home
- List policies on one Lambda role.
- Name where secrets should live.
In short
- Start from a real story, then name the AWS services.
- Link existing chapters — do not copy their labs.
- Design for failure: retries, DLQ, idempotency, rollback.
- Measure before you buy provisioned concurrency or multi-region.
15. Architecture decision checklist
- Write the user journey in five bullets with no AWS names.
- Mark each step sync (user waits) or async.
- Name failure mode: retry, DLQ, compensate, or alert-only.
- Name the idempotency key for every write.
- Pick data store from access patterns (link DynamoDB modeling).
- Estimate monthly cost at 1x and 10x traffic (USD and INR).
- Confirm account concurrency and service quotas in ap-south-1.
- Decide auth: Cognito, IAM, Lambda authorizer, or none.
- Name on-call and which CloudWatch alarm pages them.
- Link the deep chapter you will not rewrite.
- Only then open console or IaC.
16. Copy-paste quick commands (read-only first)
# Region and identity
aws configure get region
aws sts get-caller-identity
# Lambda landscape
aws lambda list-functions --region ap-south-1 --max-items 20 \
--query 'Functions[].{N:FunctionName,R:Runtime,T:Timeout,M:MemorySize}' --output table
aws lambda get-account-settings --region ap-south-1
# API Gateway (HTTP APIs)
aws apigatewayv2 get-apis --region ap-south-1 --query 'Items[].{N:Name,Id:ApiId,Ep:ProtocolType}' --output table
# Queues and topics
aws sqs list-queues --region ap-south-1
aws sns list-topics --region ap-south-1 --query 'Topics[].TopicArn'
# Event buses and state machines
aws events list-event-buses --region ap-south-1
aws stepfunctions list-state-machines --region ap-south-1 --query 'stateMachines[].name'
# DynamoDB tables (names only)
aws dynamodb list-tables --region ap-south-1
Run these in a sandbox account. Prefer read-only IAM while learning.
17. More industry and stack stories
- Fintech (Aisha, Lagos, NGN): bank webhooks must return 200 fast — SQS absorbs spikes; ledger Lambda is idempotent on paymentId.
- Ecommerce (Rohan, Pune, INR): Black Friday — API Gateway throttle + SQS order intake; SNS fans inventory, email, analytics.
- Healthcare (Mei, Singapore, SGD): appointment reminders via SNS SMS; PHI only in DynamoDB with condition keys.
- EdTech (Diego, São Paulo, BRL): EventBridge nightly cleanup of draft quizzes; Lambda timeout 30s, not 15 min.
- Logistics (Fatima, Casablanca, MAD): package scans on custom EventBridge bus; Step Functions customs saga.
- Media (Kenji, Osaka, JPY): S3 → Lambda thumbnails; never write thumbs to the watched prefix.
- SaaS (Priya, Bengaluru, INR): Cognito groups + DynamoDB PK tenantId; one Lambda authorizer for all routes.
- Gov (Omar, Amman, JOD): strangler — peel one PDF form route per sprint from the monolith.
- Startup (Sofia, Sofia, EUR): start with Function URL for demos; move to HTTP API when partners need JWT.
- Retail (Luis, Mexico City, MXN): store POS sync via SQS FIFO when order matters; Standard when it does not.
- Python: handlers thin; put domain logic in plain modules for unit tests without Lambda.
- Node: prefer async/await; never block the event loop on sync DNS.
- Java: SnapStart for cold starts; keep dependencies lean.
- .NET: AspNetCoreServer for low-traffic tenants; watch package size.
- Go: single static binary; great for SQS workers.
- PHP: keep Laravel queues on ECS; Lambda for S3/webhooks glue.
18. Glossary (short)
| Term | Meaning |
|---|---|
| Cold start | First invoke pays init; later invokes reuse the env |
| Idempotency | Same request twice → same effect |
| DLQ | Dead-letter queue for failed messages |
| Choreography | Services react to events; no central conductor |
| Orchestration | Central workflow (Step Functions) directs steps |
| Fan-out | One event → many consumers |
| Fan-in | Many branches join before next step |
| Strangler fig | Peel routes from monolith gradually |
| Saga | Distributed tx via steps + compensations |
| Provisioned concurrency | Keep N envs warm; you pay for ready capacity |
19. Practice: explain out loud
- 60 seconds: everyday story for serverless security.
- 60 seconds: sync vs async with a checkout example.
- 60 seconds: when you refuse Lambda.
- 60 seconds: DLQ + idempotency in one breath.
- Record once; cut fillers; record again.
20. Safe lab hygiene
- Tag every lab resource with owner and expiry date.
- Set a monthly AWS Budget alarm in INR or USD before experiments.
- Prefer read-only commands first; mutate in a sandbox account.
- Delete queues, APIs, tables you created — DynamoDB and APIGW leave footprints.
- Never put production secrets in env vars or screenshots.
- Do not enable provisioned concurrency for a hello-world.
21. How this chapter links others
- Compute depth: Lambda.
- HTTP edge: API Gateway.
- Data modeling: DynamoDB.
- Messaging: SQS/SNS.
- Events: EventBridge.
- Workflows: Step Functions.
- Project chapters (build-*): worked assemblies — link, do not paste.
22. Myths to drop
| Myth | Reality |
|---|---|
| Serverless means zero servers | Servers exist; you do not manage them |
| Always cheaper than EC2 | Steady high load can favor EC2/Savings Plans |
| No Ops needed | You own IAM, data, alarms, cost, incidents |
| One Lambda per app is fine | Bounded contexts scale better |
| Queues are optional decoration | Queues are the load leveler and blast-radius wall |
23. Error budget thinking for serverless
If your monthly error budget is 0.1% on checkout, a fan-out that retries aggressively can burn the budget with duplicate emails while money stays correct. Separate business correctness SLOs from notification SLOs.
- Write two SLOs: money-correct and notify-delivered.
- Retries on money path: bounded + idempotent.
- Retries on notify path: best-effort + DLQ.
- Page humans on money DLQ; ticket on notify DLQ.
24. Regional notes (ap-south-1)
- Build labs in Mumbai (ap-south-1) unless your org mandates elsewhere.
- Some services launch first in us-east-1 — check feature availability.
- Data residency for INR fintech may require in-region only.
- Latency to end users in India usually favors ap-south-1.
25. Naming conventions that save incidents
# Suggested prefixes
# Lambda: pay-intake-prod, pay-worker-prod
# SQS: pay-orders.fifo / pay-orders-dlq
# SNS: pay-order-events
# EB bus: pay.domain
# SFN: pay-refund-saga
# DDB: pay-orders-prod
Include env (dev/stage/prod) and domain. Future you grepping CloudWatch will thank present you.
26. Pre-mortems (ten minutes)
- Imagine tomorrow headline: double charge in AED. What broke?
- Imagine DLQ depth 50,000 after a bad deploy. How do you drain?
- Imagine Cognito outage. Do APIs fail closed or serve read-only?
- Write answers in the runbook before go-live.
27. Currency and locale in examples
Rotate currencies in designs: INR, USD, EUR, AED, NGN, BRL, JPY, SGD. Rotate names: Aisha, Rohan, Mei, Diego, Fatima, Kenji, Priya, Omar, Sofia, Luis. This keeps mental models global — not one-country samples.
28. Worked story: stolen webhook secret
- Partner webhook shared a static secret in git.
- Rotate into Secrets Manager; Lambda GetSecretValue.
- WAF rate limit + signature verify.
- Git scan blocks future commits.
29. Anti-patterns
- One shared role for all Lambdas.
- Disabling auth in prod to debug.
- Logging full Authorization headers.
Revision, interview and comparison cards
Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.








More cards: Ravi Sir's Cards.
Practice Tasks
London Legal LLP is a law business in London. Oliver Hughes looks after its IT and cloud work. They count money in GBP and run their AWS resources in the eu-west-2 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.
0 / 16
Easy Least privilege — 1
Why: Idea.
What to do: Enter 1 if least privilege means only needed actions/resources.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Easy Cognito users — 1
Why: Idea.
What to do: Enter 1 if Cognito user pools handle end-user auth.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Easy Secrets not git — 1
Why: Idea.
What to do: Enter 1 if secrets belong in Secrets Manager/SSM not git.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Easy WAF edge — 1
Why: Idea.
What to do: Enter 1 if WAF helps with bot/abuse at the edge.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Easy No Authz logs — 1
Why: Idea.
What to do: Enter 1 if Authorization headers must not be logged.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Easy API throttle — 1
Why: Idea.
What to do: Enter 1 if API stage throttles limit anonymous bursts.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Easy Redact PII logs — 1
Why: Idea.
What to do: Enter 1 if PII must be redacted from logs.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Easy STS caller identity
Why: Whoami.
What to do: Show caller identity
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Execution role — 1
Why: Idea.
What to do: Enter 1 if execution role is what Lambda may call in AWS.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Medium No Admin on Lambda — 1
Why: Idea.
What to do: Enter 1 if AdministratorAccess on Lambda is an anti-pattern.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Medium Authorizer needed — 1
Why: Idea.
What to do: Enter 1 if money APIs need an authorizer/JWT.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Medium Rotate secrets — 1
Why: Idea.
What to do: Enter 1 if secrets should rotate on schedule or after leak.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Medium SourceArn conditions — 1
Why: Idea.
What to do: Enter 1 if aws:SourceArn helps confused deputy cases.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Medium Deny star sketch
Why: LP.
What to do: YAML idea: effect: Deny action: "*" when learning least privilege contrasts.
- Start from the top-level keys the task names.
- Indent child keys with 2 spaces (no tabs).
- Fill in each property with the value from the task.
- Click Check answer. Key order does not matter.
Hard Defense in depth — 1
Why: Idea.
What to do: Enter 1 if security needs multiple layers not one checkbox.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Hard Invoke vs exec — 1
Why: Idea.
What to do: Enter 1 if invoke permission differs from execution role.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.