Authentication and Authorization Domain - Request Authentication, Token Resolution, and Trust Boundaries
Overview
This request boundary is the first line of enforcement for apps/api/src/server.ts. It requires a per-request X-Request-Id on protected paths, parses Authorization: Bearer ..., resolves the bearer token into one of several authenticated contexts, and projects tenant identity onto the request before any route handler runs. That context is then consumed by downstream route logic, idempotency persistence, and audit capture.
The API enforces these checks inside Fastify hooks rather than relying on the edge to supply trusted identity fields. The code needs request-local state for request.auth, request.tenantId, request.usAccess, request.jpAccess, and request.logAuditEvent, and it persists idempotency and audit data from the same in-process request context. Public health and documentation paths are explicitly bypassed; everything else enters the trust boundary through the plugins registered in buildServer().
Architecture Overview
flowchart TD
Client[Client Request] --> Server[Fastify App]
Server --> AuthPlugin[authPlugin onRequest]
AuthPlugin -->|public path| PublicRoute[Public Route]
AuthPlugin -->|protected path| XRequestId[X Request Id check]
XRequestId --> TokenParse[Bearer token parsing]
TokenParse --> ApiKey[resolveApiKey]
TokenParse --> Jwt[verifyJwt]
TokenParse --> UsToken[verifyUsAccessToken]
TokenParse --> JpToken[verifyJpAccessToken]
ApiKey --> RequestAuth[request.auth]
Jwt --> RequestAuth
UsToken --> UsScoped[request.auth plus request.usAccess]
JpToken --> JpScoped[request.auth plus request.jpAccess]
RequestAuth --> TenantPlugin[tenantPlugin preHandler]
UsScoped --> TenantPlugin
JpScoped --> TenantPlugin
TenantPlugin --> IdempotencyPlugin[idempotencyPlugin preHandler]
IdempotencyPlugin --> RouteHandler[Route Handler]
RouteHandler --> AuditDecorator[request.logAuditEvent]
RouteHandler --> IdemStore[onSend idempotency write]
AuditDecorator --> ComplianceStore[recordAuditEvent]
IdemStore --> Prisma[(Prisma idempotency table)]
RouteHandler --> Response[HTTP Response]
Request Trust Boundary
The server assembles the request boundary in a fixed order inside buildServer():
authPluginruns first ononRequest.tenantPluginruns onpreHandler.idempotencyPluginruns onpreHandlerandonSend.auditPlugindecorates the request withlogAuditEvent.- Routes are registered only after those plugins.
That order matters because later code reads the request fields created earlier. tenantPlugin depends on request.auth, idempotencyPlugin depends on request.tenantId, and auditPlugin depends on both request.tenantId and request.auth.
Request Authentication Plugin
[!NOTE]
authPluginaccepts API keys, JWTs, US access tokens, and JP access tokens, but its unauthenticated error message saysAuthorization: Bearer <PARTNER_API_KEY> is required. The runtime behavior is broader than the text of the error response.
apps/api/src/plugins/auth.ts
authPlugin is the primary authentication gate. It allows only the explicitly public paths and "/docs" URLs to bypass authentication; everything else must present a non-empty X-Request-Id header and a valid Bearer token.
Request decorators
| Property | Type | Description |
|---|---|---|
request.auth |
`AuthContext \ | undefined` |
request.usAccess |
`UsAccessContext \ | undefined` |
request.jpAccess |
`JpAccessContext \ | undefined` |
Token resolution order
| Order | Resolver | Result |
|---|---|---|
| 1 | resolveApiKey(token) |
Accepts partner API keys and assigns request.auth. |
| 2 | verifyJwt(token) |
Accepts JWTs and assigns request.auth. |
| 3 | verifyUsAccessToken(token) |
Builds a scoped client context, assigns request.auth, and stores request.usAccess. |
| 4 | verifyJpAccessToken(token) |
Builds a scoped client context, assigns request.auth, and stores request.jpAccess. |
US and JP access tokens are projected into a narrow client-scoped auth shape inside this plugin:
actorType: "client"actorId: consentIdscopes: dataCategories
That projection is what downstream handlers see when they read request.auth.
Resolved Access Context Types
apps/api/src/services/us-api.ts
apps/api/src/services/jp-api.ts
UsAccessContext
| Property | Type | Description |
|---|---|---|
consentId |
string |
Consent bound to the US access token. |
tenantId |
string |
Tenant bound to the US access token. |
purpose |
ConsentPurpose |
Purpose embedded in the token. |
dataCategories |
DataCategory[] |
Granted US data categories. |
JpAccessContext
| Property | Type | Description |
|---|---|---|
consentId |
string |
Consent bound to the JP access token. |
tenantId |
string |
Tenant bound to the JP access token. |
purpose |
JpConsentPurpose |
Purpose embedded in the token. |
dataCategories |
JpDataCategory[] |
Granted JP data categories. |
Hook behavior
| Hook | Behavior |
|---|---|
onRequest |
Skips public paths, requires X-Request-Id, parses Authorization, and resolves bearer tokens in order. |
onRequest failure |
Returns 400 for missing X-Request-Id or 401 for unresolved bearer authentication. |
Tenant Projection Plugin
[!NOTE]
/v1/auth/token/introspectreceives a JSON body field namedtoken, but the handler does not verify that token. Its response is built from the already-authenticatedrequest.auth,request.auth?.tenantId, andrequest.auth?.scopes.
apps/api/src/plugins/tenant.ts
tenantPlugin copies tenant identity from the resolved auth context to request.tenantId before route handlers execute. It only does work when request.auth is present.
Request decorators
| Property | Type | Description |
|---|---|---|
request.tenantId |
`string \ | undefined` |
Hook behavior
| Hook | Behavior |
|---|---|
preHandler |
If request.auth exists, sets request.tenantId = request.auth.tenantId. |
preHandler failure |
Returns 400 with { error: "missing tenant" } when request.auth exists but has no tenant ID. |
This plugin is the bridge between authentication and tenant-scoped persistence. Downstream handlers do not read request.auth.tenantId directly for tenant writes; they consume the projected request.tenantId.
POST Idempotency Plugin
apps/api/src/plugins/idempotency.ts
idempotencyPlugin activates only for authenticated tenant-scoped POST requests. It looks for an idempotency-key header, hashes the request body, checks persisted keys, and either short-circuits the request or stores the eventual response during onSend.
Request decorators
| Property | Type | Description |
|---|---|---|
request.idempotencyKey |
`string \ | undefined` |
request.idempotencyRequestHash |
`string \ | undefined` |
Persisted idempotency record
| Field | Type | Description |
|---|---|---|
tenantId |
string |
Tenant partition for the record. |
key |
string |
Idempotency key from the header. |
requestHash |
string |
SHA-256 hash of the serialized request body. |
responseJson |
unknown |
Response payload captured from onSend. |
status |
string |
Stored as "completed". |
expiresAt |
Date |
Set to 24 hours after write. |
Hook behavior
| Hook | Behavior |
|---|---|
preHandler |
Only runs for POST requests that already have request.tenantId. |
preHandler with key |
Computes the body hash, checks prisma.idempotencyKey.findUnique, and replays the stored response if found. |
preHandler without key |
Leaves the request untouched. |
onSend |
Writes the captured response payload to prisma.idempotencyKey when request.idempotencyKey and request.tenantId are set. |
Audit Event Capture Plugin
[!NOTE] The replay path always responds with HTTP
200, even if the original request returned a different status code such as201or an error status. The storedresponseJsonis replayed, but the original status code is not preserved.
apps/api/src/plugins/audit.ts
auditPlugin adds request.logAuditEvent, a per-request helper that records compliance events only when both tenant and auth context are present. It pushes the audit payload to recordAuditEvent with the current request metadata.
Request decorators
| Property | Type | Description |
|---|---|---|
request.logAuditEvent |
(input) => Promise<void> |
Writes an audit event for the current request when tenant and auth are available. |
Captured event fields
| Field | Source | Description |
|---|---|---|
tenantId |
request.tenantId |
Tenant owning the action. |
actorType |
request.auth.actorType |
Actor type from the resolved auth context. |
actorId |
request.auth.actorId |
Actor ID from the resolved auth context. |
action |
input.action |
Business action to record. |
targetType |
input.targetType |
Audited object type. |
targetId |
input.targetId |
Audited object identifier. |
ip |
request.ip |
Source IP address. |
userAgent |
request.headers["user-agent"] ?? "unknown" |
User-agent string, defaulting to unknown. |
metadata |
input.metadata ?? {} |
Additional audit details. |
Hook behavior
| Hook | Behavior |
|---|---|
| Decorator | Installs request.logAuditEvent on every request. |
| Runtime guard | Returns immediately when request.tenantId or request.auth is missing. |
| Storage call | Delegates to recordAuditEvent from @lita/compliance. |
Server Assembly and Route Registration
apps/api/src/server.ts
buildServer() creates the Fastify application, initializes telemetry, installs the trust-boundary plugins, mounts the route trees, and exposes the public health endpoints.
Public method
| Method | Description |
|---|---|
buildServer |
Builds and configures the Fastify application, registers plugins and routes, and adds the public health endpoints. |
Initialization and registration order
| Step | Action |
|---|---|
| 1 | Calls initOtel(). |
| 2 | Creates Fastify with buildLogger() and bodyLimit: 1_048_576. |
| 3 | Installs Zod validator and serializer compilers. |
| 4 | Registers cors, helmet, and rateLimit. |
| 5 | Registers authPlugin, tenantPlugin, idempotencyPlugin, and auditPlugin. |
| 6 | Registers registerV1Routes(app). |
| 7 | Registers usRoutes under "/api/v1/us". |
| 8 | Registers jpRoutes under "/api/v1/jp". |
| 9 | Exposes "/healthz" and "/readyz". |
| 10 | Exposes "/openapi.json" as the API specification document. |
The plugin order is part of the trust boundary: authentication runs before tenant projection, which runs before idempotency, which is the state that route handlers consume.
API Integration
Introspect Current Request Authentication
{
"title": "Introspect Current Request Authentication",
"description": "Returns the authenticated request context that the API resolved from the Bearer token",
"method": "POST",
"baseUrl": "<ApiBaseUrl>",
"endpoint": "/v1/auth/token/introspect",
"headers": [
{
"key": "Authorization",
"value": "Bearer <token>",
"required": true
},
{
"key": "X-Request-Id",
"value": "<request-id>",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "json",
"requestBody": "{\n \"token\": \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.example\"\n}",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Authentication context returned by the request boundary",
"body": "{\n \"active\": true,\n \"tenantId\": \"tenant_01HZXKQ2WQ8M6Y3R9V1T0ABCD\",\n \"scopes\": [\n \"accounts\",\n \"balances\"\n ]\n}"
}
}
}
Health Check
{
"title": "Health Check",
"description": "Returns the service health status",
"method": "GET",
"baseUrl": "<ApiBaseUrl>",
"endpoint": "/healthz",
"headers": [],
"queryParams": [],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Service is healthy",
"body": "{\n \"status\": \"ok\"\n}"
}
}
}
Readiness Check
{
"title": "Readiness Check",
"description": "Returns the service readiness status",
"method": "GET",
"baseUrl": "<ApiBaseUrl>",
"endpoint": "/readyz",
"headers": [],
"queryParams": [],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Service is ready",
"body": "{\n \"status\": \"ready\"\n}"
}
}
}
Feature Flows
Protected Request Through the Trust Boundary
sequenceDiagram
participant C as Client
participant S as Fastify App
participant A as authPlugin
participant T as tenantPlugin
participant I as idempotencyPlugin
participant H as Route Handler
participant AU as auditPlugin
participant P as Prisma
C->>S: HTTP request
S->>A: onRequest
A->>A: check public path
A->>A: require X Request Id
A->>A: parse Bearer token
A->>A: resolveApiKey
A->>A: verifyJwt
A->>A: verifyUsAccessToken
A->>A: verifyJpAccessToken
A-->>S: request.auth and token context set
S->>T: preHandler
T-->>S: request.tenantId projected
S->>I: preHandler
I->>P: findUnique by tenantId and key
alt existing idempotency record
I-->>S: send stored response
else new request
I-->>S: store idempotency metadata on request
S->>H: execute handler
H->>AU: request.logAuditEvent
AU->>P: recordAuditEvent
H-->>S: response payload
S->>I: onSend
I->>P: create idempotencyKey record
S-->>C: HTTP response
end
Bearer Token Resolution Order
flowchart TD
Start([Bearer token received]) --> ApiKeyCheck[resolveApiKey]
ApiKeyCheck -->|match| ApiKeySet[request.auth set]
ApiKeyCheck -->|no match| JwtCheck[verifyJwt]
JwtCheck -->|match| JwtSet[request.auth set]
JwtCheck -->|no match| UsCheck[verifyUsAccessToken]
UsCheck -->|match| UsSet[request.auth and request.usAccess set]
UsCheck -->|no match| JpCheck[verifyJpAccessToken]
JpCheck -->|match| JpSet[request.auth and request.jpAccess set]
JpCheck -->|no match| Deny[401 unauthorized]
POST Idempotency Storage and Replay
sequenceDiagram
participant C as Client
participant I as idempotencyPlugin
participant P as Prisma
participant H as Route Handler
C->>I: POST with idempotency-key
I->>P: findUnique tenantId key
alt record exists
I-->>C: replay stored response with 200
else new record
I->>I: compute requestHash
I-->>H: continue request
H-->>I: response payload
I->>P: create idempotencyKey row
I-->>C: response
end
State Management
Per Request Decorations
| Decorator | Created By | Consumed By | Purpose |
|---|---|---|---|
request.auth |
authPlugin |
tenantPlugin, auditPlugin, route handlers |
Holds the resolved authenticated context. |
request.usAccess |
authPlugin |
US route handlers | Marks the request as carrying a US scoped access token. |
request.jpAccess |
authPlugin |
JP route handlers | Marks the request as carrying a JP scoped access token. |
request.tenantId |
tenantPlugin |
idempotencyPlugin, auditPlugin, route handlers |
Projects tenant identity onto the request. |
request.idempotencyKey |
idempotencyPlugin |
idempotencyPlugin onSend |
Stores the header value for the response write-back. |
request.idempotencyRequestHash |
idempotencyPlugin |
idempotencyPlugin onSend |
Stores the SHA-256 request body fingerprint. |
request.logAuditEvent |
auditPlugin |
Route handlers | Writes compliance audit events on demand. |
Request Lifecycle Summary
| Phase | State Change |
|---|---|
onRequest |
Authentication is resolved and request-level auth fields are populated. |
preHandler |
Tenant identity is projected into request.tenantId. |
preHandler |
POST idempotency may short-circuit with a stored response. |
| Handler execution | Route-specific business logic runs only after the trust boundary is satisfied. |
onSend |
Successful or failed responses can be persisted for idempotency replay. |
| Explicit audit call | Route handlers may record business events through request.logAuditEvent. |
Error Handling
Boundary Errors
| Component | Condition | HTTP Status | Payload Shape |
|---|---|---|---|
authPlugin |
Missing or blank X-Request-Id |
400 |
{ error: { code, message, request_id, retryable } } |
authPlugin |
No resolver accepts the Bearer token | 401 |
{ error: { code: "unauthorized", message, request_id, retryable } } |
tenantPlugin |
Auth exists but tenant ID is missing | 400 |
{ error: "missing tenant" } |
idempotencyPlugin |
Existing key found | 200 |
Stored responseJson body |
auditPlugin |
Missing tenant or auth | No-op | No response change |
Auth Error Payloads
The authentication plugin returns structured JSON with request_id: request.id and retryable: false. That makes the boundary errors traceable across logs, audit trails, and client retries.
Dependencies
| Dependency | Use in this boundary |
|---|---|
@lita/auth |
Resolves API keys and JWTs into AuthContext. |
@lita/db |
Persists idempotency records through prisma.idempotencyKey. |
@lita/compliance |
Records audit events through recordAuditEvent. |
@lita/observability |
Initializes telemetry with initOtel() and application logging with buildLogger(). |
fastify |
Hosts the hooks that enforce the trust boundary. |
fastify-plugin |
Wraps the plugin implementations. |
jose |
Verifies and signs access tokens in the US and JP services used by the auth plugin. |
zod |
Validates request and response payloads for the route mounted behind the boundary. |
Key Classes Reference
| Class | Responsibility |
|---|---|
auth.ts |
Enforces X-Request-Id, resolves Bearer token types, and attaches authenticated request context. |
tenant.ts |
Projects tenantId onto the request before route handlers run. |
idempotency.ts |
Replays duplicate tenant-scoped POST requests and persists final responses. |
audit.ts |
Adds request.logAuditEvent and records compliance audit events. |
server.ts |
Builds the Fastify app, registers the trust-boundary plugins, and exposes public health endpoints. |
auth.ts |
Exposes POST /v1/auth/token/introspect for the authenticated request context. |
[!NOTE]
POST /v1/auth/token/introspectvalidates its own request body schema, but its response is derived fromrequest.authrather than from the postedtoken. In this boundary, the endpoint is an authenticated context echo, not a standalone token verifier.