Open-source personal finance manager. Self-hosted, privacy-first.
fix: stop background sync from erroring healthy connections when a provider is unregistered (#546)
Tássio Noronha661ea21cf4c1
diff --git a/backend/app/api/connections.py b/backend/app/api/connections.pyindex 778fc1be..1b9e0b9e 100644--- a/backend/app/api/connections.py+++ b/backend/app/api/connections.py@@ -10,7 +10,11 @@ from app.core.workspace_context import (current_writable_workspace,)from app.providers import all_known_providers-from app.providers.base import ProviderUserActionRequired, SessionExpiredError+from app.providers.base import (+ ProviderNotConfiguredError,+ ProviderUserActionRequired,+ SessionExpiredError,+)from app.schemas.bank_connection import (BankConnectionRead,ConnectionSettingsUpdate,@@ -188,6 +192,8 @@ async def sync_connection()except SessionExpiredError as e:raise HTTPException(status_code=status.HTTP_410_GONE, detail=str(e))+ except ProviderNotConfiguredError as e:+ raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(e))except Exception as e:raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,diff --git a/backend/app/core/config.py b/backend/app/core/config.pyindex d7e95163..2a43882b 100644--- a/backend/app/core/config.py+++ b/backend/app/core/config.py@@ -120,7 +120,15 @@ class Settings(BaseSettings):# external dependency on the Brazilian government endpoint).tesouro_direto_enabled: bool = True- model_config = SettingsConfigDict(env_file=".env", secrets_dir=CREDENTIALS_DIRECTORY)+ # The CWD-relative ".env" is kept for backward compatibility; the anchored+ # backend/.env guarantees the API and the Celery worker/beat resolve the+ # same file no matter which working directory each service is launched+ # from (a systemd unit without WorkingDirectory= used to leave the worker+ # with default settings, silently disabling every bank-sync provider).+ model_config = SettingsConfigDict(+ env_file=(".env", Path(__file__).resolve().parents[2] / ".env"),+ secrets_dir=CREDENTIALS_DIRECTORY,+ )@lru_cachediff --git a/backend/app/providers/base.py b/backend/app/providers/base.pyindex 8406dd33..0d68a1fe 100644--- a/backend/app/providers/base.py+++ b/backend/app/providers/base.py@@ -209,6 +209,17 @@ class ProviderRateLimited(Exception):"""+class ProviderNotConfiguredError(Exception):+ """Raised when a connection references a provider missing from the registry.++ This is a server configuration problem, not a bank problem — typically one+ process (e.g. the Celery worker) is not loading the environment that+ enables the provider while the API process is. The credentials are fine,+ so callers must not flip the connection to "error": the reconnect banner+ would send the user chasing the wrong fix (and burning setup tokens).+ """++class FxRateProvider(ABC):"""Abstract interface for FX rate providers."""diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.pyindex 7932bf34..6304250d 100644--- a/backend/app/services/connection_service.py+++ b/backend/app/services/connection_service.py@@ -22,6 +22,7 @@ from app.models.user import Userfrom app.providers import get_providerfrom app.providers.base import (HoldingData,+ ProviderNotConfiguredError,ProviderRateLimited,ProviderUserActionRequired,SessionExpiredError,@@ -1146,9 +1147,20 @@ async def sync_connection(import_pending = conn_settings.get("import_pending", True)use_provider_cats = await admin_service.use_provider_categories(session)+ # Resolve the provider before the error-handling block: an unregistered+ # provider is a server misconfiguration, and the catch-all below would+ # wrongly stamp the (healthy) connection with status="error".try:provider = get_provider(connection.provider)+ except ValueError as exc:+ raise ProviderNotConfiguredError(+ f"Provider '{connection.provider}' is not configured in this process. "+ "If connecting from the web app works but background sync fails, the "+ "worker service is likely not loading the environment (.env) that "+ "enables this provider."+ ) from exc+ try:# Refresh credentials if neededcredentials = await provider.refresh_credentials(connection.credentials)connection.credentials = credentialsdiff --git a/backend/app/tasks/sync_tasks.py b/backend/app/tasks/sync_tasks.pyindex b3c1e68b..f562e872 100644--- a/backend/app/tasks/sync_tasks.py+++ b/backend/app/tasks/sync_tasks.py@@ -9,6 +9,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_asynfrom app.worker import celery_appfrom app.core.config import get_settingsfrom app.models.bank_connection import BankConnection+from app.providers.base import ProviderNotConfiguredErrorfrom app.services import connection_servicelogger = logging.getLogger(__name__)@@ -52,6 +53,10 @@ async def _sync_all() -> int:logger.info("Syncing connection %s (last_sync=%s)", conn_id, last_sync)await _sync_one(session_maker, conn_id, user_id)synced += 1+ except ProviderNotConfiguredError as exc:+ # Actionable one-liner instead of a buried traceback: this+ # means THIS process is missing the provider's configuration.+ logger.error("Skipping connection %s: %s", conn_id, exc)except Exception:logger.exception("Background sync failed for connection %s", conn_id)diff --git a/backend/tests/test_config.py b/backend/tests/test_config.pyindex b22785d6..5a7c7c83 100644--- a/backend/tests/test_config.py+++ b/backend/tests/test_config.py@@ -16,6 +16,15 @@ def secrets(tmp_path: Path):return d+def test_env_file_is_anchored_to_backend_dir():+ """The worker/beat must resolve the same .env as the API regardless of the+ working directory each service is launched from."""+ env_files = Settings.model_config["env_file"]+ backend_env = Path(__file__).resolve().parents[1] / ".env"+ assert isinstance(env_files, tuple)+ assert backend_env in tuple(Path(p) for p in env_files)++def test_oidc_secret_reads_from_secrets_dir(secrets: Path):write(secrets, "oidc_client_secret", "file-secret")diff --git a/backend/tests/test_connection_service_coverage.py b/backend/tests/test_connection_service_coverage.pyindex 13cc4185..31550112 100644--- a/backend/tests/test_connection_service_coverage.py+++ b/backend/tests/test_connection_service_coverage.py@@ -27,6 +27,7 @@ from app.providers.base import (HoldingData,InstitutionData,InstitutionListData,+ ProviderNotConfiguredError,ProviderUserActionRequired,SessionExpiredError,TransactionData,@@ -317,6 +318,26 @@ async def test_sync_fuzzy_matches_manual_transaction(session: AsyncSession, test# ---------------------------------------------------------------------------+async def test_sync_unregistered_provider_keeps_status(+ session: AsyncSession, test_user, test_workspace,+):+ """A provider missing from the registry is a server misconfiguration (e.g.+ the Celery worker not loading .env) — the connection must keep its status+ instead of flipping to "error", which would show a misleading reconnect+ banner for perfectly healthy credentials."""+ conn = await _make_connection(session, test_user.id, "GhostBank")+ conn_id = conn.id++ with pytest.raises(ProviderNotConfiguredError, match="not configured"):+ await sync_connection(session, conn_id, test_workspace.id, test_user.id)++ refreshed = (await session.execute(+ select(BankConnection).where(BankConnection.id == conn_id)+ )).scalar_one()+ assert refreshed.status == "active"++@pytest.mark.asyncioasync def test_sync_session_expired_marks_expired(session: AsyncSession, test_user, test_workspace):conn = await _make_connection(session, test_user.id, "ExpiredBank")