Add FinanceKit device publisher
Problem
The native Apple client can read authorized Wallet accounts, balances and transactions through FinanceKit, but Sure had no provider ingestion contract for it. The foreground-only draft in #3529 tied source identity to one enrollment and had no durable receipt, ordered replay, device replacement fence, repair generation, or explicit conflict workflow.
Result
This replaces that draft with FinanceKit publisher protocol 2 while retaining its reviewed financial and privacy guarantees.
The server contract is complete and does not wait on Apple. The client ships foreground sync first: the background delivery extension needs com.apple.developer.financekit granted to a second App ID (am.sure.insights.financekit-background), and it is iOS 26 only. Neither constrains this PR. The same wire format, durable inbox, receipts and conflict workflow serve a foreground "Sync now" and an unattended background wake identically, so the client can adopt the contract now and add the wake trigger later with no protocol change and no ledger migration. There is no background-only server work to split out — nothing here is exclusive to unattended delivery.
Publisher boundary
- Enrollment, account mapping, activation, repair, conflict resolution, and disconnect remain behind normal OAuth or API-key authentication, family scoping, admin checks, preview opt-in, and the FinanceKit family allowlist.
- Activation issues a high-entropy credential restricted to one publisher upload URL. Sure stores only its SHA-256 digest; the credential cannot read financial data or call another API.
- Publisher replacement reuses stable server account lineages, atomically revokes the prior writer, and preserves source transaction identities and tombstones.
Durable ingestion
- Uploads are immutable, byte-bounded protocol 2 batches identified by generation, stream, sequence, batch, capture, and chunk IDs. Captures are limited to 100 chunks so they fit in the bounded inbox.
- Every sequence after the first binds the exact predecessor payload digest, including every chunk within a capture. A failed chunk rolls back the capture, and retries honor every chunk’s backoff deadline.
- The server validates the full typed payload before storing its exact bytes and returns a stable 202 receipt. Identical response-loss retries return the same receipt; identity or sequence reuse with different bytes returns 409.
- The inbox accepts bounded out-of-order work but applies only the contiguous stream. Canonical changes, the applied receipt, and stream cursor commit atomically.
- Stream failures are split by whether a retry can succeed. Protocol violations and stored payload bytes that no longer parse are permanent: they revoke later batches and the publisher credential, and require an authenticated repair that creates a new generation and stream. Record validation failures retry under bounded exponential backoff and fence only after
Financekit::MAX_ATTEMPTS, because a cleared credential is recoverable only through a foreground, OAuth-authenticated repair — no background wake can reissue one, so a single lost race must not end ingestion. - A scheduled inbox sweep recovers lost jobs, retries downstream processing, and removes applied or revoked payload bytes after seven days.
Provider and financial behavior
- Stable
FinancekitAccountLineagerecords own canonical provider links across device replacement. - Balance observations are retained as typed history; only the newest booked value updates the account balance. Conflicting reuse of an observation identity cannot change either value.
- Transaction identity is lineage plus the FinanceKit source UUID. Imports disable heuristic amount/date matching.
- Same-ID pending-to-booked transitions remain supported. Different IDs are not silently merged.
- Omission never deletes data. Only explicit tombstones retract unprotected FinanceKit-owned entries.
- Protected edits, locks, splits, transfer pairs and fees, reconciliation, and source reappearance create durable conflicts exposed through authenticated list and resolution endpoints. Pending-to-booked settlement preserves user-edited ledger fields. Unresolved replacement identities remain blocked; explicit repair resolution allows eligible identities to retry.
retry_after_repairis an explicit, user-initiated fence: it resolves the conflict, clears the credential and revokes queued work, and is distinct from the automatic retry path above.
Privacy and operations
- Publisher credentials, consent, balance payloads, and event arrays are filtered from request diagnostics.
- Publisher upload and receipt endpoints are throttled by both IP and publisher ID in
rack_attack's credential-guessing section, alongside every other endpoint that checks a credential against a stored value. They sit outsideApi::V1::BaseController, so its per-key limiting never applies. Guessing a 256-bitSecureRandomtoken is infeasible; the limit bounds the row-locked validation work an accepted upload performs per publisher. - Device contact, durable acceptance, canonical import, and downstream completion have separate health timestamps.
- Family financial-data reset and user-family transfer account for publisher lineages and conflicts.
- OpenAPI schemas, fixtures, and client and operator documentation are updated for protocol 2. Review history and the standalone protocol narrative are retained in this PR rather than separate repository documents.
Review context
This keeps the strongest findings from #3529: whole-payload validation, exact decimal money, deterministic sign mapping, explicit account mapping, no heuristic transaction claiming, conservative tombstones, and family/admin authorization.
It adopts the durable inbox and ordering lessons from the earlier #3489 design without adding a custom JOSE envelope. TLS protects transport, the upload credential has narrow authority, financial bodies are redacted from diagnostics, and retained payload bytes have a bounded lifetime.
Related to #3485.
Known gaps, deliberately not addressed here
- No web UI. Enrollment, mapping, activation, repair and conflict resolution are API-only.
ProviderConnectionStatussurfaces a read-only health row; there is no_financekit_panel. A family that loses the publishing device can still revoke throughDELETE /api/v1/financekit/connections/{id}, but not from Sure's settings pages. Worth closing before the flag is enabled beyond a disposable test family. Payload.validate_batch!runs inside the accept row lock, andProcessor#apply_next!holds the same lock across a whole multi-chunk capture, so a device upload serialises behind an in-flight import for that item. Correct, and bounded to one family at preview scale; splitting item-independent from item-dependent validation is the fix if it ever matters.
Validation
Regression coverage verifies protected and reconciled entries, transfer pairs, pending settlement during review, conflict resolution followed by repair, replacement mapping retries, internal chunk digests, later-chunk retry deadlines, capture size limits, conflicting balance identities, and accepted/applied receipt schemas.
- Full Rails suite on
c9054fb7a: 9,358 tests, 37,906 assertions, zero failures, zero errors, 33 skips. - Ruby lint, Biome, Brakeman, API endpoint consistency, and
git diff --check: pass. - OpenAPI regenerated from documentation-only rswag specs: 444 examples, zero failures; 98 error-response examples deliberately skipped because behavior is tested in Minitest.
- ERB lint reports four pre-existing errors in unchanged
accounts/_account_sidebar_tabs,layouts/application, andpages/dashboard/_balance_sheettemplates. This change edits no ERB, JavaScript, CSS, or browser setup. - GitHub Actions on
c9054fb7a: all checks pass, including full unit/integration tests, browser system tests, Ruby and JavaScript lint, Ruby and JavaScript security scans, and Pipelock security scan.
Local tests use disposable PostgreSQL and Redis containers with this branch's schema. Native-client integration remains an alpha validation step; rollout stays behind preview opt-in and the FinanceKit family allowlist.
Alpha integration checks
- Enroll an allowlisted preview family, map accounts, activate, and complete a foreground native-client sync.
- Upload a capture with multiple chunks, retry identical requests after simulated response loss, and poll receipts through application.
- Confirm pending-to-booked transitions while user edits, reconciliations, locks, and transfer pairs retain their ledger values.
- Replace the publishing device and verify stable account/transaction identities and idempotent mapping retries.
- Resolve a conflict through
retry_after_repair, repair the publisher, and verify the next eligible capture imports successfully.
Documentation cleanup
Removed docs/api/financekit-review.md and docs/api/financekit.md in this PR. The client guide links to the generated OpenAPI reference and the operator guide. The schema source at docs/api/financekit/schemas.json remains required by OpenAPI generation and receipt validation. No deferred removal PR is needed for these two files.
The removed protocol narrative is preserved below for alpha integration context; the repository's OpenAPI reference and operator guide remain the maintained documentation.
Protocol 2 integration context
FinanceKit device publisher (protocol 2)
Related issue: #3485.
FinanceKit is modeled as a device publisher inside Sure's provider architecture. The iOS client reads explicitly authorized Apple Wallet accounts, persists an encrypted local outbox, and uploads bounded batches whenever iOS grants foreground or background execution. Sure remains the financial system of record after a batch is accepted and applied.
Foreground "Sync now" is sufficient for alpha testing. Background delivery is an optional client execution mode using the same server protocol.
The protocol deliberately separates two trust domains:
- Setup, account mapping, repair, conflict resolution, and disconnection use Sure's normal OAuth or
X-Api-Keyauthentication. - Batch upload uses a random, revocable credential restricted to one publisher URL. It cannot read financial data or call any other API.
TLS protects transport. The server stores only a SHA-256 digest of the publisher credential. Financial payloads are never written to request logs, receipts, or diagnostics.
Eligibility and discovery
GET /api/v1/financekit/capabilities requires read access. It reports protocol version 2, background_publisher delivery, and server limits. Enrollment and management require read_write, an active family administrator, preview opt-in, FINANCEKIT_ENABLED=true, and an exact family allowlist match.
The protocol 2 delivery value background_publisher names the device-publisher contract; it does not require or confirm background execution on the device. Foreground uploads use this same capability.
A disabled capability does not affect the caller's existing read-only Sure access.
Enrollment, mapping, and activation
- The client gets capabilities through the normal authenticated API.
- The user selects Wallet accounts and explicitly acknowledges family visibility and remote processing. The client sends that immutable consent record to
POST /connectionswith a stable enrollment UUID. - The client maps every selected FinanceKit account through
PUT /connections/{connection_id}/account_mappings/{source_id}. It must explicitly create a canonical account or link a writable same-family account with the same currency and type. POST /connections/{connection_id}/activatereturns the upload URL, publisher and stream identifiers, generation, stable account-lineage bindings, limits, and the one-purpose publisher credential. The plaintext credential is returned only when it is issued.
Enrollment and mapping requests are idempotent for identical input. Conflicting reuse returns 409. A canonical account can have only one FinanceKit lineage writer and cannot be silently claimed from another provider.
POST /credential rotates a lost publisher credential without changing the stream. POST /repair revokes queued work and credentials, increments the generation, and starts a new stream at sequence 1. DELETE /connections/{id} revokes publishing and releases provider links while retaining already imported ledger history.
A replacement device enrolls with replaces_connection_id, maps to the prior lineage, then activates. Activation atomically revokes the old publisher. Lineage-owned transaction identities and tombstones survive, so replacement does not duplicate or resurrect financial activity.
Ordered batch upload
POST /publishers/{publisher_id}/batches accepts application/json with the restricted bearer credential. The optional Idempotency-Key must equal batch_id; optional X-Sure-Payload-SHA256 must match the exact request bytes.
Each immutable batch contains:
- connection, publisher, generation, and stream identifiers;
- a monotonically increasing sequence;
- the previous batch's SHA-256 payload digest, except on sequence 1;
- capture and chunk identifiers and indexes;
- capture mode and completion metadata;
- the exact selected account scope; and
- up to 500 typed account, balance, transaction, or tombstone events.
The server validates the complete payload before durably storing the exact bytes and returns 202 with a stable receipt. Retrying the same batch bytes returns the same receipt. Reusing its batch ID or stream position with different bytes returns 409. Up to 100 batches may wait per publisher, allowing later batches to arrive before a missing sequence. A capture must contain at most 100 chunks; larger histories must be split into multiple captures. Oversized captures are rejected with 413 capture_limit before accepting any bytes into the inbox.
The inbox worker applies only the next contiguous batch whose predecessor digest matches. Canonical changes, the applied receipt, and the stream cursor commit in one database transaction. A crash before commit leaves the batch retryable; a crash after commit leaves an applied receipt. Permanent validation or stream failure fences the generation, revokes later queued batches and the credential, and requires explicit repair.
Payload bytes are removed seven days after application, permanent failure, or revocation. Digests, typed source identities, balance observations, tombstones, receipts, and audit-safe error codes remain.
Event and financial semantics
The client receives a stable lineage_id and mapping_version for every selected FinanceKit source account. Every event repeats that binding. The server rejects stale or foreign mappings before import.
Amounts are unsigned exact decimal strings with explicit currency and credit or debit direction. JSON numbers, negative magnitudes, exponent notation, unknown currencies, and precision overflow are rejected. Sure normalizes signs once:
- transaction debit is positive expense and credit is negative income;
- asset balance credit is money held and debit is overdraft;
- credit-card balance debit is debt and credit is overpayment.
Balance observations are append-only source history. Only the newest booked observation materializes the canonical account balance. Reusing an observation identity with different money fails with balance_observation_conflict and requires repair; it never changes the retained observation or canonical balance. Available balance never replaces booked balance.
Transaction identity is the stable account lineage plus the FinanceKit source UUID. The provider adapter disables heuristic amount/date matching. Same-ID pending-to-booked transitions are supported; a changed source UUID remains a separate identity. Source-only rejected and memo records do not invent ledger activity.
Omission never deletes data, even for a complete snapshot. Only an explicit transaction tombstone may retract an unprotected FinanceKit-owned entry. User-edited, locked, reconciled, split, transferred, or otherwise protected records create a durable conflict instead. Open conflicts requiring review are listed at GET /connections/{connection_id}/conflicts and resolved explicitly with PATCH /connections/{connection_id}/conflicts/{id}. keep_sure closes the conflict while preserving the Sure ledger entry; retry_after_repair closes the conflict, fences the publisher into repair_required, revokes queued work and credentials, and requires the authenticated client to call POST /repair before uploads can resume.
Health and recovery
GET /connections/{id} exposes separate timestamps for device contact, durable acceptance, canonical import, downstream scheduling, and capture time. This prevents a received batch from being presented as fully imported.
The client should handle responses as follows:
- 202: retain the receipt, then delete the matching local outbox batch.
- 401: stop uploads and use normal authentication to rotate the publisher credential.
- 403: publishing is revoked, ineligible, or requires repair; do not retry blindly.
- 409: stop the stream and fetch connection health. Repair when the server reports
repair_required. - 413: rebuild within the advertised byte and record limits.
- 429 or 503: retain the exact bytes and retry after
Retry-Afterwith bounded backoff.
OpenAPI schemas live in schemas.json and are loaded by spec/swagger_helper.rb.
Protocol 2 review and design history
FinanceKit protocol 2 design record
Protocol 2 replaces the foreground-only draft from PR #3529. It keeps the parts that review established as safe: family/admin and preview gates, explicit mapping, complete typed validation, exact decimal money, deterministic sign normalization, disabled heuristic matching, same-ID pending transitions, protected-record checks, and explicit tombstones.
The foreground draft was not sufficient for an iOS publisher. It coupled collection to a live user request, treated device-local FinanceKit IDs as if one enrollment owned them forever, could not acknowledge work durably before canonical import, and had no ordered replay, replacement fence, repair generation, or visible conflict workflow.
Protocol 2 adds:
- a background-compatible one-purpose publisher credential;
- durable immutable batches and stable receipts;
- generation, stream, sequence, predecessor digest, capture, and chunk metadata;
- a contiguous inbox worker with bounded retry and explicit repair;
- stable family account lineages across device replacement;
- append-only balance observations;
- durable protected-entry conflicts and an authenticated resolution API; and
- separate receipt, import, and downstream health.
The earlier PR #3489 demonstrated useful durable-inbox and ordering concepts, but protocol 2 does not adopt its custom JOSE envelope. TLS already protects transport, Sure controls both endpoints, and envelope cryptography would add key rotation and recovery failure modes without protecting data after server acceptance. The design instead narrows credential authority, stores only its digest, redacts financial bodies, validates exact bytes before persistence, and deletes accepted payload bytes after a bounded replay window.
The protocol does not infer deletion from a snapshot, merge changed FinanceKit transaction UUIDs, or let a background credential read from Sure. Those choices preserve deterministic source identity and keep destructive reconciliation explicit.
Summary by CodeRabbit
-
New Features
- Added FinanceKit background publishing with secure enrollment, account mapping, credential management, connection health, and capabilities discovery.
- Added durable, validated batch uploads with idempotent receipts, ordered processing, retries, downstream syncing, and support for account, balance, transaction, and tombstone events.
- Added conflict detection, resolution, repair workflows, and canonical account lineage management.
-
Documentation
- Added FinanceKit API schemas, protocol guidance, client integration details, and hosting requirements.
-
Security
- Expanded sensitive-parameter log filtering and access controls.