Consent Management Domain Validation Tooling for Consent-First Integrations
Overview
This section documents the verification assets that exercise consent-first flows across the Lita monolith, the US Fastify microservice, and the Go data gateway. The goal is to make it obvious which validation path proves which behavior: local consent registration and snapshot storage in the FastAPI monolith, consent lifecycle and guard-rail enforcement in the US service, and error translation in the Go gateway.
The monolith path is centered on documents/lita-testing-guide.md and backend/tests/interface/test_lita_endpoints.py. The US service path is centered on services/us-api/test/flows.test.ts and the consent lifecycle functions in services/us-api/src/services/consentService.ts. The Go gateway path is the focused handlers_test.go contract check for domain error mapping.
Validation Path Selection
| Need to verify | Use this asset | What it proves |
|---|---|---|
| Consent, token, snapshot, and score flow in the FastAPI monolith | documents/lita-testing-guide.md + backend/tests/interface/test_lita_endpoints.py |
Consent creation, token issuance, bearer-protected snapshot round-trip, and repeated scoring with identical request_id |
| Consent lifecycle and refresh-limit enforcement in the US service | services/us-api/test/flows.test.ts |
Consent creation, consent revocation, refresh-limit rejection, and category guard rails |
| Consent lifecycle behavior in the US service implementation | services/us-api/src/services/consentService.ts |
How consent records are created, revoked, audited, and treated as active |
| Go gateway error contract | services/us-data-gateway/internal/handlers/handlers_test.go |
HTTP status and JSON error code mapping for consent and category failures |
| One-command local smoke run | ./scripts/lita_smoke_test.sh |
End-to-end local validation against the SQLite fallback |
Architecture Overview
flowchart TB
subgraph Guides [Validation Guides]
LitaGuide[documents lita testing guide]
UsServiceDocs[US service docs]
end
subgraph Monolith [FastAPI Monolith Validation]
PytestModule[backend tests interface test lita endpoints]
FastAPIApp[Lita FastAPI app]
LitaEndpoints[backend src interface lita endpoints]
LitaRepo[backend src infra mysql lita repository]
end
subgraph USService [US Fastify Validation]
FlowsTest[services us api test flows test]
RegisterRoutes[registerUsRoutes]
ConsentService[services us api src services consentService]
Prisma[Prisma]
end
subgraph Gateway [Go Gateway Validation]
GoHandlersTest[services us data gateway internal handlers handlers test go]
WriteError[writeError]
end
LitaGuide --> PytestModule
PytestModule --> FastAPIApp
FastAPIApp --> LitaEndpoints
LitaEndpoints --> LitaRepo
UsServiceDocs --> FlowsTest
FlowsTest --> RegisterRoutes
RegisterRoutes --> ConsentService
ConsentService --> Prisma
GoHandlersTest --> WriteError
Component Structure
1. Monolith Consent Validation
Lita Testing Guide
[!NOTE] The monolith regression test for
/api/lita/v1/scoreposts withoutAuthorizationorX-Request-Idheaders. That validation path proves the implemented local scoring behavior and request-id idempotency, not the customer-hosted scoring header contract described in the external API specification.
documents/lita-testing-guide.md
This guide is the manual and scripted smoke-test path for the monolith consent API. It walks through the exact sequence used by the local smoke script: create a consent, issue a token, store a snapshot, read it back, and call scoring twice with the same request_id.
Validated flow
POST /api/lita/v1/consentsPOST /api/lita/v1/consents/{consent_reference}/tokensPOST /api/lita/v1/data/snapshotsGET /api/lita/v1/data/snapshots/latestPOST /api/lita/v1/score
Commands referenced by the guide
pytest backend/tests/interface/test_lita_endpoints.py -q
uvicorn src.main:app --app-dir backend --host 0.0.0.0 --reload --port 8000
./scripts/lita_smoke_test.sh
What the guide proves
- Consent creation works against the local FastAPI app.
- Token issuance returns an access token that can be used as
Bearer. - Snapshot storage and retrieval round-trip through the local data layer.
- Repeating the same score request with the same
request_idreturns an identical response.
Pytest Regression Module
backend/tests/interface/test_lita_endpoints.py
This module is the automated regression path for the monolith. It uses FastAPI’s test client and verifies the consent, token, snapshot, and score flows end to end.
Test helpers and scenarios
| Helper or test | Purpose |
|---|---|
_register_consent |
Creates a consent with a 30-day expiry and asserts 201 Created |
_issue_access_token |
Exchanges a consent reference for an access token and asserts 201 Created |
test_lita_consent_snapshot_round_trip |
Stores a payload under a bearer token and confirms the latest snapshot returns the same payload |
test_lita_scoring_is_idempotent |
Posts the same scoring request twice and asserts the second response matches the first byte-for-byte |
Key behaviors asserted by the module
- Consent creation returns the submitted
consent_reference. - Token issuance returns
access_token. - Snapshot read/write preserves the payload exactly.
- Scoring uses request-id idempotency.
Lita Endpoint Models
backend/src/interface/lita_endpoints.py
These models define the request and response shapes used by the monolith validation path.
ConsentRequest
| Property | Type | Description |
|---|---|---|
consent_reference |
str |
Unique consent reference provided by the client |
customer_reference |
str |
Customer reference associated with the consent |
applicant_reference |
Optional[str] |
Optional applicant reference |
country |
Optional[str] |
Optional country code |
product_type |
Optional[str] |
Optional product type |
data_categories |
List[str] |
Granted data categories |
refresh_permissions |
List[str] |
Granted refresh permissions |
expires_at |
datetime |
Consent expiry timestamp |
refresh_allowed |
bool |
Whether refresh is allowed |
ConsentResponse
| Property | Type | Description |
|---|---|---|
consent_reference |
str |
Stored consent reference |
customer_reference |
str |
Stored customer reference |
applicant_reference |
Optional[str] |
Stored applicant reference |
country |
Optional[str] |
Stored country code |
product_type |
Optional[str] |
Stored product type |
data_categories |
List[str] |
Stored data categories |
refresh_permissions |
List[str] |
Stored refresh permissions |
expires_at |
datetime |
Stored consent expiry |
refresh_allowed |
bool |
Stored refresh flag |
revoked_at |
Optional[datetime] |
Revocation timestamp |
created_at |
Optional[datetime] |
Creation timestamp |
updated_at |
Optional[datetime] |
Last update timestamp |
TokenResponse
| Property | Type | Description |
|---|---|---|
consent_reference |
str |
Consent reference bound to the token |
access_token |
str |
Issued bearer token |
expires_at |
datetime |
Token expiry timestamp |
SnapshotResponse
| Property | Type | Description |
|---|---|---|
consent_reference |
str |
Consent reference that owns the snapshot |
version |
str |
Snapshot version string |
stored_at |
datetime |
Snapshot persistence timestamp |
payload |
Dict[str, Any] |
Stored JSON payload |
Lita Endpoint Helper Functions
| Function | Purpose |
|---|---|
_serialise_consent |
Converts the repository model into ConsentResponse |
_get_consent_and_token |
Validates bearer authentication, token state, consent state, and expiry before snapshot access |
register_consent |
Creates a consent and maps duplicate consent references to 409 Conflict |
get_consent |
Looks up a consent by consent_reference and returns 404 when missing |
issue_token |
Issues a token for an existing consent and returns the expiry |
read_snapshot |
Returns the latest stored snapshot for the consent or 404 when none exists |
Monolith API Surface Under Test
Register Consent
{
"title": "Register Consent",
"description": "Creates a consent record for the monolith consent API validation flow",
"method": "POST",
"baseUrl": "<LitaApiBaseUrl>",
"endpoint": "/api/lita/v1/consents",
"headers": [
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "json",
"requestBody": "{\n \"consent_reference\": \"consent_local_001\",\n \"customer_reference\": \"customer_abc\",\n \"applicant_reference\": \"applicant_xyz\",\n \"country\": \"GB\",\n \"product_type\": \"CREDIT_CARD\",\n \"data_categories\": [\n \"balances\",\n \"transactions\"\n ],\n \"refresh_permissions\": [\n \"balances:read\",\n \"transactions:read\"\n ],\n \"expires_at\": \"2030-01-01T00:00:00Z\",\n \"refresh_allowed\": true\n}",
"formData": [],
"rawBody": "",
"responses": {
"201": {
"description": "Consent created",
"body": "{\n \"consent_reference\": \"consent_local_001\",\n \"customer_reference\": \"customer_abc\",\n \"applicant_reference\": \"applicant_xyz\",\n \"country\": \"GB\",\n \"product_type\": \"CREDIT_CARD\",\n \"data_categories\": [\n \"balances\",\n \"transactions\"\n ],\n \"refresh_permissions\": [\n \"balances:read\",\n \"transactions:read\"\n ],\n \"expires_at\": \"2030-01-01T00:00:00Z\",\n \"refresh_allowed\": true,\n \"revoked_at\": null,\n \"created_at\": \"2024-01-01T12:00:00Z\",\n \"updated_at\": \"2024-01-01T12:00:00Z\"\n}"
},
"409": {
"description": "Consent reference already exists",
"body": "{\n \"detail\": \"Consent reference already exists\"\n}"
}
}
}
Get Consent
{
"title": "Get Consent",
"description": "Fetches a stored consent by consent reference",
"method": "GET",
"baseUrl": "<LitaApiBaseUrl>",
"endpoint": "/api/lita/v1/consents/{consent_reference}",
"headers": [],
"queryParams": [],
"pathParams": [
{
"key": "consent_reference",
"value": "consent_local_001",
"required": true
}
],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Consent returned",
"body": "{\n \"consent_reference\": \"consent_local_001\",\n \"customer_reference\": \"customer_abc\",\n \"applicant_reference\": \"applicant_xyz\",\n \"country\": \"GB\",\n \"product_type\": \"CREDIT_CARD\",\n \"data_categories\": [\n \"balances\",\n \"transactions\"\n ],\n \"refresh_permissions\": [\n \"balances:read\",\n \"transactions:read\"\n ],\n \"expires_at\": \"2030-01-01T00:00:00Z\",\n \"refresh_allowed\": true,\n \"revoked_at\": null,\n \"created_at\": \"2024-01-01T12:00:00Z\",\n \"updated_at\": \"2024-01-01T12:00:00Z\"\n}"
},
"404": {
"description": "Consent not found",
"body": "{\n \"detail\": \"Consent not found\"\n}"
}
}
}
Issue Access Token
{
"title": "Issue Access Token",
"description": "Issues a bearer token for an existing consent",
"method": "POST",
"baseUrl": "<LitaApiBaseUrl>",
"endpoint": "/api/lita/v1/consents/{consent_reference}/tokens",
"headers": [
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [
{
"key": "consent_reference",
"value": "consent_local_001",
"required": true
}
],
"bodyType": "json",
"requestBody": "{\n \"expires_in_days\": 30\n}",
"formData": [],
"rawBody": "",
"responses": {
"201": {
"description": "Token issued",
"body": "{\n \"consent_reference\": \"consent_local_001\",\n \"access_token\": \"token_9f2d7c1f3a5e4b1c\",\n \"expires_at\": \"2030-02-01T00:00:00Z\"\n}"
},
"404": {
"description": "Consent not found",
"body": "{\n \"detail\": \"Consent not found\"\n}"
}
}
}
Store Snapshot
{
"title": "Store Snapshot",
"description": "Stores a versioned JSON snapshot under a valid bearer token",
"method": "POST",
"baseUrl": "<LitaApiBaseUrl>",
"endpoint": "/api/lita/v1/data/snapshots",
"headers": [
{
"key": "Authorization",
"value": "Bearer <ACCESS_TOKEN>",
"required": true
},
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "json",
"requestBody": "{\n \"version\": \"1.1\",\n \"payload\": {\n \"balances\": {\n \"available\": 1500,\n \"currency\": \"GBP\"\n },\n \"transactions\": [\n {\n \"amount\": -20,\n \"description\": \"Coffee\"\n },\n {\n \"amount\": -50,\n \"description\": \"Groceries\"\n }\n ]\n }\n}",
"formData": [],
"rawBody": "",
"responses": {
"201": {
"description": "Snapshot stored",
"body": "{\n \"consent_reference\": \"consent_local_001\",\n \"version\": \"1.1\",\n \"stored_at\": \"2024-01-01T12:10:00Z\",\n \"payload\": {\n \"balances\": {\n \"available\": 1500,\n \"currency\": \"GBP\"\n },\n \"transactions\": [\n {\n \"amount\": -20,\n \"description\": \"Coffee\"\n },\n {\n \"amount\": -50,\n \"description\": \"Groceries\"\n }\n ]\n }\n}"
},
"401": {
"description": "Bearer token required",
"body": "{\n \"detail\": \"Bearer token required\"\n}"
},
"403": {
"description": "Token revoked or consent revoked or consent expired",
"body": "{\n \"detail\": \"Token revoked\"\n}"
},
"404": {
"description": "Consent not found or no data available",
"body": "{\n \"detail\": \"Consent not found\"\n}"
}
}
}
Get Latest Snapshot
{
"title": "Get Latest Snapshot",
"description": "Returns the most recent snapshot for the consent bound to the bearer token",
"method": "GET",
"baseUrl": "<LitaApiBaseUrl>",
"endpoint": "/api/lita/v1/data/snapshots/latest",
"headers": [
{
"key": "Authorization",
"value": "Bearer <ACCESS_TOKEN>",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Latest snapshot returned",
"body": "{\n \"consent_reference\": \"consent_local_001\",\n \"version\": \"1.1\",\n \"stored_at\": \"2024-01-01T12:10:00Z\",\n \"payload\": {\n \"balances\": {\n \"available\": 1500,\n \"currency\": \"GBP\"\n },\n \"transactions\": [\n {\n \"amount\": -20,\n \"description\": \"Coffee\"\n },\n {\n \"amount\": -50,\n \"description\": \"Groceries\"\n }\n ]\n }\n}"
},
"401": {
"description": "Bearer token required",
"body": "{\n \"detail\": \"Bearer token required\"\n}"
},
"404": {
"description": "No data available for consent",
"body": "{\n \"detail\": \"No data available for consent\"\n}"
}
}
}
Score Consent Decision
{
"title": "Score Consent Decision",
"description": "Posts a scoring request and verifies repeated request_id values return the same response",
"method": "POST",
"baseUrl": "<LitaApiBaseUrl>",
"endpoint": "/api/lita/v1/score",
"headers": [
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "json",
"requestBody": "{\n \"version\": \"1.1\",\n \"request_id\": \"req-demo-001\",\n \"applicant\": {\n \"applicant_reference\": \"app-100\",\n \"country\": \"GB\"\n },\n \"context\": {\n \"product_type\": \"CREDIT_CARD\"\n },\n \"features\": {\n \"credit_utilization\": 0.65,\n \"debt_to_income_ratio\": 0.4,\n \"credit_history_months\": 30,\n \"monthly_income\": 6000\n }\n}",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Deterministic score returned",
"body": "{\n \"version\": \"1.1\",\n \"request_id\": \"req-demo-001\",\n \"score\": 712,\n \"decision\": \"APPROVE\",\n \"approved_limit\": 4000,\n \"model\": {\n \"name\": \"credit_card_v2\",\n \"version\": \"2.3.1\"\n },\n \"reasons\": [\n {\n \"code\": \"HIGH_UTILIZATION\"\n },\n {\n \"code\": \"SHORT_HISTORY\"\n }\n ]\n}"
}
}
}
2. US Microservice Validation
US Consent Service
services/us-api/src/services/consentService.ts
This service is the core behavior under the US route tests. It creates consent records, revokes them, returns receipts, and enforces whether a consent is still active.
Public methods
| Method | Description | Returns |
|---|---|---|
createConsent |
Creates a new consent, logs the creation event, and returns the stored consent | Promise<Consent> |
revokeConsent |
Marks the consent revoked, revokes active tokens, disconnects connections, logs the revocation, and attempts webhook dispatch | Promise<{ consentId: string }> |
getConsentReceipt |
Returns audit-friendly consent metadata | Promise<{ consent_id: string; status: string; purpose: string; data_categories: DataCategory[]; consent_disclosure_version: string; expires_at: string; created_at: string }> |
ensureConsentActive |
Throws when the consent is missing, revoked, or expired | Promise<Consent> |
CreateConsentPayload
| Property | Type | Description |
|---|---|---|
user |
{ country: 'US'; user_reference?: string } |
Consent owner details |
purpose |
Purpose |
Declared consent purpose |
data_categories |
DataCategory[] |
Granted data categories |
access_duration_days |
`number | undefined` |
expires_at |
`string | undefined` |
refresh_permissions |
`{ enabled: boolean; max_refresh_per_day: number } | undefined` |
consent_disclosure_version |
string |
Consent disclosure version |
Behavior captured by the service
createConsentassignsPENDING_USER_ACTION.revokeConsentupdates the consent toREVOKED, revokes tokens, disconnects connections, creates aconsentLog, and best-effort dispatches aconsent_revokedwebhook.getConsentReceiptreturns the consent metadata needed for audit and compliance checks.ensureConsentActivethrowsCONSENT_REVOKEDfor missing, inactive, or expired consents.
US Fastify Flow Tests
services/us-api/test/flows.test.ts
This file validates the US microservice route behavior with a mocked Prisma client and mocked middleware. It does not hit external systems; it verifies the route logic after auth has already been satisfied by the test doubles.
Test harness setup
prismaMockcoversconsent,consentLog,token,connection,refreshEvent,evidenceSnapshot,decision, andaccessLog.requirePartnerAuthis mocked to setrequest.partnerId = 'partner_1'.requireAccessTokenis mocked to setrequest.accessClaimswithconsent_id,purpose,data_categories, andjti.- The Fastify app installs
errorHandlerbefore registeringregisterUsRoutes.
Test cases
| Test | Endpoint | What it proves |
|---|---|---|
creates consent |
POST /api/v1/us/consents |
The consent route accepts a consent request and returns success |
revokes consent |
POST /api/v1/us/consents/consent_1/revoke |
The revoke route succeeds for an existing consent |
refresh token enforces limit |
POST /api/v1/us/tokens/refresh |
The refresh flow rejects requests that exceed the daily refresh limit |
returns category not allowed for accounts |
GET /api/v1/us/data/accounts |
The account route rejects access when the granted category is missing |
US API Surface Under Test
Create Consent
{
"title": "Create Consent",
"description": "Creates a US consent and returns the stored consent record",
"method": "POST",
"baseUrl": "<UsApiBaseUrl>",
"endpoint": "/api/v1/us/consents",
"headers": [
{
"key": "Authorization",
"value": "Bearer <PARTNER_TOKEN>",
"required": true
},
{
"key": "X-Request-Id",
"value": "<uuid>",
"required": true
},
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "json",
"requestBody": "{\n \"user\": {\n \"country\": \"US\",\n \"user_reference\": \"user_123\"\n },\n \"purpose\": \"LENDING_UNDERWRITING\",\n \"data_categories\": [\n \"ACCOUNTS\",\n \"BALANCES\"\n ],\n \"access_duration_days\": 365,\n \"expires_at\": \"2024-12-31T00:00:00Z\",\n \"refresh_permissions\": {\n \"enabled\": true,\n \"max_refresh_per_day\": 4\n },\n \"consent_disclosure_version\": \"v1\"\n}",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Consent created",
"body": "{\n \"id\": \"cst_us_1a2b3c4d5e6f\",\n \"partnerId\": \"partner_1\",\n \"userReference\": \"user_123\",\n \"country\": \"US\",\n \"purpose\": \"LENDING_UNDERWRITING\",\n \"dataCategories\": [\n \"ACCOUNTS\",\n \"BALANCES\"\n ],\n \"status\": \"PENDING_USER_ACTION\",\n \"consentDisclosureVersion\": \"v1\",\n \"expiresAt\": \"2024-12-31T00:00:00Z\",\n \"refreshEnabled\": true,\n \"maxRefreshPerDay\": 4\n}"
}
}
}
Revoke Consent
{
"title": "Revoke Consent",
"description": "Revokes an existing US consent and cascades token and connection updates",
"method": "POST",
"baseUrl": "<UsApiBaseUrl>",
"endpoint": "/api/v1/us/consents/{consent_id}/revoke",
"headers": [
{
"key": "Authorization",
"value": "Bearer <PARTNER_TOKEN>",
"required": true
},
{
"key": "X-Request-Id",
"value": "<uuid>",
"required": true
}
],
"queryParams": [],
"pathParams": [
{
"key": "consent_id",
"value": "consent_1",
"required": true
}
],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Consent revoked",
"body": "{\n \"consentId\": \"consent_1\"\n}"
},
"404": {
"description": "Consent not found",
"body": "{\n \"error\": \"NOT_FOUND\"\n}"
}
}
}
Refresh Access Token
{
"title": "Refresh Access Token",
"description": "Attempts to refresh access credentials within the daily limit and returns a rate-limit error when the limit is exceeded",
"method": "POST",
"baseUrl": "<UsApiBaseUrl>",
"endpoint": "/api/v1/us/tokens/refresh",
"headers": [
{
"key": "Authorization",
"value": "Bearer <PARTNER_TOKEN>",
"required": true
},
{
"key": "X-Request-Id",
"value": "<uuid>",
"required": true
},
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "json",
"requestBody": "{\n \"refresh_token\": \"rtk_live_123\"\n}",
"formData": [],
"rawBody": "",
"responses": {
"429": {
"description": "Refresh limit exceeded",
"body": "{\n \"error\": {\n \"code\": \"REFRESH_LIMIT_EXCEEDED\",\n \"message\": \"Refresh limit exceeded\"\n },\n \"request_id\": \"req_3\"\n}"
}
}
}
Get Accounts
{
"title": "Get Accounts",
"description": "Returns token-scoped accounts and enforces consent category checks",
"method": "GET",
"baseUrl": "<UsApiBaseUrl>",
"endpoint": "/api/v1/us/data/accounts",
"headers": [
{
"key": "Authorization",
"value": "Bearer <ACCESS_TOKEN>",
"required": true
},
{
"key": "X-Request-Id",
"value": "<uuid>",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"403": {
"description": "Category not allowed",
"body": "{\n \"error\": {\n \"code\": \"CATEGORY_NOT_ALLOWED\",\n \"message\": \"Transactions not permitted by consent\"\n },\n \"request_id\": \"req_4\"\n}"
}
}
}
3. Go Gateway Error Contract Validation
Go Gateway Handler Tests
[!NOTE]
services/us-api/test/flows.test.tsstubsrequirePartnerAuthandrequireAccessToken, so it validates route behavior, consent state transitions, and limit enforcement after authentication has already been satisfied.
services/us-data-gateway/internal/handlers/handlers_test.go
This file validates the gateway’s error writer contract. It does not exercise routing; it asserts that the domain error constants are converted into the expected HTTP status codes and JSON payloads.
Test cases
| Test | Function under test | Expected HTTP status | Expected JSON body |
|---|---|---|---|
TestCategoryNotAllowedReturns403 |
writeError with ErrCategoryNotAllowed |
403 Forbidden |
{"error":"CATEGORY_NOT_ALLOWED"} |
TestConsentRevokedReturns409 |
writeError with ErrConsentRevoked |
409 Conflict |
{"error":"CONSENT_REVOKED"} |
Contract coverage
ErrCategoryNotAllowedmaps to403.ErrConsentRevokedmaps to409.- The response body always contains the
errorfield.
Feature Flows
Monolith Consent Smoke Test Flow
sequenceDiagram
participant Engineer as Engineer
participant Guide as Lita Testing Guide
participant Pytest as Pytest Module
participant App as FastAPI App
participant Router as Lita Endpoints
participant Repo as Lita Repository
participant Db as SQLite Or MySQL
Engineer->>Guide: Run local smoke test
Guide->>Pytest: pytest backend tests interface test lita endpoints
Pytest->>App: Create consent
App->>Router: Register and serialise consent
Router->>Repo: Persist consent
Repo->>Db: Insert consent row
Db-->>Repo: Stored consent
Repo-->>Router: Consent model
Router-->>App: Consent response
App-->>Pytest: 201 Created
Pytest->>App: Issue token
App->>Router: Issue access token
Router->>Repo: Persist token
Repo-->>Router: Token row
Router-->>App: Token response
App-->>Pytest: 201 Created
Pytest->>App: Store snapshot with Bearer token
App->>Router: Validate bearer token
Router->>Repo: Write snapshot
Repo->>Db: Insert snapshot row
Db-->>Repo: Stored snapshot
Repo-->>Router: Snapshot model
Router-->>App: Snapshot response
App-->>Pytest: 201 Created
Pytest->>App: Read latest snapshot with same Bearer token
App->>Router: Validate bearer token
Router->>Repo: Load latest snapshot
Repo-->>Router: Snapshot model
Router-->>App: Latest snapshot response
App-->>Pytest: 200 OK
Pytest->>App: Score same request_id twice
App-->>Pytest: Identical score response
Pytest-->>Engineer: Pass or fail
US Consent Lifecycle Flow
sequenceDiagram
participant Tester as Jest Test
participant App as Fastify App
participant Auth as Partner And Access Middleware
participant Routes as registerUsRoutes
participant Service as consentService
participant Prisma as Prisma
Tester->>App: Build Fastify app
App->>Auth: requirePartnerAuth and requireAccessToken
Auth-->>App: Inject partnerId and accessClaims
App->>Routes: Register US routes
Tester->>App: POST /api/v1/us/consents
App->>Service: createConsent
Service->>Prisma: Insert consent row
Prisma-->>Service: Consent row
Service-->>App: Consent response
App-->>Tester: 200 OK
Tester->>App: POST /api/v1/us/consents/id/revoke
App->>Service: revokeConsent
Service->>Prisma: Update consent, tokens, and connections
Prisma-->>Service: Updated rows
Service-->>App: Revoke result
App-->>Tester: 200 OK
Tester->>App: POST /api/v1/us/tokens/refresh
App-->>Tester: 429 Too Many Requests
Tester->>App: GET /api/v1/us/data/accounts
App-->>Tester: 403 Category not allowed
Go Gateway Error Mapping Flow
sequenceDiagram
participant Test as Go Test
participant Recorder as Response Recorder
participant Writer as writeError
Test->>Recorder: Create httptest recorder
Test->>Writer: writeError with domain error
Writer-->>Recorder: Status code and JSON body
Recorder-->>Test: Captured payload
Test-->>Test: Assert status and error string
State Management
Monolith Idempotency State
- Scoring requests are keyed by
request_id. - The repeated call in
backend/tests/interface/test_lita_endpoints.pyproves the second response is identical to the first. - The implementation overview and test module both treat the score decision as cached by
request_id.
US Consent Lifecycle State
createConsentstores consents inPENDING_USER_ACTION.revokeConsentmoves the consent toREVOKED.ensureConsentActiverejects missing, inactive, or expired consents withCONSENT_REVOKED.refreshEvent.countis used by the refresh flow to enforce daily refresh limits.
Gateway Error State
- The Go gateway validation is stateless at the test level.
- The only asserted state is the error constant that determines the HTTP status and JSON error code.
Error Handling
| Asset | Error behavior |
|---|---|
backend/src/interface/lita_endpoints.py |
Missing consent returns 404; duplicate consent reference returns 409; missing bearer token returns 401; revoked or expired token returns 403; missing latest snapshot returns 404 |
services/us-api/src/services/consentService.ts |
Missing consent returns 404; inactive or expired consent returns CONSENT_REVOKED |
services/us-api/test/flows.test.ts |
Refresh-limit rejection returns 429; missing category access returns 403 |
services/us-data-gateway/internal/handlers/handlers_test.go |
Domain errors are translated into 403 or 409 with a JSON error field |
Caching Strategy
| Cache or reuse point | Key | What is reused | Invalidation behavior |
|---|---|---|---|
| Monolith scoring decision | request_id |
The entire score response | Reused for repeated requests with the same request_id |
| Latest consent snapshot lookup | Consent token context | Most recent stored snapshot | Recomputed from storage on each read |
| US refresh-limit enforcement | Per-consent refresh count | Daily refresh usage | Re-evaluated from refreshEvent.count |
| Gateway error mapping | Domain error constant | HTTP status and error string | Determined at write time |
Dependencies
Monolith validation
- FastAPI test client
pytestuvicorn- SQLite fallback used by the smoke guide when
DATABASE_URLis unset - MySQL when
DATABASE_URLpoints at the production database
US service validation
- Jest
- Fastify
- Prisma client shape mocked in the test file
pg-memfor in-memory PostgreSQL behavior in related test infrastructureerrorHandlerfromservices/us-api/src/middleware/errorHandler.js
Go gateway validation
- Standard library
net/http,net/http/httptest, andencoding/json
Testing Considerations
- Use
documents/lita-testing-guide.mdwhen you need the fastest end-to-end local proof that consent creation, token issuance, snapshots, and scoring still work together. - Use
backend/tests/interface/test_lita_endpoints.pywhen you want automated regression coverage with the FastAPI test client. - Use
services/us-api/test/flows.test.tswhen you need to verify US consent state transitions, refresh limits, or category guard rails. - Use
services/us-data-gateway/internal/handlers/handlers_test.gowhen you need to verify domain error translation and HTTP status mapping at the gateway boundary. - Use
./scripts/lita_smoke_test.shwhen you want the monolith flow validated in one command.
Key Classes Reference
| Class | Location | Responsibility |
|---|---|---|
lita_endpoints.py |
lita_endpoints.py |
FastAPI consent, token, snapshot, and scoring validation surface for the monolith |
test_lita_endpoints.py |
test_lita_endpoints.py |
Pytest regression coverage for consent registration, token issuance, snapshot round-trip, and scoring idempotency |
lita-testing-guide.md |
lita-testing-guide.md |
Manual and scripted smoke-test instructions for the monolith consent flow |
consentService.ts |
consentService.ts |
US consent creation, revocation, receipt, and active-consent checks |
flows.test.ts |
flows.test.ts |
US Fastify flow validation for consent, refresh, and account-access behavior |
handlers_test.go |
handlers_test.go |
Go gateway error contract validation for consent and category failures |