Skip to Content
Cloud Engineering Academy
4. API Development & Integration

Module project: the Account Information API (Cognito, ownership checks, idempotency, throttling and WAF)

Run, attack and optionally deploy a .NET 10 Account Information API where each customer sees only their own accounts: Cognito access tokens and scopes, server-side customer mapping, validation, idempotent statement requests, ProblemDetails, correlation IDs, throttling and AWS WAF.

advanced⏱ 4 h 🟡 Low costDVA-C03SAA-C03SCS-C03

Assumes: .NET 10 LTS · ASP.NET Core 10 (JwtBearer 10.0.15) · AWS SDK for .NET v4 (AWSSDK.DynamoDBv2 4.1.0.2) · Amazon.Lambda.AspNetCoreServer.Hosting 2.2.1 · Microsoft.Extensions.Http.Resilience 10.11.0 · xUnit v3 4.0.3 · Amazon.CDK.Lib 2.277.0 · Cdklabs.CdkNag 3.0.2 · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this project you can:

  • Run an ASP.NET Core 10 API locally with a local test token issuer, and run its 55 automated tests without an AWS account.
  • Explain how the API separates operation-level authorisation (scopes, in policies) from object-level authorisation (does this customer own this account, in the data layer), and prove it with a second user.
  • Show that "not yours" and "does not exist" are indistinguishable (404) so the API is not an account-enumeration oracle.
  • Use the 400 versus 422 split: 400 for malformed input, 422 for well-formed input that breaks a business rule.
  • Make the one write endpoint safe to retry with an Idempotency-Key, and describe the DynamoDB conditional-write design behind it.
  • Read the CDK stack that puts Cognito, API Gateway, Lambda, DynamoDB and AWS WAF around the same binary, and deploy it for under an hour in the sandbox account, then tear it down.
  • State the difference between API Gateway throttling, the in-app per-customer limiter and WAF rate-based rules, and why a bank wants all three.

This page is the module project for Module 4. It pulls together REST API design, OAuth 2.0, OIDC and JWTs, Cognito user pools, Request validation, CORS, Idempotency keys, Calling partner APIs, API security with WAF and the OWASP API Top 10 and API monitoring. It feeds Capstone 1.

Prerequisites

  • The lessons above. Read at least the REST design, OAuth/JWT, idempotency and WAF lessons first.
  • Docker Desktop. The .NET 10 SDK, curl and jq are optional for the local part.
  • For the optional deployment (Parts 4 and 5): AWS CLI v2 with learn-sandbox, Node.js with the AWS CDK CLI (npm i -g aws-cdk), the .NET 10 SDK, and CDK bootstrapped in us-east-1. Use only the sandbox account.

Why this matters in banking

An Account Information API is the first thing a bank exposes to a mobile app or a partner, and it is where the most expensive mistakes live. Broken object-level authorisation (OWASP API1) means customer A changes ACC-0000012345 to ACC-0000067890 in the URL and reads customer B's balance. A retried statement request that creates two statements, or a payment that is created twice, becomes a complaint. A missing rate limit lets one script scrape the whole customer base. And none of it can be diagnosed if you cannot connect a customer's error to a log line.

This project makes each control concrete, with a test that fails if the control is removed.

The idea in plain language

The API has five operations and a very simple rule: the customer is never something the client tells you. The client proves who it is with an access token. The server takes the token's sub (a stable user id from Cognito), looks it up in its own table to find the Harbourline customer id, and puts that id into every data query. If the account is not in that customer's list, the answer is "not found".

Analogy: a branch counter. The teller does not ask "which customer's accounts shall I show?" They look at your verified ID, find your record in their own system and only open your files. If you ask for a file number that is not yours, they say "I have no such file", not "that belongs to someone else".

What the AWS services do here

ServiceRole in the projectLocal stand-in
Amazon Cognito user poolAuthenticates users (authorization code with PKCE), issues access tokens containing the scopes harbourline-accounts/accounts.read and harbourline-accounts/statements.writePOST /dev/tokens local test issuer (Development only)
Amazon API Gateway REST APITLS edge, Cognito authoriser with scope checks per method, request validation, stage throttling, access logsKestrel on http://localhost:5080
AWS Lambda (dotnet10, arm64)Runs the same ASP.NET Core binary through the Lambda hosting packageKestrel
Amazon DynamoDB (on-demand, TTL)Idempotency records, one item per scoped keyIn-memory idempotency store
AWS WAFManaged rule groups plus a rate-based rule per IP (Lab 4.7)Not emulated
Amazon CloudWatch Logs and X-RayStructured JSON logs and tracesConsole output

Microsoft / Azure comparison

You know (Microsoft/Azure)In this projectWhat's different
Azure API Management with validate-jwtAPI Gateway Cognito authoriser with AuthorizationScopes, plus JwtBearer inside the appTwo layers: the gateway rejects early, the app re-validates because it must not trust the network
Entra ID app roles and scopesCognito resource server and custom scopesScopes are resource-server-id/scope-name; the access token has a scope claim and no aud
Azure Functions Premium behind APIMOne ASP.NET Core app on LambdaThe Lambda hosting package maps API Gateway events to ASP.NET Core requests; the same code runs on Kestrel
APIM rate-limit-by-keyStage throttling plus RateLimiter partitioned by customer plus WAFGateway limits are per stage and method, WAF is per IP, only the app knows the customer
Azure Front Door WAFAWS WAF web ACL on the API stageManaged rule groups are named differently; association is by stage ARN
Cosmos DB with TTL for dedupeDynamoDB conditional put with a TTL attributeA conditional write is the atomic "claim"

Architecture

Inside the app, a request passes through these layers in order:

The ordering is not accidental. CORS runs before authentication so a browser preflight needs no token. The rate limiter runs after authentication so it can use the customer as the key. Ownership is enforced at the very end, in the data layer, where the customerId argument comes from the validated token.

Step-by-step implementation

The project folder is labs/m04-account-information-api. Solution: Harbourline.AccountInformation.slnx.

openapi/                                          design contract (Lab 4.1)
src/Harbourline.AccountInformation.Api/           ASP.NET Core minimal API (Kestrel locally, Lambda in AWS)
tests/Harbourline.AccountInformation.Api.Tests/   55 tests
infra/cdk/Harbourline.AccountInformation.Infra/   HlM04-AccountInformation and HlM04-Waf stacks

Part 1: run the tests (free)

Run the tests in Docker

MSYS_NO_PATHCONV=1 docker run --rm --memory 3g \
  -v "$PWD/labs/m04-account-information-api:/src" \
  -v cea-nuget-m04:/root/.nuget/packages \
  -w /src mcr.microsoft.com/dotnet/sdk:10.0 \
  sh -c "dotnet test --solution Harbourline.AccountInformation.slnx; find . -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} +"

Expected result (verified 2026-11-18 in Docker): total: 55, failed: 0, succeeded: 54, skipped: 1. The skipped test, Claim_complete_replay_against_real_table, talks to a real DynamoDB table and runs only with RUN_AWS_TESTS=1.

Map the tests to the requirements

RequirementTest class and examples
AuthenticationAuthenticationTests: no token is 401 with a bearer challenge; an ID token is rejected (APIs accept access tokens only); a token for another app client, from another issuer, expired or tampered is rejected
Operation authorisationA read-only token cannot request statements (403); a valid token for a user with no customer record is 403
Object authorisation (second user)OwnershipTests: each customer lists only their own accounts; someone else's account looks exactly like a missing one; someone else's transactions are not found; you cannot request a statement for someone else's account; a client-supplied customer id is ignored
Money representationAccount_response_carries_money_as_decimal_string_and_no_customer_id: balances are strings, never floating point, and the response does not leak the internal customer id
ValidationStatementRequestTests: missing or malformed Idempotency-Key is 400; shape errors (missing field, bad enum, malformed JSON, wrong date format) are 400; business rule errors (reversed range, more than 12 months, future date) are 422
PaginationTransactionPagingTests: walking all pages returns every transaction once, newest first; malformed pageSize, dates and cursors are 400; a cursor issued for other filters is rejected
IdempotencyReplay of the first response for same key and body; same key with different body is 422; the same key from another customer does not collide; the store tests cover the conditional put, replay, mismatch while in progress, reclaiming an abandoned lock and TTL expiry
ObservabilityCrossCuttingTests: caller correlation id echoed; unsafe ids replaced; X-Amzn-Trace-Id root used when no header; ProblemDetails carry correlation and trace ids
ThrottlingThe fourth request in the window is 429 with Retry-After, and other customers are unaffected
ResilienceCoreBankingResilienceTests: transient 503s are retried; 404 is not retried; a persistent failure opens the circuit and stops calling the core; the API returns 503 with Retry-After when the core is down

Part 2: run it locally and try to break it (free)

Start the API

dotnet run --project src/Harbourline.AccountInformation.Api   # http://localhost:5080, Development

Two fictional customers are seeded: sub-alice-0001 maps to CUS-00012345 (two GBP accounts) and sub-bob-0002 maps to CUS-00067890 (one EUR account).

Mint a token for Alice and call the API

# Mint a local test token for Alice (Development only: /dev/tokens does not exist in Production).
TOKEN=$(curl -s -X POST localhost:5080/dev/tokens -H "Content-Type: application/json" \
  -d '{"subject":"sub-alice-0001","scopes":["harbourline-accounts/accounts.read","harbourline-accounts/statements.write"]}' | jq -r .access_token)

curl -s localhost:5080/v1/accounts -H "Authorization: Bearer $TOKEN" | jq
curl -s "localhost:5080/v1/accounts/ACC-0000012345/transactions?pageSize=5" -H "Authorization: Bearer $TOKEN" | jq

Attack it as Alice

# Bob's account: expect 404 (the same answer as a nonexistent account).
curl -i localhost:5080/v1/accounts/ACC-0000067890 -H "Authorization: Bearer $TOKEN"
# A malformed id: also 404 (it cannot belong to anyone).
curl -i localhost:5080/v1/accounts/not-an-account -H "Authorization: Bearer $TOKEN"
# No token: 401.
curl -i localhost:5080/v1/accounts
# Bad page size: 400 ProblemDetails with an errors object.
curl -i "localhost:5080/v1/accounts/ACC-0000012345/transactions?pageSize=500" -H "Authorization: Bearer $TOKEN"

Look at each response body. They are application/problem+json with a type, title, status, instance, a correlationId and a traceId. Copy a correlationId and find the same value in the JSON log line the API wrote to its console.

Replay the write

curl -i -X POST localhost:5080/v1/accounts/ACC-0000012345/statement-requests \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -H "Idempotency-Key: 3f1c9a52-6a8e-4c39-b5a5-0f6f2d9b7e11" \
  -d '{"fromDate":"2026-10-01","toDate":"2026-10-31","format":"pdf"}'

You should get 202 Accepted with a Location header. Send the identical command again: the same body returns with an idempotent-replay marker and no second statement request. Change "format":"pdf" to "csv" and reuse the key: 422 (key reused with a different request).

Part 3: read the design decisions (free)

Authentication (Auth/CognitoAuthentication.cs)

Cognito access tokens have no aud claim, so audience validation is off and the API checks three things instead: the issuer, token_use == "access", and client_id against an allow list of app clients. The signature algorithm is pinned to RS256 so an attacker cannot ask for none or an HMAC variant. MapInboundClaims = false keeps claim names as issued (sub, scope, client_id) rather than renaming them to long Microsoft schema names. The same AccessTokenChecks run in local test mode, so tests exercise the production rules.

Authorisation (Auth/AuthenticationSetup.cs, Accounts/AccountStores.cs)

Policies accounts:read and statements:write require an authenticated user, a customer_id claim and the matching scope. CustomerClaimsTransformation adds customer_id by looking up sub in ICustomerDirectory. A user with no record gets no claim and therefore a 403. Handlers read customer_id from the principal only, never from the URL, query string or body. The store methods take customerId as a parameter, so an unfiltered query is impossible to write by accident.

Validation (Accounts/RequestValidation.cs)

Shape errors (malformed JSON, wrong type, missing field) are 400. Business rule errors (reversed dates, a range over 12 months, a future end date) are 422. In AWS, API Gateway repeats the shape check with a JSON Schema model before the Lambda is invoked; the app repeats it anyway, because the app must be safe when reached directly.

Idempotency (Idempotency/)

The filter requires an Idempotency-Key, scopes it by customer (customerId#key), fingerprints the request, and asks the store to begin. DynamoDbIdempotencyStore uses a conditional PutItem to claim the key atomically. Outcomes: started (run the endpoint and store the response), replay (return the stored response), mismatch (422) and in progress (409 with Retry-After). An abandoned lock can be reclaimed after a timeout, and DynamoDB TTL deletes completed records later. See Idempotency keys for the full reasoning.

Observability (Hosting/)

CorrelationIdMiddleware accepts a well-formed caller X-Correlation-ID (8 to 64 letters, digits and hyphens, so it cannot inject log text), falls back to the root of X-Amzn-Trace-Id, and otherwise generates a UUID v7. It echoes the id and puts it in a logging scope, so every JSON log line of the request carries it. GlobalExceptionHandler turns exceptions into RFC 9457 ProblemDetails without stack traces.

Throttling (Hosting/RateLimiting.cs, CDK stage settings)

API Gateway stage throttling is set to a steady rate of 20 requests per second with a burst of 40 across the stage. The app has a fixed-window limiter partitioned by customer_id (120 per minute by default) returning 429 with Retry-After. WAF adds a per-IP rate-based rule (100 requests per 60 seconds in this lab). Three layers, three different keys.

Resilience (Accounts/CoreBankingAccountStore.cs)

The optional Accounts:Source=CoreBanking mode reads from a simulated core banking system through a typed HttpClient with the standard resilience pipeline: total timeout, retries with exponential back-off and jitter (GET only), a circuit breaker and a per-attempt timeout. A 404 from the core means "not visible to this customer". This is the Lab 4.4 pattern from Calling partner APIs.

Part 4: deploy for under an hour (credits)

Cost and scope

Deploying creates a Cognito user pool, a REST API, a Lambda function, a DynamoDB table and log groups. Lab traffic costs cents. The WAF stack in Part 5 costs about 0.011 USD per hour while it exists, so deploy it, test and destroy it the same day. Use only the sandbox account.

Sign in and publish the API for Lambda

aws sso login --profile learn-sandbox
aws sts get-caller-identity --profile learn-sandbox

# Publish for the Lambda arm64 runtime.
dotnet publish src/Harbourline.AccountInformation.Api -c Release -r linux-arm64 --self-contained false -o artifacts/api

Deploy identity, data, Lambda and the REST API

cd infra/cdk
# Pick a globally unique Cognito domain prefix.
cdk deploy HlM04-AccountInformation --profile learn-sandbox -c domainPrefix=hl-m04-accounts-<yourname> -c owner=<yourname>

Keep the outputs: ApiUrl, UserPoolId, WebClientId and HostedDomain.

Create two test users and map them

In the Console: Cognito → User pools → hl-m04-customers → Users → Create user. Use addresses like alice@example.com and bob@example.com and strong passwords. Read each user's sub from the user's details, then redeploy with the mapping:

cdk deploy HlM04-AccountInformation --profile learn-sandbox -c domainPrefix=hl-m04-accounts-<yourname> \
  -c customerMapJson='{"<alice-sub>":"CUS-00012345","<bob-sub>":"CUS-00067890"}'

Without the mapping, a valid token for a user not in the map gets a 403 from the app. That is the behaviour you want from the second layer.

Get tokens and call the API

Use the hosted login with authorization code plus PKCE using the WebClientId and HostedDomain outputs, for example with Postman's OAuth 2.0 helper (callback http://localhost:5173/callback, scopes openid, harbourline-accounts/accounts.read, harbourline-accounts/statements.write). Call ApiUrl with the access token. Repeat the Part 2 attacks as Alice and as Bob.

Part 5: add and attack AWS WAF (Lab 4.7, credits)

Deploy the web ACL

cdk deploy HlM04-Waf --profile learn-sandbox -c domainPrefix=hl-m04-accounts-<yourname>

The stack creates a regional web ACL with two AWS managed rule groups (AWSManagedRulesCommonRuleSet, AWSManagedRulesKnownBadInputsRuleSet) and a rate-based rule that blocks with a 429 after 100 requests per IP in a 60 second window, then associates it with the API stage.

Attack your own API from one IP

API=https://<api-id>.execute-api.us-east-1.amazonaws.com/learn
for i in $(seq 1 300); do curl -s -o /dev/null -w "%{http_code}\n" "$API/v1/accounts"; done | sort | uniq -c

Expect mostly 401 (no token) at first, then 429 once WAF's detection kicks in, which can take a minute or two. Only attack APIs you own. Load-testing third-party endpoints can breach their terms and the law.

Destroy the web ACL now

cdk destroy HlM04-Waf --profile learn-sandbox

AWS Console instructions

  • Cognito: Console → Amazon Cognito → User pools → hl-m04-customers. Check App integration → Resource servers (the scopes), App clients (hl-m04-web, public client, PKCE) and Users.
  • API Gateway: Console → API Gateway → hl-m04-account-information → Resources. Open each method's Method request and confirm the authorisation scopes. Stages → learn → Logs and tracing shows access logs.
  • WAF: Console → AWS WAF → Web ACLs → us-east-1 → hl-m04-account-information → Sampled requests, to see what was blocked.
  • DynamoDB: Console → Tables → hl-m04-idempotency → Explore items, to see a stored key (customer and key, never the secret body).

Menu wording changes over time (⚠ VERIFY).

AWS CLI

# Find the stack outputs
aws cloudformation describe-stacks --stack-name HlM04-AccountInformation \
  --query "Stacks[0].Outputs" --profile learn-sandbox --region us-east-1

# Tail the Lambda's structured logs, filtered by one correlation id
aws logs tail /aws/lambda/hl-m04-account-information --since 15m --format short \
  --filter-pattern '"<correlation-id>"' --profile learn-sandbox --region us-east-1

# Idempotency records (expect scoped keys such as CUS-00012345#<uuid>)
aws dynamodb scan --table-name hl-m04-idempotency --max-items 5 --profile learn-sandbox --region us-east-1

The scan is for a small lab table only. Never scan a production table.

Infrastructure as Code

The project ships CDK in C#. A Terraform version is not included; the equivalent resources are aws_cognito_user_pool, aws_cognito_resource_server, aws_api_gateway_rest_api with a COGNITO_USER_POOLS authorizer, aws_lambda_function, aws_dynamodb_table with TTL and aws_wafv2_web_acl with aws_wafv2_web_acl_association.

AccountInformationStack.cs (scopes and a scoped method)
var readScope = new ResourceServerScope(new ResourceServerScopeProps
{
    ScopeName = "accounts.read", ScopeDescription = "Read your own accounts and transactions",
});
var resourceServer = pool.AddResourceServer("ResourceServer", new UserPoolResourceServerOptions
{
    Identifier = "harbourline-accounts",
    Scopes = [readScope /* , writeScope */],
});

MethodOptions Scoped(string scopeName) => new()
{
    Authorizer = authorizer,
    AuthorizationType = AuthorizationType.COGNITO,
    AuthorizationScopes = [$"harbourline-accounts/{scopeName}"],   // API Gateway checks the access token's scope
};

accounts.AddMethod("GET", integration, Scoped("accounts.read"));
AccountInformationStack.cs (least-privilege table access)
// Four item-level actions on one table: no Scan, no table administration.
function.AddToRolePolicy(new PolicyStatement(new PolicyStatementProps
{
    Actions = ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem"],
    Resources = [table.TableArn],
}));

Complete code

The complete project is in labs/m04-account-information-api/. The core of the authorisation design, the endpoint registration:

Accounts/AccountEndpoints.cs (registration and customer resolution)
var v1 = app.MapGroup("/v1")
    .RequireRateLimiting(RateLimiting.PerCustomerPolicy)
    .RequireCors(CorsSetup.PolicyName);

v1.MapGet("/accounts", ListAccounts).RequireAuthorization(Policies.AccountsRead);
v1.MapGet("/accounts/{accountId}", GetAccount).RequireAuthorization(Policies.AccountsRead);
v1.MapGet("/accounts/{accountId}/transactions", ListTransactions).RequireAuthorization(Policies.AccountsRead);
v1.MapPost("/accounts/{accountId}/statement-requests", CreateStatementRequest)
    .RequireAuthorization(Policies.StatementsWrite)
    .AddEndpointFilter<IdempotencyFilter>();
v1.MapGet("/statement-requests/{statementRequestId}", GetStatementRequest).RequireAuthorization(Policies.AccountsRead);

// The customer always comes from the validated token, never from the URL, query or body.
private static string CustomerId(ClaimsPrincipal user) =>
    user.FindFirst(CustomerClaimsTransformation.CustomerIdClaim)?.Value
    ?? throw new InvalidOperationException("Authorisation policy guarantees a customer_id claim.");
Accounts/AccountEndpoints.cs (one answer for missing and not yours)
internal static async Task<IResult> GetAccount(string accountId, ClaimsPrincipal user, IAccountStore store, CancellationToken ct)
{
    if (!RequestValidation.AccountIdPattern().IsMatch(accountId))
    {
        return NotFound(); // a malformed id cannot belong to anyone
    }

    var account = await store.GetAccountAsync(CustomerId(user), accountId, ct);
    return account is null ? NotFound() : Results.Ok(AccountResponse.From(account));
}
Auth/CognitoAuthentication.cs (access-token checks)
public static string? Check(ClaimsPrincipal? principal, IReadOnlyCollection<string> allowedClientIds)
{
    var tokenUse = principal?.FindFirst("token_use")?.Value;
    var clientId = principal?.FindFirst("client_id")?.Value;

    if (!string.Equals(tokenUse, "access", StringComparison.Ordinal))
        return "Only access tokens are accepted (an ID token is for the client, not for APIs).";

    if (clientId is null || !allowedClientIds.Contains(clientId, StringComparer.Ordinal))
        return "This app client may not call the API.";

    return null;
}

Code explained line by line

  1. MapGroup("/v1") with RequireRateLimiting and RequireCors applies the per-customer limiter and CORS policy to all five endpoints in one place, so a new endpoint cannot forget them.
  2. Each endpoint names its policy with RequireAuthorization. accounts:read and statements:write are separate scopes, so a read-only token cannot create anything.
  3. AddEndpointFilter<IdempotencyFilter>() wraps only the one write endpoint. Reads are naturally idempotent and need no key.
  4. CustomerId(user) throws if the claim is missing. The authorisation policy already guarantees it, so reaching the exception means a wiring mistake, which should be loud.
  5. The regular expression check returns the same 404 as a missing account. Returning 400 for malformed ids and 404 for unknown ones would let an attacker learn which ids have a valid shape.
  6. store.GetAccountAsync(CustomerId(user), accountId, ct) passes the customer into the query. The "not yours" case is a query that returns nothing, not a separate check afterwards.
  7. Check runs inside OnTokenValidated, after the signature and lifetime are already verified. token_use stops an ID token being used as an API credential; client_id stops a token minted for some other app client in the same pool.
  8. ValidateAudience = false is deliberate because Cognito access tokens carry client_id instead of aud. It is paired with the explicit client allow list. Switching audience validation on without understanding this causes every token to fail.
  9. In Program.cs, app.UseCors() comes before UseAuthentication() and UseRateLimiter() comes after it; UseAuthorization() follows the limiter. Reordering these changes behaviour (preflight failures, or a limiter that can only key on IP).

Security considerations

⚠ Learning shortcut — not for production

The customer directory is a map from configuration (CustomerDirectory__MapJson), the user pool and DynamoDB table use RemovalPolicy.DESTROY, MFA is optional, the Lambda function runs without a VPC and with X-Ray on, /dev/tokens exists in Development, and CORS allows a single placeholder origin. In production: a customer table written at onboarding and keyed by sub, RETAIN and deletion protection on the pool and table, required MFA with step-up, threat protection, a VPC or PrivateLink path to the core banking system, a real front-end origin list, and AWS WAF attached from day one.

  • BOLA is the main risk (OWASP API1). The second-user tests exist because it is the easiest bug to ship.
  • Access tokens only. An ID token is a statement to the client about the user; an API that accepts it can be called with tokens never meant for it.
  • Local token issuer. Auth:Mode=LocalTestIssuer is refused outside Development by an explicit InvalidOperationException. Keep that guard; it is a control.
  • No stack traces, no internal ids. Errors are ProblemDetails; account responses omit the customer id.
  • Logs. Log the correlation id, customer id and outcome. Do not log tokens, full account numbers or request bodies. UK GDPR treats identifiers as personal data, so retention and access to these logs need a decision (⚠ legal review required; this project does not make a system compliant with anything).
  • Money as decimal strings. Never double for amounts.
  • Least privilege. The Lambda role has four DynamoDB item actions on one table and the managed basic execution policy.

Banking use case

A retail bank's mobile app shows balances and recent transactions, and lets the customer request a statement as a PDF or CSV. The first call after login is GET /v1/accounts; the customer never types an account id into the URL themselves. The statement request is the only write, and mobile networks retry, so it carries an idempotency key. The gateway protects the front door (token, scope, schema, throttle), WAF absorbs scripted abuse, and the app enforces what only it can: which customer owns which account. Support staff investigate a complaint by pasting the correlation id from the customer's error message into the log search.

Common mistakes

  • Trusting a customerId in the path, query or body. The identity is the token, not anything the client writes.
  • Returning 403 for "not yours". That confirms the resource exists. Return 404.
  • Accepting ID tokens because they "validate fine".
  • Turning on audience validation for Cognito access tokens and then wondering why every request is a 401.
  • Putting the rate limiter before authentication, which can then only key by IP.
  • Trusting API Gateway alone. If the Lambda can be reached by another path, it needs its own checks. Keep the app's validation even when the gateway also validates.
  • Leaving the WAF stack deployed. It bills hourly; destroy it the same day.
  • Using the Development token endpoint outside Development.

Troubleshooting

SymptomLikely causeFix
401 from API Gateway with a valid-looking tokenAn ID token was sent instead of an access tokenSend the access token
403 from API GatewayThe token lacks the scope required by that methodRequest the scope in the authorize call
403 from the app (ProblemDetails)The user's sub is not in customerMapJsonRedeploy with the mapping
502 from API GatewayLambda failed to start: missing publish output or wrong architectureRepublish for linux-arm64; read /aws/lambda/hl-m04-account-information
cdk deploy fails on the domainCognito domain prefix already takenChoose another domainPrefix
cdk synth reports cdk-nag errorsA rule fired that is not acknowledged, or an ID lacks its bracketed suffixRead the finding, fix it or acknowledge it with a reason using the exact ID
dotnet test is green but dotnet build infra/cdk/... failsTest runs do not necessarily build the CDK projectBuild the CDK project explicitly (it compiles after the cdk-nag v3 fixes above)
429 immediately in testsThe per-customer limiter window is tiny in the test configurationIntended: the test proves the limiter
No log lines for a correlation idLogs not yet delivered, or filtering the wrong groupWait a minute; use /aws/lambda/hl-m04-account-information

Cost and cleanup

Local part: free. Deployed part: credits (cents per hour; WAF about 0.011 USD per hour plus request charges while it exists; Cognito Essentials is free up to a monthly-active-user allowance, ⚠ VERIFY the current tier and prices).

cd infra/cdk
cdk destroy HlM04-Waf HlM04-AccountInformation --profile learn-sandbox

# Nothing tagged for the lab should remain (the tagging API can lag a few minutes):
aws resourcegroupstaggingapi get-resources \
  --tag-filters Key=Project,Values=cea-lab Key=Lab,Values=m04-account-information-api \
  --query "ResourceTagMappingList[].ResourceARN" --profile learn-sandbox --region us-east-1

# Local build output
find labs/m04-account-information-api -type d \( -name bin -o -name obj -o -name TestResults -o -name cdk.out \) -prune -exec rm -rf {} +

The stacks use RemovalPolicy.DESTROY for the user pool, table and log groups so that teardown is complete. That is a learning shortcut; production retains them.

Exercises

  • 🟢 Guided: run the tests, start the API, and perform the four attacks as Alice. Fill in a table of request, status, and the reason the API gave.
  • 🟡 Challenge: add a new read operation, GET /v1/accounts/{accountId}/balance, with the accounts.read scope. Add it to the OpenAPI design file first, then to the handlers, then to the CDK resource tree. Write an ownership test with the second user before you write the handler.
  • 🔴 Live problem: a partner reports that "some statement requests are created twice, but only when their mobile network is bad". Logs show two different Idempotency-Key values 4 seconds apart. Decide whether the API, the client or both are at fault, what you would ask the client team to change, and what server-side evidence you can add (a log field, a metric) to prove duplicates are client-generated keys rather than a store failure.

Assignment

Produce the project deliverable for your portfolio repository: (1) a README with the architecture diagram and the table of requirements to tests, (2) the OpenAPI design file updated for your new endpoint, (3) the output of the four attacks, (4) a short threat model listing five threats against this API with the control and the test for each, and (5) a one-page note on what must change before this could handle real customer data. This is the seed of Capstone 1.

Solutions

Knowledge check

Interview questions

  • "How do you make sure customer A cannot read customer B's accounts?" The customer comes from the validated token mapped on the server, every query is parameterised by that customer, "not yours" returns 404, and a second-user test fails the build if it regresses.
  • "Why not accept the customer id in the URL?" Anything the client sends can be changed. The token is the only trusted statement about identity.
  • "What does the gateway do that the app must also do?" Authenticate, check scopes and validate shapes. The gateway fails fast and cheaply, but the app must not assume the gateway is the only path to it.
  • "How would you roll this out?" Deploy behind WAF, start in count mode for managed rules, add alarms on 4xx, 5xx, throttles and idempotency mismatches, and rehearse the runbook for a leaked token.

Certification practice

Completion checklist

  • I ran the tests and saw total: 55, succeeded: 54, skipped: 1
  • I attacked the API as Alice and understood every status code
  • I can explain why "not yours" is a 404 and where the customer id comes from
  • I read the CDK stack and the cdk-nag v3 notes
  • If I deployed: I destroyed the WAF stack, then the API stack, and the tag query returned nothing
  • I wrote the portfolio README and threat model

Key takeaways

  • Identity is the token; the customer is resolved on the server and passed into every query.
  • Authorise operations with scopes and objects with ownership. Both are needed.
  • Return 404 for missing and not-yours alike; return 400 for malformed input and 422 for business-rule failures.
  • Idempotency keys are scoped by customer, fingerprinted and stored with a conditional write plus TTL.
  • Throttle at three layers (gateway, WAF, app) because each sees a different identity.
  • With cdk-nag v3, register the pack as a validation plugin and acknowledge findings with exact IDs and honest reasons.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page