Authentication and Authorization Domain
Overview
This section covers the Fastify middleware and route protection used by the US API service to authenticate partners, validate consent-scoped bearer tokens, protect internal analytics routes, and standardize request correlation and error responses. The implementation centers on request-scoped metadata: partner identity is attached to the request, access-token claims are decoded into request.accessClaims, and request IDs are propagated into responses, audit logs, and error payloads.
The result is a single security and instrumentation surface for external and internal routes. Partner-facing routes are gated by partner credentials, consent-backed data routes are gated by RS256 JWT access tokens, internal analytics routes are gated by a separate internal token, and every response can be correlated with a request ID and persisted access log entry.
Architecture Overview
flowchart TD
PartnerClient[Partner Client]
InternalClient[Internal Analytics Client]
subgraph MiddlewareStack[Fastify Security and Instrumentation]
EnsureRequestId[ensureRequestId]
RequirePartnerAuth[requirePartnerAuth]
RequireAccessToken[requireAccessToken]
RequireInternalAuth[requireInternalAuth]
ErrorHandler[errorHandler]
AuditLogger[registerAuditLogger]
end
subgraph RouteLayer[Protected Routes]
ExternalRoutes[Consent Scoped Data Routes]
InternalAnalyticsRoutes[registerInternalAnalyticsRoutes]
end
subgraph Persistence[Persistence and Observability]
AccessLogTable[prisma accessLog]
ConsentStore[Consent and Token Stores]
AnalyticsStore[Analytics Tables]
end
PartnerClient --> EnsureRequestId
InternalClient --> EnsureRequestId
EnsureRequestId --> RequirePartnerAuth
EnsureRequestId --> RequireAccessToken
EnsureRequestId --> RequireInternalAuth
RequirePartnerAuth --> ExternalRoutes
RequireAccessToken --> ExternalRoutes
RequireInternalAuth --> InternalAnalyticsRoutes
ExternalRoutes --> AuditLogger
InternalAnalyticsRoutes --> AuditLogger
ExternalRoutes -.-> ErrorHandler
InternalAnalyticsRoutes -.-> ErrorHandler
AuditLogger --> AccessLogTable
ExternalRoutes --> ConsentStore
InternalAnalyticsRoutes --> AnalyticsStore
Middleware Components
Request ID Propagation
services/us-api/src/middleware/requestId.ts
ensureRequestId creates or preserves the correlation ID used across request handling, response headers, audit logs, and error envelopes.
Public Methods
| Method | Description |
|---|---|
ensureRequestId |
Ensures every request has an x-request-id value and mirrors it back as X-Request-Id on the response. |
Behavior
- Reads
request.headers['x-request-id']. - Reuses the incoming value when it is a non-empty string.
- Generates a new UUID with
crypto.randomUUID()when the header is missing or empty. - Writes the normalized ID back to
request.headers['x-request-id']. - Emits
X-Request-Idon the response withreply.header(...).
Request/Response Correlation
| Property | Type | Description |
|---|---|---|
request.headers['x-request-id'] |
string |
Normalized request ID stored on the request object. |
reply.header('X-Request-Id') |
string |
Response header emitted for downstream correlation. |
Partner Authentication
services/us-api/src/middleware/partnerAuth.ts
requirePartnerAuth enforces partner authentication before partner-scoped routes can execute. It accepts multiple token sources, validates the token against configured API keys, and attaches the resolved partner token to the request for downstream logging.
Public Methods
| Method | Description |
|---|---|
requirePartnerAuth |
Validates partner credentials and stores the accepted token on request.partnerId. |
Behavior
- Checks
request.headers.authorizationfirst. - Accepts a bearer token when the header starts with
Bearer. - Falls back to
x-partner-token. - Falls back to
x-api-key. - Falls back to the
partner_tokenquery parameter. - Rejects missing or unknown tokens with
ApiError(403, 'PARTNER_AUTH_REQUIRED'). - Compares the token against
config.partnerApiKeys. - Stores the accepted token string in
request.partnerId.
Request Augmentation
| Property | Type | Description |
|---|---|---|
FastifyRequest.partnerId |
`string \ | undefined` |
Consent Scoped Access Tokens
[!NOTE] The customer-facing US API document describes partner authentication as static API keys or OIDC, but the implementation in
requirePartnerAuthonly checks the submitted token againstconfig.partnerApiKeys. No OIDC verification path appears in the provided code.
services/us-api/src/middleware/accessToken.ts
requireAccessToken enforces RS256 JWT bearer tokens and extracts consent-scoped claims into the request for downstream authorization checks.
Public Methods
| Method | Description |
|---|---|
requireAccessToken |
Validates access-token JWTs, enforces required claims, and stores the decoded claims on request.accessClaims. |
Behavior
- Reads the token from
Authorization: Bearer ...first. - Falls back to
x-access-token. - Falls back to the
access_tokenquery parameter. - Rejects missing tokens with
ApiError(403, 'TOKEN_REQUIRED'). - Verifies the token with
jwt.verify(..., config.jwtPublicKey, { algorithms: ['RS256'] }). - Rejects non-object payloads with
ApiError(403, 'INVALID_TOKEN'). - Requires all of the following claims:
consent_idpurposedata_categoriesjti
- Stores the decoded claims in
request.accessClaims.
Request Augmentation
| Property | Type | Description |
|---|---|---|
FastifyRequest.accessClaims |
`AccessClaims \ | undefined` |
Access Claims
| Property | Type | Description |
|---|---|---|
consent_id |
string |
Consent identifier attached to the token. |
purpose |
Purpose |
Declared use purpose for the token. |
data_categories |
DataCategory[] |
Allowed data categories carried by the token. |
jti |
string |
Token identifier used for traceability. |
Documented Claim Values
The repository documentation defines the allowed claim values used by the token model:
- Purpose:
RENTAL_SCREENING,LENDING_UNDERWRITING,ACCOUNT_OPENING,INCOME_VERIFICATION,FRAUD_PREVENTION,GENERAL_PERSONAL_FINANCE - Data categories:
IDENTITY_BASIC,ACCOUNTS,BALANCES,TRANSACTIONS,INCOME,EMPLOYMENT,CASHFLOW_FEATURES,DEVICE_RISK,WATCHLIST_SCREENING
Internal API Authentication
services/us-api/src/middleware/internalAuth.ts
requireInternalAuth protects internal-only routes with a separate shared secret.
Public Methods
| Method | Description |
|---|---|
requireInternalAuth |
Validates the internal token supplied in the request and rejects unauthorized callers. |
Behavior
- Reads
x-internal-token. - Falls back to
Authorization: Bearer .... - Compares the token to
config.internalApiToken. - Rejects missing or mismatched tokens with
ApiError(403, 'FORBIDDEN', 'Internal API token required.').
Request Acceptance Rules
| Token Source | Accepted |
|---|---|
x-internal-token |
Yes |
Authorization: Bearer ... |
Yes |
| Anything else | No |
Audit Logging
services/us-api/src/middleware/auditLogger.ts
registerAuditLogger captures completed requests and persists access logs with partner, consent, route, and status metadata.
Public Methods
| Method | Description |
|---|---|
registerAuditLogger |
Registers an onResponse hook that writes access-log rows after requests finish. |
Behavior
- Registers a Fastify
onResponsehook. - Skips logging entirely when audit logging has been disabled.
- Reads:
request.headers['x-request-id']request.partnerIdrequest.accessClaims?.consent_idrequest.routeOptions?.urlrequest.raw.urlreply.statusCode
- Persists a row with
prisma.accessLog.create(...). - Generates a log ID with the
al_prefix. - Disables audit logging permanently if Prisma initialization fails.
- Logs a warning only once when audit logging is disabled.
Persisted Access Log Fields
| Field | Type | Description |
|---|---|---|
id |
string |
Generated access-log identifier with al_ prefix. |
requestId |
string |
Request correlation ID. |
partnerId |
`string \ | null` |
consentId |
`string \ | null` |
route |
string |
Route template or raw URL used for the request. |
statusCode |
number |
Final HTTP status returned to the client. |
Module State
| Variable | Type | Description |
|---|---|---|
auditLoggingEnabled |
boolean |
Controls whether access-log writes are attempted. |
auditLoggingDisabledLogged |
boolean |
Prevents duplicate warnings after a Prisma initialization failure. |
Standardized Error Handling
services/us-api/src/middleware/errorHandler.ts
errorHandler converts domain errors into the shared US API error envelope and ensures every failure carries the request ID.
Public Methods
| Method | Description |
|---|---|
errorHandler |
Converts ApiError instances and unexpected failures into standardized JSON responses. |
Behavior
- Reads
request.headers['x-request-id']. - For
ApiErrorinstances:- Uses the error’s
statusCode - Returns
error.code - Returns
error.message - Returns
error.details
- Uses the error’s
- For unexpected errors:
- Returns HTTP 500
- Uses
errorResponse('PROVIDER_UNAVAILABLE', 'Unexpected error')
- Always includes
request_idin the response body.
Standard Error Envelope
| Property | Type | Description |
|---|---|---|
error.code |
string |
Machine-readable error code. |
error.message |
string |
Human-readable error message. |
error.details |
unknown |
Optional error payload. |
request_id |
string |
Correlation ID copied from the request. |
Internal Analytics Protection
services/us-api/src/routes/internalAnalytics.ts
registerInternalAnalyticsRoutes exposes internal analytics endpoints guarded by requireInternalAuth.
Public Methods
| Method | Description |
|---|---|
registerInternalAnalyticsRoutes |
Registers protected internal analytics endpoints on a Fastify instance. |
Route Guards
| Endpoint | Guard |
|---|---|
POST /internal/analytics/events |
requireInternalAuth |
GET /internal/analytics/psu-consent/metrics |
requireInternalAuth |
Request Schemas
eventSchema
| Property | Type | Description |
|---|---|---|
psu_id |
string |
PSU identifier for the analytics event. |
consent_session_id |
string |
Session identifier for the consent flow. |
product |
string |
Product label attached to the event. |
country |
string |
Country code for the event. |
provider |
string |
Provider identifier. |
institution_id |
`string \ | null \ |
timestamp |
string |
ISO datetime string. |
failure_reason |
`string \ | null \ |
event_name |
ConsentEventNames |
Event name accepted by the analytics pipeline. |
metricsQuerySchema
| Property | Type | Description |
|---|---|---|
start_date |
string |
Required YYYY-MM-DD start date. |
end_date |
string |
Required YYYY-MM-DD end date. |
product |
`string \ | undefined` |
country |
`string \ | undefined` |
provider |
`string \ | undefined` |
institution_id |
`string \ | undefined` |
Authentication Model in the Repository Docs
documents/us-api-v1.md
documents/us-api-v1.md
The US API specification defines the external auth contract that this middleware stack implements and enforces:
- Partner → Lita Authentication
- Static API keys or OIDC are documented for partners.
- Documented headers:
Authorization: Bearer <PARTNER_TOKEN>X-Request-Id: <uuid>
- Consent Scoped Access Tokens
- JWTs are described as short-lived and RS256-signed.
- Scope is bound to:
- Consent ID
- Purpose
- Data categories
- Data Access API
- All data endpoints require
Authorization: Bearer <ACCESS_TOKEN>. - The specification says scope and connection status are enforced on every request.
- All data endpoints require
- Standard Error Format
- The document defines a response envelope with
errorandrequest_id.
- The document defines a response envelope with
documents/lita-consent-data-api.md
documents/lita-consent-data-api.md
The consent-data specification uses the same correlation pattern for customer-facing integrations:
- Lita → Customer Scoring API
Authorization: Bearer <CLIENT_API_KEY>X-Request-Id: <uuid>Content-Type: application/json
- Customer → Lita Data Access API
Authorization: Bearer <ACCESS_TOKEN>
- Idempotency
- The document explicitly ties request identity to
X-Request-Id.
- The document explicitly ties request identity to
API Integration
Internal Consent Event Ingestion
Internal Consent Event Ingestion
{
"title": "Internal Consent Event Ingestion",
"description": "Ingests a consent event into the internal analytics pipeline and requires internal authentication",
"method": "POST",
"baseUrl": "<UsApiBaseUrl>",
"endpoint": "/internal/analytics/events",
"headers": [
{
"key": "X-Internal-Token",
"value": "<internal-token>",
"required": true
},
{
"key": "Authorization",
"value": "Bearer <internal-token>",
"required": true
},
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "json",
"requestBody": "{\n \"psu_id\": \"psu_123\",\n \"consent_session_id\": \"sess_123\",\n \"product\": \"product_a\",\n \"country\": \"US\",\n \"provider\": \"provider_a\",\n \"institution_id\": \"inst_123\",\n \"timestamp\": \"2024-01-01T00:05:00.000Z\",\n \"failure_reason\": null,\n \"event_name\": \"consent_completed\"\n}",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Event accepted and applied",
"body": "{\n \"status\": \"completed\"\n}"
},
"409": {
"description": "Dimension mismatch returned by applyConsentEvent",
"body": "{\n \"status\": \"dimension_mismatch\"\n}"
},
"400": {
"description": "Invalid body or query payload",
"body": "{\n \"error\": {\n \"code\": \"INVALID_BODY\",\n \"message\": \"Validation failed\",\n \"details\": \"string\"\n },\n \"request_id\": \"req_123\"\n}"
},
"403": {
"description": "Missing or invalid internal token",
"body": "{\n \"error\": {\n \"code\": \"FORBIDDEN\",\n \"message\": \"Internal API token required.\",\n \"details\": null\n },\n \"request_id\": \"req_123\"\n}"
}
}
}
Internal PSU Consent Metrics
Internal PSU Consent Metrics
{
"title": "Internal PSU Consent Metrics",
"description": "Returns aggregated PSU consent metrics for internal analytics consumers and requires internal authentication",
"method": "GET",
"baseUrl": "<UsApiBaseUrl>",
"endpoint": "/internal/analytics/psu-consent/metrics",
"headers": [
{
"key": "X-Internal-Token",
"value": "<internal-token>",
"required": true
},
{
"key": "Authorization",
"value": "Bearer <internal-token>",
"required": true
}
],
"queryParams": [
{
"key": "start_date",
"value": "2024-01-01",
"required": true
},
{
"key": "end_date",
"value": "2024-01-31",
"required": true
},
{
"key": "product",
"value": "product_a",
"required": false
},
{
"key": "country",
"value": "US",
"required": false
},
{
"key": "provider",
"value": "provider_a",
"required": false
},
{
"key": "institution_id",
"value": "inst_123",
"required": false
}
],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Aggregated metrics returned",
"body": "{\n \"daily\": [],\n \"funnel\": [],\n \"failures\": [],\n \"latency\": []\n}"
},
"400": {
"description": "Invalid date range or malformed query",
"body": "{\n \"error\": {\n \"code\": \"INVALID_QUERY\",\n \"message\": \"start_date must be <= end_date\",\n \"details\": \"string\"\n },\n \"request_id\": \"req_123\"\n}"
},
"403": {
"description": "Missing or invalid internal token",
"body": "{\n \"error\": {\n \"code\": \"FORBIDDEN\",\n \"message\": \"Internal API token required.\",\n \"details\": null\n },\n \"request_id\": \"req_123\"\n}"
}
}
}
Feature Flows
Partner Authenticated Request with Correlation and Logging
sequenceDiagram
participant C as Partner Client
participant R as ensureRequestId
participant P as requirePartnerAuth
participant H as Protected Route Handler
participant L as registerAuditLogger
participant E as errorHandler
C->>R: Send request with optional x-request-id
R-->>C: Normalize request id and mirror X-Request-Id
C->>P: Send partner token in Authorization or fallback header
P-->>H: Attach request.partnerId after validation
H->>L: Complete handler and emit response
L-->>C: Persist access log with request id partner id consent id route status
alt Missing or invalid partner token
P-->>E: Throw ApiError PARTNER_AUTH_REQUIRED
E-->>C: Return standardized error envelope
end
Internal Analytics Request Protection
sequenceDiagram
participant I as Internal Client
participant R as ensureRequestId
participant A as requireInternalAuth
participant M as registerInternalAnalyticsRoutes
participant E as errorHandler
I->>R: Send request with optional x-request-id
R-->>I: Mirror X-Request-Id on response
I->>A: Send x-internal-token or Authorization bearer token
A-->>M: Allow route execution when token matches config.internalApiToken
M-->>I: Return analytics data or event status
alt Missing or invalid internal token
A-->>E: Throw ApiError FORBIDDEN
E-->>I: Return standardized error envelope
end
State Management
Module Scoped State
| State | File | Purpose |
|---|---|---|
auditLoggingEnabled |
auditLogger.ts |
Stops access-log writes after a Prisma initialization failure. |
auditLoggingDisabledLogged |
auditLogger.ts |
Prevents repeated warnings once logging has been disabled. |
request.partnerId |
partnerAuth.ts |
Request-scoped partner credential stored for logging. |
request.accessClaims |
accessToken.ts |
Request-scoped consent claims stored for downstream authorization. |
request.headers['x-request-id'] |
requestId.ts |
Correlation ID normalized for response and logging. |
Request Lifecycle Summary
ensureRequestIdnormalizes the request ID at ingress.requirePartnerAuth,requireAccessToken, orrequireInternalAuthestablish the request identity boundary.- Route handlers use the attached request metadata for authorization decisions and analytics.
registerAuditLoggerpersists the completed request after the response is sent.errorHandlerreturns a consistent error envelope with the same request ID.
Integration Points
- Fastify hooks:
preHandler,onResponse, and the global error handler. - JWT verification:
jsonwebtokenwith RS256 public-key verification. - Configuration:
config.partnerApiKeysconfig.jwtPublicKeyconfig.internalApiToken
- Persistence:
prisma.accessLogprisma.consentprisma.token
- Internal analytics:
applyConsentEventfetchDailyMetricsfetchFunnelMetricsfetchFailureBreakdownfetchLatencyMetrics
- Documentation contracts:
documents/us-api-v1.mddocuments/lita-consent-data-api.md
Error Handling
The middleware layer uses a split model:
- Authentication failures
PARTNER_AUTH_REQUIREDTOKEN_REQUIREDINVALID_TOKENFORBIDDEN
- Internal analytics validation failures
INVALID_BODYINVALID_QUERY
- Unexpected infrastructure failures
- Standardized to
PROVIDER_UNAVAILABLEbyerrorHandler
- Standardized to
Behavior by Component
| Component | Failure Mode | Response |
|---|---|---|
requirePartnerAuth |
Missing or unknown partner token | 403 PARTNER_AUTH_REQUIRED |
requireAccessToken |
Missing, malformed, or claim-incomplete JWT | 403 TOKEN_REQUIRED or 403 INVALID_TOKEN |
requireInternalAuth |
Missing or incorrect internal token | 403 FORBIDDEN |
registerInternalAnalyticsRoutes |
Invalid body or date range | 400 INVALID_BODY or 400 INVALID_QUERY |
errorHandler |
Non-ApiError exception |
500 PROVIDER_UNAVAILABLE |
Dependencies
- Fastify:
FastifyInstance,FastifyRequest,FastifyReply - JWT:
jsonwebtoken - Crypto:
crypto.randomUUID()and random ID generation - Prisma: access-log persistence and authorization-related records
- Configuration:
configvalues for partner, access, and internal tokens - Zod: request validation for internal analytics routes
- Analytics services: consent-event processing and metrics queries
Testing Considerations
The provided tests and route behavior imply the following coverage areas:
requirePartnerAuth- Accept bearer partner tokens.
- Accept
x-partner-tokenandx-api-keyfallbacks. - Reject missing tokens with
PARTNER_AUTH_REQUIRED.
requireAccessToken- Reject missing tokens with
TOKEN_REQUIRED. - Reject invalid RS256 signatures with
INVALID_TOKEN. - Reject claims missing
consent_id,purpose,data_categories, orjti.
- Reject missing tokens with
requireInternalAuth- Accept either
x-internal-tokenor bearer header when the token matchesconfig.internalApiToken. - Reject all other values with
FORBIDDEN.
- Accept either
ensureRequestId- Preserve incoming IDs.
- Generate new IDs when absent.
- Echo the value back as
X-Request-Id.
registerAuditLogger- Persist request, partner, consent, route, and status metadata.
- Disable logging after Prisma initialization failures.
errorHandler- Serialize
ApiErrorinstances witherror.code,error.message,error.details, andrequest_id. - Convert unexpected errors to
PROVIDER_UNAVAILABLE.
- Serialize
Key Classes Reference
| Class | Responsibility |
|---|---|
requestId.ts |
Normalizes request IDs and mirrors them to the response. |
partnerAuth.ts |
Validates partner credentials and records the validated token on the request. |
accessToken.ts |
Verifies consent-scoped JWT access tokens and attaches decoded claims to the request. |
internalAuth.ts |
Protects internal analytics routes with a separate shared token. |
auditLogger.ts |
Persists access logs after responses complete. |
errorHandler.ts |
Standardizes API and unexpected errors into the shared JSON envelope. |
internalAnalytics.ts |
Registers internal analytics routes behind internal authentication. |
us-api-v1.md |
Defines the US API authentication and request-correlation contract. |
lita-consent-data-api.md |
Defines the customer-facing authentication and request-correlation contract. |