Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

fix(enable-banking): mark connections expired when the bank ends consent (#1108)

Carlos Ferrús Ferriae9433297104
diff --git a/backend/app/providers/enable_banking.py b/backend/app/providers/enable_banking.py
index d2570962..d6538222 100644
--- a/backend/app/providers/enable_banking.py
+++ b/backend/app/providers/enable_banking.py
@@ -54,6 +54,10 @@ DEFAULT_HISTORY_DAYS = 90
# Shorter window retried when a bank rejects the default one as out of bounds.
FALLBACK_HISTORY_DAYS = 30
TRANSACTION_PAGE_LIMIT = 50 # safety cap
+# Session states after which no data can be read until the user re-authorizes.
+TERMINAL_SESSION_STATUSES = frozenset(
+ {"EXPIRED", "REVOKED", "CLOSED", "CANCELLED", "INVALID"}
+)
def _map_cash_account_type(eb_type: Optional[str]) -> str:
@@ -568,6 +572,13 @@ class EnableBankingProvider(BankProvider):
if not session_id:
raise SessionExpiredError("Enable Banking session_id missing")
data = await self._request("GET", f"/sessions/{session_id}")
+ # The bank can end consent well before `valid_until`; EB still answers
+ # 200 here but flags the session, and every account call then fails.
+ # Raise so the connection is marked expired instead of "syncing" zero
+ # accounts forever.
+ status = (data.get("status") or "").upper()
+ if status in TERMINAL_SESSION_STATUSES:
+ raise SessionExpiredError(f"Enable Banking session is {status}")
uids = self._account_uids(data)
# EB keys each account by a uid scoped to this session; the
# identification_hash is the id that survives a reauthorisation. It comes
diff --git a/backend/tests/test_providers_enable_banking.py b/backend/tests/test_providers_enable_banking.py
index 34e3a9fe..75ed730f 100644
--- a/backend/tests/test_providers_enable_banking.py
+++ b/backend/tests/test_providers_enable_banking.py
@@ -829,3 +829,102 @@ def test_txn_fingerprint_includes_transaction_date():
assert fp1 != fp2
+
+
+# ----- session status on sync -----
+
+
+def _session_payload(status: str) -> dict:
+ """GET /sessions/{id} as Enable Banking returns it (account uids only).
+
+ `valid_until` is always in the future: the status alone must decide."""
+ valid_until = (
+ (datetime.now(timezone.utc) + timedelta(days=180))
+ .replace(microsecond=0)
+ .isoformat()
+ .replace("+00:00", "Z")
+ )
+ return {
+ "status": status,
+ "accounts": ["acc-uid-1"],
+ "accounts_data": [{"uid": "acc-uid-1", "identification_hash": "hash-1"}],
+ "aspsp": {"name": "Openbank", "country": "ES"},
+ "access": {"valid_until": valid_until},
+ }
+
+
+async def test_get_accounts_raises_when_session_expired_at_bank(eb_keys):
+ """The bank can end consent long before `valid_until`. EB then still
+ answers GET /sessions with 200 but `status: EXPIRED`, and every account
+ call fails with a 400 ASPSP_ERROR. That must surface as an expired
+ session, not as a sync that silently finds no accounts."""
+ provider = EnableBankingProvider()
+ details_calls: list[str] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ if request.url.path == "/sessions/sess-1":
+ return httpx.Response(200, json=_session_payload("EXPIRED"))
+ details_calls.append(request.url.path)
+ return httpx.Response(
+ 400,
+ json={
+ "code": 400,
+ "message": "Error interacting with ASPSP",
+ "detail": {"message": "Unauthorized, authentication failure"},
+ "error": "ASPSP_ERROR",
+ },
+ )
+
+ with _patch_client(provider, handler):
+ with pytest.raises(SessionExpiredError):
+ await provider.get_accounts({"session_id": "sess-1"})
+ assert details_calls == []
+
+
[email protected]("status", ["REVOKED", "CLOSED", "CANCELLED", "INVALID"])
+async def test_get_accounts_raises_for_other_terminal_session_states(eb_keys, status):
+ provider = EnableBankingProvider()
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json=_session_payload(status))
+
+ with _patch_client(provider, handler):
+ with pytest.raises(SessionExpiredError):
+ await provider.get_accounts({"session_id": "sess-1"})
+
+
+async def test_get_accounts_authorized_session_returns_accounts(eb_keys):
+ provider = EnableBankingProvider()
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ if path == "/sessions/sess-1":
+ return httpx.Response(200, json=_session_payload("AUTHORIZED"))
+ if path == "/accounts/acc-uid-1/details":
+ return httpx.Response(
+ 200,
+ json={
+ "uid": "acc-uid-1",
+ "name": "CUENTA CORRIENTE",
+ "currency": "EUR",
+ "cash_account_type": "CACC",
+ "account_id": {"iban": "ES0000000000000000001172"},
+ },
+ )
+ if path == "/accounts/acc-uid-1/balances":
+ return httpx.Response(
+ 200,
+ json={"balances": [{
+ "balance_type": "CLBD",
+ "balance_amount": {"amount": "859.43", "currency": "EUR"},
+ }]},
+ )
+ return httpx.Response(404)
+
+ with _patch_client(provider, handler):
+ accounts = await provider.get_accounts({"session_id": "sess-1"})
+ assert [a.external_id for a in accounts] == ["acc-uid-1"]
+ assert accounts[0].balance == Decimal("859.43")