Aller au contenu principal

bank-sync

Status: implemented (services/bank-sync, contract: docs/dev/phase4-contracts.md, Bank-sync service; specs: features.md "Money"). Runs in the apps profile of docker-compose.yml on port 8092 (BANK_PROVIDERS=mock by default) and is reached through the gateway route /v1/bank.

Role: synchronises the association bank accounts per site, read-only: accounts, balance snapshots and booked transactions. It publishes every new transaction on bank.transaction.v1 for finance (payment matching) and tracks consent expiry.

Limits: no payment initiation, no matching (finance does it), no notification delivery (events only). IBANs are stored masked (last 4 characters). Amounts are integer minor units assuming 2 decimals.

Providers​

All providers implement one interface (internal/provider): Start (token check or authorisation URL), Complete (redirect code → session), Accounts (with balances), Transactions (booked, by date range) and Revoke. HTTP calls use a per-request timeout (BANK_HTTP_TIMEOUT), retry network errors, 429 and 5xx with exponential backoff (honouring Retry-After, max 30 s) and never log requests, bodies or credentials.

ProviderFlowData
wiseRead-only API token (personal or business) entered once, validated with GET /v2/profilesGET /v4/profiles/{id}/balances?types=STANDARD (one account per balance, reference profile/balance/currency), GET /v1/profiles/{id}/balance-statements/{balanceId}/statement.json in 180-day windows (referenceNumber = transaction ID)
enablebankingApplication JWT (RS256, kid = application ID, iss enablebanking.com, aud api.enablebanking.com, 1 h) on every call; POST /auth → bank consent URL; POST /sessions with the code → session and consent valid_untilGET /sessions/{id}, GET /accounts/{uid}/details and /balances (booked balance preferred), GET /accounts/{uid}/transactions?date_from&date_to following continuation_key (status BOOK only; ID = entry_reference, else transaction_id, else a content hash)
mockActive at once; with an institution it returns an authorisation URL pointing straight to the callback (to exercise the consent flow locally)Two EUR accounts, 0–2 transactions per day derived from the account and the date (stable IDs, some remittances quote invoice numbers), 90-day consent

Wise strong customer authentication: balance statements of EU/UK profiles require SCA. Wise answers 403 with x-2fa-approval-result: REJECTED and a one-time token in x-2fa-approval; the provider signs it (RSA SHA-256, WISE_SCA_PRIVATE_KEY, whose public key must be uploaded in the Wise account settings) and replays the call with x-2fa-approval and X-Signature. Without a key the sync fails with ErrSCA.

Verified against fakes only

Both real providers are implemented from their public documentation and tested against httptest fakes of the documented endpoints (JWT and SCA signatures verified). They have not been exercised with real credentials: check field names (Wise statement details, Enable Banking accounts shape) and the Enable Banking redirect URL registration on the first real connection.

Connections​

Fields: id, site_id, provider, name, institution ({name, country}, aggregators), status (pending → active → expired | error, deleted), auth_url (while pending), expires_at (consent end, none for Wise tokens), last_sync_at, last_sync_error (consent | credentials | unavailable, never provider messages), created_by.

  • Credentials (Wise token, Enable Banking session ID) are sealed with cryptox.Keyring, subject = connection ID, and never returned. Deleting a connection revokes the provider session (best effort), crypto-shreds the key and soft-deletes the connection; its accounts become disconnected and keep their transactions.
  • Consent flow: the state is <connection id>.<32 random bytes>; only its SHA-256 is stored, valid BANK_CONSENT_STATE_TTL. The bank redirects the browser to BANK_REDIRECT_URL?code=…&state=… (a web page, because Enable Banking only accepts registered redirect URLs); the page reads the connection ID from the state and calls GET /v1/bank/connections/{id}/callback?code=&state=. ?error= from the bank answers 400 authorisation_failed.
  • Consent expiry: the lease job bank-sync-consents (every BANK_CONSENT_CHECK_INTERVAL) publishes bank.connection.consent_expiring once, BANK_CONSENT_NOTICE (7 days) before expires_at, and moves expired connections to expired with bank.connection.consent_expired. A provider refusing the consent during a sync has the same effect. Renewal = delete and recreate the connection.

Synchronisation​

The lease job bank-sync-run (every BANK_SYNC_INTERVAL, default 6 h) and POST /v1/bank/connections/{id}/sync synchronise active connections; a per-connection lease (bank-sync-connection-<id>, 30 min) prevents concurrent runs (409 sync_in_progress). For each provider account:

  1. upsert the account (connection_id + provider reference unique), masked IBAN, currency, balance snapshot;
  2. read transactions from synced_until - BANK_SYNC_OVERLAP (3 days, late bookings) or, on the first run, today - BANK_SYNC_LOOKBACK (90 days), to today;
  3. skip provider IDs already imported for the account (unique index account_id + provider_id), insert the new ones oldest first by batches of 500, each batch in one transaction with its bank.transaction.imported events and an audit record; the last batch advances synced_until.

Provider errors are recorded on the connection (last_sync_error) and do not stop the periodic run.

Authorization​

finance.account.read and finance.account.manage are sensitive (step-up). authz maps finance.account.* to the Permify entity finance_account, so:

ResourceCheck
accountfinance.account.read on atl:finance:<site>:account/<id>, parent atl:settings:<site>:site/<site>
connection (read)finance.account.read on the site ARN atl:settings:<site>:site/<site>
connection (create, delete, callback, sync)finance.account.manage on the site ARN
listsLookup scope of finance.account.read (sites; account IDs for accounts and transactions)

Connections have no Permify entity of their own: they are always checked at site level (their ARN atl:finance:<site>:connection/<id> is only the audit resource). Unreadable resources answer 404; step-up and admin-mode denials are returned as is. An empty Lookup scope (e.g. no step-up) yields an empty list, or the site check denial when site is given.

API​

All routes need an authenticated caller; see the API reference.

MethodPathDescription
GET/v1/bank/connections?site&statusconnections (ascending ID cursor)
POST/v1/bank/connections{site_id, provider, name, token?, institution?} → 201 (active or pending with auth_url)
GET/v1/bank/connections/{id}one connection
DELETE/v1/bank/connections/{id}revoke, shred, soft delete → 204
GET/v1/bank/connections/{id}/callback?code&statecomplete the consent flow
POST/v1/bank/connections/{id}/syncsynchronise now → {accounts, imported}
GET/v1/bank/accounts?site&connection&statusaccounts (ascending ID cursor)
GET/v1/bank/accounts/{id}one account
GET/v1/bank/transactions?site&account&from&to&directiontransactions, newest booking date first (cursor on booking date + ID)

Events​

DirectionTopicContent
outbank.transaction.v1bank.transaction.imported {transaction_id, account_id, site_id, amount_cents, currency, booking_date, counterparty, remittance} (subject = transaction ID)
outbank.connection.v1created, authorized, consent_expiring, consent_expired, deleted: {connection_id, site_id, provider, status, expires_at?}
outaudit.records.v1writes (bank.connection.create / authorize / delete / sync / expire / notify_expiring, bank.account.sync) and every read (bank.connection.list / read, bank.account.list / read, bank.transaction.list), IDs only

The contract names the consent events bank.consent.expiring / bank.consent.expired; they are published as bank.connection.consent_expiring / consent_expired so that they stay on bank.connection.v1 (the outbox derives the topic from the first two segments of the type).

Data (MongoDB bank)​

CollectionContent
connectionsconnections with the sealed credential and state hash
accountsaccounts (unique connection_id + ref)
transactionstransactions (unique account_id + provider_id; account_id / site_id + booking_date + _id)
data_keyskeyring data keys (one per connection, deleted on shred)
outbox, lockspending Kafka messages, leases

Configuration​

VariableDefaultDescription
HTTP_ADDR:8092Listen address
METRICS_ADDR:9192Prometheus listener
MONGO_URI, MONGO_DATABASEmongodb://localhost:27017/?directConnection=true, bankMongoDB
KAFKA_BROKERSlocalhost:19092Outbox relay
PRINCIPAL_PUBLIC_KEYrequiredVerifies X-Atl-Principal
AUTHZ_URLhttp://localhost:8081authz ConnectRPC
CRYPTO_KEK_SOURCE, CRYPTO_KEKenv, requiredKeyring KEK (or Barbican)
BANK_PROVIDERSmockenabled providers: mock, wise, enablebanking
BANK_SYNC_INTERVAL6hperiodic sync
BANK_SYNC_LOOKBACK2160hhistory read on the first sync
BANK_SYNC_OVERLAP72hre-read window before the last synced date
BANK_CONSENT_CHECK_INTERVAL1hconsent expiry job
BANK_CONSENT_NOTICE168hconsent_expiring notice
BANK_CONSENT_DURATION2160hconsent requested from aggregators (max 180 days)
BANK_CONSENT_STATE_TTL1htime to complete a consent flow
BANK_REDIRECT_URLhttp://localhost:3000/finance/bank/callbackweb callback page
BANK_HTTP_TIMEOUT30sprovider request timeout
WISE_API_URLhttps://api.wise.comsandbox: https://api.sandbox.transferwise.tech
WISE_SCA_PRIVATE_KEY—PEM (or base64 PEM) RSA key signing SCA challenges
ENABLEBANKING_API_URLhttps://api.enablebanking.comAPI base URL
ENABLEBANKING_APP_ID, ENABLEBANKING_PRIVATE_KEYrequired with enablebankingapplication ID (JWT kid) and its RSA private key (PEM or base64 PEM)
ENABLEBANKING_PSU_TYPEbusinessbusiness or personal

Plus the common APP_ENV, LOG_LEVEL, OTEL_EXPORTER_OTLP_ENDPOINT (see environment variables).