~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(auth): distinguish migration failures from credential failures at login (#3637)
LearningCircuit9d0e506fa915
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex 5f14b68ea0..b40c696702 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -34,6 +34,17 @@ from .sqlcipher_utils import ()+class DatabaseInitializationError(Exception):+ """Raised when a per-user database opens but its schema can't be initialised.++ Distinct from credential / decryption failures (which return ``None``+ from :py:meth:`DatabaseManager.open_user_database`) so callers — chiefly+ the login route — can avoid penalising the user's lockout counter and+ surface a different error message. The credentials are valid; the+ database state isn't.+ """++class DatabaseManager:"""Manages encrypted SQLCipher databases for each user."""@@ -610,15 +621,24 @@ class DatabaseManager:"Pre-migration backup failed — proceeding with migration")- # Let migration failures propagate to the outer except: a half-- # initialised DB whose alembic_version disagrees with the schema- # is *not* "safe" — every later query that touches a table the- # failed migration was supposed to create raises confusing- # downstream errors (e.g. "no such table: papers" on academic- # source saves). Failing the open here means login fails loudly- # and ops sees a clean migration traceback instead of cascading- # PendingRollbackErrors hours later.- initialize_database(engine)+ # Init failures need to be distinguishable from credential+ # failures at the call site: the credentials worked (we+ # decrypted and ran SELECT 1), but the schema couldn't be+ # brought up. Re-raise as a typed error so the login route+ # can skip the lockout counter and surface a server-error+ # message instead of "Invalid username or password".+ try:+ initialize_database(engine)+ except Exception as init_err:+ elapsed_ms = (time.perf_counter() - open_start) * 1000+ logger.exception(+ f"Database migration failed for {username} "+ f"after {elapsed_ms:.0f}ms — refusing login"+ )+ engine.dispose()+ raise DatabaseInitializationError(+ f"Database initialisation failed for {username}: {init_err}"+ ) from init_err# Store connection AFTER migrations completewith self._connections_lock:@@ -637,6 +657,10 @@ class DatabaseManager:)return engine+ except DatabaseInitializationError:+ # Already logged + engine disposed at the raise site. Re-raise+ # past the catch-all below so callers see the typed error.+ raiseexcept Exception:elapsed_ms = (time.perf_counter() - open_start) * 1000logger.exception(diff --git a/src/local_deep_research/database/thread_local_session.py b/src/local_deep_research/database/thread_local_session.pyindex 8de7c53b2e..c899ea46ee 100644--- a/src/local_deep_research/database/thread_local_session.py+++ b/src/local_deep_research/database/thread_local_session.py@@ -87,8 +87,19 @@ class ThreadLocalSessionManager:f"Thread {thread_id}: Creating new database session for user {username}")- # Ensure database is open- engine = db_manager.open_user_database(username, password)+ # Ensure database is open. open_user_database returns None for+ # credential failures and raises DatabaseInitializationError when+ # the schema can't be initialised; from a worker-thread caller+ # both mean "no usable session right now" so collapse them.+ from .encrypted_db import DatabaseInitializationError++ try:+ engine = db_manager.open_user_database(username, password)+ except DatabaseInitializationError:+ logger.exception(+ f"Thread {thread_id}: database init failed for user {username}"+ )+ return Noneif not engine:logger.error(f"Thread {thread_id}: Failed to open database for user {username}"diff --git a/src/local_deep_research/library/download_management/status_tracker.py b/src/local_deep_research/library/download_management/status_tracker.pyindex a22f7525e8..2e46973961 100644--- a/src/local_deep_research/library/download_management/status_tracker.py+++ b/src/local_deep_research/library/download_management/status_tracker.py@@ -52,10 +52,25 @@ class ResourceStatusTracker:self.password = password# Use the global db_manager singleton to share cached connections- from ...database.encrypted_db import db_manager+ from ...database.encrypted_db import (+ DatabaseInitializationError,+ db_manager,+ )self.db_manager = db_manager- self.engine = db_manager.open_user_database(username, password)+ try:+ self.engine = db_manager.open_user_database(username, password)+ except DatabaseInitializationError:+ # Surface init failures from the schedulers/library-init+ # callers as a plain RuntimeError — they all wrap construction+ # in try/except already, and propagating the typed exception+ # would couple every caller to encrypted_db's internals.+ logger.exception(+ f"[STATUS_TRACKER] Database init failed for user: {username}"+ )+ raise RuntimeError(+ f"Database initialisation failed for user {username}"+ ) from Noneself.Session = sessionmaker(bind=self.engine)# Create tables if they don't existdiff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.pyindex cb06895e61..e6a9384aff 100644--- a/src/local_deep_research/web/auth/routes.py+++ b/src/local_deep_research/web/auth/routes.py@@ -20,7 +20,7 @@ from flask import (from loguru import loggerfrom ...database.auth_db import auth_db_session-from ...database.encrypted_db import db_manager+from ...database.encrypted_db import DatabaseInitializationError, db_managerfrom ...database.models.auth import Userfrom ...database.thread_local_session import thread_cleanupfrom sqlalchemy.exc import IntegrityError@@ -116,8 +116,31 @@ def login():allow_registrations=config.get("allow_registrations", True),), 429- # Try to open user's encrypted database- engine = db_manager.open_user_database(username, password)+ # Try to open user's encrypted database. Two distinct failure modes:+ # - return None → credentials invalid OR DB missing → 401, count toward lockout+ # - raise DatabaseInitializationError → credentials valid but schema+ # can't be brought up (e.g. world-writable migrations dir tripping+ # the alembic_runner permission check) → 503, do NOT count toward+ # lockout. The user's password is correct; punishing them with a+ # lockout for a server-side configuration problem would be wrong.+ try:+ engine = db_manager.open_user_database(username, password)+ except DatabaseInitializationError:+ logger.warning(+ f"Login refused for {sanitize_for_log(username)}: "+ "database initialisation failed (see traceback above). "+ "Lockout counter NOT incremented — credentials are valid."+ )+ flash(+ "Database initialisation failed. The server is misconfigured — "+ "please check the server logs or contact the administrator.",+ "error",+ )+ return render_template(+ "auth/login.html",+ has_encryption=db_manager.has_encryption,+ allow_registrations=config.get("allow_registrations", True),+ ), 503if engine is None:# Invalid credentials or database doesn't existdiff --git a/tests/database/test_encrypted_db_manager.py b/tests/database/test_encrypted_db_manager.pyindex b61b0bf24b..0a5e741d0d 100644--- a/tests/database/test_encrypted_db_manager.py+++ b/tests/database/test_encrypted_db_manager.py@@ -282,19 +282,20 @@ class TestDatabaseOpening:assert result is None@patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_open_database_migration_failure_returns_none(+ def test_open_database_migration_failure_raises_typed_error(self, mock_data_dir, tmp_path):- """A failure inside ``initialize_database`` must surface as None.-- Regression: the open path used to swallow migration exceptions and- cache the engine anyway, leaving downstream queries to hit a- schema/alembic_version mismatch (e.g. ``no such table: papers``).- Now the failure propagates to the outer cleanup path: engine- disposed, no entry stored in ``connections``, ``None`` returned —- same shape as any other open failure.+ """Init failures raise DatabaseInitializationError, not return None.++ The login route uses the type distinction to skip the lockout+ counter (credentials are valid; only the schema couldn't come up)+ and to flash a server-error message instead of "Invalid username+ or password". The engine must still be disposed and not cached."""- from local_deep_research.database.encrypted_db import DatabaseManager+ from local_deep_research.database.encrypted_db import (+ DatabaseInitializationError,+ DatabaseManager,+ )mock_data_dir.return_value = tmp_path@@ -337,11 +338,13 @@ class TestDatabaseOpening:"Migrations directory has insecure permissions (world-writable)"),):- result = manager.open_user_database(- "testuser", "password"- )+ with pytest.raises(+ DatabaseInitializationError+ ):+ manager.open_user_database(+ "testuser", "password"+ )- assert result is Noneassert "testuser" not in manager.connectionsmock_engine.dispose.assert_called_once()diff --git a/tests/web/auth/test_auth_routes.py b/tests/web/auth/test_auth_routes.pyindex 176c3835eb..24ae85fc2f 100644--- a/tests/web/auth/test_auth_routes.py+++ b/tests/web/auth/test_auth_routes.py@@ -188,6 +188,61 @@ class TestLogin:)assert response.status_code == 401+ def test_returns_503_for_database_init_failure_without_lockout(self):+ """A DatabaseInitializationError should yield 503 and bypass lockout.++ Regression for the migration-failure path: the user's password is+ valid (we got far enough to attempt schema init), so penalising+ them with a lockout for a server-side configuration problem+ (e.g. world-writable migrations dir) would be wrong.+ """+ from local_deep_research.database.encrypted_db import (+ DatabaseInitializationError,+ )++ app = Flask(__name__)+ app.secret_key = "test"+ app.config["WTF_CSRF_ENABLED"] = False++ with (+ patch(+ "local_deep_research.web.auth.routes.load_server_config"+ ) as mock_config,+ patch(+ "local_deep_research.web.auth.routes.db_manager"+ ) as mock_db_manager,+ patch(+ "local_deep_research.web.auth.routes.render_template"+ ) as mock_render,+ patch(+ "local_deep_research.web.auth.routes.get_account_lockout_manager"+ ) as mock_lockout_factory,+ ):+ mock_config.return_value = {"allow_registrations": True}+ mock_db_manager.open_user_database.side_effect = (+ DatabaseInitializationError("boom")+ )+ mock_render.return_value = "Login Page"++ mock_lockout = mock_lockout_factory.return_value+ mock_lockout.is_locked.return_value = False++ from local_deep_research.web.auth.routes import auth_bp++ app.register_blueprint(auth_bp)++ with app.test_client() as client:+ response = client.post(+ "/auth/login",+ data={+ "username": "validuser",+ "password": "correctpassword",+ },+ )+ assert response.status_code == 503+ # Critical: do not punish the user for a server-side bug.+ mock_lockout.record_failure.assert_not_called()+class TestRegisterPage:"""Tests for GET /register endpoint."""