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-api uses request middleware to accept partner tokens, access tokens, and internal tokens.
  • services/us-data-gateway uses a bearer JWT plus Redis-backed revocation state.
  • services/us-data-gateway/cmd/us-data-gateway/main.go loads 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.go sets REDIS_URL to localhost:6379 in init() 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:

  • ensureRequestId assigns x-request-id when the client does not send one.
  • registerAuditLogger writes 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_FINANCE
  • DataCategoryValues: IDENTITY_BASIC, ACCOUNTS, BALANCES, TRANSACTIONS, INCOME, EMPLOYMENT, CASHFLOW_FEATURES, DEVICE_RISK, WATCHLIST_SCREENING
  • ConnectionStatusValues: 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:

  • requestId
  • partnerId
  • consentId
  • route
  • statusCode

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
  • createConsent stores the consent in PENDING_USER_ACTION.
  • exchangeToken changes PENDING_USER_ACTION to ACTIVE before issuing tokens.
  • refreshToken refuses to mint a new pair if refresh is disabled, the consent has expired, or the daily limit has been reached.
  • revokeConsent disconnects related consent records and leaves any active refresh tokens revoked via revokedAt.

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] ensureConnectionsReady throws REAUTH_REQUIRED only when it finds a connection with status REAUTH_REQUIRED. When it finds DEGRADED, 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:

  1. config.Load() reads runtime settings.
  2. pgxpool.New opens the PostgreSQL pool with DatabaseURL.
  3. redis.NewClient creates the Redis client from RedisURL.
  4. parsePublicKey parses JWTPublicKey into an RSA public key.
  5. auth.TokenVerifier is created with the RSA key and Redis client.
  6. handlers.Handler is created with the DB pool, provider, and token verifier.
  7. 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
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.partnerId carries the accepted partner token through the request lifecycle.
  • request.accessClaims carries consent ID, purpose, categories, and JWT ID after verification.
  • x-request-id is normalized before the response logger runs.
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:

  • ACTIVE
  • REAUTH_REQUIRED
  • DEGRADED
  • DISCONNECTED

Error Handling

services/us-api/src/middleware/errorHandler.ts formats API failures into a consistent JSON shape:

  • ApiError responses include error.code, error.message, error.details, and request_id.
  • Unexpected failures return PROVIDER_UNAVAILABLE with 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

  • fastify for the US API middleware and route registration
  • jsonwebtoken for RSA JWT verification and signing
  • Prisma for access logs, consents, tokens, connections, and webhook delivery rows
  • crypto for request IDs, token IDs, token hashes, and webhook signatures
  • pgxpool for PostgreSQL access in the Go data gateway
  • go-redis for access-token revocation state
  • jwt/v5 for RSA verification in the Go data gateway
  • fetch for webhook dispatch and scoring callback replay
  • Provider abstraction in the Go gateway, currently wired to MockProvider

Testing Considerations

  • services/us-data-gateway/internal/handlers/handlers_test.go verifies that ErrCategoryNotAllowed becomes HTTP 403 with CATEGORY_NOT_ALLOWED.
  • The same test file verifies that ErrConsentRevoked becomes HTTP 409 with CONSENT_REVOKED.
  • services/us-api/test/flows.test.ts covers consent creation, consent revocation, refresh throttling, and category enforcement.
  • Startup tests for the Go gateway should cover the REDIS_URL fallback path in init() and the RSA public-key parsing path in parsePublicKey.

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