Account management: lifecycle APIs, data ownership and customer-only authorisation
Design the account management service: a lifecycle state machine, account APIs that return 404 for other people's accounts, an access-grant model for joint and delegated access, DynamoDB tables with optimistic concurrency, and the 15-section write-up.
Assumes: .NET 10 LTS · ASP.NET Core 10 · AWS SDK for .NET v4 (AWSSDK.DynamoDBv2 4.x) · CDK v2 (Amazon.CDK.Lib 2.277.0) · Terraform AWS provider v6 · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Define the system of record for each account fact and explain why the cloud service usually holds a projection, not the master copy.
- Model the account lifecycle (open, frozen, closed) as a state machine with rules about who may move an account between states.
- Design account APIs where a customer can only ever see their own accounts, including joint accounts and delegated access, and prevent broken object-level authorisation (BOLA, often called IDOR).
- Design a DynamoDB access-grant table with a reverse index and optimistic concurrency for status changes.
- Compare in-code authorisation with a policy engine such as Amazon Verified Permissions.
- Write the account management architecture using the 15-section template.
Prerequisites
- Digital banking platform (tokens, BFFs)
- DynamoDB for banking correctness and DynamoDB fundamentals
- IAM in depth for the difference between AWS authorisation and application authorisation
- REST API design for resource design
- Tools: .NET 10 SDK or Docker for the code
Why this matters in banking
The most expensive authorisation bug in banking is not an exotic cryptographic flaw. It is this:
GET /accounts/ACC-0000000042/transactions -> 200 OK (customer A, their own account)
GET /accounts/ACC-0000000043/transactions -> 200 OK (customer A, someone else's account!)The service checked "is the caller signed in?" but not "does this account belong to this caller?". The fix is a design rule applied to every endpoint, not a patch to one. A reviewer will ask where the rule lives, how you know it cannot be bypassed and how you would detect a miss.
Two further realities make account management harder than it looks:
- The core banking system is the master. The cloud service sees a copy. Writes to balances, limits and status often must go to the core, and the copy lags behind. Design for staleness, and show "as at" times.
- Accounts are shared. Joint holders, parents and children, business signatories, power of attorney, and third-party access under open banking all change who may do what.
The idea in plain language
An account is a container of money plus rules. The customer is a person or company. Between them sits the relationship: who may view, who may pay, who may change details, who may close it. Authorisation is therefore not "does the customer own it?" but "what does this relationship allow for this action right now?".
The service has three jobs:
- Serve account information quickly and only to those allowed to see it.
- Change account attributes safely (nickname, limits, contact preferences, status) with audit.
- Publish account events so other services react (notifications, fraud, reporting).
Analogy: a safe-deposit room. The room clerk checks your ID and the box's register: which boxes are in your name, which are shared with whom, whether any is frozen by a court order. Having a key to the room does not open every box. Having a key to the wrong box gets you "no such box here", not "that box is not yours", because the clerk will not even confirm it exists.
System of record versus projection
| Fact | System of record | Cloud copy | How it is kept fresh | Staleness the design accepts |
|---|---|---|---|---|
| Balance, available balance | Core banking | Cached projection | Events from core, or read-through with short cache | Seconds; show "as at" |
| Account status (open, frozen, closed) | Core banking | Projection | Events plus reconciliation | Seconds for freeze; freeze must also apply at the payment check |
| Nickname, notification preferences | Cloud account service | Master | Written directly | None |
| Access grants (who can see what) | Account service (master) or identity platform, per bank decision | Master | Written directly, audited | None: this decides security |
| Product terms, interest rate | Product catalogue | Projection | Daily sync | Hours |
Rule of thumb: the master of a fact is the service that must be correct when the others are down. The access grant table is the security master here, so it must not be cached for long.
Lifecycle
Only some transitions are legal. Closed is terminal: a closed account is never reopened; a new account is opened instead. Which roles may freeze, release or close is a bank policy decision ⚠ VERIFY; the architecture's job is to enforce it and record who did it.
What problem the AWS services solve
| Service | Role | Limits and sharp edges |
|---|---|---|
| Amazon DynamoDB | Access-grant table, account projection, consent and preferences | Strongly consistent reads available on the base table but not on global secondary indexes; item size limit 400 KB; design keys from access patterns |
| DynamoDB conditional writes | Optimistic concurrency: update only if the version matches | A failed condition raises ConditionalCheckFailedException; the caller re-reads and decides |
| Amazon API Gateway + JWT authoriser | Authenticate the caller; pass the customer id downstream | Authentication, not object-level authorisation |
| Amazon Verified Permissions | Managed policy store and decision service using the Cedar policy language | Evaluate cost per authorisation request and latency in your design ⚠ VERIFY pricing; you must keep entities (resources, relationships) fed into it or pass them per request |
| Amazon EventBridge | Publishes AccountStatusChanged and similar events | At-least-once delivery, so consumers deduplicate |
| Amazon Aurora PostgreSQL | Alternative store when you need relational joins across holders and accounts | More to operate; schema changes need migration discipline |
| AWS CloudTrail / application audit log | Who changed what | CloudTrail records AWS API calls, not your application's business actions, so write an application audit record too |
Honest limitation: IAM policies and API Gateway authorisers decide who may call an API, not which customer's rows they may see. Row-level business authorisation is your code (or a policy engine you call from your code).
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
ASP.NET Core resource-based authorisation (IAuthorizationService with a resource) | Same code, running on ECS/Lambda | Nothing AWS-specific: the pattern is yours. Place the check in a shared library so every endpoint uses it |
| Azure SQL row-level security | Aurora PostgreSQL row-level security policies; DynamoDB leading-key IAM conditions | DynamoDB fine-grained access (dynamodb:LeadingKeys) suits service-to-user data separation, but customer-level rules usually stay in application code |
| Azure Cosmos DB partition key per tenant | DynamoDB partition key per customer | Both reward key design; DynamoDB needs an explicit reverse index for "who has access to this account" |
| Open Policy Agent / Azure custom policy | Amazon Verified Permissions (Cedar) | Managed; policies are data, reviewable and versioned apart from code |
Optimistic concurrency with rowversion in EF Core | DynamoDB ConditionExpression on a version attribute | Same idea; you write the condition yourself |
Architecture
Security-boundary view
| Boundary | Control |
|---|---|
| Customer to BFF | OIDC token, step-up for sensitive changes |
| BFF to account service | Service identity (SigV4 or mTLS) plus a signed customer-id claim; the service never trusts a customer id from the URL |
| Account service to DynamoDB | Task role limited to the three tables; condition keys by table; VPC gateway endpoint with an endpoint policy |
| Account service to core banking | Private link only; credentials in Secrets Manager; request IDs for tracing |
| Staff to account service | Separate API with SSO, MFA, role checks and reason-code requirement; four-eyes for freeze release |
| Logs | Immutable audit stream to the log archive account |
Step-by-step implementation
Define the resources and the API contract (sections 2 and 8)
| Method and path | Who | Rule |
|---|---|---|
GET /accounts | Customer | Lists accounts where the caller has any grant. Never accepts a customer id parameter |
GET /accounts/{accountId} | Customer | Needs View. Returns 404 if there is no grant (not 403) |
GET /accounts/{accountId}/transactions | Customer | Needs View; pagination with a cursor, not offsets |
PATCH /accounts/{accountId} | Customer | Needs Owner for nickname and preferences; step-up for contact changes |
POST /accounts/{accountId}/freeze | Customer (self-freeze of a card or account) or staff | Needs Owner or a staff role; recorded with a reason |
POST /accounts/{accountId}/release | Staff only | Four-eyes; reason code required |
POST /accounts/{accountId}/close | Customer with Owner + staff | Zero balance check against the core; step-up |
Use RFC 9457 ProblemDetails for errors and an ETag for concurrency on updates (If-Match required on PATCH).
Model the grants (section 9)
An access grant says "customer C has level L on account A, until date D (optional)". Levels in increasing power: View, Transact, Owner. Joint accounts have two grants. A business signatory has Transact with a payment limit stored on the grant. Third-party access under open banking is a consent, not a grant, and is checked separately (Open Banking lesson).
Choose keys from access patterns (section 9)
| Access pattern | How it is served |
|---|---|
| List my accounts | Query the grants table, partition key CUSTOMER#<id>, sort key begins with ACCOUNT# |
| Can I do X on account A? | GetItem with partition CUSTOMER#<id>, sort ACCOUNT#<id> (strongly consistent) |
| Who has access to account A? (staff, estate cases) | Global secondary index with partition ACCOUNT#<id>, sort CUSTOMER#<id> |
| Revoke access | Delete or mark expired the grant item; write an audit record |
Why the key design matters: the customer id from the token is the partition key, so a query cannot return another customer's rows. That is defence in depth: even a bug in the endpoint code cannot list someone else's accounts from that call.
Put the check in one place (section 7 and 8)
Write one AccountAuthorizer class. Every endpoint calls it with the caller's grant, the account and the action. Add an architecture test that fails the build if a route in the account service is mapped without authorisation metadata.
Use optimistic concurrency for status changes (section 9 and 11)
Every account item carries a version number. A status change is a conditional UpdateItem that requires the expected version and increments it. If two staff freeze and release at once, one gets a conflict and must re-read.
Emit events and audit (section 10 and 15)
After each committed change, publish an event and write an audit record: who, what, when, from where, reason, before and after. Use the transactional outbox pattern (outbox with EF Core) or DynamoDB Streams so the event is never lost when the process crashes between write and publish.
AWS Console instructions
- Console → DynamoDB → Tables → Create table. Name
hl-m14-account-grants, partition keypk(String), sort keysk(String). Choose On-demand. - Table → Indexes → Create global index: name
by-account, partitiongsi1pk, sortgsi1sk, projection All. - Table → Additional settings: enable Point-in-time recovery, encryption with an AWS managed or customer managed key, and add the four course tags.
- Explore items → Create item and add one grant:
pk = CUSTOMER#CUS-00000042,sk = ACCOUNT#ACC-0000000042,level = Owner,gsi1pk = ACCOUNT#ACC-0000000042,gsi1sk = CUSTOMER#CUS-00000042.
AWS CLI
# Create the grants table with an on-demand billing mode and a reverse index.
aws dynamodb create-table \
--table-name hl-m14-account-grants \
--attribute-definitions AttributeName=pk,AttributeType=S AttributeName=sk,AttributeType=S \
AttributeName=gsi1pk,AttributeType=S AttributeName=gsi1sk,AttributeType=S \
--key-schema AttributeName=pk,KeyType=HASH AttributeName=sk,KeyType=RANGE \
--billing-mode PAY_PER_REQUEST \
--global-secondary-indexes '[{"IndexName":"by-account","KeySchema":[{"AttributeName":"gsi1pk","KeyType":"HASH"},{"AttributeName":"gsi1sk","KeyType":"RANGE"}],"Projection":{"ProjectionType":"ALL"}}]' \
--tags Key=Project,Value=cea-lab Key=Lab,Value=m14-l4 Key=Environment,Value=learn Key=Owner,Value=learner \
--profile learn-sandbox --region us-east-1
# Add one fictional grant: customer 42 owns account 42.
aws dynamodb put-item --table-name hl-m14-account-grants --profile learn-sandbox --region us-east-1 \
--item '{"pk":{"S":"CUSTOMER#CUS-00000042"},"sk":{"S":"ACCOUNT#ACC-0000000042"},"level":{"S":"Owner"},"gsi1pk":{"S":"ACCOUNT#ACC-0000000042"},"gsi1sk":{"S":"CUSTOMER#CUS-00000042"}}'
# List this customer's accounts: the partition key comes from the token, never from user input.
aws dynamodb query --table-name hl-m14-account-grants --profile learn-sandbox --region us-east-1 \
--key-condition-expression "pk = :c AND begins_with(sk, :a)" \
--expression-attribute-values '{":c":{"S":"CUSTOMER#CUS-00000042"},":a":{"S":"ACCOUNT#"}}'Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.DynamoDB;
using Constructs;
using DdbAttribute = Amazon.CDK.AWS.DynamoDB.Attribute;
public sealed class AccountGrantsStack : Stack
{
public AccountGrantsStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
{
var table = new Table(this, "Grants", new TableProps
{
TableName = "hl-m14-account-grants",
PartitionKey = new DdbAttribute { Name = "pk", Type = AttributeType.STRING },
SortKey = new DdbAttribute { Name = "sk", Type = AttributeType.STRING },
BillingMode = BillingMode.PAY_PER_REQUEST,
Encryption = TableEncryption.AWS_MANAGED,
PointInTimeRecoverySpecification = new PointInTimeRecoverySpecification { PointInTimeRecoveryEnabled = true },
RemovalPolicy = RemovalPolicy.DESTROY, // lab only: RETAIN in production
});
table.AddGlobalSecondaryIndex(new GlobalSecondaryIndexProps
{
IndexName = "by-account",
PartitionKey = new DdbAttribute { Name = "gsi1pk", Type = AttributeType.STRING },
SortKey = new DdbAttribute { Name = "gsi1sk", Type = AttributeType.STRING },
ProjectionType = ProjectionType.ALL,
});
}
}Option: a policy engine
Amazon Verified Permissions lets you write the ownership rule as a Cedar policy instead of C#:
// "Holders may view accounts they hold." Resource attribute 'holders' is a set of Customer entities.
permit (
principal is Customer,
action == Action::"ViewAccount",
resource is Account
)
when { resource.holders.contains(principal) && resource.status != "Closed" };Trade-off: the rule becomes reviewable by non-developers and testable apart from the service, but every decision is a network call (cost and latency) and you must supply the entity data. Many banks keep a fast in-process check for the hot path and use a policy engine for administrative actions ⚠ VERIFY service quotas and pricing before choosing.
Complete code
The authorisation core is plain C# so it can be unit tested without AWS. The DynamoDB store is a thin adapter around it.
namespace Harbourline.Accounts.Domain;
public enum AccountStatus { Open, Frozen, Closed }
public enum AccessLevel { View = 1, Transact = 2, Owner = 3 }
public enum AccountAction { View, Transact, ChangeDetails, Freeze, Close }
public sealed record Account(string AccountId, string Currency, AccountStatus Status, int Version);
public sealed record AccessGrant(string CustomerId, string AccountId, AccessLevel Level, DateOnly? ExpiresOn);
public enum AuthzDecision { Allowed, NotFound, Forbidden, StateConflict }
public static class AccountAuthorizer
{
/// <summary>
/// Decides one action. NotFound is returned when the caller has no usable grant, so the response
/// never confirms that someone else's account exists.
/// </summary>
public static AuthzDecision Decide(AccessGrant? grant, Account? account, AccountAction action, DateOnly today)
{
if (grant is null || account is null || grant.AccountId != account.AccountId)
{
return AuthzDecision.NotFound;
}
if (grant.ExpiresOn is { } expires && expires < today)
{
return AuthzDecision.NotFound;
}
if (grant.Level < RequiredLevel(action))
{
return AuthzDecision.Forbidden;
}
// State rules: frozen and closed accounts stay visible but cannot move money or be changed.
return account.Status switch
{
AccountStatus.Open => AuthzDecision.Allowed,
AccountStatus.Frozen when action is AccountAction.View or AccountAction.Close => AuthzDecision.Allowed,
AccountStatus.Closed when action is AccountAction.View => AuthzDecision.Allowed,
_ => AuthzDecision.StateConflict,
};
}
private static AccessLevel RequiredLevel(AccountAction action) => action switch
{
AccountAction.View => AccessLevel.View,
AccountAction.Transact => AccessLevel.Transact,
_ => AccessLevel.Owner,
};
private static readonly Dictionary<AccountStatus, AccountStatus[]> Moves = new()
{
[AccountStatus.Open] = [AccountStatus.Frozen, AccountStatus.Closed],
[AccountStatus.Frozen] = [AccountStatus.Open, AccountStatus.Closed],
};
public static bool CanMove(AccountStatus from, AccountStatus to) =>
Moves.TryGetValue(from, out var next) && next.Contains(to);
}using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
namespace Harbourline.Accounts.Infrastructure;
public sealed class DynamoDbAccountStatusWriter(IAmazonDynamoDB dynamo, string table)
{
/// <summary>Returns true if the status changed, false if another writer got there first (version mismatch).</summary>
public async Task<bool> TryChangeStatusAsync(
string accountId, int expectedVersion, string newStatus, string actor, CancellationToken ct)
{
try
{
await dynamo.UpdateItemAsync(new UpdateItemRequest
{
TableName = table,
Key = new Dictionary<string, AttributeValue>
{
["pk"] = new() { S = $"ACCOUNT#{accountId}" },
["sk"] = new() { S = "PROFILE" },
},
UpdateExpression = "SET #status = :new, #version = #version + :one, changedBy = :actor",
ConditionExpression = "#version = :expected",
ExpressionAttributeNames = new() { ["#status"] = "status", ["#version"] = "version" },
ExpressionAttributeValues = new()
{
[":new"] = new() { S = newStatus },
[":expected"] = new() { N = expectedVersion.ToString() },
[":one"] = new() { N = "1" },
[":actor"] = new() { S = actor },
},
}, ct);
return true;
}
catch (ConditionalCheckFailedException)
{
return false;
}
}
}Code explained line by line
AccessLevelvalues are ordered numbers sogrant.Level < RequiredLevel(action)is a single comparison. Adding a level later means one enum change.Decidereturns a decision, not a boolean, because the API maps different decisions to different HTTP responses:NotFoundto 404,Forbiddento 403,StateConflictto 409.- The first
ifreturnsNotFoundfor a missing grant and for an account id that does not match the grant. The secondiftreats expired grants as absent. In both cases nothing about the account's existence leaks. - The
switchexpression encodes state rules: an open account permits any action the level allows; a frozen account permits viewing and closing (closing a frozen account may be required by process, a bank policy to confirm ⚠ VERIFY); a closed account is view-only; anything else is a conflict. CanMoveis the transition table.Closedhas no entry, so it is terminal.- The DynamoDB writer builds an
UpdateItemwhoseConditionExpressionis#version = :expected. Attribute names are aliased (#status,#version) becausestatusis a DynamoDB reserved word. - The expression increments the version in the same atomic operation, so two concurrent writers cannot both succeed.
ConditionalCheckFailedExceptionis an expected business outcome (someone else changed it), so it becomesfalserather than an error. The caller re-reads the account and decides.
Security considerations
⚠ Learning shortcut — not for production
The sample reads the grant and the account with two calls and then decides. In production, read both with strong consistency (or in one transaction read), keep the grant check and the action in one request path, and add an architecture test that every mapped route requires the authoriser. Also record every denied attempt: a customer repeatedly probing other account ids is a fraud signal, not noise.
- BOLA/IDOR is the main threat. The partition key built from the token's customer id, the
NotFoundresponse and the shared authoriser are three layers against it (threat modelling). - Never accept
customerIdfrom the client. The BFF supplies it from the validated token. - Do not use sequential account ids as secrets. Opaque ids help, but authorisation is the real control.
- Freeze must be authoritative. A frozen account must also be blocked at the payment service and the core, not only hidden in the UI.
- Staff access is a separate attack surface. Use SSO with MFA, role-based access, reason codes, time-bound elevation and four-eyes. Log every staff view of customer data.
- Data protection: the account projection contains personal data. Encrypt, limit retention after closure per your records schedule ⚠ VERIFY, and handle data-subject requests through a defined process.
Banking use case
Harbourline's customer Alex (fictional) has a personal current account, a joint savings account with a partner, and is a signatory on a small business account with a payment limit of GBP 2,000.
GET /accountsreturns three accounts, each with the caller's level, because Alex holds three grants.- Alex's partner removes Alex's access to the joint account through the bank's process. The grant item is deleted and an audit record is written; the next call returns two accounts. Tokens already issued do not change this, because grants are read on each request.
- The fraud team freezes the personal account after suspicious logins. The status event updates the projection within seconds; payments are blocked in the payment service, which reads the same status. Alex can still view the account and its history.
- A branch employee tries to release the freeze alone. The API requires a second approver; the attempt is logged and rejected.
Common mistakes
- Checking authentication but not ownership → BOLA → route every call through one authoriser and add an architecture test.
- Returning 403 for other people's accounts → confirms the account exists → return 404.
- Trusting the customer id in the request → impersonation → derive it from the token.
- Caching grants for hours → revoked access keeps working → short cache or none; grants are the security master.
- Using the core's balance as a cache of truth for status checks → frozen accounts still pay during sync lag → enforce status at the payment step too.
- Updating status without a version check → lost updates → conditional writes.
- Auditing only through CloudTrail → CloudTrail does not see business actions → write application audit records.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Customer sees an empty account list | Grants not created during onboarding, or wrong key prefix | Check the onboarding step that writes grants; query by CUSTOMER#<id> |
ConditionalCheckFailedException on every status change | Client sends a stale version, or attribute missing on old items | Re-read before update; back-fill version = 0 |
ValidationException: Attribute name is a reserved keyword | Used status directly in an expression | Alias with ExpressionAttributeNames |
| Query on the index returns stale data | GSI reads are eventually consistent | Use the base table for security decisions; use the index for staff reporting |
| Throttling on one customer | Hot partition from heavy polling | Cache on the BFF, use push notifications, or spread the key |
| Staff cannot release a freeze | Second approver missing | Check four-eyes configuration and approver role mapping |
| Projection shows old balance | Event consumer behind or failed | Check consumer lag, dead-letter queue, and reconciliation report |
Cost and cleanup
Label: 🟢 free at lab volumes. On-demand DynamoDB charges per request and storage, and the always-free tier covers small usage ⚠ VERIFY current allowances. Point-in-time recovery adds a small storage charge. The code and the authorisation tests run locally with no AWS account.
# Delete the table you created.
aws dynamodb delete-table --table-name hl-m14-account-grants --profile learn-sandbox --region us-east-1
# Confirm nothing tagged for the course remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
--profile learn-sandbox --region us-east-1Exercises
- 🟢 Guided: write xUnit tests for
AccountAuthorizer.Decide: owner can view; view-level cannot transact; expired grant givesNotFound; grant for another account givesNotFound; frozen account allowsViewbut notTransact. - 🟡 Challenge: add a per-grant
PaymentLimitfor business signatories and extend the decision so a payment above the limit returnsForbidden. Decide whether that rule belongs inAccountAuthorizeror in the payments service, and record an ADR. - 🔴 Live problem: the security team found that
GET /accounts/{id}returns200for a closed joint account to a holder whose access was removed two days ago, because the BFF caches grants for 24 hours. Find the design change that fixes it without making every request slow, list what you would measure, and describe how you will prove the fix.
Assignment
Create architecture/account-management/ with the 15-section document, the lifecycle state diagram, the key-design table, the authoriser with tests, an ADR on "404 instead of 403" and an ADR on "grants are the security master and are not cached beyond N seconds". Add a threat table (BOLA, privilege escalation by staff, stale grants, lost updates) with the control for each.
Solutions
using Harbourline.Accounts.Domain;
using Xunit;
public class AccountAuthorizerTests
{
private static readonly DateOnly Today = new(2026, 11, 18);
private static Account Acc(AccountStatus s = AccountStatus.Open) => new("ACC-1", "GBP", s, 1);
private static AccessGrant Grant(AccessLevel l, DateOnly? exp = null, string acc = "ACC-1") => new("CUS-1", acc, l, exp);
[Fact] public void Owner_can_view() =>
Assert.Equal(AuthzDecision.Allowed, AccountAuthorizer.Decide(Grant(AccessLevel.Owner), Acc(), AccountAction.View, Today));
[Fact] public void View_level_cannot_transact() =>
Assert.Equal(AuthzDecision.Forbidden, AccountAuthorizer.Decide(Grant(AccessLevel.View), Acc(), AccountAction.Transact, Today));
[Fact] public void Expired_grant_is_not_found() =>
Assert.Equal(AuthzDecision.NotFound, AccountAuthorizer.Decide(Grant(AccessLevel.Owner, Today.AddDays(-1)), Acc(), AccountAction.View, Today));
[Fact] public void Grant_for_another_account_is_not_found() =>
Assert.Equal(AuthzDecision.NotFound, AccountAuthorizer.Decide(Grant(AccessLevel.Owner, acc: "ACC-2"), Acc(), AccountAction.View, Today));
[Fact] public void Frozen_allows_view_but_not_transact()
{
var g = Grant(AccessLevel.Owner);
Assert.Equal(AuthzDecision.Allowed, AccountAuthorizer.Decide(g, Acc(AccountStatus.Frozen), AccountAction.View, Today));
Assert.Equal(AuthzDecision.StateConflict, AccountAuthorizer.Decide(g, Acc(AccountStatus.Frozen), AccountAction.Transact, Today));
}
}Why: the tests cover each branch of the decision. Notice that "no grant" and "wrong account" and "expired" all give NotFound: the caller learns nothing.
Recommended: keep the limit value on the grant (it is a relationship attribute), but enforce the rule in the payments service, which knows the amount, currency conversion and daily totals. AccountAuthorizer answers "may this person transact on this account at all?"; the payments service answers "may they transact this amount now?". Splitting the rule avoids the account service needing to know about cumulative spending.
ADR consequence: two services must agree on the grant schema, so version it and publish changes as events.
Options: (1) no grant caching on the BFF at all, since a GetItem on DynamoDB is single-digit milliseconds; (2) cache for a very short time (for example 15 seconds) with explicit invalidation by an event when a grant changes; (3) embed grants in a short-lived token (stale for the token lifetime, usually unacceptable for revocation). Choose (1) or (2) and record the maximum staleness as a requirement. Measure: p95 added latency, DynamoDB request rate, number of requests served on grants older than the limit, and time from revocation to denial. Prove the fix with an automated test that revokes a grant and asserts denial within the stated bound.
Knowledge check
Answer: A 403 confirms that the account exists, which helps an attacker enumerate valid ids. A 404 reveals nothing. Use 403 only when the caller can see the account but lacks permission for the action.
Answer: The query can then only return that customer's items, even if the endpoint code has a bug. It is a structural safeguard, a second layer behind the authoriser.
Answer: Lost updates. Two staff acting at once could overwrite each other's changes. With a version check, exactly one write succeeds and the other must re-read and decide.
Answer: No. IAM controls which AWS principals can call AWS APIs, such as a task role reading a table. It does not know which application customer is calling the service. Customer-level authorisation is application logic or a policy engine.
Answer: To serve reads quickly and keep working when the core is slow or in a maintenance window, with a stated staleness. The projection is rebuilt from events and reconciled against the core.
Interview questions
- How do you stop a user reading someone else's account through the API? Take the customer id from the token, check a grant on every request in one shared authoriser, key data by customer, return 404 for non-grants, test it automatically and log denied probes.
- How would you model joint accounts? Each holder has an access grant on the account with a level, and the reverse index lists holders. Limits and expiry live on the grant.
- When would you use a policy engine instead of code? When rules change often, need review by non-developers, or must be consistent across many services; accept the cost of an extra call and managing entity data.
- How do you handle two people editing an account at once? Optimistic concurrency with a version attribute and
If-Match/ETagat the API. - What belongs in the audit record? Actor, action, target, before and after, reason, timestamp, source, correlation id, and outcome including denials.
Certification practice
A banking API stores account grants in DynamoDB. The team wants a request for another customer's data to be impossible to satisfy even if an endpoint has a coding error. Which design helps most?
A. Use a table-wide scan filtered in code. B. Use the authenticated customer id from the token as the partition key in queries. C. Expose the table through a public endpoint. D. Store all grants in one item.
Answer: B. Scoping the query to the caller's partition limits what any code path can return. A reads everything. C exposes data. D creates a hot, oversized item.
Two operators update the same DynamoDB account item at the same time and one change is lost. Which feature prevents this?
A. Eventually consistent reads B. A conditional write using a version attribute C. Global tables D. TTL
Answer: B. A condition on the expected version makes the second write fail and signals a conflict. A affects reads. C replicates across Regions, which can create more write conflicts rather than fewer. D deletes items by time.
A bank wants authorisation rules (who may view or change an account) stored as reviewable policies separate from application code. Which AWS service is designed for this?
A. AWS KMS B. Amazon Verified Permissions C. AWS Shield D. Amazon Macie
Answer: B. Verified Permissions stores and evaluates Cedar policies for application authorisation. A manages keys, C protects against DDoS, D discovers sensitive data.
Completion checklist
- I can say which system is the master for each account fact
- I can explain why other people's accounts return 404
- I wrote and ran authoriser tests
- I can explain optimistic concurrency with a version attribute
- I wrote the 15-section document with a no-compliance-claims touchpoints table
- I ran the cleanup steps and confirmed nothing is still billing
Key takeaways
- The core banking system is the master; the cloud service holds projections and must say how stale they may be.
- Authorisation is per request and per object: derive identity from the token, check a grant, and return 404 for non-grants.
- Key design can make the dangerous query impossible; code and tests make it safe.
- Lifecycle rules (frozen, closed) apply at the payment step too, not just in the UI.
- Application audit records are separate from CloudTrail and must include denied attempts.
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.
Customer onboarding: KYC/AML integration, secure document upload and consent
Design a customer onboarding architecture on AWS: an orchestrated KYC workflow that calls an identity-verification provider, secure document upload with quarantine and scanning, a manual-review step, consent capture and the data-protection controls a bank's reviewers will ask about.
Payment processing: initiation, screening, settlement and idempotency
Design an end-to-end payment architecture on AWS: idempotent initiation, validation, a fail-closed sanctions-screening hook, a hold-submit-settle saga with a pivot point, a double-entry ledger, ISO 20022 messages, and the failure scenarios a design authority will probe.