Open-source personal finance manager. Self-hosted, privacy-first.
fix(connections): don't report a slow bank import as a failed connection (#1199)
Shayn Hornik19f1434b92a6
diff --git a/charts/securo/templates/frontend/configmap-nginx.yaml b/charts/securo/templates/frontend/configmap-nginx.yamlindex a4941249..59e00738 100644--- a/charts/securo/templates/frontend/configmap-nginx.yaml+++ b/charts/securo/templates/frontend/configmap-nginx.yaml@@ -29,6 +29,20 @@ data:proxy_set_header X-Forwarded-Proto $scheme;}+ # Connecting a bank imports its whole history in this one request,+ # which can outlast nginx's default 60s read timeout (issue #1148).+ # Mirrors frontend/default.conf.template.+ location = /api/connections/oauth/callback {+ resolver ${NGINX_RESOLVER} valid=5s;+ set $upstream ${BACKEND_URL};+ proxy_pass $upstream;+ proxy_read_timeout 300s;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ }+# Never cache index.html so new deployments are always picked up immediatelylocation = /index.html {add_header Cache-Control "no-store, no-cache, must-revalidate";diff --git a/frontend/default.conf.template b/frontend/default.conf.templateindex 98c1a417..c9bcefae 100644--- a/frontend/default.conf.template+++ b/frontend/default.conf.template@@ -23,6 +23,21 @@ server {proxy_set_header X-Forwarded-Proto $scheme;}+ # Connecting a bank imports its whole history in this one request; a+ # SimpleFIN link with several institutions can take well over nginx's+ # default 60s read timeout, which turned a working import into a 504+ # "Failed to connect bank" (issue #1148).+ location = /api/connections/oauth/callback {+ resolver ${NGINX_RESOLVER} valid=5s;+ set $upstream ${BACKEND_URL};+ proxy_pass $upstream;+ proxy_read_timeout 300s;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ }+# Never cache index.html so new deployments are always picked up immediatelylocation = /index.html {add_header Cache-Control "no-store, no-cache, must-revalidate";diff --git a/frontend/src/components/token-connect-dialog.test.tsx b/frontend/src/components/token-connect-dialog.test.tsxnew file mode 100644index 00000000..2a33b2f5--- /dev/null+++ b/frontend/src/components/token-connect-dialog.test.tsx@@ -0,0 +1,74 @@+import { fireEvent, screen, waitFor } from '@testing-library/react'+import { AxiosError, AxiosHeaders } from 'axios'+import { beforeEach, expect, it, vi } from 'vitest'+import { renderWithProviders, t } from '@/test/utils'++const api = vi.hoisted(() => ({+ list: vi.fn(),+ handleCallback: vi.fn(),+ waitForNewConnection: vi.fn(),+ toastSuccess: vi.fn(),+ toastError: vi.fn(),+}))+vi.mock('@/lib/api', () => ({ connections: { list: api.list, handleCallback: api.handleCallback } }))+vi.mock('@/lib/await-new-connection', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/await-new-connection')>()),+ waitForNewConnection: api.waitForNewConnection,+}))+vi.mock('@/contexts/auth-context', () => ({ useAuth: () => ({ user: { id: 'me' } }) }))+vi.mock('sonner', () => ({ toast: { success: api.toastSuccess, error: api.toastError } }))++import { TokenConnectDialog } from './token-connect-dialog'++function gatewayTimeout(): AxiosError {+ const config = { headers: new AxiosHeaders() }+ return new AxiosError('timeout', undefined, config, undefined, {+ status: 504, statusText: 'Gateway Timeout', headers: {}, config, data: '<html>504</html>',+ })+}++function submit(onClose = vi.fn()) {+ renderWithProviders(<TokenConnectDialog open onClose={onClose} provider="simplefin" />)+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'setup-token' } })+ fireEvent.click(screen.getByRole('button', { name: t('accounts.tokenConnect.connect') }))+ return onClose+}++beforeEach(() => {+ vi.resetAllMocks()+ api.list.mockResolvedValue([{ id: 'existing', provider: 'simplefin' }])+})++it('reports success when a slow import outlasts the proxy and then lands (#1148)', async () => {+ api.handleCallback.mockRejectedValue(gatewayTimeout())+ api.waitForNewConnection.mockResolvedValue({ id: 'new', provider: 'simplefin' })++ const onClose = submit()++ await waitFor(() => expect(onClose).toHaveBeenCalled())+ expect(api.waitForNewConnection).toHaveBeenCalledWith('simplefin', new Set(['existing']), 'me')+ expect(api.toastSuccess).toHaveBeenCalledWith(t('accounts.connected'))+ expect(api.toastError).not.toHaveBeenCalled()+})++it('still reports the failure when no connection appears', async () => {+ api.handleCallback.mockRejectedValue(gatewayTimeout())+ api.waitForNewConnection.mockResolvedValue(null)++ const onClose = submit()++ await waitFor(() => expect(api.toastError).toHaveBeenCalledWith(t('accounts.connectError')))+ expect(onClose).not.toHaveBeenCalled()+})++it('does not wait on an error the backend itself returned', async () => {+ const config = { headers: new AxiosHeaders() }+ api.handleCallback.mockRejectedValue(new AxiosError('bad', undefined, config, undefined, {+ status: 400, statusText: '', headers: {}, config, data: { detail: 'Invalid token' },+ }))++ submit()++ await waitFor(() => expect(api.toastError).toHaveBeenCalledWith('Invalid token'))+ expect(api.waitForNewConnection).not.toHaveBeenCalled()+})diff --git a/frontend/src/components/token-connect-dialog.tsx b/frontend/src/components/token-connect-dialog.tsxindex 321205b1..e726b552 100644--- a/frontend/src/components/token-connect-dialog.tsx+++ b/frontend/src/components/token-connect-dialog.tsx@@ -2,7 +2,9 @@ import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import { useQueryClient } from '@tanstack/react-query'import axios from 'axios'+import { useAuth } from '@/contexts/auth-context'import { connections } from '@/lib/api'+import { isGatewayTimeout, waitForNewConnection } from '@/lib/await-new-connection'import { invalidateFinancialQueries } from '@/lib/invalidate-queries'import {Dialog,@@ -35,6 +37,7 @@ export function TokenConnectDialog({reconnectConnectionId,}: TokenConnectDialogProps) {const { t } = useTranslation()+ const { user } = useAuth()const queryClient = useQueryClient()const [token, setToken] = useState('')const [submitting, setSubmitting] = useState(false)@@ -55,6 +58,21 @@ export function TokenConnectDialog({const handleSubmit = async () => {if (!token.trim()) returnsetSubmitting(true)+ const onConnected = () => {+ invalidateFinancialQueries(queryClient)+ queryClient.invalidateQueries({ queryKey: ['connections'] })+ toast.success(t(isReconnect ? 'accounts.reconnected' : 'accounts.connected'))+ onClose()+ }+ // Connections that already exist, so a slow import that outlasts a proxy+ // timeout can still be recognised when it lands.+ const userId = user?.id+ const knownIds = isReconnect || !userId+ ? null+ : await connections.list().then(+ (list) => new Set(list.map((c) => c.id)),+ () => null,+ )try {await connections.handleCallback(token.trim(),@@ -63,11 +81,12 @@ export function TokenConnectDialog({supportsAssetSync && !isReconnect ? { sync_assets: syncAssets } : undefined,reconnectConnectionId,)- invalidateFinancialQueries(queryClient)- queryClient.invalidateQueries({ queryKey: ['connections'] })- toast.success(t(isReconnect ? 'accounts.reconnected' : 'accounts.connected'))- onClose()+ onConnected()} catch (err) {+ if (knownIds && isGatewayTimeout(err) && userId && (await waitForNewConnection(provider, knownIds, userId))) {+ onConnected()+ return+ }const detail =axios.isAxiosError(err) && err.response?.data?.detail? typeof err.response.data.detail === 'string'@@ -139,7 +158,9 @@ export function TokenConnectDialog({disabled={submitting}/><p className="text-xs text-muted-foreground">- {t('accounts.tokenConnect.tokenHelp')}+ {submitting && !isReconnect+ ? t('accounts.oauthCallback.linking')+ : t('accounts.tokenConnect.tokenHelp')}</p></div>diff --git a/frontend/src/lib/await-new-connection.test.ts b/frontend/src/lib/await-new-connection.test.tsnew file mode 100644index 00000000..e08a498e--- /dev/null+++ b/frontend/src/lib/await-new-connection.test.ts@@ -0,0 +1,92 @@+import { AxiosError, AxiosHeaders } from 'axios'+import { describe, expect, it, vi } from 'vitest'+import type { BankConnection } from '@/types'+import { isGatewayTimeout, waitForNewConnection } from './await-new-connection'++function axiosError(status?: number): AxiosError {+ const config = { headers: new AxiosHeaders() }+ return new AxiosError(+ 'failed',+ undefined,+ config,+ undefined,+ status === undefined ? undefined : { status, statusText: '', headers: {}, config, data: {} },+ )+}++const conn = (id: string, provider = 'simplefin', user_id = 'me') =>+ ({ id, provider, user_id }) as BankConnection++describe('isGatewayTimeout', () => {+ it('is true when no response came back or a gateway gave up', () => {+ expect(isGatewayTimeout(axiosError())).toBe(true)+ expect(isGatewayTimeout(axiosError(502))).toBe(true)+ expect(isGatewayTimeout(axiosError(504))).toBe(true)+ })++ it('is false for an answer from the backend itself', () => {+ expect(isGatewayTimeout(axiosError(400))).toBe(false)+ expect(isGatewayTimeout(axiosError(500))).toBe(false)+ expect(isGatewayTimeout(new Error('boom'))).toBe(false)+ })+})++describe('waitForNewConnection', () => {+ it('returns the connection that appears after the timeout', async () => {+ const list = vi+ .fn()+ .mockResolvedValueOnce([conn('old')])+ .mockRejectedValueOnce(new Error('504'))+ .mockResolvedValueOnce([conn('old'), conn('other', 'pluggy'), conn('new')])++ const found = await waitForNewConnection('simplefin', new Set(['old']), 'me', {+ intervalMs: 1,+ timeoutMs: 1000,+ list,+ })++ expect(found?.id).toBe('new')+ expect(list).toHaveBeenCalledTimes(3)+ })++ it('gives up with null when two new connections make it ambiguous', async () => {+ const list = vi.fn().mockResolvedValue([conn('old'), conn('mine'), conn('theirs')])++ const found = await waitForNewConnection('simplefin', new Set(['old']), 'me', {+ intervalMs: 1,+ timeoutMs: 1000,+ list,+ })++ expect(found).toBeNull()+ expect(list).toHaveBeenCalledTimes(1)+ })++ it('gives up with null when nothing new appears', async () => {+ const list = vi.fn().mockResolvedValue([conn('old'), conn('other', 'pluggy')])++ const found = await waitForNewConnection('simplefin', new Set(['old']), 'me', {+ intervalMs: 1,+ timeoutMs: 20,+ list,+ })++ expect(found).toBeNull()+ })++ it('ignores a connection another workspace member added meanwhile', async () => {+ const list = vi+ .fn()+ .mockResolvedValueOnce([conn('old'), conn('teammate', 'simplefin', 'someone-else')])+ .mockResolvedValueOnce([conn('old'), conn('teammate', 'simplefin', 'someone-else'), conn('new')])++ const found = await waitForNewConnection('simplefin', new Set(['old']), 'me', {+ intervalMs: 1,+ timeoutMs: 1000,+ list,+ })++ expect(found?.id).toBe('new')+ expect(list).toHaveBeenCalledTimes(2)+ })+})diff --git a/frontend/src/lib/await-new-connection.ts b/frontend/src/lib/await-new-connection.tsnew file mode 100644index 00000000..21464c0b--- /dev/null+++ b/frontend/src/lib/await-new-connection.ts@@ -0,0 +1,45 @@+import axios from 'axios'+import { connections } from '@/lib/api'+import type { BankConnection } from '@/types'++// A gateway or proxy gave up on the request (no response at all, or a+// 502/503/504) — the backend may still be working on it and finish.+export function isGatewayTimeout(err: unknown): boolean {+ if (!axios.isAxiosError(err)) return false+ if (!err.response) return true+ return [502, 503, 504].includes(err.response.status)+}++// Connecting a bank imports its history inside the callback request, which+// can outlast a proxy's timeout while the import itself succeeds (issue+// #1148). Poll the connection list until a connection for `provider` that+// `userId` owns and that wasn't in `knownIds` appears; null once `timeoutMs`+// passes without one. Connections other workspace members add in the+// meantime don't count. The client can't tell which connection its own+// request created, so when more than one new one shows up (the same user+// connected twice at once) it gives up with null rather than claim one.+export async function waitForNewConnection(+ provider: string,+ knownIds: ReadonlySet<string>,+ userId: string,+ {+ intervalMs = 5000,+ timeoutMs = 180_000,+ list = connections.list,+ }: { intervalMs?: number; timeoutMs?: number; list?: () => Promise<BankConnection[]> } = {},+): Promise<BankConnection | null> {+ const deadline = Date.now() + timeoutMs+ while (Date.now() < deadline) {+ await new Promise((resolve) => setTimeout(resolve, intervalMs))+ try {+ const added = (await list()).filter(+ (c) => c.provider === provider && c.user_id === userId && !knownIds.has(c.id),+ )+ if (added.length === 1) return added[0]+ if (added.length > 1) return null+ } catch {+ // The list can fail for the same reason the callback did; keep trying.+ }+ }+ return null+}