Authentication and Authorization Domain
Overview
This domain covers the runtime auth split used by the US services in the repository: partner-scoped requests, consent-scoped access tokens, internal service calls, and request auditing. The code paths in services/us-api and services/us-data-gateway enforce different token sources and different verification rules, so the deployment has to provision the matching secrets and route requests to the correct service boundary.
The visible implementation separates three trust levels in the US API and one JWT validation boundary in the US data gateway. Partner tokens are matched against an allowlist, access tokens are signed with an RSA private key and verified with the public key, and internal calls are gated by a shared internal token. The data gateway then re-verifies bearer JWTs and checks Redis for session revocation before serving US account data.
Architecture Overview
flowchart TB
Client[Partner or User Client]
subgraph DeploymentSecrets[Deployment Secrets]
PartnerKeys[partnerApiKeys]
InternalToken[internalApiToken]
JwtPrivate[jwtPrivateKey]
JwtPublic[jwtPublicKey]
RedisURL[REDIS_URL]
GoJwtPublic[JWTPublicKey]
end
subgraph USApi[US API]
PartnerMW[requirePartnerAuth]
AccessMW[requireAccessToken]
InternalMW[requireInternalAuth]
ConsentSvc[consentService]
TokenSvc[tokenService]
ConnectionSvc[connectionService]
AuditMW[registerAuditLogger]
end
subgraph Gateway[US Data Gateway]
Main[main]
Verify[TokenVerifier Verify]
Handler[Handler]
end
Postgres[(PostgreSQL)]
Redis[(Redis)]
Provider[Mock Provider]
Client --> PartnerMW
Client --> AccessMW
Client --> InternalMW
Client --> Main
PartnerMW --> ConsentSvc
PartnerMW --> TokenSvc
AccessMW --> TokenSvc
AccessMW --> ConnectionSvc
InternalMW --> Postgres
AuditMW --> Postgres
Main --> Verify
Main --> Redis
Verify --> Redis
Handler --> Postgres
Handler --> Provider
PartnerKeys --> PartnerMW
InternalToken --> InternalMW
JwtPrivate --> TokenSvc
JwtPublic --> AccessMW
GoJwtPublic --> Verify
RedisURL --> Main
Deployment-Time Routing and Secret Configuration
The visible code does not centralize auth in a single gateway; instead, it distributes auth decisions across middleware and service startup:
services/us-apiuses request middleware to accept partner tokens, access tokens, and internal tokens.services/us-data-gatewayuses a bearer JWT plus Redis-backed revocation state.services/us-data-gateway/cmd/us-data-gateway/main.goloads the database, Redis, and JWT public key at startup before wiring handlers.
Runtime Secret Matrix
| Secret or Config | Consumed By | Purpose |
|---|---|---|
config.partnerApiKeys |
requirePartnerAuth |
Allowlist for partner requests |
config.internalApiToken |
requireInternalAuth |
Shared service-to-service token |
config.jwtPrivateKey |
issueTokens in tokenService.ts |
Signs access JWTs |
config.jwtPublicKey |
requireAccessToken, introspectToken |
Verifies access JWTs |
config.tokenTtlSeconds |
issueTokens |
Sets access token lifetime |
config.scoringCallbackUrl |
replayDecision |
Sends replay payloads to the scoring callback |
PORT |
services/us-data-gateway/internal/config/config.go |
HTTP listen port |
DATABASE_URL |
services/us-data-gateway/internal/config/config.go |
PostgreSQL connection string |
REDIS_URL |
services/us-data-gateway/internal/config/config.go |
Redis connection string |
JWT_PUBLIC_KEY |
services/us-data-gateway/internal/config/config.go |
RSA public key for token verification |
PROVIDER |
services/us-data-gateway/internal/config/config.go |
Provider selection |
REDIS_URL fallback |
services/us-data-gateway/cmd/us-data-gateway/main.go |
Defaults to localhost:6379 when unset |
Request Identity and Audit Logging
[!IMPORTANT]
services/us-data-gateway/cmd/us-data-gateway/main.gosetsREDIS_URLtolocalhost:6379ininit()when the variable is missing, so Redis connectivity is still attempted with a local default during startup.
services/us-api/src/middleware/requestId.ts and services/us-api/src/middleware/auditLogger.ts form the request tracing path:
ensureRequestIdassignsx-request-idwhen the client does not send one.registerAuditLoggerwrites an access log entry on every response.- The audit log stores the request ID, partner ID, consent ID, resolved route, and response status.
The logging path is disabled after a Prisma initialization error, which is tracked by a module-level flag so the service stops retrying the same failing write path.
US API Auth Middleware
services/us-api/src/middleware/accessToken.ts
services/us-api/src/middleware/partnerAuth.ts
services/us-api/src/middleware/internalAuth.ts
services/us-api/src/middleware/requestId.ts
services/us-api/src/middleware/errorHandler.ts
services/us-api/src/middleware/auditLogger.ts
services/us-api/src/routes/internalAnalytics.ts
Domain Values
PurposeValues:RENTAL_SCREENING,LENDING_UNDERWRITING,ACCOUNT_OPENING,INCOME_VERIFICATION,FRAUD_PREVENTION,GENERAL_PERSONAL_FINANCEDataCategoryValues:IDENTITY_BASIC,ACCOUNTS,BALANCES,TRANSACTIONS,INCOME,EMPLOYMENT,CASHFLOW_FEATURES,DEVICE_RISK,WATCHLIST_SCREENINGConnectionStatusValues:ACTIVE,REAUTH_REQUIRED,DEGRADED,DISCONNECTED
Request Auth State
| Field | Type | Description |
|---|---|---|
request.accessClaims |
AccessClaims |
Populated by requireAccessToken after JWT verification |
request.partnerId |
string |
Populated by requirePartnerAuth with the accepted partner token |
request.headers['x-request-id'] |
string |
Normalized by ensureRequestId for downstream logging |
AccessClaims
| Property | Type | Description |
|---|---|---|
consent_id |
string |
Consent identifier extracted from the verified access token |
purpose |
Purpose |
Token purpose claim |
data_categories |
DataCategory[] |
Granted data categories |
jti |
string |
JWT ID used for auditing and revocation lookups |
Public and Operational Methods
| Method | Description |
|---|---|
ensureRequestId |
Ensures every request has an x-request-id header and mirrors it back as X-Request-Id |
requirePartnerAuth |
Accepts partner credentials from Authorization, x-partner-token, x-api-key, or partner_token and checks them against config.partnerApiKeys |
requireAccessToken |
Accepts access credentials from Authorization, x-access-token, or access_token, verifies RS256 JWTs with config.jwtPublicKey, and attaches request.accessClaims |
requireInternalAuth |
Accepts x-internal-token or Authorization bearer credentials and checks them against config.internalApiToken |
errorHandler |
Converts ApiError instances into structured JSON responses and wraps unexpected errors as PROVIDER_UNAVAILABLE |
registerAuditLogger |
Writes a prisma.accessLog row on each response and disables audit writes after a Prisma initialization failure |
registerInternalAnalyticsRoutes |
Registers the internal analytics endpoints guarded by requireInternalAuth |
Auth Middleware Behavior
requirePartnerAuth and requireAccessToken both accept multiple token locations. The accepted token is copied into request-scoped state so later layers can log it or derive consent context without re-reading headers.
errorHandler returns a JSON envelope with the error code, message, details, and request_id when the error is an ApiError. For everything else, it returns a 500 with PROVIDER_UNAVAILABLE.
Request Auditing
| Field | Type | Description |
|---|---|---|
auditLoggingEnabled |
boolean |
Global switch that turns off audit writes after a Prisma initialization error |
auditLoggingDisabledLogged |
boolean |
Prevents repeated warning logs after audit logging is disabled |
registerAuditLogger writes the following fields to prisma.accessLog.create:
requestIdpartnerIdconsentIdroutestatusCode
Consent and Token Services
services/us-api/src/services/consentService.ts
services/us-api/src/services/tokenService.ts
services/us-api/src/services/connectionService.ts
services/us-api/src/webhooks/webhookService.ts
CreateConsentPayload
| Property | Type | Description |
|---|---|---|
user |
{ country: 'US'; user_reference?: string } |
Consent subject payload; the country is fixed to US |
purpose |
Purpose |
Intended purpose for the consent |
data_categories |
DataCategory[] |
Categories being granted |
access_duration_days |
`number | undefined` |
expires_at |
`string | undefined` |
refresh_permissions |
`{ enabled: boolean; max_refresh_per_day: number } | undefined` |
consent_disclosure_version |
string |
Disclosure version recorded with the consent |
TokenPair
| Property | Type | Description |
|---|---|---|
access_token |
string |
Signed RSA access JWT |
refresh_token |
string |
Opaque refresh token string |
expires_in |
number |
Access token lifetime in seconds |
scope |
{ purpose: Purpose; data_categories: DataCategory[] } |
Scope returned with the token pair |
Public Methods
| Method | Description |
|---|---|
createConsent |
Creates a consent record with PENDING_USER_ACTION, writes a CREATED log entry, and resolves the expiry timestamp from expires_at or access_duration_days |
revokeConsent |
Marks the consent REVOKED, revokes active tokens, disconnects related connections, records a REVOKED log entry, and attempts webhook delivery |
getConsentReceipt |
Returns the consent receipt fields used by the client and downstream services |
ensureConsentActive |
Rejects missing, revoked, or expired consent records with CONSENT_REVOKED |
exchangeToken |
Validates the optional link token, activates pending consent, issues token pairs, and dispatches the consent_activated webhook when applicable |
refreshToken |
Validates a refresh token hash, checks consent status and expiry, enforces refresh limits, and issues a new token pair |
introspectToken |
Verifies access JWTs with config.jwtPublicKey and confirms the token exists in the token store |
ensureConnectionsReady |
Resolves connection state for a consent and throws REAUTH_REQUIRED when a connection requires re-authentication |
recordConnectionRefresh |
Updates lastRefreshedAt and restores connection status to ACTIVE |
dispatchWebhook |
Sends partner webhook events with a signed payload and records delivery attempts |
signPayload |
Computes the HMAC signature used in webhook delivery |
Consent and Token Flow
createConsentstores the consent inPENDING_USER_ACTION.exchangeTokenchangesPENDING_USER_ACTIONtoACTIVEbefore issuing tokens.refreshTokenrefuses to mint a new pair if refresh is disabled, the consent has expired, or the daily limit has been reached.revokeConsentdisconnects related consent records and leaves any active refresh tokens revoked viarevokedAt.
Connection Readiness
| State | Meaning |
|---|---|
ACTIVE |
No connection requires re-authentication and no degraded connection blocks the flow |
REAUTH_REQUIRED |
A connection is marked for re-authentication and the service throws REAUTH_REQUIRED |
DEGRADED |
One or more connections are degraded, but the service returns the degraded status instead of throwing |
DISCONNECTED |
Used by revokeConsent to invalidate connections tied to a revoked consent |
Webhook Side Effects
[!NOTE]
ensureConnectionsReadythrowsREAUTH_REQUIREDonly when it finds a connection with statusREAUTH_REQUIRED. When it findsDEGRADED, it returns the degraded status instead of rejecting the request.
dispatchWebhook creates a webhookDelivery row before each outbound POST, signs the event payload with signPayload, and updates the delivery record to DELIVERED or FAILED based on the HTTP response. Delivery failures raise PROVIDER_UNAVAILABLE after the database record is updated.
US Data Gateway Authentication
services/us-data-gateway/cmd/us-data-gateway/main.go
services/us-data-gateway/internal/auth/auth.go
services/us-data-gateway/internal/config/config.go
services/us-data-gateway/internal/handlers/handlers.go
services/us-data-gateway/internal/provider/provider.go
Startup and Configuration
main.go wires the gateway in this order:
config.Load()reads runtime settings.pgxpool.Newopens the PostgreSQL pool withDatabaseURL.redis.NewClientcreates the Redis client fromRedisURL.parsePublicKeyparsesJWTPublicKeyinto an RSA public key.auth.TokenVerifieris created with the RSA key and Redis client.handlers.Handleris created with the DB pool, provider, and token verifier.- HTTP routes are registered on
http.NewServeMux.
Config
| Property | Type | Description |
|---|---|---|
Port |
string |
HTTP port used by http.ListenAndServe |
DatabaseURL |
string |
PostgreSQL DSN |
RedisURL |
string |
Redis address |
JWTPublicKey |
string |
PEM-encoded RSA public key |
Provider |
string |
Provider selector, defaulting to mock |
Claims
| Property | Type | Description |
|---|---|---|
ConsentID |
string |
Consent identifier, serialized as cid |
Purpose |
string |
Purpose claim, serialized as pur |
Categories |
[]string |
Allowed category list, serialized as cat |
RegisteredClaims |
jwt.RegisteredClaims |
Standard JWT registered claims, including jti via ID |
TokenVerifier
| Property | Type | Description |
|---|---|---|
PublicKey |
*rsa.PublicKey |
RSA public key used to verify RS256 access tokens |
Redis |
*redis.Client |
Redis client used to check token session state |
Handler
| Property | Type | Description |
|---|---|---|
DB |
*pgxpool.Pool |
Database pool used for consent lookups |
Provider |
provider.Provider |
Data provider abstraction used for account, balance, transaction, and income data |
Auth |
auth.TokenVerifier |
JWT and revocation verifier |
Provider Interface
| Method | Description |
|---|---|
FetchAccounts |
Loads account data for a consent |
FetchBalances |
Loads balance data for a consent |
FetchTransactions |
Loads transaction data with date filters |
FetchTransactionsSync |
Loads sync deltas for a consent and cursor |
FetchIncome |
Loads income data with a lookback window |
Handler Request Path
| Method | Description |
|---|---|
Accounts |
Checks bearer auth, enforces the ACCOUNTS category, verifies consent activity, and returns accounts |
Balances |
Checks bearer auth, enforces the BALANCES category, verifies consent activity, and returns balances |
Transactions |
Checks bearer auth, enforces the TRANSACTIONS category, verifies consent activity, and returns transactions |
TransactionsSync |
Checks bearer auth, enforces the TRANSACTIONS category, verifies consent activity, and returns transaction deltas |
Income |
Checks bearer auth, enforces the INCOME category, verifies consent activity, and returns income rows |
authorize |
Requires a bearer token and delegates verification to Auth.Verify |
ensureConsentActive |
Confirms the consent exists, is ACTIVE, and has not expired |
Token Verification Flow
TokenVerifier.Verify enforces this chain:
- Parse the JWT with
jwt.ParseWithClaims. - Reject anything that does not use RS256.
- Read Redis session state from
session:<claims.ID>. - Reject the token if
session["revoked"] == "true".
Redis Session Revocation Store
The Redis lookup key is session:<claims.ID>, where claims.ID is the JWT ID from the token’s registered claims. The gateway only checks one field from that hash:
| Redis Field | Expected Value | Meaning |
|---|---|---|
revoked |
true |
The access token is invalid and must be rejected |
If the hash lookup fails or Redis returns an error, verification fails before the request reaches the handler.
API Integration
US Data Gateway Endpoints
Get US Accounts
{
"title": "Get US Accounts",
"description": "Returns consent-scoped account data after bearer verification, category gating, and consent status checks.",
"method": "GET",
"baseUrl": "<USDataGatewayBaseUrl>",
"endpoint": "/api/v1/us/data/accounts",
"headers": [
{
"key": "Authorization",
"value": "Bearer <access_token>",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Success",
"body": "{\n \"accounts\": [\n {\n \"account_token\": \"acct_tok_1\",\n \"name\": \"Checking\",\n \"type\": \"depository\",\n \"mask\": \"1234\"\n },\n {\n \"account_token\": \"acct_tok_2\",\n \"name\": \"Savings\",\n \"type\": \"depository\",\n \"mask\": \"5678\"\n }\n ]\n}"
},
"403": {
"description": "Missing token or category not allowed",
"body": "{\n \"error\": \"CATEGORY_NOT_ALLOWED\"\n}"
},
"409": {
"description": "Consent revoked or expired",
"body": "{\n \"error\": \"CONSENT_REVOKED\"\n}"
},
"500": {
"description": "Unexpected error",
"body": "{\n \"error\": \"INTERNAL_ERROR\"\n}"
}
}
}
Get US Balances
{
"title": "Get US Balances",
"description": "Returns consent-scoped balance data after bearer verification, category gating, and consent status checks.",
"method": "GET",
"baseUrl": "<USDataGatewayBaseUrl>",
"endpoint": "/api/v1/us/data/balances",
"headers": [
{
"key": "Authorization",
"value": "Bearer <access_token>",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Success",
"body": "{\n \"balances\": [\n {\n \"account_token\": \"acct_tok_1\",\n \"available\": 1200,\n \"current\": 1500,\n \"currency\": \"USD\"\n },\n {\n \"account_token\": \"acct_tok_2\",\n \"available\": 3000,\n \"current\": 3200,\n \"currency\": \"USD\"\n }\n ]\n}"
},
"403": {
"description": "Missing token or category not allowed",
"body": "{\n \"error\": \"CATEGORY_NOT_ALLOWED\"\n}"
},
"409": {
"description": "Consent revoked or expired",
"body": "{\n \"error\": \"CONSENT_REVOKED\"\n}"
},
"500": {
"description": "Unexpected error",
"body": "{\n \"error\": \"INTERNAL_ERROR\"\n}"
}
}
}
Get US Transactions
{
"title": "Get US Transactions",
"description": "Returns consent-scoped transaction data after bearer verification, category gating, and consent status checks. The handler forwards the optional from and to query parameters to the provider.",
"method": "GET",
"baseUrl": "<USDataGatewayBaseUrl>",
"endpoint": "/api/v1/us/data/transactions",
"headers": [
{
"key": "Authorization",
"value": "Bearer <access_token>",
"required": true
}
],
"queryParams": [
{
"key": "from",
"value": "2024-10-01T00:00:00Z",
"required": false
},
{
"key": "to",
"value": "2024-10-31T23:59:59Z",
"required": false
}
],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Success",
"body": "{\n \"transactions\": [\n {\n \"transaction_id\": \"txn_1\",\n \"account_token\": \"acct_tok_1\",\n \"amount\": 1200,\n \"currency\": \"USD\",\n \"posted_at\": \"2024-10-01T00:00:00Z\",\n \"merchant_name\": \"Rent Co\",\n \"merchant_category\": \"RENT\"\n },\n {\n \"transaction_id\": \"txn_2\",\n \"account_token\": \"acct_tok_1\",\n \"amount\": 85,\n \"currency\": \"USD\",\n \"posted_at\": \"2024-10-02T00:00:00Z\",\n \"merchant_name\": \"Card\",\n \"merchant_category\": \"DEBT\"\n }\n ]\n}"
},
"403": {
"description": "Missing token or category not allowed",
"body": "{\n \"error\": \"CATEGORY_NOT_ALLOWED\"\n}"
},
"409": {
"description": "Consent revoked or expired",
"body": "{\n \"error\": \"CONSENT_REVOKED\"\n}"
},
"500": {
"description": "Unexpected error",
"body": "{\n \"error\": \"INTERNAL_ERROR\"\n}"
}
}
}
Get US Transaction Sync
{
"title": "Get US Transaction Sync",
"description": "Returns transaction sync deltas after bearer verification, category gating, and consent status checks. The handler forwards the optional cursor query parameter to the provider.",
"method": "GET",
"baseUrl": "<USDataGatewayBaseUrl>",
"endpoint": "/api/v1/us/data/transactions/sync",
"headers": [
{
"key": "Authorization",
"value": "Bearer <access_token>",
"required": true
}
],
"queryParams": [
{
"key": "cursor",
"value": "cursor_next_1",
"required": false
}
],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Success",
"body": "{\n \"added\": [\n {\n \"transaction_id\": \"txn_3\",\n \"account_token\": \"acct_tok_2\",\n \"amount\": 45,\n \"currency\": \"USD\",\n \"posted_at\": \"2024-10-03T00:00:00Z\",\n \"merchant_name\": \"Coffee\",\n \"merchant_category\": \"FOOD\"\n }\n ],\n \"modified\": [\n {\n \"transaction_id\": \"txn_2\",\n \"account_token\": \"acct_tok_1\",\n \"amount\": 90,\n \"currency\": \"USD\",\n \"posted_at\": \"2024-10-02T00:00:00Z\",\n \"merchant_name\": \"Card\",\n \"merchant_category\": \"DEBT\"\n }\n ],\n \"removed\": [\n {\n \"transaction_id\": \"txn_4\"\n }\n ],\n \"next_cursor\": \"cursor_next_1\"\n}"
},
"403": {
"description": "Missing token or category not allowed",
"body": "{\n \"error\": \"CATEGORY_NOT_ALLOWED\"\n}"
},
"409": {
"description": "Consent revoked or expired",
"body": "{\n \"error\": \"CONSENT_REVOKED\"\n}"
},
"500": {
"description": "Unexpected error",
"body": "{\n \"error\": \"INTERNAL_ERROR\"\n}"
}
}
}
Get US Income
{
"title": "Get US Income",
"description": "Returns consent-scoped income rows after bearer verification, category gating, and consent status checks. The handler accepts an optional lookback_days query parameter and defaults to 180 when it is absent.",
"method": "GET",
"baseUrl": "<USDataGatewayBaseUrl>",
"endpoint": "/api/v1/us/data/income",
"headers": [
{
"key": "Authorization",
"value": "Bearer <access_token>",
"required": true
}
],
"queryParams": [
{
"key": "lookback_days",
"value": "180",
"required": false
}
],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Success",
"body": "{\n \"income\": [\n {\n \"income_id\": \"inc_1\",\n \"amount\": 5100,\n \"currency\": \"USD\",\n \"pay_date\": \"2024-09-30T00:00:00Z\"\n },\n {\n \"income_id\": \"inc_2\",\n \"amount\": 5300,\n \"currency\": \"USD\",\n \"pay_date\": \"2024-10-15T00:00:00Z\"\n }\n ]\n}"
},
"403": {
"description": "Missing token or category not allowed",
"body": "{\n \"error\": \"CATEGORY_NOT_ALLOWED\"\n}"
},
"409": {
"description": "Consent revoked or expired",
"body": "{\n \"error\": \"CONSENT_REVOKED\"\n}"
},
"500": {
"description": "Unexpected error",
"body": "{\n \"error\": \"INTERNAL_ERROR\"\n}"
}
}
}
Feature Flows
US Data Gateway Token Verification Flow
sequenceDiagram
participant Client
participant Handler
participant TokenVerifier
participant Redis
participant DB
participant Provider
Client->>Handler: Authorization Bearer access token
Handler->>TokenVerifier: Verify token
TokenVerifier->>Redis: HGetAll session jti
Redis-->>TokenVerifier: revocation state
TokenVerifier-->>Handler: claims
Handler->>DB: ensureConsentActive
DB-->>Handler: consent row
Handler->>Provider: FetchAccounts or FetchBalances or FetchTransactions or FetchTransactionsSync or FetchIncome
Provider-->>Handler: data rows
Handler-->>Client: JSON response
Consent Activation and Token Issuance Flow
sequenceDiagram
participant Partner
participant ConsentService
participant TokenService
participant DB
participant Webhooks
Partner->>ConsentService: createConsent payload
ConsentService->>DB: insert consent
ConsentService->>DB: insert consent log CREATED
Partner->>TokenService: exchangeToken consentId and linkToken
TokenService->>DB: load consent
TokenService->>DB: update consent ACTIVE if pending
TokenService->>DB: insert token row
TokenService->>DB: insert consent log TOKEN ISSUED
TokenService->>Webhooks: dispatch consent_activated when activated
Webhooks-->>TokenService: delivery result
TokenService-->>Partner: TokenPair
State Management
Request-Scoped Auth State
request.partnerIdcarries the accepted partner token through the request lifecycle.request.accessClaimscarries consent ID, purpose, categories, and JWT ID after verification.x-request-idis normalized before the response logger runs.
Consent and Token State
| State or Field | Location | Meaning |
|---|---|---|
PENDING_USER_ACTION |
createConsent, exchangeToken |
Consent exists but has not been activated yet |
ACTIVE |
exchangeToken, ensureConsentActive, refreshToken, Handler.ensureConsentActive |
Consent is usable for data access |
REVOKED |
revokeConsent |
Consent is no longer valid |
DISCONNECTED |
revokeConsent |
Connections tied to the consent are invalidated |
revokedAt |
token table via refreshToken and revokeConsent |
Marks issued refresh tokens as revoked |
session:<jti> |
Redis | Tracks whether a gateway access token has been revoked |
Connection Status Values
ConnectionStatusValues are used by ensureConnectionsReady and recordConnectionRefresh:
ACTIVEREAUTH_REQUIREDDEGRADEDDISCONNECTED
Error Handling
services/us-api/src/middleware/errorHandler.ts formats API failures into a consistent JSON shape:
ApiErrorresponses includeerror.code,error.message,error.details, andrequest_id.- Unexpected failures return
PROVIDER_UNAVAILABLEwith status 500.
services/us-data-gateway/internal/handlers/handlers.go returns a simpler error body:
{"error":"TOKEN_REQUIRED"}{"error":"CATEGORY_NOT_ALLOWED"}{"error":"CONSENT_REVOKED"}{"error":"INTERNAL_ERROR"}
The gateway also rejects invalid RS256 tokens and revoked Redis sessions before a handler can read data.
Dependencies
fastifyfor the US API middleware and route registrationjsonwebtokenfor RSA JWT verification and signingPrismafor access logs, consents, tokens, connections, and webhook delivery rowscryptofor request IDs, token IDs, token hashes, and webhook signaturespgxpoolfor PostgreSQL access in the Go data gatewaygo-redisfor access-token revocation statejwt/v5for RSA verification in the Go data gatewayfetchfor webhook dispatch and scoring callback replayProviderabstraction in the Go gateway, currently wired toMockProvider
Testing Considerations
services/us-data-gateway/internal/handlers/handlers_test.goverifies thatErrCategoryNotAllowedbecomes HTTP 403 withCATEGORY_NOT_ALLOWED.- The same test file verifies that
ErrConsentRevokedbecomes HTTP 409 withCONSENT_REVOKED. services/us-api/test/flows.test.tscovers consent creation, consent revocation, refresh throttling, and category enforcement.- Startup tests for the Go gateway should cover the
REDIS_URLfallback path ininit()and the RSA public-key parsing path inparsePublicKey.
Key Classes Reference
| Class | Responsibility |
|---|---|
accessToken.ts |
Verifies access JWTs and attaches consent claims to the request |
partnerAuth.ts |
Accepts partner tokens and resolves them to request-scoped partner identity |
internalAuth.ts |
Enforces the internal service token for protected internal routes |
requestId.ts |
Normalizes request IDs and echoes them to the response |
errorHandler.ts |
Converts auth and validation failures into a consistent JSON error envelope |
auditLogger.ts |
Writes access log rows after each response and disables logging on Prisma init failure |
consentService.ts |
Creates, revokes, and reads consents, plus connection and webhook side effects |
tokenService.ts |
Issues, refreshes, introspects, and renews consent-scoped JWTs |
connectionService.ts |
Resolves connection readiness and refresh state for consent-scoped access |
auth.go |
Verifies JWTs and checks Redis-backed revocation state |
config.go |
Loads gateway runtime config and secret values |
handlers.go |
Enforces bearer auth, consent activity, and category checks on data endpoints |
provider.go |
Defines the data provider interface and response models used by the gateway |