Skip to content

~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.

refactor(auth): centralize research DB-password guard in password_utils (#4577)

LearningCircuitc39706332262
diff --git a/src/local_deep_research/chat/routes.py b/src/local_deep_research/chat/routes.py
index 6c640a6d1e..8c712d0f64 100644
--- a/src/local_deep_research/chat/routes.py
+++ b/src/local_deep_research/chat/routes.py
@@ -38,8 +38,10 @@ from ..security.rate_limiter import _get_api_user_key, limiter
from ..settings.manager import SettingsManager
from ..web.auth.decorators import login_required
from ..web.utils.templates import render_template_with_defaults
-from ..web.auth.password_utils import get_user_password
-from ..database.encrypted_db import db_manager
+from ..web.auth.password_utils import (
+ get_user_password,
+ resolve_user_password,
+)
from ..web.routes.globals import (
cleanup_research,
is_research_thread_alive,
@@ -859,16 +861,10 @@ def send_message(session_id):
# background thread that writes token/search metrics to the
# user's encrypted database; without the password every metric
# write is silently dropped, leaving the metrics dashboard empty
- # while the research still completes (issue #4457). The direct
- # (/start_research) and follow-up routes apply the same guard.
- # Trigger: password-store TTL expiry or a server/container
- # restart while the session cookie is still valid.
- if db_manager.has_encryption and not get_user_password(username):
- logger.error(
- f"No password available for user {username} with "
- "encrypted database - cannot start chat research "
- "(session password expired or lost after server restart)"
- )
+ # while the research still completes (issue #4457). The password
+ # is re-fetched at the spawn site below, so discard it here.
+ _pw, session_expired = resolve_user_password(username)
+ if session_expired:
return jsonify(
{
"success": False,
diff --git a/src/local_deep_research/followup_research/routes.py b/src/local_deep_research/followup_research/routes.py
index b1c79cc176..73004d6390 100644
--- a/src/local_deep_research/followup_research/routes.py
+++ b/src/local_deep_research/followup_research/routes.py
@@ -12,7 +12,7 @@ from .service import FollowUpResearchService
from .models import FollowUpRequest
from ..security.decorators import require_json_body
from ..web.auth.decorators import login_required
-from ..web.auth.password_utils import get_user_password
+from ..web.auth.password_utils import resolve_user_password
# Create blueprint
followup_bp = Blueprint("followup", __name__, url_prefix="/api/followup")
@@ -189,30 +189,20 @@ def start_followup():
)
# Get user password for metrics database access.
- # Uses the shared helper (password_utils) so every route checks the
- # same three sources in the same order — avoids subtle divergence.
+ # Shared helper (password_utils) so every research entry point makes
+ # the same encryption-aware decision and logs it the same way.
# Must check BEFORE creating ResearchHistory to avoid orphaned records.
- user_password = get_user_password(username)
+ user_password, session_expired = resolve_user_password(username)
- if not user_password:
- from ..database.encrypted_db import db_manager
-
- if db_manager.has_encryption:
- logger.error(
- f"No password available for user {username} with encrypted database - "
- "cannot start follow-up research (session password expired or lost after server restart)"
- )
- # Use success/error keys to match followup API convention
- # (the followup frontend checks data.success and data.error)
- return jsonify(
- {
- "success": False,
- "error": "Your session has expired. Please log out and log back in to start research.",
- }
- ), 401
- logger.warning(
- f"No password available for metrics access for user {username}"
- )
+ if session_expired:
+ # Use success/error keys to match followup API convention
+ # (the followup frontend checks data.success and data.error)
+ return jsonify(
+ {
+ "success": False,
+ "error": "Your session has expired. Please log out and log back in to start research.",
+ }
+ ), 401
# Pre-flight: refuse to spawn a research thread (and create an
# orphan ResearchHistory row) when llm.model is empty. Mirrors the
diff --git a/src/local_deep_research/web/auth/password_utils.py b/src/local_deep_research/web/auth/password_utils.py
index 8cab2c69c0..6fc26def16 100644
--- a/src/local_deep_research/web/auth/password_utils.py
+++ b/src/local_deep_research/web/auth/password_utils.py
@@ -1,16 +1,21 @@
"""
-Shared utility for retrieving user passwords from available session sources.
+Shared utilities for resolving the current user's DB password.
-Centralises the 3-source fallback chain (session password store → Flask g →
-temp auth store) so every route that needs the current user's DB password
-uses the same logic. Without this, each route reimplemented the chain
-independently, risking subtle divergence (e.g. one route forgetting to
-check temp_auth, or using a different method alias).
+``get_user_password`` centralises the 3-source fallback chain (session
+password store → Flask g → temp auth store) so every route that needs the
+current user's DB password uses the same logic. Without this, each route
+reimplemented the chain independently, risking subtle divergence (e.g. one
+route forgetting to check temp_auth, or using a different method alias).
+
+``resolve_user_password`` builds on it with the encryption-aware guard the
+research entry points share: it returns ``(password, session_expired)`` so
+a caller can reject a run when an encrypted DB has no available password.
"""
-from typing import Optional
+from typing import Optional, Tuple
from flask import g, session
+from loguru import logger
def get_user_password(username: str) -> Optional[str]:
@@ -48,3 +53,42 @@ def get_user_password(username: str) -> Optional[str]:
return auth_data[1]
return None
+
+
+def resolve_user_password(username: str) -> Tuple[Optional[str], bool]:
+ """Resolve the user's DB password for starting a research run.
+
+ Returns ``(password, session_expired)``:
+
+ - ``session_expired`` is ``True`` only when the database is encrypted
+ and no password is available. The caller MUST reject the request
+ (e.g. a 401 telling the user to log back in) because the research's
+ background DB and metric writes would otherwise be silently dropped
+ (issue #4457) — research would appear to run while every metric write
+ fails. Trigger: session-password-store TTL expiry or a server/
+ container restart while the session cookie is still valid.
+ - For unencrypted databases ``session_expired`` is always ``False``;
+ the returned ``password`` may legitimately be ``None``.
+
+ Centralises the guard that the direct (``/start_research``), follow-up,
+ and chat research entry points all need, so the encryption-aware
+ decision and its logging live in one place instead of being copied
+ (and risking divergence) across routes. Each route still formats its
+ own error response, because their frontends expect different shapes.
+ """
+ from ...database.encrypted_db import db_manager
+
+ password = get_user_password(username) # gitleaks:allow
+ if not password and db_manager.has_encryption:
+ logger.error(
+ f"No password available for user {username} with encrypted "
+ "database - cannot start research (session password expired or "
+ "lost after server restart)"
+ )
+ return None, True
+ if not password:
+ logger.warning(
+ f"No password available for metrics access for user {username} "
+ "(unencrypted database)"
+ )
+ return password, False
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 02043086d7..6ec12880b1 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -50,10 +50,9 @@ from ...database.models import (
UserActiveResearch,
)
from ...database.models.library import Document as Document
-from ...database.encrypted_db import db_manager
from ...database.session_context import get_g_db_session, get_user_db_session
from ..auth.decorators import login_required
-from ..auth.password_utils import get_user_password
+from ..auth.password_utils import get_user_password, resolve_user_password
from ..models.database import calculate_duration
from ..services.research_service import (
export_report_to_memory,
@@ -588,25 +587,16 @@ def start_research():
# (queued research gets password later via queue processor)
user_password = None
if not should_queue:
- user_password = get_user_password(username)
-
- if not user_password:
- if db_manager.has_encryption:
- logger.error(
- f"No password available for user {username} with encrypted database - "
- "cannot start research (session password expired or lost after server restart)"
- )
- # Use status/message keys to match the research API convention
- # (the research frontend checks data.status and data.message)
- return jsonify(
- {
- "status": "error",
- "message": "Your session has expired. Please log out and log back in to start research.",
- }
- ), 401
- logger.warning(
- f"No password available for metrics access for user {username}"
- )
+ user_password, session_expired = resolve_user_password(username)
+ if session_expired:
+ # Use status/message keys to match the research API convention
+ # (the research frontend checks data.status and data.message)
+ return jsonify(
+ {
+ "status": "error",
+ "message": "Your session has expired. Please log out and log back in to start research.",
+ }
+ ), 401
# Create a record in the database with explicit UTC timestamp
import uuid
diff --git a/tests/chat/test_chat_research_triggering.py b/tests/chat/test_chat_research_triggering.py
index 662febba9e..6ab81f5560 100644
--- a/tests/chat/test_chat_research_triggering.py
+++ b/tests/chat/test_chat_research_triggering.py
@@ -90,21 +90,18 @@ class TestResearchTriggering:
)
session_id = json.loads(create_response.data)["session_id"]
- # Patch only the chat-route references: get_user_password returns
- # None (password lost) and db_manager reports an encrypted DB. The
- # session lookup above used the real stored password and is
- # unaffected (get_user_db_session imports its own references).
+ # The route delegates the encryption-aware decision to the shared
+ # resolve_user_password helper; simulate "encrypted DB, password
+ # lost" -> (None, session_expired=True).
with (
patch(
- "local_deep_research.chat.routes.get_user_password",
- return_value=None,
+ "local_deep_research.chat.routes.resolve_user_password",
+ return_value=(None, True),
),
- patch("local_deep_research.chat.routes.db_manager") as mock_db,
patch(
"local_deep_research.chat.routes.start_research_process"
) as mock_start_research,
):
- mock_db.has_encryption = True
response = authenticated_client.post(
f"/api/chat/sessions/{session_id}/messages",
json={
@@ -126,9 +123,8 @@ class TestResearchTriggering:
):
"""Non-encrypted DB must NOT be blocked by the password guard.
- The guard is encryption-aware: unencrypted installs have no
- encryption key requirement, so a missing get_user_password() value
- must not 401 the chat research path.
+ resolve_user_password returns (None, session_expired=False) for an
+ unencrypted install, so the chat research path must proceed.
"""
create_response = authenticated_client.post(
"/api/chat/sessions",
@@ -139,15 +135,13 @@ class TestResearchTriggering:
with (
patch(
- "local_deep_research.chat.routes.get_user_password",
- return_value=None,
+ "local_deep_research.chat.routes.resolve_user_password",
+ return_value=(None, False),
),
- patch("local_deep_research.chat.routes.db_manager") as mock_db,
patch(
"local_deep_research.chat.routes.start_research_process"
) as mock_start_research,
):
- mock_db.has_encryption = False
response = authenticated_client.post(
f"/api/chat/sessions/{session_id}/messages",
json={
diff --git a/tests/followup_research/test_routes_coverage.py b/tests/followup_research/test_routes_coverage.py
index 7f0f54acc4..e8b97fbc59 100644
--- a/tests/followup_research/test_routes_coverage.py
+++ b/tests/followup_research/test_routes_coverage.py
@@ -571,7 +571,11 @@ class TestStartFollowupNoPassword:
patch(RUN_RESEARCH),
patch(RESEARCH_HISTORY),
patch("uuid.uuid4", return_value=Mock(__str__=lambda s: "id4")),
- patch(f"{MODULE}.logger") as mock_logger,
+ # The unencrypted "no password" warning now fires inside the
+ # shared resolve_user_password helper, so assert on its logger.
+ patch(
+ "local_deep_research.web.auth.password_utils.logger"
+ ) as mock_logger,
patch(
"local_deep_research.database.encrypted_db.db_manager",
mock_db_mgr,
diff --git a/tests/web/auth/test_password_utils_gaps.py b/tests/web/auth/test_password_utils_gaps.py
index 75ae611b05..5385501c35 100644
--- a/tests/web/auth/test_password_utils_gaps.py
+++ b/tests/web/auth/test_password_utils_gaps.py
@@ -4,9 +4,13 @@ from unittest.mock import MagicMock, patch
import flask
-from local_deep_research.web.auth.password_utils import get_user_password
+from local_deep_research.web.auth.password_utils import (
+ get_user_password,
+ resolve_user_password,
+)
MODULE = "local_deep_research.web.auth.password_utils"
+DB_MANAGER = "local_deep_research.database.encrypted_db.db_manager"
class TestGetUserPassword:
@@ -205,3 +209,44 @@ class TestGetUserPassword:
result = get_user_password("frank")
assert result == "from_g"
mock_session_store.get_session_password.assert_not_called()
+
+
+class TestResolveUserPassword:
+ """Tests for resolve_user_password, the shared research-entry guard.
+
+ Returns (password, session_expired); session_expired is True only when
+ the DB is encrypted AND no password is available (#4457).
+ """
+
+ def test_password_present_is_not_expired(self):
+ """A real password -> (password, False), regardless of encryption."""
+ with (
+ patch(f"{MODULE}.get_user_password", return_value="pw"),
+ patch(DB_MANAGER) as mock_db,
+ ):
+ mock_db.has_encryption = True
+ password, session_expired = resolve_user_password("alice")
+ assert password == "pw"
+ assert session_expired is False
+
+ def test_no_password_encrypted_is_expired(self):
+ """Encrypted DB + no password -> (None, True): caller must reject."""
+ with (
+ patch(f"{MODULE}.get_user_password", return_value=None),
+ patch(DB_MANAGER) as mock_db,
+ ):
+ mock_db.has_encryption = True
+ password, session_expired = resolve_user_password("alice")
+ assert password is None
+ assert session_expired is True
+
+ def test_no_password_unencrypted_is_not_expired(self):
+ """Unencrypted DB + no password -> (None, False): caller proceeds."""
+ with (
+ patch(f"{MODULE}.get_user_password", return_value=None),
+ patch(DB_MANAGER) as mock_db,
+ ):
+ mock_db.has_encryption = False
+ password, session_expired = resolve_user_password("alice")
+ assert password is None
+ assert session_expired is False
diff --git a/tests/web/routes/test_encrypted_db_password_check.py b/tests/web/routes/test_encrypted_db_password_check.py
index d29ea5ea6d..2e98382615 100644
--- a/tests/web/routes/test_encrypted_db_password_check.py
+++ b/tests/web/routes/test_encrypted_db_password_check.py
@@ -92,7 +92,11 @@ def _authenticated_client(app, has_encryption=False, password_available=True):
patches = [
patch("local_deep_research.web.auth.decorators.db_manager", mock_db),
- patch(f"{_ROUTES_MOD}.db_manager", mock_db),
+ # The guard reads has_encryption via the shared resolve_user_password
+ # helper, which imports db_manager from encrypted_db (not the route
+ # module). Patch it at the source so the real get_user_password chain
+ # (session_password_store, patched below) still drives the result.
+ patch("local_deep_research.database.encrypted_db.db_manager", mock_db),
patch(
f"{_ROUTES_MOD}.get_user_db_session",
side_effect=_fake_session,
diff --git a/tests/web/routes/test_research_routes_extracted_helpers.py b/tests/web/routes/test_research_routes_extracted_helpers.py
index aee465ac84..d1d54804c9 100644
--- a/tests/web/routes/test_research_routes_extracted_helpers.py
+++ b/tests/web/routes/test_research_routes_extracted_helpers.py
@@ -37,10 +37,12 @@ def app():
flask_app.register_blueprint(research_bp)
with (
patch("local_deep_research.web.auth.decorators.db_manager") as mock_db,
- patch(f"{MODULE}.db_manager") as mock_enc_db,
+ # The password guard delegates to resolve_user_password; default it
+ # to "not expired" so the general tests are not blocked. The two
+ # dedicated guard tests below override this.
+ patch(f"{MODULE}.resolve_user_password", return_value=(None, False)),
):
mock_db.is_user_connected.return_value = True
- mock_enc_db.has_encryption = False
yield flask_app
@@ -104,7 +106,10 @@ def _happy_path_patches(ms, sm, fake_thread):
patch(_GET_USER_DB, side_effect=_ctx_factory(ms)),
patch(_SM_MANAGER, return_value=sm),
patch(_SM_SETTINGS, return_value=sm),
- patch(f"{MODULE}.get_user_password", return_value="pw"),
+ # The route derives user_password from the resolve_user_password
+ # guard, so feed the run's password through it (not the now-unused
+ # direct get_user_password call).
+ patch(f"{MODULE}.resolve_user_password", return_value=("pw", False)),
patch(f"{MODULE}.start_research_process", return_value=fake_thread),
patch(_SAVE_STRATEGY),
patch(f"{MODULE}.log_settings"),
@@ -435,7 +440,8 @@ class TestStartResearchEncryptedDbGate:
session["session_id"] = "sid-1"
def test_encrypted_db_no_password_returns_401(self, client, app):
- """When has_encryption=True and no password, return 401 before DB writes."""
+ """Route returns 401 (before DB writes) when the guard reports the
+ session expired (encrypted DB, no password)."""
ms = _mock_db_session(active_count=0)
sm = _make_settings_manager()
@@ -447,10 +453,8 @@ class TestStartResearchEncryptedDbGate:
patch(_GET_USER_DB, side_effect=_ctx_factory(ms)),
patch(_SM_MANAGER, return_value=sm),
patch(_SM_SETTINGS, return_value=sm),
- patch(f"{MODULE}.db_manager") as mock_enc_db,
- patch(f"{MODULE}.get_user_password", return_value=None),
+ patch(f"{MODULE}.resolve_user_password", return_value=(None, True)),
):
- mock_enc_db.has_encryption = True
resp = client.post(
"/api/start_research",
json={"query": "test query", "model": "llama3"},
@@ -479,8 +483,9 @@ class TestStartResearchEncryptedDbGate:
patch(_GET_USER_DB, side_effect=_ctx_factory(ms)),
patch(_SM_MANAGER, return_value=sm),
patch(_SM_SETTINGS, return_value=sm),
- patch(f"{MODULE}.db_manager") as mock_enc_db,
- patch(f"{MODULE}.get_user_password", return_value=None),
+ patch(
+ f"{MODULE}.resolve_user_password", return_value=(None, False)
+ ),
patch(
f"{MODULE}.start_research_process", return_value=fake_thread
) as mock_start,
@@ -489,7 +494,6 @@ class TestStartResearchEncryptedDbGate:
patch(f"{MODULE}.ResearchHistory"),
patch(f"{MODULE}.UserActiveResearch"),
):
- mock_enc_db.has_encryption = False
resp = client.post(
"/api/start_research",
json={"query": "test query", "model": "llama3"},
diff --git a/tests/web/routes/test_research_routes_start_research_coverage.py b/tests/web/routes/test_research_routes_start_research_coverage.py
index aa92415c1b..bd29fe86ec 100644
--- a/tests/web/routes/test_research_routes_start_research_coverage.py
+++ b/tests/web/routes/test_research_routes_start_research_coverage.py
@@ -132,7 +132,14 @@ def app():
with (
patch("local_deep_research.web.auth.decorators.db_manager") as mock_db,
- patch(f"{MODULE}.db_manager") as mock_enc_db,
+ # The password guard now reads has_encryption via the shared
+ # resolve_user_password helper, which imports db_manager from
+ # encrypted_db. Patch it at the source so the real password-
+ # resolution chain (incl. temp_auth) still runs; has_encryption=False
+ # keeps the guard from 401-ing when no password is configured.
+ patch(
+ "local_deep_research.database.encrypted_db.db_manager"
+ ) as mock_enc_db,
):
mock_db.is_user_connected.return_value = True
mock_enc_db.has_encryption = False