Skip to Content
Cloud Engineering Academy
5. Security for Banking & Finance

Secure code review checklist for .NET on AWS

Review every Harbourline pull request against twenty concrete checks โ€” from object-level authorisation and idempotent payments to AWS credentials, logging of personal data and SSRF โ€” each with a bad and a good C# example.

intermediateโฑ 2 h ๐ŸŸข FreeDVA-C03SCS-C03

Assumes: .NET 10 LTS ยท ASP.NET Core 10 ยท AWS SDK for .NET v4 ยท EF Core 10 ยท Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Explain what human secure code review finds that the scanners in Pipeline security scanning cannot.
  • Apply a twenty-point checklist to an ASP.NET Core pull request for a banking service on AWS, and recognise each issue in real C#.
  • Write the fix for each item using .NET 10 and AWS SDK for .NET v4 idioms.
  • Set up a pull-request template, CODEOWNERS and review rules so the checklist is actually used โ€” and produces evidence.
  • Prioritise review effort by risk: which files and changes deserve a security champion's eyes.

Prerequisites

Why this matters in banking

A fictional but very ordinary incident: Harbourline's mobile app calls GET /accounts/{accountId}/transactions. The endpoint checks that the caller has a valid token. It does not check that the account belongs to the caller. A curious customer changes ACC-0000012345 to ACC-0000012346 and sees a stranger's salary, rent and medical payments. Every scanner passed: the token check exists, the SQL is parameterised, the packages are current. The flaw is in the logic, and only a reviewer who asks "whose account is this?" catches it.

This class of bug โ€” broken object-level authorisation (BOLA) โ€” has been the top item of the OWASP API Security Top 10 since its first edition. For a bank it is a personal-data breach that may need reporting to the regulator within 72 hours under UK GDPR, a conduct issue, and a front-page story. Duplicate payments from a missing idempotency check, card numbers in logs, and a role that can read every bucket are the same: correct-looking code with a banking-specific flaw.

Secure code review is also a control auditors ask about. Payment-card and banking security standards expect changes to be reviewed for security by someone other than the author before release. The checklist in this lesson gives that review structure and leaves a trail.

The idea in plain language

A secure code review is a second developer reading a change with an attacker's eyes and a list of questions. The list matters: without one, reviewers comment on naming and formatting and miss the missing ownership check. With one, every review asks the same twenty questions, and the answers are recorded.

The checklist does not replace tools. Scanners are better at remembering thousands of CVEs and regex patterns; humans are better at intent, context and business rules. Divide the work:

Leave to toolsKeep for humans
Known-vulnerable packages, secrets patterns, weak hash calls, IaC misconfigurationWho may call this? Whose data is this? Can it run twice? What happens when it fails halfway? What does the log line contain?

Analogy: a bank's four-eyes principle for payments. The system checks the IBAN checksum and the sanctions list automatically. The second approver checks something the system cannot: "Does it make sense that this customer is paying ยฃ48,000 to a new beneficiary at 03:00?" Code review is the four-eyes check for software.

What problem the practice solves

Review finds logic, authorisation, data-handling and design defects before they ship, and it spreads security knowledge through the team. Its limits are honest ones:

  • Attention is finite. Reviews of more than a few hundred changed lines catch far fewer defects. Keep pull requests small.
  • Reviewers trust the author. The checklist counters that by forcing specific questions.
  • Not every change needs a security champion. Route by risk: changes touching authentication, authorisation, payments, cryptography, IAM, logging of personal data, or the pipeline go to the security champions through CODEOWNERS; others get a normal peer review with the same checklist.
  • AWS no longer offers an automated reviewer for new work โ€” Amazon CodeGuru Reviewer is in maintenance (see the module service notes). Amazon Inspector code security and open-source SAST help, but neither understands Harbourline's ownership rules.

Microsoft / Azure comparison

You know (Microsoft/Azure)On AWSWhat's different
Azure DevOps branch policies (minimum reviewers, required reviewers by path)GitHub branch protection / rulesets + CODEOWNERS; or CodeCommit approval rule templatesSame idea; GitHub is the default in these labs
Managed identity + DefaultAzureCredentialIAM role + AWS SDK default credential chainNever construct credentials in code on AWS either
Azure.Extensions.AspNetCore.Configuration.Secrets (Key Vault config provider)Amazon.Extensions.Configuration.SystemsManager (Parameter Store and Secrets Manager config provider, v7.x)Secrets Manager values can be read through the Parameter Store reference path /aws/reference/secretsmanager/...
Data Protection keys in Blob Storage + Key VaultData Protection keys in Parameter Store (Amazon.AspNetCore.DataProtection.SSM) encrypted with KMSNeeded as soon as you run more than one container
Azure SQL Always EncryptedApplication-side field encryption with KMS data keysYou own the crypto code; see Module 5 index, lesson 11
Microsoft Security Development Lifecycle (SDL)AWS has no single SDLC framework for customers; banks use OWASP ASVS / SAMM plus internal standardsBring your SDL habits with you

Architecture

Where review sits in the delivery flow, and which changes are routed to whom:

Security-boundary view

The checklist maps to the trust boundaries of the Accounts API:

Step-by-step implementation

Add the checklist to the pull-request template

Create .github/pull_request_template.md with the twenty items as tick boxes plus "N/A" allowed. Authors self-review first; reviewers verify. A ticked box is a claim the reviewer checks, not a formality.

Route risky paths to security champions

Add CODEOWNERS entries for src/**/Auth*/, src/Harbourline.Payments.*, infra/, .github/workflows/ and any file with Crypto in the name. Turn on "Require review from Code Owners" in branch protection.

Enforce independence

In branch protection require at least one approval, dismiss stale approvals when new commits are pushed, and require approval of the most recent push by someone other than its author. This gives the four-eyes principle a technical enforcement.

Review in the right order

Read the PR description and the threat model first, then the tests (they tell you what the author thinks the code does), then the code along the request path: entry point โ†’ authorisation โ†’ validation โ†’ business logic โ†’ data access โ†’ logging and errors.

Record findings with severity

Use a prefix on review comments โ€” [block], [should], [nit] โ€” so the author knows what must change before merge. Blocking security comments are resolved by the reviewer, not the author.

Feed lessons back

When a review finds a pattern twice, turn it into an automated rule (a Semgrep or Roslyn rule, a unit test helper, a shared library), and remove it from the human checklist's emphasis.

The twenty checks

Each check has a question for the reviewer, a bad example, and a good one. All code targets .NET 10 and AWS SDK for .NET v4.

1. Is every endpoint authenticated by default?

Opt-in authorisation ([Authorize] on each controller) fails open: forget it once and the endpoint is public.

Bad
builder.Services.AddAuthorization();
// ...
app.MapGet("/internal/accounts/export", ExportAll); // no RequireAuthorization() - public by accident
Good
builder.Services.AddAuthorizationBuilder()
    // Every endpoint requires an authenticated user unless it explicitly opts out.
    .SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())
    .AddPolicy("accounts:read", p => p.RequireClaim("scope", "accounts:read"));

app.MapGet("/health", () => Results.Ok()).AllowAnonymous(); // deliberate, visible exception

Reviewer look-for: any AllowAnonymous, any new route, any change to authentication options (issuer, audience, ValidateLifetime).

2. Does the code check that the caller owns the object? (BOLA)

Bad
app.MapGet("/accounts/{accountId}/transactions", async (string accountId, ITransactionStore store) =>
    Results.Ok(await store.ListAsync(accountId))); // any logged-in customer can read any account
Good
app.MapGet("/accounts/{accountId}/transactions", async (
    string accountId, ClaimsPrincipal user, IAccountStore accounts, ITransactionStore store, CancellationToken ct) =>
{
    var customerId = user.FindFirstValue("customer_id");
    var account = await accounts.FindAsync(accountId, ct);
    // Same response for "not found" and "not yours": do not confirm that an account exists.
    if (account is null || account.CustomerId != customerId)
    {
        return Results.NotFound();
    }
    return Results.Ok(await store.ListAsync(accountId, ct));
}).RequireAuthorization("accounts:read");

Reviewer look-for: every identifier that comes from the route, query or body โ€” is it tied to the authenticated principal before use? Prefer deriving the ID from the token (/me/accounts) where possible.

3. Is input validated and is over-posting impossible?

Binding directly to an entity lets a caller set fields they should not (mass assignment).

Bad
app.MapPut("/customers/{id}", async (string id, Customer customer, BankDbContext db) =>
{
    db.Update(customer);              // caller can also send "kycStatus": "verified", "riskRating": "low"
    await db.SaveChangesAsync();
});
Good
public sealed record UpdateContactRequest(
    [property: EmailAddress, MaxLength(254)] string Email,
    [property: RegularExpression(@"^\+44 ?7\d{3} ?\d{6}$")] string Phone);

app.MapPut("/me/contact", async (UpdateContactRequest req, ClaimsPrincipal user, BankDbContext db, CancellationToken ct) =>
{
    var customer = await db.Customers.SingleAsync(c => c.CustomerId == user.FindFirstValue("customer_id"), ct);
    customer.Email = req.Email;       // only the fields this endpoint is allowed to change
    customer.Phone = req.Phone;
    await db.SaveChangesAsync(ct);
    return Results.NoContent();
});
// .NET 10: builder.Services.AddValidation() makes minimal APIs enforce the DataAnnotations above
// and return a 400 ValidationProblem automatically.

Reviewer look-for: entities used as request types; missing length limits; allow-lists (currency is GBP or EUR, scheme is one of five values) rather than deny-lists.

4. Is every query parameterised?

Bad
var rows = await db.Transactions
    .FromSqlRaw($"SELECT * FROM transactions WHERE reference LIKE '%{search}%'") // string built from input
    .ToListAsync(ct);
Good
// FromSql with an interpolated string turns {search} into a DbParameter, not text.
var pattern = $"%{search}%";
var rows = await db.Transactions
    .FromSql($"SELECT * FROM transactions WHERE account_id = {accountId} AND reference LIKE {pattern}")
    .ToListAsync(ct);

The same rule applies to Dapper (new { accountId } parameters), DynamoDB ExecuteStatement (PartiQL with Parameters), and Athena queries (use execution parameters, not concatenation).

Reviewer look-for: FromSqlRaw, ExecuteSqlRaw, SqlCommand with + or $"...", PartiQL strings built from input.

5. Is money handled as decimal with explicit rounding and currency?

Bad
double fee = amount * 0.015;                 // binary floating point: 0.1 + 0.2 != 0.3
var total = Math.Round(amount + fee);        // rounds to whole pounds, banker's rounding by default
Good
public readonly record struct Money(decimal Amount, string Currency)
{
    public static Money Of(decimal amount, string currency) =>
        currency is "GBP" or "EUR"
            ? new(decimal.Round(amount, 2, MidpointRounding.AwayFromZero), currency)
            : throw new ArgumentOutOfRangeException(nameof(currency));

    public Money Add(Money other) =>
        other.Currency == Currency ? Of(Amount + other.Amount, Currency)
                                   : throw new InvalidOperationException("Currency mismatch.");
}

var fee = Money.Of(payment.Amount * 0.015m, payment.Currency); // rounding rule stated, not implied

Reviewer look-for: double/float near money, implicit Math.Round mode, cross-currency arithmetic, negative amounts where only positive are allowed.

6. Can a money movement be submitted twice?

Mobile networks retry. Without idempotency, a retry is a second payment.

Bad
app.MapPost("/payments", async (CreatePayment cmd, IPaymentService svc, CancellationToken ct) =>
    Results.Created($"/payments/{(await svc.CreateAsync(cmd, ct)).PaymentId}", null));
Good
app.MapPost("/payments", async (
    [FromHeader(Name = "Idempotency-Key")] string? key,
    CreatePayment cmd, ClaimsPrincipal user, IPaymentService svc, CancellationToken ct) =>
{
    if (string.IsNullOrWhiteSpace(key) || key.Length > 64)
    {
        return Results.Problem(statusCode: 400, title: "Idempotency-Key header is required.");
    }
    // Scope the key to the customer so two customers cannot collide; the store rejects a reused
    // key with a different request body (hash) and returns the original result for an exact retry.
    var result = await svc.CreateOnceAsync(user.FindFirstValue("customer_id")!, key, cmd, ct);
    return result.IsReplay ? Results.Ok(result.Payment) : Results.Created($"/payments/{result.Payment.PaymentId}", result.Payment);
});

Deep dive: Transaction integrity and non-repudiation.

7. Are concurrent updates safe?

Two simultaneous withdrawals can both read a balance of ยฃ100 and both succeed.

Bad
var account = await db.Accounts.SingleAsync(a => a.AccountId == id, ct);
if (account.Balance >= amount) { account.Balance -= amount; }   // read-check-write race
await db.SaveChangesAsync(ct);
Good (DynamoDB conditional write, AWS SDK v4)
await dynamo.UpdateItemAsync(new UpdateItemRequest
{
    TableName = "hl-accounts",
    Key = new() { ["account_id"] = new AttributeValue { S = id } },
    // The check and the update happen atomically in DynamoDB.
    UpdateExpression = "SET balance = balance - :amt",
    ConditionExpression = "balance >= :amt AND #s = :open",
    ExpressionAttributeNames = new() { ["#s"] = "status" },
    ExpressionAttributeValues = new()
    {
        [":amt"] = new AttributeValue { N = amount.ToString(CultureInfo.InvariantCulture) },
        [":open"] = new AttributeValue { S = "open" },
    },
}, ct); // throws ConditionalCheckFailedException instead of overdrawing

With EF Core and a relational database, use a concurrency token ([Timestamp] / IsRowVersion() or a PostgreSQL xmin mapping) and handle DbUpdateConcurrencyException.

8. Are there secrets in code, config or tests?

Bad
var conn = "Host=hl-db.cluster-xyz.us-east-1.rds.amazonaws.com;Username=app;Password=Summer2026!";
Good
// Program.cs: load configuration from Parameter Store / Secrets Manager using the task role.
builder.Configuration.AddSystemsManager("/hl/accounts-api/", TimeSpan.FromMinutes(15));
// Or fetch on demand with caching; prefer RDS IAM authentication where possible.
var conn = builder.Configuration.GetConnectionString("Accounts")
    ?? throw new InvalidOperationException("Connection string not configured.");

Reviewer look-for: passwords, keys, tokens and private keys in appsettings*.json, tests, Dockerfiles, and launchSettings.json. Gitleaks catches most patterns; the reviewer catches the ones that look like ordinary strings. See Module 5 index, lesson 9, for rotation.

9. Do AWS clients use the default credential chain and dependency injection?

Bad
var s3 = new AmazonS3Client(new BasicAWSCredentials("AKIA...", "..."), RegionEndpoint.USEast1);
Good
// The SDK finds credentials itself: ECS task role, Lambda execution role, EC2 instance profile,
// or the developer's SSO profile locally. Clients are thread-safe singletons.
builder.Services.AddDefaultAWSOptions(builder.Configuration.GetAWSOptions());
builder.Services.AddAWSService<IAmazonS3>();
builder.Services.AddAWSService<IAmazonDynamoDB>();

Reviewer look-for: BasicAWSCredentials, SessionAWSCredentials with literals, new AmazonXxxClient() per request (socket exhaustion), hard-coded account IDs or ARNs that should be configuration.

10. Does the IAM change grant only what this code calls?

Bad (task role policy)
{ "Effect": "Allow", "Action": ["s3:*", "kms:*"], "Resource": "*" }
Good
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadStatementsForThisService",
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::hl-m05-statements-111122223333/statements/*"
    },
    {
      "Sid": "DecryptOnlyViaS3",
      "Effect": "Allow",
      "Action": "kms:Decrypt",
      "Resource": "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
      "Condition": { "StringEquals": { "kms:ViaService": "s3.us-east-1.amazonaws.com" } }
    }
  ]
}

Reviewer look-for: compare each new SDK call in the diff with the policy change in the same PR. Actions without matching code are excess; code without matching actions will fail in production. Details: Least privilege in practice.

11. Do logs avoid personal data, card data and secrets?

Bad
logger.LogInformation("Payment {@Payment} for {Email} with card {Pan}", payment, customer.Email, card.Pan);
// Destructuring (@) writes every property, including IBANs and names, to CloudWatch for years.
Good
logger.LogInformation(
    "Payment {PaymentId} created for account {AccountId}, amount {Amount} {Currency}, correlation {CorrelationId}",
    payment.PaymentId, payment.DebtorAccountId, payment.Amount, payment.Currency, correlationId);
// Card data never reaches this service: it handles tokens and pan_last4 only.

Also check: user-supplied strings logged as structured values (not concatenated into the message template) to prevent log forging; CloudWatch log groups with a retention period; CloudWatch Logs data protection policies as a safety net, not the primary control.

12. Do errors reveal internals?

Bad
catch (Exception ex) { return Results.Problem(ex.ToString()); } // stack trace, SQL, table names to the caller
Good
builder.Services.AddProblemDetails(o => o.CustomizeProblemDetails = ctx =>
    ctx.ProblemDetails.Extensions["correlationId"] = ctx.HttpContext.TraceIdentifier);
// ...
app.UseExceptionHandler();      // RFC 9457 ProblemDetails, no exception detail outside Development
app.UseStatusCodePages();
if (!app.Environment.IsDevelopment())
{
    app.UseHsts();
}

Reviewer look-for: UseDeveloperExceptionPage outside Development, OpenAPI/Swagger UI exposed in production without authorisation, distinct messages that reveal whether an account or user exists.

13. Is cryptography delegated to proven services and APIs?

Bad
using var md5 = MD5.Create();                               // broken for integrity
var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(payload));
var token = new Random().Next().ToString();                 // predictable
using var aes = Aes.Create(); aes.Mode = CipherMode.ECB;    // leaks patterns
Good
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(payload));          // integrity
var token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)); // unpredictable
// Encryption: AES-GCM with a KMS data key (envelope encryption), never a home-made scheme.
using var gcm = new AesGcm(dataKey, tagSizeInBytes: 16);
gcm.Encrypt(nonce, plaintext, ciphertext, tag, associatedData);
// Integrity across systems: HMAC with a KMS HMAC key, or KMS asymmetric Sign/Verify.

Reviewer look-for: MD5, SHA1, DES, TripleDES, CipherMode.ECB, System.Random for anything security-related, keys or IVs in code, reused nonces, comparing MACs with == instead of CryptographicOperations.FixedTimeEquals.

14. Is deserialisation restricted to known types?

Bad
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }; // Newtonsoft
var msg = JsonConvert.DeserializeObject(body, settings);   // attacker chooses the .NET type to create
Good
// System.Text.Json with explicit polymorphism: only listed types can be created.
[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
[JsonDerivedType(typeof(FasterPaymentRequested), "fps")]
[JsonDerivedType(typeof(SepaPaymentRequested), "sepa_ct")]
public abstract record PaymentEvent(string PaymentId);

var evt = JsonSerializer.Deserialize<PaymentEvent>(sqsMessage.Body, JsonOptions.Strict);

BinaryFormatter was removed from .NET 9 onwards (it throws at run time), but old libraries and TypeNameHandling other than None still appear in legacy banking code being migrated. Messages from SQS, SNS and EventBridge are untrusted input too, even inside your VPC.

15. Can the service be made to call arbitrary URLs? (SSRF)

Bad
app.MapPost("/webhooks/test", async (string url, HttpClient http) =>
    await http.GetStringAsync(url)); // url = http://169.254.169.254/latest/meta-data/iam/... 
Good
private static readonly HashSet<string> AllowedHosts = new(StringComparer.OrdinalIgnoreCase)
{
    "partner-api.example.com", "sanctions.example.net",
};

if (!Uri.TryCreate(input, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps
    || !AllowedHosts.Contains(uri.Host))
{
    return Results.Problem(statusCode: 400, title: "Destination not allowed.");
}
// Defence in depth on AWS: IMDSv2 required (hop limit 1 for containers), egress filtering,
// and named HttpClients with fixed BaseAddress for each partner.

16. Are S3 keys and pre-signed URLs constrained?

Bad
var key = $"statements/{request.FileName}";   // "../../exports/all-customers.csv"
var url = await s3.GetPreSignedURLAsync(new GetPreSignedUrlRequest
{
    BucketName = bucket, Key = key, Expires = DateTime.UtcNow.AddDays(7),
});
Good
// Build the key from server-side facts, never from a client-supplied path.
var key = $"statements/{customerId}/{accountId}/{statementMonth:yyyy-MM}.pdf";
var url = await s3.GetPreSignedURLAsync(new GetPreSignedUrlRequest
{
    BucketName = bucket,
    Key = key,
    Verb = HttpVerb.GET,
    Expires = DateTime.UtcNow.AddMinutes(5),   // short-lived; also bounded by the role session lifetime
});

The ownership check from item 2 must run before the URL is generated: a pre-signed URL is a bearer token that anyone holding it can use.

17. Is transport security intact (TLS, certificate validation, CORS)?

Bad
var handler = new HttpClientHandler
{
    ServerCertificateCustomValidationCallback = (_, _, _, _) => true, // accepts any certificate
};
builder.Services.AddCors(o => o.AddDefaultPolicy(p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
Good
builder.Services.AddHttpClient("partner", c => c.BaseAddress = new Uri("https://partner-api.example.com/"));
// Default validation; for mTLS add a client certificate, do not weaken server validation.
builder.Services.AddCors(o => o.AddPolicy("web", p => p
    .WithOrigins("https://online.harbourline.example")
    .WithMethods("GET", "POST")
    .WithHeaders("Authorization", "Content-Type", "Idempotency-Key")));

Certificates and mTLS: Certificates, TLS and mTLS.

18. Is resource use bounded?

Bad
app.MapGet("/accounts/{id}/transactions", (string id, int pageSize, ...) =>
    store.ListAsync(id, pageSize));   // pageSize=10000000; no rate limit; unbounded upload size
Good
builder.Services.AddRateLimiter(o =>
{
    o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    o.AddPolicy("per-customer", ctx => RateLimitPartition.GetTokenBucketLimiter(
        ctx.User.FindFirstValue("customer_id") ?? "anonymous",
        _ => new TokenBucketRateLimiterOptions
        {
            TokenLimit = 20, TokensPerPeriod = 10, ReplenishmentPeriod = TimeSpan.FromSeconds(1), QueueLimit = 0,
        }));
});
// ...
var size = Math.Clamp(pageSize ?? 50, 1, 200);  // server-side cap on page size

Also check CancellationToken is passed through to AWS SDK and database calls, request body size limits for uploads, and timeouts on outbound HttpClient calls. WAF rate rules are the outer layer (AWS WAF and AWS Shield); the application limit protects per-customer fairness.

19. Is sensitive data protected at field level and are keys shared correctly?

Bad
builder.Services.AddDataProtection(); // keys in the container filesystem: lost on restart,
                                      // different on each task -> antiforgery and cookies break
customer.NationalInsuranceNumber = request.Nino; // stored in clear text in a wide table
Good
builder.Services.AddDataProtection()
    .SetApplicationName("hl-accounts-api")
    .PersistKeysToAWSSystemsManager("/hl/accounts-api/dataprotection"); // SecureString, KMS-encrypted

// Field-level encryption with a KMS data key and an encryption context naming the field.
customer.NationalInsuranceNumberCipher = await fieldEncryptor.EncryptAsync(
    request.Nino, new EncryptionContext("customers", "national_insurance_number", customer.CustomerId), ct);

Reviewer look-for: new columns or attributes holding special-category or identity data without encryption or masking; production data copied to tests; tokens rather than card numbers (PAN) anywhere outside the tokenisation boundary (PCI DSS on AWS).

20. Are security-relevant actions audited?

Bad
await beneficiaries.AddAsync(newBeneficiary, ct);   // no record of who added a payee, from where
Good
await beneficiaries.AddAsync(newBeneficiary, ct);
await audit.WriteAsync(new AuditEvent(
    EventId: Guid.CreateVersion7().ToString(),
    OccurredAt: timeProvider.GetUtcNow(),
    Actor: user.FindFirstValue("sub")!,
    Action: "beneficiary.created",
    Resource: $"beneficiary/{newBeneficiary.BeneficiaryId}",
    Outcome: "success",
    SourceIp: http.Connection.RemoteIpAddress?.ToString(),
    CorrelationId: http.TraceIdentifier), ct);

Adding a payee, changing contact details, raising a limit and approving a payment are classic fraud steps; investigators need to reconstruct them. The audit_events schema comes from the canonical model. How these records are retained and presented to auditors: Audit logging and evidence collection.

AWS Console instructions

Code review happens in GitHub, but two AWS consoles help reviewers verify claims in a PR:

  • IAM โ†’ Roles โ†’ (task role) โ†’ Permissions โ†’ Simulate (or the IAM Policy Simulator) to check that a changed policy allows exactly the new SDK calls and nothing broader.
  • IAM Access Analyzer โ†’ Policy validation is built into the policy editor (IAM โ†’ Policies โ†’ Create policy โ†’ JSON): it flags wildcards, invalid actions and security warnings as you paste the policy from the PR.

AWS CLI

Commands a reviewer can run to check an IAM change in a PR without deploying it:

# Validate the policy document from the PR (findings: ERROR, SECURITY_WARNING, WARNING, SUGGESTION).
aws accessanalyzer validate-policy \
  --policy-type IDENTITY_POLICY \
  --policy-document file://infra/policies/accounts-api-task-role.json \
  --profile learn-sandbox

# Check that the new policy does not grant a specific dangerous action.
aws accessanalyzer check-access-not-granted \
  --policy-type IDENTITY_POLICY \
  --policy-document file://infra/policies/accounts-api-task-role.json \
  --access '[{"actions":["s3:DeleteObject","kms:ScheduleKeyDeletion","iam:PassRole"]}]' \
  --profile learn-sandbox

# Compare the new policy with the old one: does it grant anything new?
aws accessanalyzer check-no-new-access \
  --policy-type IDENTITY_POLICY \
  --existing-policy-document file://old-policy.json \
  --new-policy-document file://infra/policies/accounts-api-task-role.json \
  --profile learn-sandbox

These Access Analyzer policy checks are API calls with no resources created; custom policy checks are charged per call โš  VERIFY current price (a handful of calls costs cents at most).

Infrastructure as Code

The repository-level controls that make review mandatory can themselves be code. A GitHub ruleset via Terraform (GitHub provider) keeps them reviewable:

governance/branch-protection.tf
terraform {
  required_providers {
    github = { source = "integrations/github", version = "~> 6.0" } # โš  VERIFY current major
  }
}

resource "github_repository_ruleset" "main" {
  name        = "main-protection"
  repository  = "harbourline-accounts-api"
  target      = "branch"
  enforcement = "active"

  conditions {
    ref_name {
      include = ["~DEFAULT_BRANCH"]
      exclude = []
    }
  }

  rules {
    deletion         = true
    non_fast_forward = true

    pull_request {
      required_approving_review_count   = 1
      require_code_owner_review         = true
      dismiss_stale_reviews_on_push     = true
      require_last_push_approval        = true # the last pusher cannot be the only approver
      required_review_thread_resolution = true
    }

    required_status_checks {
      required_check {
        context = "gate" # the SARIF gate job from the scanning lesson
      }
    }
  }
}

Complete code

Pull-request template

.github/pull_request_template.md
## What and why
<!-- One paragraph. Link the ticket and the threat model section, if any. -->

## Security self-review (tick, or write N/A with a reason)
- [ ] 1  New endpoints are authenticated by default; any AllowAnonymous is justified
- [ ] 2  Every ID from route/query/body is checked against the caller (object-level authorisation)
- [ ] 3  Request DTOs only; inputs validated with allow-lists and length limits
- [ ] 4  All SQL / PartiQL / Athena queries are parameterised
- [ ] 5  Money is decimal with explicit currency and rounding
- [ ] 6  Money-moving POSTs require and honour Idempotency-Key
- [ ] 7  Concurrent updates are safe (conditional writes / concurrency tokens)
- [ ] 8  No secrets in code, config, tests or Dockerfiles
- [ ] 9  AWS clients via DI and the default credential chain
- [ ] 10 IAM changes match the SDK calls in this PR, no wildcards
- [ ] 11 Logs contain no personal data, card data or secrets; retention set
- [ ] 12 Errors use ProblemDetails; no stack traces or existence leaks
- [ ] 13 Crypto uses KMS / standard .NET APIs; no MD5/SHA1/ECB/System.Random
- [ ] 14 Deserialisation restricted to known types
- [ ] 15 No outbound calls to user-controlled URLs
- [ ] 16 S3 keys built server-side; pre-signed URLs short-lived and post-authorisation
- [ ] 17 TLS validation intact; CORS restricted
- [ ] 18 Rate limits, page-size caps, timeouts, cancellation
- [ ] 19 Sensitive fields encrypted/masked; Data Protection keys shared
- [ ] 20 Security-relevant actions write audit events

## Tests
<!-- Include at least one negative test for authorisation or validation changes. -->

A secure baseline Program.cs for the Accounts API

This file pulls several checks together so new services start from the right defaults. It compiles against ASP.NET Core 10 with the packages listed in the comment.

src/Harbourline.Accounts.Api/Program.cs
// Packages: Microsoft.AspNetCore.Authentication.JwtBearer 10.0.x,
//           AWSSDK.Extensions.NETCore.Setup 4.x, AWSSDK.DynamoDBv2 4.x,
//           Amazon.AspNetCore.DataProtection.SSM 4.0.3
using System.Security.Claims;
using System.Threading.RateLimiting;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;

var builder = WebApplication.CreateBuilder(args);

// Check 9: AWS clients from DI, credentials from the default chain (task role in ECS).
builder.Services.AddDefaultAWSOptions(builder.Configuration.GetAWSOptions());
builder.Services.AddAWSService<IAmazonDynamoDB>();

// Check 1: JWT bearer authentication and a fallback policy that requires authentication.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.Authority = builder.Configuration["Auth:Authority"];   // e.g. a Cognito user pool issuer URL
        o.Audience = builder.Configuration["Auth:Audience"];
        o.MapInboundClaims = false;                              // keep claim names as issued
    });
builder.Services.AddAuthorizationBuilder()
    .SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())
    .AddPolicy("accounts:read", p => p.RequireClaim("scope", "accounts:read"));

// Check 12: RFC 9457 ProblemDetails with a correlation ID, no exception details.
builder.Services.AddProblemDetails(o => o.CustomizeProblemDetails = ctx =>
    ctx.ProblemDetails.Extensions["correlationId"] = ctx.HttpContext.TraceIdentifier);

// Check 18: per-customer token-bucket rate limit.
builder.Services.AddRateLimiter(o =>
{
    o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    o.AddPolicy("per-customer", ctx => RateLimitPartition.GetTokenBucketLimiter(
        ctx.User.FindFirstValue("customer_id") ?? "anonymous",
        _ => new TokenBucketRateLimiterOptions
        {
            TokenLimit = 20,
            TokensPerPeriod = 10,
            ReplenishmentPeriod = TimeSpan.FromSeconds(1),
            QueueLimit = 0,
        }));
});

// Check 19: Data Protection keys shared across tasks, stored as SecureString parameters.
builder.Services.AddDataProtection()
    .SetApplicationName("hl-accounts-api")
    .PersistKeysToAWSSystemsManager("/hl/accounts-api/dataprotection");

var app = builder.Build();

app.UseExceptionHandler();
app.UseStatusCodePages();
if (!app.Environment.IsDevelopment())
{
    app.UseHsts();
}
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();

app.MapGet("/health", () => Results.Ok(new { status = "ok" })).AllowAnonymous();

// Checks 2, 18: ownership verified against the token; page size capped.
app.MapGet("/accounts/{accountId}", async (
        string accountId, ClaimsPrincipal user, IAmazonDynamoDB dynamo,
        ILogger<Program> logger, CancellationToken ct) =>
    {
        var customerId = user.FindFirstValue("customer_id");
        if (customerId is null || !accountId.StartsWith("ACC-", StringComparison.Ordinal) || accountId.Length != 14)
        {
            return Results.NotFound();
        }

        var item = await dynamo.GetItemAsync(new GetItemRequest
        {
            TableName = "hl-accounts",
            Key = new() { ["account_id"] = new AttributeValue { S = accountId } },
            ConsistentRead = true,
        }, ct);

        if (item.Item is not { Count: > 0 } || item.Item["customer_id"].S != customerId)
        {
            // Check 11: log IDs, not personal data. Check 12: same response for missing and not-yours.
            logger.LogWarning("Account {AccountId} not found or not owned by caller", accountId);
            return Results.NotFound();
        }

        return Results.Ok(new
        {
            accountId,
            currency = item.Item["currency"].S,
            balance = decimal.Parse(item.Item["balance"].N, System.Globalization.CultureInfo.InvariantCulture),
            status = item.Item["status"].S,
        });
    })
    .RequireAuthorization("accounts:read")
    .RequireRateLimiting("per-customer");

app.Run();

// Makes the generated Program class visible to WebApplicationFactory<Program> in the test project.
public partial class Program;

A negative authorisation test

Every PR that touches an endpoint should include a test proving a customer cannot read someone else's data.

tests/Harbourline.Accounts.Api.Tests/OwnershipTests.cs
using System.Net;
using Xunit;

public sealed class OwnershipTests(AccountsApiFactory factory) : IClassFixture<AccountsApiFactory>
{
    [Fact]
    public async Task Customer_cannot_read_another_customers_account()
    {
        // The factory replaces IAmazonDynamoDB with a fake seeded with ACC-0000000001 owned by CUS-00000001,
        // and issues a test token for CUS-00000002.
        var client = factory.CreateClientFor(customerId: "CUS-00000002");

        var response = await client.GetAsync("/accounts/ACC-0000000001", TestContext.Current.CancellationToken);

        Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // not 200, and not 403 (no existence leak)
    }
}

The AccountsApiFactory (a WebApplicationFactory<Program> with a fake DynamoDB client and a test authentication handler) must also replace the Systems Manager client and the Data Protection key repository (for example with a temporary folder), because PersistKeysToAWSSystemsManager otherwise tries to resolve AWS credentials when the test host starts. It follows the pattern used in the Module 4 labs.

Code explained line by line

Program.cs

  1. AddDefaultAWSOptions / AddAWSService โ€” registers one thread-safe DynamoDB client resolved with the default credential chain; no credentials appear in code.
  2. MapInboundClaims = false โ€” keeps JWT claim names (sub, scope, customer_id) as issued, so authorisation checks read the claim you expect rather than a remapped long URI.
  3. SetFallbackPolicy(...RequireAuthenticatedUser...) โ€” any endpoint without explicit metadata requires a logged-in user; /health opts out visibly with AllowAnonymous().
  4. AddProblemDetails + UseExceptionHandler โ€” unhandled exceptions become a generic RFC 9457 response with a correlation ID the support team can search for in CloudWatch.
  5. RateLimitPartition.GetTokenBucketLimiter keyed by customer_id โ€” each customer gets their own bucket of 20 requests, refilled at 10 per second; extra requests get 429.
  6. PersistKeysToAWSSystemsManager โ€” every task shares the same Data Protection key ring, stored as SecureString parameters encrypted with KMS; the task role needs the matching ssm:GetParametersByPath/ssm:PutParameter permissions on that path only.
  7. UseHsts outside Development โ€” tells browsers to use HTTPS only (TLS itself terminates at the load balancer or API Gateway).
  8. Input shape check on accountId โ€” cheap rejection before calling DynamoDB.
  9. ConsistentRead = true โ€” the ownership check reads the latest committed data.
  10. item.Item["customer_id"].S != customerId โ€” the object-level authorisation check; returns 404 for both "missing" and "not yours".
  11. decimal.Parse(..., InvariantCulture) โ€” DynamoDB numbers are strings; parse them as decimal with the invariant culture, never double.

OwnershipTests.cs โ€” a negative test: it asserts what must not happen. Positive tests alone ("owner can read") would pass on the vulnerable code.

Security considerations

โš  Learning shortcut โ€” not for production

The baseline returns account balances straight from DynamoDB and logs warnings without rate-limiting the log itself. In production, balances come from the core ledger with its own consistency guarantees, repeated authorisation failures from one customer feed fraud monitoring, and the API sits behind WAF and API Gateway with their own limits.

  • Reviewers need context. Give them the threat model and data classification for the service. A reviewer who does not know a field is special-category data cannot flag it in a log line.
  • Review the tests as hard as the code. Missing negative tests are a finding.
  • Treat AI-generated code like any other contribution. Assistants readily produce AllowAnyOrigin, TypeNameHandling.All or new AmazonS3Client(new BasicAWSCredentials(...)) from old examples. The checklist applies regardless of who โ€” or what โ€” wrote the code.
  • Do not paste production data or secrets into review comments, tickets or chat while discussing a finding.
  • Review evidence is retained. The pull request (description, checklist, approvals, scanner results) is the record an auditor samples. Do not squash away the review history by merging outside the protected branch flow.

Banking use case

Harbourline's Payments Service team adds "edit a saved beneficiary's IBAN". The author ticks all twenty boxes. The security champion's review finds three issues:

  1. Check 2: the endpoint loads the beneficiary by beneficiaryId but does not check beneficiary.CustomerId against the caller. [block]
  2. Check 20: no audit event. Changing a payee's IBAN is a classic step in authorised push-payment fraud and account-takeover attacks; the fraud team needs the event with source IP and correlation ID. [block]
  3. Business rule (beyond the checklist): a changed IBAN should be treated as a new payee โ€” requiring step-up authentication and Confirmation of Payee โ€” rather than an edit. [block], escalated to the product owner because it is a design decision.

The author fixes 1 and 2 with a negative test and an audit_events write; 3 becomes a design change agreed with the fraud team. The PR history shows who found what and when โ€” useful later when internal audit samples changes to payment functionality. The checklist is not the end of review; it is the floor.

Common mistakes

  • Ticking boxes without reading โ†’ the template becomes theatre. โ†’ Reviewers spot-check at least the items the diff touches and comment on them explicitly.
  • Reviewing 2,000-line pull requests โ†’ defects slip through. โ†’ Split changes; review infrastructure and application changes separately when they are large.
  • Only reviewing the happy path โ†’ missing ownership checks and error leaks. โ†’ Ask "what if this ID belongs to someone else / this call fails halfway / this runs twice?"
  • Approving your own change via a second account or an admin merge โ†’ breaks segregation of duties. โ†’ Rulesets with require_last_push_approval, and admin bypass logged and reviewed.
  • Fixing a review finding with a suppression โ†’ a #pragma warning disable CA5351 added "to get the build green". โ†’ Suppressions follow the governance in the scanning lesson.
  • Forgetting configuration and IaC โ†’ the code is perfect but the task role has s3:*. โ†’ Check 10 is part of every review that touches AWS calls.

Troubleshooting

SymptomLikely causeFix
Endpoint returns 401 after adding the fallback policyEndpoint was previously anonymous by accidentDecide: add AllowAnonymous() with a reason, or fix the client to send a token
403 with a valid tokenPolicy requires a claim the token lacks, or claims were remappedInspect the token; set MapInboundClaims = false; check the scope name
ConditionalCheckFailedException in logsThe conditional write correctly blocked an overdraft or concurrent updateMap it to a 409/422 ProblemDetails; do not retry blindly
Antiforgery or cookie errors after scaling to 2+ tasksData Protection keys not sharedPersist keys to SSM (or S3) with KMS, set SetApplicationName
AccessDeniedException on ssm:GetParametersByPath at start-upTask role lacks permission on the parameter pathGrant the action on arn:aws:ssm:us-east-1:<account>:parameter/hl/accounts-api/* only
Code owners not requested on a PRCODEOWNERS path pattern wrong or file not on default branchTest patterns; the file must be on the base branch
Analyzer warning CA2100 on a parameterised queryAnalyzer cannot prove the string is constantUse FromSql interpolation; if truly safe, suppress with reason via governance

Cost and cleanup

Cost: free. Everything in this lesson runs locally or in GitHub. The optional Access Analyzer validate-policy calls are free; check-access-not-granted and check-no-new-access are custom policy checks billed per call โš  VERIFY current price โ€” a few calls cost well under USD 1. No AWS resources are created, so there is nothing to tear down. If you created a test GitHub ruleset with Terraform, run terraform destroy in governance/ or delete the ruleset in Repository โ†’ Settings โ†’ Rules โ†’ Rulesets.

Exercises

  • ๐ŸŸข Guided: Copy the baseline Program.cs into a new web project, add the fake-DynamoDB WebApplicationFactory, and write the negative ownership test. Then remove the ownership check and watch the test fail.

  • ๐ŸŸก Challenge: Review this snippet against the checklist and list every finding with its check number and severity:

    app.MapPost("/transfers", async (Transfer t, BankDbContext db, ILogger<Program> log) =>
    {
        var from = await db.Accounts.FindAsync(t.FromAccountId);
        if ((double)from!.Balance > t.Amount) from.Balance -= (decimal)t.Amount;
        db.Add(new Transaction { AccountId = t.FromAccountId, Amount = -(decimal)t.Amount, Reference = t.Reference });
        await db.SaveChangesAsync();
        log.LogInformation($"Transfer {System.Text.Json.JsonSerializer.Serialize(t)}");
        return Results.Ok();
    });
  • ๐Ÿ”ด Live problem: A senior developer pushes back: "The checklist slows us down; we have SAST and WAF, so the review can be one approval from anyone in the team." The release manager asks you for a recommendation by the end of the day. Write it.

Assignment

Add to your portfolio repository: the PR template, a CODEOWNERS file with risk-based routing, the baseline Program.cs, and at least three negative tests (ownership, missing idempotency key, over-posting). Write a short REVIEW-GUIDE.md that explains which paths go to security champions and why.

Solutions

Knowledge check

Interview questions

  • "What do you look for first when reviewing a banking API change?" โ€” Authorisation at object level: for every identifier, whose is it and is that checked against the caller? Then idempotency and concurrency for money movements, then what goes into logs.
  • "How do you make secure code review scale?" โ€” Risk-based routing with CODEOWNERS, small PRs, a checklist in the template, automation of recurring findings, and security champions in each team rather than a central bottleneck.
  • "How do you give an application on ECS access to S3 without keys?" โ€” A task role with least-privilege permissions; the SDK's default credential chain picks up temporary credentials from the ECS credentials endpoint.
  • "What would you check in a PR that adds a new IAM policy?" โ€” That every action matches an SDK call in the diff, resources are specific ARNs, conditions such as kms:ViaService are used where possible, and Access Analyzer validation shows no warnings.
  • "How does code review support audit and compliance?" โ€” It is a documented, independent control over change. The PR record โ€” checklist, approvals, scanner results โ€” is evidence. Whether it satisfies a specific requirement is for the bank's compliance team and assessors to judge.

Certification practice

Completion checklist

  • I can name at least ten of the twenty checks from memory and explain why each matters in a bank
  • I added the PR template and CODEOWNERS routing to a repository
  • I wrote a negative ownership test and saw it fail when the check was removed
  • I reviewed the challenge snippet and found at least eight issues
  • I validated an IAM policy from a PR with Access Analyzer (optional)

Key takeaways

  • Scanners find known patterns; review finds missing ownership checks, duplicate payments, races and personal data in logs โ€” the defects that hurt banks most.
  • Make review consistent with a twenty-point checklist in the PR template, and make it independent with CODEOWNERS and branch rules.
  • On AWS specifically: default credential chain and DI for clients, IAM changes that match SDK calls, short-lived pre-signed URLs after authorisation, shared Data Protection keys, and SSRF defences around instance metadata.
  • Every money-moving endpoint needs idempotency, atomic balance updates, decimal arithmetic and an audit event.
  • The PR record is evidence of a change control; it supports โ€” but never by itself proves โ€” compliance.

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