Skip to content

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

fix(enable-banking): match accounts by a stable id so reauth cannot duplicate (#1106)

José Gázquez86c94a9539c7
diff --git a/backend/alembic/versions/097_account_stable_external_id.py b/backend/alembic/versions/097_account_stable_external_id.py
new file mode 100644
index 00000000..a830e1bd
--- /dev/null
+++ b/backend/alembic/versions/097_account_stable_external_id.py
@@ -0,0 +1,36 @@
+"""add stable_external_id to accounts (Enable Banking reauth duplication)
+
+Revision ID: 097
+Revises: 096
+Create Date: 2026-10-02
+
+Enable Banking identifies an account by a `uid` that is scoped to a single
+session, so reauthorising (which mints a new session) hands back a new uid for
+the same real account. The sync matched accounts only on `external_id`, so it
+inserted a second row and left the original — with its transactions, rules and
+name overrides — behind.
+
+EB publishes an `identification_hash` precisely to match the same account across
+sessions. Persist it here so the sync can rebind the existing row to the new uid
+instead of duplicating.
+
+Additive and nullable: existing rows are unaffected and backfill themselves on
+the next sync, since `stable_external_id` is provider-owned like `masked_number`.
+"""
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "097"
+down_revision: Union[str, None] = "096"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.add_column("accounts", sa.Column("stable_external_id", sa.String(255), nullable=True))
+
+
+def downgrade() -> None:
+ op.drop_column("accounts", "stable_external_id")
diff --git a/backend/app/models/account.py b/backend/app/models/account.py
index f8ffc664..d930f0fc 100644
--- a/backend/app/models/account.py
+++ b/backend/app/models/account.py
@@ -24,6 +24,10 @@ class Account(Base):
UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True
)
connection_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("bank_connections.id"), nullable=True)
+ # The provider's id for this account, and the first key the sync matches on.
+ # Expected to be stable across re-syncs, but not guaranteed: Enable Banking
+ # mints a `uid` scoped to a single session, so it is re-keyed on every
+ # reauthorisation. `stable_external_id` is the value that survives that.
external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
name: Mapped[str] = mapped_column(String(255))
display_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
@@ -31,6 +35,12 @@ class Account(Base):
# the provider exposes one. Provider-owned like `name`: refreshed on sync,
# not user-editable. Never holds the full identifier.
masked_number: Mapped[Optional[str]] = mapped_column(String(4), nullable=True)
+ # Provider-owned and session-independent (Enable Banking's
+ # identification_hash): the durable half of the pair with `external_id`. It
+ # survives that being re-keyed, so the sync matches on it to avoid
+ # duplicating the account after a reconnect. Refreshed alongside `name`,
+ # never blanked by a missing value.
+ stable_external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
type: Mapped[str] = mapped_column(String(50)) # checking, savings, credit_card
balance: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0.00"))
currency: Mapped[str] = mapped_column(String(3), default="USD")
diff --git a/backend/app/providers/base.py b/backend/app/providers/base.py
index b173db56..10810f38 100644
--- a/backend/app/providers/base.py
+++ b/backend/app/providers/base.py
@@ -55,6 +55,11 @@ def mask_last4(value: Optional[str]) -> Optional[str]:
@dataclass
class AccountData:
+ # The provider's identifier for this account. It is expected to be stable
+ # across re-syncs, and the sync matches an incoming account on it first. A
+ # provider that re-keys it — Enable Banking mints a `uid` scoped to a single
+ # session — must also set `stable_external_id`, or re-syncing inserts a
+ # duplicate instead of recognising the account it already imported.
external_id: str
name: str
type: str # checking, savings, credit_card
@@ -71,6 +76,12 @@ class AccountData:
# identical name (issue #408). Never the full identifier — see mask_last4.
masked_number: Optional[str] = None
shared_balance_group: Optional[str] = None
+ # The provider's session-independent identifier for this account, when it
+ # offers one. See `external_id` above: it is *supposed* to be stable, and
+ # Enable Banking is the provider that breaks that. This is the value that
+ # survives (EB's `identification_hash`), and the sync uses it to rebind the
+ # existing row to the new uid instead of duplicating the account.
+ stable_external_id: Optional[str] = None
# Per-account institution override (SimpleFIN — issue #345). None = same
# as connection. The external id is the provider's stable org id
# (SimpleFIN conn_id) so a renamed bank updates its row instead of
diff --git a/backend/app/providers/enable_banking.py b/backend/app/providers/enable_banking.py
index 67dbb751..46a642b1 100644
--- a/backend/app/providers/enable_banking.py
+++ b/backend/app/providers/enable_banking.py
@@ -497,7 +497,9 @@ class EnableBankingProvider(BankProvider):
return inst.logo
return None
- async def _build_account(self, raw: dict) -> AccountData:
+ async def _build_account(
+ self, raw: dict, stable_external_id: Optional[str] = None
+ ) -> AccountData:
uid = raw.get("uid") or raw.get("account_uid") or ""
currency = raw.get("currency") or "EUR"
# EB doesn't include balances in the session payload; fetch separately.
@@ -524,6 +526,9 @@ class EnableBankingProvider(BankProvider):
balance=balance,
currency=currency,
masked_number=mask_last4(_account_identifier(raw)),
+ # From the session payload: `uid` is scoped to one session, this
+ # hash is what lets a later session find the same account again.
+ stable_external_id=stable_external_id,
)
# ----- account / transaction fetches -----
@@ -563,19 +568,31 @@ class EnableBankingProvider(BankProvider):
if not session_id:
raise SessionExpiredError("Enable Banking session_id missing")
data = await self._request("GET", f"/sessions/{session_id}")
+ 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
+ # in the same payload we just fetched, so carry it through — otherwise a
+ # reconnect re-keys every account and the sync duplicates them all.
+ stable_external_ids = {
+ entry.get("uid"): entry.get("identification_hash")
+ for entry in (data.get("accounts_data") or [])
+ if isinstance(entry, dict) and entry.get("uid")
+ }
result: list[AccountData] = []
- for uid in self._account_uids(data):
+ for uid in uids:
try:
details = await self._request("GET", f"/accounts/{uid}/details")
- except (httpx.HTTPError, SessionExpiredError) as exc:
- # Without details we can't safely name/type the account, and a
- # bare-uid AccountData would overwrite the stored name with a
- # placeholder. Skip this account for this run (non-destructive:
- # the existing row and its transactions are left intact and the
- # next sync retries) rather than corrupt it.
+ except httpx.HTTPError as exc:
+ # A *transient* per-account failure. Without details we can't
+ # safely name/type the account, and a bare-uid AccountData would
+ # overwrite the stored name with a placeholder. Skip this account
+ # for this run (non-destructive: the existing row and its
+ # transactions are left intact and the next sync retries) rather
+ # than corrupt it. SessionExpiredError is deliberately NOT caught
+ # here: a dead consent is global, never per-account.
logger.warning("Failed to fetch details for account %s: %s", uid, exc)
continue
- result.append(await self._build_account(details))
+ result.append(await self._build_account(details, stable_external_ids.get(uid)))
return result
async def get_transactions(
diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.py
index 52af8508..6e7737be 100644
--- a/backend/app/services/connection_service.py
+++ b/backend/app/services/connection_service.py
@@ -1327,9 +1327,59 @@ async def _find_existing_connected_account(
)
)
account = result.scalar_one_or_none()
- if account or connection.provider != "simplefin":
+ if account is not None:
return account
+ # The provider re-keyed this account. Enable Banking issues a `uid` scoped to
+ # one session, so reauthorising changes it while `stable_external_id` (the
+ # identification_hash) survives. Rebind the existing row — keeping its
+ # transactions, rules and name overrides — instead of inserting a duplicate.
+ # EB does not guarantee the hash is unique, so require exactly one unclaimed
+ # candidate: a row another incoming account already took in this run carries
+ # an external_id that is in the batch, and adopting it a second time would
+ # put both transaction feeds on one account.id.
+ if acc_data.stable_external_id:
+ stable_rows = (await session.execute(
+ select(Account).where(
+ Account.connection_id == connection.id,
+ Account.stable_external_id == acc_data.stable_external_id,
+ )
+ )).scalars().all()
+ stable_rows = [
+ row for row in stable_rows if row.external_id not in incoming_external_ids
+ ]
+ if len(stable_rows) > 1:
+ return None
+ if len(stable_rows) == 1:
+ stable_rows[0].external_id = acc_data.external_id
+ return stable_rows[0]
+
+ # Last resort for rows that predate `stable_external_id` (added by migration
+ # 097, and only ever backfilled by a *successful* sync — which a user whose
+ # bank was failing never had). The masked identifier is the closest thing to
+ # an account number we keep. Two guards, both fail-closed: a single candidate
+ # (a shared last-4 must never merge two accounts), and candidates limited to
+ # rows with no stable id — a row that is already identified is a different
+ # account, so adopting it would overwrite its identity and mix histories.
+ if connection.provider == "enable_banking" and acc_data.masked_number:
+ masked_rows = (await session.execute(
+ select(Account).where(
+ Account.connection_id == connection.id,
+ Account.masked_number == acc_data.masked_number,
+ Account.currency == acc_data.currency,
+ Account.stable_external_id.is_(None),
+ )
+ )).scalars().all()
+ masked_rows = [
+ row for row in masked_rows if row.external_id not in incoming_external_ids
+ ]
+ if len(masked_rows) == 1:
+ masked_rows[0].external_id = acc_data.external_id
+ return masked_rows[0]
+
+ if connection.provider != "simplefin":
+ return None
+
normalized_name = _normalized_account_name(acc_data.name)
if not normalized_name:
return None
@@ -2077,6 +2127,11 @@ async def sync_connection(
# that intermittently omits it can't blank out a known mask.
if acc_data.masked_number is not None:
account.masked_number = acc_data.masked_number
+ # Backfills existing accounts on their next sync, same rule as
+ # masked_number: provider-owned, and a payload that omits it
+ # must not blank a value that is already known.
+ if acc_data.stable_external_id is not None:
+ account.stable_external_id = acc_data.stable_external_id
# Backfills existing accounts on next sync (issue #345).
if institution is not None:
account.institution_id = institution.id
@@ -2115,6 +2170,7 @@ async def sync_connection(
workspace_id=workspace_id,
connection_id=connection.id,
external_id=acc_data.external_id,
+ stable_external_id=acc_data.stable_external_id,
name=acc_data.name,
display_name=institution.name if institution else None,
masked_number=acc_data.masked_number,
diff --git a/backend/tests/test_connection_service.py b/backend/tests/test_connection_service.py
index 84fe6e56..3bcb3f70 100644
--- a/backend/tests/test_connection_service.py
+++ b/backend/tests/test_connection_service.py
@@ -1052,6 +1052,140 @@ async def test_simplefin_rekey_respects_institution_and_closed_account(
assert customized_bank_b.external_id == "old-bank-b"
+async def test_find_existing_connected_account_refuses_ambiguous_masked_number(
+ session: AsyncSession, test_user, test_workspace,
+):
+ """A shared last-4 must never merge two different accounts.
+
+ Four digits collide (two accounts at one bank can both end 5531). When more
+ than one legacy row matches we refuse to guess: a duplicate is recoverable,
+ but transactions attached to the wrong account are not.
+ """
+ conn = await _make_connection(session, test_user.id, "AmbiguousBank")
+ for suffix in ("a", "b"):
+ session.add(Account(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ connection_id=conn.id,
+ external_id=f"old-{suffix}",
+ masked_number="5531",
+ name=f"Cuenta {suffix}",
+ type="checking",
+ balance=Decimal("0"),
+ currency="EUR",
+ ))
+ await session.flush()
+
+ matched = await _find_existing_connected_account(
+ session,
+ conn,
+ AccountData(
+ external_id="new-uid",
+ name="Cuenta a",
+ type="checking",
+ balance=Decimal("0"),
+ currency="EUR",
+ masked_number="5531",
+ ),
+ None,
+ {"new-uid"},
+ )
+
+ assert matched is None
+
+
+async def test_find_existing_connected_account_does_not_rebind_a_claimed_stable_external_id(
+ session: AsyncSession, test_user, test_workspace,
+):
+ """A stable id already claimed in this run must not be adopted twice.
+
+ Enable Banking does not guarantee `identification_hash` is unique. If two
+ incoming accounts carry the same hash, the first can claim a row by
+ external_id and the second would then rebind that same row, storing both
+ transaction feeds against one account.id.
+ """
+ conn = await _make_connection(session, test_user.id, "SharedHashBank")
+ claimed = Account(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ connection_id=conn.id,
+ external_id="uid-b1",
+ stable_external_id="hash-shared",
+ name="A",
+ type="checking",
+ balance=Decimal("0"),
+ currency="EUR",
+ )
+ session.add(claimed)
+ await session.flush()
+
+ matched = await _find_existing_connected_account(
+ session,
+ conn,
+ AccountData(
+ external_id="uid-b2",
+ name="B",
+ type="checking",
+ balance=Decimal("0"),
+ currency="EUR",
+ stable_external_id="hash-shared",
+ ),
+ None,
+ {"uid-b1", "uid-b2"},
+ )
+
+ assert matched is None
+
+
+async def test_find_existing_connected_account_masked_fallback_skips_rows_with_a_stable_external_id(
+ session: AsyncSession, test_user, test_workspace,
+):
+ """The masked fallback is for legacy rows only, never for identified ones.
+
+ When a persisted account's details request is skipped (partial provider
+ failure) and a *different* account surfaces with the same masked number and
+ currency, the fallback would rebind the skipped row and overwrite its stable
+ id — mixing two account histories. Rows that already carry a stable id are
+ identified, so they must be out of scope for the fallback.
+ """
+ conn = await _make_connection(session, test_user.id, "MaskedBank")
+ identified = Account(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ connection_id=conn.id,
+ external_id="old-uid",
+ stable_external_id="hash-old",
+ masked_number="5531",
+ name="Cuenta vieja",
+ type="checking",
+ balance=Decimal("0"),
+ currency="EUR",
+ )
+ session.add(identified)
+ await session.flush()
+
+ matched = await _find_existing_connected_account(
+ session,
+ conn,
+ AccountData(
+ external_id="new-uid",
+ name="Cuenta nueva",
+ type="checking",
+ balance=Decimal("0"),
+ currency="EUR",
+ masked_number="5531",
+ stable_external_id="hash-new",
+ ),
+ None,
+ {"new-uid"},
+ )
+
+ assert matched is None
+
+
@pytest.mark.asyncio
async def test_simplefin_rekey_reserves_ids_from_later_accounts(
session: AsyncSession, test_user, test_workspace,
diff --git a/backend/tests/test_connection_service_coverage.py b/backend/tests/test_connection_service_coverage.py
index 55414276..e3e68a7b 100644
--- a/backend/tests/test_connection_service_coverage.py
+++ b/backend/tests/test_connection_service_coverage.py
@@ -580,6 +580,191 @@ async def test_sync_fuzzy_matches_manual_transaction(session: AsyncSession, test
assert manual.payee == "Starbucks"
+async def test_sync_rematches_rekeyed_account_by_stable_external_id(
+ session: AsyncSession, test_user, test_workspace,
+):
+ """Reauthorising a provider re-keys its accounts; reuse the row, don't duplicate.
+
+ Enable Banking's `uid` is scoped to a single session, so reauth hands back a
+ new uid for the same real account. Matching only on external_id inserted a
+ second account row and left the original (with its transactions) behind.
+ `identification_hash` survives the reauth, so the sync must rebind the
+ existing row to the new uid.
+ """
+ conn = await _make_connection(session, test_user.id, "ReauthBank")
+ conn_id, workspace_id, user_id = conn.id, test_workspace.id, test_user.id
+ existing = Account(
+ id=uuid.uuid4(), user_id=user_id, workspace_id=workspace_id,
+ connection_id=conn_id, external_id="old-uid", stable_external_id="hash-1",
+ name="Checking", type="checking", balance=Decimal("10"), currency="EUR",
+ )
+ session.add(existing)
+ await session.commit()
+
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock_provider.get_accounts = AsyncMock(return_value=[
+ AccountData(external_id="new-uid", stable_external_id="hash-1", name="Checking",
+ type="checking", balance=Decimal("25"), currency="EUR"),
+ ])
+ mock_provider.get_transactions = AsyncMock(return_value=[])
+
+ p1, p2, p3 = _patch_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn_id, workspace_id, user_id)
+
+ rows = (await session.execute(
+ select(Account).where(Account.connection_id == conn_id)
+ )).scalars().all()
+ assert len(rows) == 1, f"re-keyed account was duplicated: {len(rows)} rows"
+ assert rows[0].id == existing.id
+ assert rows[0].external_id == "new-uid"
+ assert rows[0].stable_external_id == "hash-1"
+
+
+async def test_sync_rematches_legacy_account_by_masked_number(
+ session: AsyncSession, test_user, test_workspace,
+):
+ """Rows predating `stable_external_id` must survive a reauth too.
+
+ A user whose bank was failing never had a stable_external_id backfilled — the sync
+ that would have done it is the one that was failing. When the bank recovers
+ after a reconnect the uid is new and the hash is unknown to us, so the
+ masked identifier is the last thing that still identifies the account.
+ Match on it rather than insert a duplicate.
+ """
+ conn = await _make_connection(session, test_user.id, "LegacyBank")
+ conn.provider = "enable_banking"
+ conn_id, workspace_id, user_id = conn.id, test_workspace.id, test_user.id
+ existing = Account(
+ id=uuid.uuid4(), user_id=user_id, workspace_id=workspace_id,
+ connection_id=conn_id, external_id="old-uid", stable_external_id=None,
+ masked_number="5531", name="CUENTA CORRIENTE", type="checking",
+ balance=Decimal("10"), currency="EUR",
+ )
+ session.add(existing)
+ await session.commit()
+
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock_provider.get_accounts = AsyncMock(return_value=[
+ AccountData(external_id="new-uid", stable_external_id="hash-1", masked_number="5531",
+ name="CUENTA CORRIENTE", type="checking",
+ balance=Decimal("25"), currency="EUR"),
+ ])
+ mock_provider.get_transactions = AsyncMock(return_value=[])
+
+ p1, p2, p3 = _patch_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn_id, workspace_id, user_id)
+
+ rows = (await session.execute(
+ select(Account).where(Account.connection_id == conn_id)
+ )).scalars().all()
+ assert len(rows) == 1, f"legacy account was duplicated: {len(rows)} rows"
+ assert rows[0].id == existing.id
+ assert rows[0].external_id == "new-uid"
+ # The sync also backfills the hash it just learned, so the next reauth
+ # matches on the exact id instead of falling back to the mask.
+ assert rows[0].stable_external_id == "hash-1"
+
+
+async def test_sync_ambiguous_stable_external_id_does_not_match(
+ session: AsyncSession, test_user, test_workspace,
+):
+ """Two unclaimed rows with the same stable_external_id must not match.
+
+ EB does not guarantee the hash is unique. If two rows share the same
+ stable_external_id, the sync must fail closed (return None) rather than
+ fall through to the masked-number tier, which could merge unrelated
+ account histories.
+ """
+ conn = await _make_connection(session, test_user.id, "AmbiguousBank")
+ conn_id, workspace_id, user_id = conn.id, test_workspace.id, test_user.id
+ existing1 = Account(
+ id=uuid.uuid4(), user_id=user_id, workspace_id=workspace_id,
+ connection_id=conn_id, external_id="uid-1", stable_external_id="hash-dup",
+ masked_number="1234", name="Checking A", type="checking", balance=Decimal("10"), currency="EUR",
+ )
+ existing2 = Account(
+ id=uuid.uuid4(), user_id=user_id, workspace_id=workspace_id,
+ connection_id=conn_id, external_id="uid-2", stable_external_id="hash-dup",
+ masked_number="5678", name="Checking B", type="checking", balance=Decimal("20"), currency="EUR",
+ )
+ session.add_all([existing1, existing2])
+ await session.commit()
+
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock_provider.get_accounts = AsyncMock(return_value=[
+ AccountData(external_id="new-uid", stable_external_id="hash-dup",
+ masked_number="1234", name="Checking A", type="checking",
+ balance=Decimal("25"), currency="EUR"),
+ ])
+ mock_provider.get_transactions = AsyncMock(return_value=[])
+
+ p1, p2, p3 = _patch_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn_id, workspace_id, user_id)
+
+ rows = (await session.execute(
+ select(Account).where(Account.connection_id == conn_id)
+ )).scalars().all()
+ # Must insert a new row, not rebind either existing one
+ assert len(rows) == 3, f"ambiguous stable_external_id should not match: {len(rows)} rows"
+ assert all(r.external_id != "new-uid" for r in rows if r.id in (existing1.id, existing2.id))
+
+
+async def test_sync_masked_number_fallback_not_used_for_pluggy(
+ session: AsyncSession, test_user, test_workspace,
+):
+ """The masked-number fallback must be limited to Enable Banking.
+
+ Pluggy keeps external_id stable across syncs, so a missing account is
+ genuinely missing. The fallback should not apply to non-EB providers.
+ """
+ conn = await _make_connection(session, test_user.id, "PluggyBank")
+ conn.provider = "pluggy"
+ conn_id, workspace_id, user_id = conn.id, test_workspace.id, test_user.id
+ existing = Account(
+ id=uuid.uuid4(), user_id=user_id, workspace_id=workspace_id,
+ connection_id=conn_id, external_id="pluggy-uid-1", stable_external_id=None,
+ masked_number="5531", name="CUENTA CORRIENTE", type="checking",
+ balance=Decimal("10"), currency="EUR",
+ )
+ session.add(existing)
+ await session.commit()
+
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock_provider.get_accounts = AsyncMock(return_value=[
+ AccountData(external_id="pluggy-uid-2", stable_external_id=None,
+ masked_number="5531", name="CUENTA CORRIENTE", type="checking",
+ balance=Decimal("25"), currency="EUR"),
+ ])
+ mock_provider.get_transactions = AsyncMock(return_value=[])
+
+ p1, p2, p3 = _patch_helpers()
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ p1, p2, p3:
+ await sync_connection(session, conn_id, workspace_id, user_id)
+
+ rows = (await session.execute(
+ select(Account).where(Account.connection_id == conn_id)
+ )).scalars().all()
+ # Must insert a new row, not rebind the existing one
+ assert len(rows) == 2, f"masked-number fallback should not apply to Pluggy: {len(rows)} rows"
+ assert rows[0].id == existing.id
+ assert rows[0].external_id == "pluggy-uid-1"
+
+
# ---------------------------------------------------------------------------
# sync_connection: SessionExpired / ProviderUserActionRequired
# ---------------------------------------------------------------------------
@@ -842,4 +1027,4 @@ async def test_sync_holdings_updates_existing_asset(session: AsyncSession, test_
assert len(rows) == 1 # updated, not duplicated
assert rows[0].name == "New Name"
assert rows[0].currency == "EUR"
- assert rows[0].units == Decimal("8")
+ assert rows[0].units == Decimal("8")
\ No newline at end of file
diff --git a/backend/tests/test_providers_enable_banking.py b/backend/tests/test_providers_enable_banking.py
index a0bec7f1..38d8d79e 100644
--- a/backend/tests/test_providers_enable_banking.py
+++ b/backend/tests/test_providers_enable_banking.py
@@ -6,6 +6,7 @@ HTTP is mocked end-to-end via httpx.MockTransport.
"""
from __future__ import annotations
+import re
from datetime import date, datetime, timedelta, timezone
from decimal import Decimal
from unittest.mock import patch
@@ -554,6 +555,78 @@ async def test_refresh_credentials_valid_passes(eb_keys):
assert out is creds
+async def test_get_accounts_raises_session_expired_when_details_unauthorized(eb_keys):
+ """A 401 on one account's /details kills the whole consent, not just it.
+
+ ``_request`` maps 401/410 to SessionExpiredError precisely because EB's
+ access token is session-scoped: the consent is dead for every account. The
+ per-account ``except httpx.HTTPError`` must not swallow it — doing so stored
+ an empty account list and left the connection "active" (issue #1013).
+ """
+ provider = EnableBankingProvider()
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ if request.url.path == "/sessions/sess-x":
+ return httpx.Response(200, json={
+ "session_id": "sess-x",
+ "accounts_data": [{"uid": "acc-1"}, {"uid": "acc-2"}],
+ })
+ # Anchored on purpose: ``endswith`` would also match a deeper path such
+ # as /accounts/a/b/details, and ``.+`` in the middle matches it too.
+ if re.fullmatch(r"/accounts/[^/]+/details", request.url.path):
+ return httpx.Response(401, json={"code": 401, "error": "INVALID_TOKEN"})
+ raise AssertionError(f"unexpected path {request.url.path}")
+
+ with _patch_client(provider, handler):
+ with pytest.raises(SessionExpiredError):
+ await provider.get_accounts(_CREDENTIALS)
+
+
+async def test_get_accounts_exposes_stable_external_id(eb_keys):
+ """EB's `uid` is session-scoped; `identification_hash` is the stable key.
+
+ Reauthorising mints a new session, so the same real account comes back with
+ a new uid. The hash is what survives that, and it already rides in the
+ /sessions payload this method fetches — carry it out on AccountData so the
+ sync can re-match the existing row instead of creating a duplicate.
+ """
+ provider = EnableBankingProvider()
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ if path == "/sessions/sess-x":
+ return httpx.Response(200, json={
+ "session_id": "sess-x",
+ "accounts_data": [
+ {
+ "uid": "acc-1",
+ "identification_hash": "hash-1",
+ "identification_hashes": ["hash-1"],
+ },
+ ],
+ })
+ if path == "/accounts/acc-1/details":
+ return httpx.Response(200, json={
+ "uid": "acc-1",
+ "display_name": "Main",
+ "currency": "EUR",
+ "cash_account_type": "CACC",
+ })
+ if path == "/accounts/acc-1/balances":
+ return httpx.Response(200, json={"balances": []})
+ raise AssertionError(f"unexpected path {path}")
+
+ with _patch_client(provider, handler):
+ accounts = await provider.get_accounts(_CREDENTIALS)
+
+ assert len(accounts) == 1
+ assert accounts[0].external_id == "acc-1"
+ assert accounts[0].stable_external_id == "hash-1"
+
+
+
# ----- account identifier / masking (issue #408) -----