Banking and Financial Data DOMAIN - Consent-scoped US data gateway and provider boundary

Files: 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, services/us-data-gateway/internal/provider/mock.go, services/us-data-gateway/internal/handlers/handlers_test.go

Overview

This gateway is the narrow consent-enforcement boundary for US banking data. It accepts access tokens, verifies the JWT signature and session state, checks that the requested data category is inside the consented scope, confirms the consent is still active in PostgreSQL, and then exposes account, balance, transaction, transaction-sync, and income data through a small HTTP surface.

The service does not inherit the full monolith architecture. It is a focused Go process that boots its own PostgreSQL pool, Redis client, JWT public key, and provider implementation, then wires a net/http mux directly to five data endpoints plus a health endpoint. The provider abstraction is intentionally thin: the gateway only depends on a Provider interface and a mock implementation in the provided code.

Architecture Overview

flowchart TD
    Client[Client or calling service] --> Server[net http server]
    Server --> Accounts[Handler Accounts]
    Server --> Balances[Handler Balances]
    Server --> Transactions[Handler Transactions]
    Server --> TxSync[Handler TransactionsSync]
    Server --> Income[Handler Income]
    Server --> Health[Health endpoint]

    subgraph Bootstrap[Bootstrap and Wiring]
        Main[main]
        Load[config Load]
        ParseKey[parsePublicKey]
        Mux[http ServeMux]
    end

    subgraph AuthBoundary[Consent scoped auth boundary]
        Authorize[Handler authorize]
        Verify[TokenVerifier Verify]
        Redis[(Redis session hash)]
    end

    subgraph ConsentStore[Consent store]
        ConsentCheck[Handler ensureConsentActive]
        Postgres[(PostgreSQL consents table)]
    end

    subgraph ProviderBoundary[Provider boundary]
        ProviderAPI[Provider interface]
        Mock[MockProvider]
    end

    Main --> Load
    Main --> ParseKey
    Main --> Mux
    Mux --> Accounts
    Mux --> Balances
    Mux --> Transactions
    Mux --> TxSync
    Mux --> Income
    Mux --> Health

    Accounts --> Authorize
    Balances --> Authorize
    Transactions --> Authorize
    TxSync --> Authorize
    Income --> Authorize

    Authorize --> Verify
    Verify --> Redis

    Accounts --> ConsentCheck
    Balances --> ConsentCheck
    Transactions --> ConsentCheck
    TxSync --> ConsentCheck
    Income --> ConsentCheck
    ConsentCheck --> Postgres

    Accounts --> ProviderAPI
    Balances --> ProviderAPI
    Transactions --> ProviderAPI
    TxSync --> ProviderAPI
    Income --> ProviderAPI
    ProviderAPI --> Mock

Component Structure

1. Bootstrap and HTTP Surface

main and parsePublicKey

[!IMPORTANT] Two code-level mismatches are provable in the provided source: - services/us-data-gateway/cmd/us-data-gateway/main.go always selects provider.MockProvider{} for every cfg.Provider value, so the PROVIDER setting does not change runtime behavior. - services/us-data-gateway/internal/auth/auth.go expects JWT claims named cid, pur, and cat, while the US API token issuer shown in the repository signs consent_id, purpose, and data_categories. Tokens minted by that issuer will not satisfy this verifier’s required fields.

File: services/us-data-gateway/cmd/us-data-gateway/main.go

main is the executable entrypoint. It loads configuration, connects to PostgreSQL and Redis, parses the RSA public key, builds the Handler, and registers the HTTP routes on a ServeMux. parsePublicKey converts the configured PEM string into an *rsa.PublicKey for JWT verification.

Function Description
main Loads config, creates dependencies, registers routes, and starts http.ListenAndServe on cfg.Port.
parsePublicKey Parses the configured PEM public key into an RSA public key used by JWT verification.
init Sets REDIS_URL to localhost:6379 when the environment variable is unset.

Config

File: services/us-data-gateway/internal/config/config.go

Property Type Description
Port string HTTP listen port used by main.
DatabaseURL string PostgreSQL connection string passed to pgxpool.New.
RedisURL string Redis address passed to redis.NewClient.
JWTPublicKey string PEM-encoded RSA public key used by parsePublicKey.
Provider string Provider selector read by main; the current switch still resolves to MockProvider for every value.

Public methods

Method Description
Load Reads environment variables and builds a Config value.

Internal helpers

Method Description
getEnv Reads an environment variable with a fallback value.

2. Auth Boundary

Claims

File: services/us-data-gateway/internal/auth/auth.go

The gateway binds JWT claim data to a consent-scoped identity. The claims structure inherits standard registered JWT claims and adds consent, purpose, and category fields.

Property Type Description
ConsentID string Consent identifier mapped from the cid JWT claim.
Purpose string Consent purpose mapped from the pur JWT claim.
Categories []string Consent categories mapped from the cat JWT claim.
RegisteredClaims jwt.RegisteredClaims Standard JWT claims including ID, ExpiresAt, and issuer metadata.

TokenVerifier

File: services/us-data-gateway/internal/auth/auth.go

Property Type Description
PublicKey *rsa.PublicKey RSA public key used to validate RS256 JWTs.
Redis *redis.Client Redis client used to inspect session revocation state.

Public methods

Method Description
Verify Verifies an RS256 token, maps claims into Claims, and rejects revoked sessions from Redis.

Verification flow

  1. Parse the token with jwt.ParseWithClaims.
  2. Reject any signing method other than RS256.
  3. Require a valid token object and a valid Claims type assertion.
  4. Read session:<claims.ID> from Redis.
  5. Reject the token when the Redis hash contains revoked=true.

Claims and token verification data flow

sequenceDiagram
    participant H as Handler
    participant A as TokenVerifier
    participant R as Redis
    participant C as PostgreSQL consent row

    H->>A: Verify token string
    A->>A: Validate RS256 and parse Claims
    A->>R: HGetAll session:<claims ID>
    R-->>A: session data
    A-->>H: Claims or error
    H->>C: ensureConsentActive
    C-->>H: consent record

3. Gateway Handlers

Handler

[!NOTE] TokenVerifier.Verify returns generic errors for invalid signature, invalid payload shape, and Redis failures. Handler.authorize passes those errors into writeError, which converts them to a 500 INTERNAL_ERROR instead of an auth-specific status code.

File: services/us-data-gateway/internal/handlers/handlers.go

The handler is the only HTTP-facing business façade in the gateway. It binds three dependencies: PostgreSQL for consent lookups, the provider boundary for banking data, and the auth verifier.

Property Type Description
DB *pgxpool.Pool PostgreSQL pool used by ensureConsentActive.
Provider provider.Provider Data source for accounts, balances, transactions, transaction sync, and income.
Auth auth.TokenVerifier JWT and session verifier used by authorize.

Public methods

Method Description
Accounts Returns consent-scoped accounts when the ACCOUNTS category is allowed.
Balances Returns consent-scoped balances when the BALANCES category is allowed.
Transactions Returns consent-scoped transactions when the TRANSACTIONS category is allowed.
TransactionsSync Returns consent-scoped sync deltas when the TRANSACTIONS category is allowed.
Income Returns consent-scoped income when the INCOME category is allowed.

Internal helpers

Method Description
ensureConsentActive Reads the consent record and rejects revoked or expired consents.
authorize Extracts the Bearer token and delegates verification to Auth.Verify.
writeError Converts handler and gateway errors into JSON error responses.
writeJSON Writes a JSON response with a specific status code.
contains Checks whether a category is present in the JWT claim list.

consentRecord

File: services/us-data-gateway/internal/handlers/handlers.go

ensureConsentActive maps the consent row to this internal record.

Property Type Description
ID string Consent identifier.
Status string Current consent status read from PostgreSQL.
ExpiresAt time.Time Expiry timestamp used to reject stale consents.
Categories []string Categories selected from the consent row query.

apiError

File: services/us-data-gateway/internal/handlers/handlers.go

Property Type Description
Status int HTTP status code written by writeError.
Code string Stable error code returned in the JSON error body.

Methods

Method Description
Error Returns the error code string.

Request handling order

Each data endpoint follows the same traced path:

  1. authorize requires Authorization: Bearer ....
  2. TokenVerifier.Verify validates the token and session state.
  3. The handler checks that the required category exists in Claims.Categories.
  4. ensureConsentActive reads the consent row and requires Status == "ACTIVE" and ExpiresAt in the future.
  5. The handler delegates to the configured Provider.
  6. Results are serialized with writeJSON.

Accounts

File: services/us-data-gateway/internal/handlers/handlers.go

Accounts is the narrowest account surface: it only requires the ACCOUNTS category and the consent to be active before calling FetchAccounts.

Balances

File: services/us-data-gateway/internal/handlers/handlers.go

Balances enforces the BALANCES category and active consent before calling FetchBalances.

Transactions

File: services/us-data-gateway/internal/handlers/handlers.go

Transactions enforces the TRANSACTIONS category, active consent, and forwards optional from and to query values to the provider.

Transactions Sync

File: services/us-data-gateway/internal/handlers/handlers.go

TransactionsSync uses the same consent and category gates as Transactions, then forwards an optional cursor query parameter to the provider.

Income

File: services/us-data-gateway/internal/handlers/handlers.go

Income enforces the INCOME category and active consent, then parses lookback_days. Invalid numeric input is ignored and the default 180 is used.

Handler flow

sequenceDiagram
    participant Client as Client
    participant S as HTTP server
    participant H as Handler
    participant V as TokenVerifier
    participant R as Redis
    participant P as PostgreSQL
    participant D as Provider

    Client->>S: Request data endpoint
    S->>H: Call endpoint method
    H->>H: authorize
    H->>V: Verify token
    V->>R: HGetAll session jti
    R-->>V: Session state
    V-->>H: Claims
    H->>H: Check category membership
    H->>P: ensureConsentActive query
    P-->>H: Consent status and expiry
    H->>D: Fetch data for consent
    D-->>H: Provider response
    H-->>Client: JSON body

4. Provider Boundary

Provider

File: services/us-data-gateway/internal/provider/provider.go

The provider boundary isolates the gateway from any specific banking integration. The handler only depends on this interface, which keeps account retrieval and transaction retrieval outside the gateway’s consent logic.

Method Description
FetchAccounts Returns accounts for a consent identifier.
FetchBalances Returns balances for a consent identifier.
FetchTransactions Returns transactions for a consent identifier and date range inputs.
FetchTransactionsSync Returns sync deltas for a consent identifier and cursor input.
FetchIncome Returns income entries for a consent identifier and lookback window.

Provider data models

File: services/us-data-gateway/internal/provider/provider.go

Account
Property Type Description
AccountToken string Account identifier exposed in JSON as account_token.
Name string Account display name.
Type string Account type string.
Mask string Short account mask.
Balance
Property Type Description
AccountToken string Account identifier exposed in JSON as account_token.
Available float64 Available balance.
Current float64 Current balance.
Currency string ISO currency code.
Transaction
Property Type Description
TransactionID string Transaction identifier exposed as transaction_id.
AccountToken string Related account identifier.
Amount float64 Transaction amount.
Currency string ISO currency code.
PostedAt string ISO timestamp string.
MerchantName string Merchant display name.
MerchantCategory string Merchant category label.
TransactionRemoval
Property Type Description
TransactionID string Removed transaction identifier.
TransactionSync
Property Type Description
Added []Transaction Newly added transactions.
Modified []Transaction Updated transactions.
Removed []TransactionRemoval Removed transaction identifiers.
NextCursor string Cursor to request the next sync page.
Income
Property Type Description
IncomeID string Income identifier exposed as income_id.
Amount float64 Income amount.
Currency string ISO currency code.
PayDate string ISO pay date.

MockProvider

File: services/us-data-gateway/internal/provider/mock.go

The mock provider supplies deterministic canned data for every method. The gateway passes consent and filter arguments into it, but the mock implementation does not use those values to vary the returned payload.

Property Type Description
MockProvider struct{} Stateless provider implementation.

Public methods

Method Description
FetchAccounts Returns two canned accounts.
FetchBalances Returns two canned balances tied to the canned accounts.
FetchTransactions Returns two canned transactions.
FetchTransactionsSync Returns one added transaction, one modified transaction, one removed transaction, and a static next cursor.
FetchIncome Returns two canned income items.

Provider data flow

flowchart TD
    H[Handler] --> I[Provider interface]
    I --> M[MockProvider]
    M --> A[Accounts]
    M --> B[Balances]
    M --> T[Transactions]
    M --> S[TransactionsSync]
    M --> N[Income]

5. Redis Session Cache

Redis session state

File: services/us-data-gateway/internal/auth/auth.go and services/us-data-gateway/cmd/us-data-gateway/main.go

Redis is used as a revocation lookup during token verification. The verifier reads a hash at session:<claims.ID> and rejects the token when that hash contains revoked=true.

Item Value
Cache key prefix session:
Key format session:<JWT registered claim ID>
Revocation field revoked
Revocation value true

Lifecycle

  1. main constructs redis.NewClient.
  2. TokenVerifier.Verify reads the session hash on every authenticated request.
  3. A revoked session fails verification before any consent or provider call executes.

6. Logging and Request Tracing

Request logging

File: services/us-data-gateway/internal/handlers/handlers.go and services/us-data-gateway/cmd/us-data-gateway/main.go

The gateway uses the standard library log package for startup and request tracing. Each data handler logs the request ID header and the consent ID after authorization succeeds.

Location Logged data
main Gateway listen port.
Accounts request_id, consent_id, and action=accounts.
Balances request_id, consent_id, and action=balances.
Transactions request_id, consent_id, and action=transactions.
TransactionsSync request_id, consent_id, and action=transactions_sync.
Income request_id, consent_id, and action=income.

API Integration

Endpoint routing

main.go registers the following paths on the HTTP mux:

  • GET /api/v1/us/data/accounts
  • GET /api/v1/us/data/balances
  • GET /api/v1/us/data/transactions
  • GET /api/v1/us/data/transactions/sync
  • GET /api/v1/us/data/income
  • GET /health

Accounts endpoint

Get Accounts

Route: GET /api/v1/us/data/accounts

{
    "title": "Get Accounts",
    "description": "Returns consent-scoped accounts after Bearer token verification, Redis session validation, category enforcement, and active-consent checks.",
    "method": "GET",
    "baseUrl": "<UsDataGatewayBaseUrl>",
    "endpoint": "/api/v1/us/data/accounts",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Accounts returned for the consent",
            "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": "Token missing, invalid, revoked, or category not allowed",
            "body": "{\n    \"error\": \"CATEGORY_NOT_ALLOWED\"\n}"
        },
        "409": {
            "description": "Consent revoked or expired",
            "body": "{\n    \"error\": \"CONSENT_REVOKED\"\n}"
        }
    }
}

Balances endpoint

Get Balances

Route: GET /api/v1/us/data/balances

{
    "title": "Get Balances",
    "description": "Returns consent-scoped balances after Bearer token verification, Redis session validation, category enforcement, and active-consent checks.",
    "method": "GET",
    "baseUrl": "<UsDataGatewayBaseUrl>",
    "endpoint": "/api/v1/us/data/balances",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Balances returned for the consent",
            "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": "Token missing, invalid, revoked, or category not allowed",
            "body": "{\n    \"error\": \"BALANCES\"\n}"
        },
        "409": {
            "description": "Consent revoked or expired",
            "body": "{\n    \"error\": \"CONSENT_REVOKED\"\n}"
        }
    }
}

Transactions endpoint

Get Transactions

Route: GET /api/v1/us/data/transactions

{
    "title": "Get Transactions",
    "description": "Returns consent-scoped transactions for an optional date range after Bearer token verification, Redis session validation, category enforcement, and active-consent checks.",
    "method": "GET",
    "baseUrl": "<UsDataGatewayBaseUrl>",
    "endpoint": "/api/v1/us/data/transactions",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "from",
            "value": "2024-10-01",
            "required": false
        },
        {
            "key": "to",
            "value": "2024-10-31",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Transactions returned for the consent",
            "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": "Token missing, invalid, revoked, or category not allowed",
            "body": "{\n    \"error\": \"TOKEN_REQUIRED\"\n}"
        },
        "409": {
            "description": "Consent revoked or expired",
            "body": "{\n    \"error\": \"CONSENT_REVOKED\"\n}"
        }
    }
}

Transactions sync endpoint

Get Transactions Sync

Route: GET /api/v1/us/data/transactions/sync

{
    "title": "Get Transactions Sync",
    "description": "Returns consent-scoped transaction sync deltas after Bearer token verification, Redis session validation, category enforcement, and active-consent checks.",
    "method": "GET",
    "baseUrl": "<UsDataGatewayBaseUrl>",
    "endpoint": "/api/v1/us/data/transactions/sync",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "cursor",
            "value": "cursor_next_1",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Transaction sync result returned for the consent",
            "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": "Token missing, invalid, revoked, or category not allowed",
            "body": "{\n    \"error\": \"CATEGORY_NOT_ALLOWED\"\n}"
        },
        "409": {
            "description": "Consent revoked or expired",
            "body": "{\n    \"error\": \"CONSENT_REVOKED\"\n}"
        }
    }
}

Income endpoint

Get Income

Route: GET /api/v1/us/data/income

{
    "title": "Get Income",
    "description": "Returns consent-scoped income after Bearer token verification, Redis session validation, category enforcement, and active-consent checks.",
    "method": "GET",
    "baseUrl": "<UsDataGatewayBaseUrl>",
    "endpoint": "/api/v1/us/data/income",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "lookback_days",
            "value": "180",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Income returned for the consent",
            "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": "Token missing, invalid, revoked, or category not allowed",
            "body": "{\n    \"error\": \"TOKEN_REQUIRED\"\n}"
        },
        "409": {
            "description": "Consent revoked or expired",
            "body": "{\n    \"error\": \"CONSENT_REVOKED\"\n}"
        }
    }
}

Health endpoint

Health Check

Route: GET /health

{
    "title": "Health Check",
    "description": "Returns a plain text readiness response for process-level health checks.",
    "method": "GET",
    "baseUrl": "<UsDataGatewayBaseUrl>",
    "endpoint": "/health",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Service is healthy",
            "body": "ok"
        }
    }
}

Feature Flows

This is the core boundary flow for the gateway. The caller presents a Bearer token, the gateway verifies it, checks the consent scope, validates consent state, and returns a provider payload without expanding the gateway into the monolith’s broader application stack.

sequenceDiagram
    participant Client as Client
    participant HTTP as HTTP mux
    participant Handler as Handler Accounts
    participant Auth as TokenVerifier Verify
    participant Redis as Redis
    participant DB as PostgreSQL
    participant Prov as MockProvider

    Client->>HTTP: GET accounts
    HTTP->>Handler: Accounts
    Handler->>Handler: authorize
    Handler->>Auth: Verify token
    Auth->>Redis: HGetAll session jti
    Redis-->>Auth: session state
    Auth-->>Handler: Claims
    Handler->>Handler: check ACCOUNTS category
    Handler->>DB: ensureConsentActive
    DB-->>Handler: consent row
    Handler->>Prov: FetchAccounts
    Prov-->>Handler: accounts
    Handler-->>Client: JSON response

TransactionsSync uses the same auth and consent gates, then forwards the cursor to the provider. The mock provider returns a canned sync page, but the handler itself is already consent-scoped before that point.

sequenceDiagram
    participant Client as Client
    participant Handler as Handler TransactionsSync
    participant Auth as TokenVerifier Verify
    participant Redis as Redis
    participant DB as PostgreSQL
    participant Prov as MockProvider

    Client->>Handler: GET transactions sync
    Handler->>Auth: Verify token
    Auth->>Redis: HGetAll session jti
    Redis-->>Auth: session state
    Auth-->>Handler: Claims
    Handler->>Handler: check TRANSACTIONS category
    Handler->>DB: ensureConsentActive
    DB-->>Handler: consent row
    Handler->>Prov: FetchTransactionsSync
    Prov-->>Handler: sync payload
    Handler-->>Client: JSON response

State Management

The gateway uses three distinct state sources:

  • JWT claims in the access token, including consent ID, purpose, categories, and jti.
  • Redis session state at session:<jti> for revocation checks.
  • PostgreSQL consent rows for status and expiry checks.
  • ACTIVE: required for all data endpoints.
  • Non-ACTIVE status: rejected as CONSENT_REVOKED.
  • Expired consent: rejected as CONSENT_REVOKED.
  • Category not present in the JWT claim list: rejected as CATEGORY_NOT_ALLOWED.

Token verification states

  • Missing Bearer token: TOKEN_REQUIRED.
  • Non-RS256 token, invalid JWT, malformed claims, or Redis failure: surfaced as generic errors by writeError.
  • Revoked Redis session: rejected by TokenVerifier.Verify.

Error Handling

writeError is the gateway’s response translator. It writes JSON bodies with a single error field and maps known apiError values to their configured status codes.

Error source HTTP result JSON body
Missing Bearer token in authorize 403 { "error": "TOKEN_REQUIRED" }
Category check failure 403 { "error": "CATEGORY_NOT_ALLOWED" }
Consent status or expiry failure 409 { "error": "CONSENT_REVOKED" }
Non-apiError auth or provider failure 500 { "error": "INTERNAL_ERROR" }

Error helper behavior

[!NOTE] The gateway distinguishes missing tokens from other auth failures, but invalid JWTs and revoked-session errors coming out of TokenVerifier.Verify are not wrapped as apiError values in the current code path. They are therefore returned as 500 INTERNAL_ERROR by writeError.

  • ErrCategoryNotAllowed writes status 403 and code CATEGORY_NOT_ALLOWED.
  • ErrConsentRevoked writes status 409 and code CONSENT_REVOKED.
  • apiError.Error() returns the code string, which lets writeError serialize it consistently.

Dependencies

External packages

  • github.com/go-redis/redis/v8
  • github.com/golang-jwt/jwt/v5
  • github.com/jackc/pgx/v5/pgxpool

Runtime services

  • PostgreSQL for consent lookup in ensureConsentActive.
  • Redis for JWT session revocation checks.
  • An RSA public key provided through JWT_PUBLIC_KEY.
  • The configured provider implementation, currently MockProvider in all cases.

Route-level dependencies

  • Authorization: Bearer <token> is required on every data endpoint.
  • X-Request-Id is logged when present, but it is not enforced by the handler.

Testing Considerations

services/us-data-gateway/internal/handlers/handlers_test.go includes two response-shape tests focused on the gateway’s consent boundary:

  • TestCategoryNotAllowedReturns403

    • Verifies writeError returns 403 for ErrCategoryNotAllowed.
    • Verifies the JSON error body is { "error": "CATEGORY_NOT_ALLOWED" }.
  • TestConsentRevokedReturns409

    • Verifies writeError returns 409 for ErrConsentRevoked.
    • Verifies the JSON error body is { "error": "CONSENT_REVOKED" }.

Additional behavior that is explicit in code and suitable for coverage:

  • Missing Authorization header returns 403 TOKEN_REQUIRED.
  • Consent status not ACTIVE returns 409 CONSENT_REVOKED.
  • Expired consent returns 409 CONSENT_REVOKED.
  • Category lists lacking the requested category return 403 CATEGORY_NOT_ALLOWED.
  • Transactions accepts optional from and to query strings.
  • Income defaults to a 180-day lookback when lookback_days is missing or invalid.
  • init injects REDIS_URL=localhost:6379 when the variable is not set.

Key Classes Reference

Class Responsibility
main.go Boots the gateway, wires dependencies, and registers HTTP routes.
config.go Loads runtime configuration from environment variables.
auth.go Verifies JWT access tokens and checks Redis-backed session revocation.
handlers.go Enforces consent scope and serves banking data endpoints.
provider.go Defines the provider boundary and response models.
mock.go Supplies canned provider responses for the gateway.
handlers_test.go Verifies gateway error mapping for category and consent failures.