Ravindra BagaleCourses & study guides मराठी Track your progress

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

Identity -> edge controls -> IAM roles -> secrets fetch -> encrypted dataNever admin role on a webhook Lambda
Rotate and scan continuously
Users: Cognito / JWT / authorizer Edge: WAF + API throttles IAM: least privilege execution roles Secrets: Secrets Manager / SSM Data: encryption + no PII in logs Defense in layers, not one checkbox
IAM, Cognito, secrets, WAF together.

4. How: control checklist

How to do it (step by step)

LayerDoDon't
AuthN/ZCognito JWT or custom authorizerOpen API with hope
IAMResource-scoped actions; condition keysAdministratorAccess on Lambda
SecretsSecrets Manager/SSM; IAM get on one secretPlaintext in template or git
EdgeWAF managed rules + API throttle stagesInfinite burst for anonymous
LogsRedact tokens and PIILog 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)

  1. sts get-caller-identity; note account.
  2. List attached policies on one Lambda role (sandbox).
  3. Confirm no plaintext secret in a sample template you own.
  4. Sketch WAF + throttle for a public login route.

Cleanup (stop billing)

  1. Do not attach Admin for lab convenience.
  2. 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

  1. Confirm region (ap-south-1 vs us-east-1 for CloudFront/ACM quirks).
  2. Check CloudWatch Logs for the function name and request id.
  3. Verify IAM execution role allows the API you call.
  4. For async: check DLQ depth and SQS age of oldest message.
  5. For APIs: curl -v and compare status, CORS headers, body.
  6. For workflows: open Step Functions execution event history.
  7. Re-read the linked deep chapter before reinventing a service.
  8. 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 / symptomFix
AdministratorAccess on LambdaReplace with resource-scoped policy.
Secrets in environment plaintextMove to Secrets Manager; grant GetSecretValue.
Public API no authAdd Cognito/JWT authorizer or IAM.
WAF missing on loginAttach web ACL; rate limit.
PII in CloudWatchRedact; structured allow-list.
Overly trusting authorizer claimsValidate issuer/audience; short TTL.
* resource on dynamodb:*Table ARN + condition keys.
Long-lived access keys on usersPrefer roles/OIDC; rotate if must.
Ignoring confused deputyUse 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

  1. List policies on one Lambda role.
  2. Name where secrets should live.

In short

  1. Start from a real story, then name the AWS services.
  2. Link existing chapters — do not copy their labs.
  3. Design for failure: retries, DLQ, idempotency, rollback.
  4. Measure before you buy provisioned concurrency or multi-region.

15. Architecture decision checklist

  1. Write the user journey in five bullets with no AWS names.
  2. Mark each step sync (user waits) or async.
  3. Name failure mode: retry, DLQ, compensate, or alert-only.
  4. Name the idempotency key for every write.
  5. Pick data store from access patterns (link DynamoDB modeling).
  6. Estimate monthly cost at 1x and 10x traffic (USD and INR).
  7. Confirm account concurrency and service quotas in ap-south-1.
  8. Decide auth: Cognito, IAM, Lambda authorizer, or none.
  9. Name on-call and which CloudWatch alarm pages them.
  10. Link the deep chapter you will not rewrite.
  11. 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)

TermMeaning
Cold startFirst invoke pays init; later invokes reuse the env
IdempotencySame request twice → same effect
DLQDead-letter queue for failed messages
ChoreographyServices react to events; no central conductor
OrchestrationCentral workflow (Step Functions) directs steps
Fan-outOne event → many consumers
Fan-inMany branches join before next step
Strangler figPeel routes from monolith gradually
SagaDistributed tx via steps + compensations
Provisioned concurrencyKeep N envs warm; you pay for ready capacity

19. Practice: explain out loud

  1. 60 seconds: everyday story for serverless security.
  2. 60 seconds: sync vs async with a checkout example.
  3. 60 seconds: when you refuse Lambda.
  4. 60 seconds: DLQ + idempotency in one breath.
  5. 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.

22. Myths to drop

MythReality
Serverless means zero serversServers exist; you do not manage them
Always cheaper than EC2Steady high load can favor EC2/Savings Plans
No Ops neededYou own IAM, data, alarms, cost, incidents
One Lambda per app is fineBounded contexts scale better
Queues are optional decorationQueues 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.

  1. Write two SLOs: money-correct and notify-delivered.
  2. Retries on money path: bounded + idempotent.
  3. Retries on notify path: best-effort + DLQ.
  4. 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)

  1. Imagine tomorrow headline: double charge in AED. What broke?
  2. Imagine DLQ depth 50,000 after a bad deploy. How do you drain?
  3. Imagine Cognito outage. Do APIs fail closed or serve read-only?
  4. 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

  1. Partner webhook shared a static secret in git.
  2. Rotate into Secrets Manager; Lambda GetSecretValue.
  3. WAF rate limit + signature verify.
  4. 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.

Revision card: Security in layers. One checkbox never stops bots, leaked keys, and over-broad roles. Cognito/JWT, WAF+throttle, least-privilege IAM, secrets vault, clean logs. Grant GetSecretValue on one secret; never AdministratorAccess on webhooks. Mei rotates a leaked key into Secrets Manager the same day.
Revision card: Security in layers · Download PNG · Open card page
Revision card: Lambda roles right. Execution role = what Lambda may call; invoke = who may call it. Resource ARNs + condition keys beat Action *. Separate roles per function; review attachments quarterly. Priya's authorizer checks issuer and audience every token.
Revision card: Lambda roles right · Download PNG · Open card page
Comparison: Admin on Lambda vs Least privilege. Admin on Lambda: AdministratorAccess for convenience. Least privilege: Only needed actions and resource ARNs.
Comparison: Admin on Lambda vs Least privilege · Download PNG · Open card page
Comparison: Plaintext env/git vs Secrets Manager. Plaintext env/git: Keys in template env committed to git. Secrets Manager: Runtime GetSecretValue; rotate versions.
Comparison: Plaintext env/git vs Secrets Manager · Download PNG · Open card page
Interview card: Least privilege?. Only the actions and resources the function needs. Start deny-by-default; add after a failing call is understood. MNC: show last access review date.
Interview card: Least privilege? · Download PNG · Open card page
Interview card: Cognito vs authorizer?. User pools issue tokens; JWT authorizer validates them on API. Custom authorizer when logic exceeds JWT checks. MNC: where do claims map to tenants?
Interview card: Cognito vs authorizer? · Download PNG · Open card page
Interview card: Is WAF enough?. No — still need authN and IAM. WAF + rate limits blunt bots on login/checkout. MNC: which managed rule groups are on?
Interview card: Is WAF enough? · Download PNG · Open card page
Interview card: Where do secrets live?. Secrets Manager or SSM SecureString — never git. Rotate on schedule; grant one GetSecretValue. MNC: prove rotation happened.
Interview card: Where do secrets live? · Download PNG · Open card page

More cards: Ravi Sir's Cards.

Practice Tasks

About this scenario

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.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Cognito users — 1

Why: Idea.

What to do: Enter 1 if Cognito user pools handle end-user auth.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Secrets not git — 1

Why: Idea.

What to do: Enter 1 if secrets belong in Secrets Manager/SSM not git.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy WAF edge — 1

Why: Idea.

What to do: Enter 1 if WAF helps with bot/abuse at the edge.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy No Authz logs — 1

Why: Idea.

What to do: Enter 1 if Authorization headers must not be logged.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy API throttle — 1

Why: Idea.

What to do: Enter 1 if API stage throttles limit anonymous bursts.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Redact PII logs — 1

Why: Idea.

What to do: Enter 1 if PII must be redacted from logs.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy STS caller identity

Why: Whoami.

What to do: Show caller identity

How:
  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium No Admin on Lambda — 1

Why: Idea.

What to do: Enter 1 if AdministratorAccess on Lambda is an anti-pattern.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Authorizer needed — 1

Why: Idea.

What to do: Enter 1 if money APIs need an authorizer/JWT.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Rotate secrets — 1

Why: Idea.

What to do: Enter 1 if secrets should rotate on schedule or after leak.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium SourceArn conditions — 1

Why: Idea.

What to do: Enter 1 if aws:SourceArn helps confused deputy cases.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Deny star sketch

Why: LP.

What to do: YAML idea: effect: Deny action: "*" when learning least privilege contrasts.

How:
  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. 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.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard Invoke vs exec — 1

Why: Idea.

What to do: Enter 1 if invoke permission differs from execution role.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.