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.

fix(security): verify the password on a cached database connection (#5596)

LearningCircuit5f29e62916da
diff --git a/.github/codeql/codeql-config.yml b/.github/codeql/codeql-config.yml
index 7a689c406d..ed507cb12b 100644
--- a/.github/codeql/codeql-config.yml
+++ b/.github/codeql/codeql-config.yml
@@ -6,3 +6,19 @@ paths-ignore:
- '**/test_*.py'
- '**/*_test.py'
- 'src/local_deep_research/security/file_write_verifier.py'
+
+# TEMPORARY (PR #5596): exclude one rule repo-wide to unblock the critical
+# cached-connection auth-bypass fix. This is broader than desired -- it turns
+# py/weak-sensitive-data-hashing off for EVERY file, not just the one false
+# positive. Preferred long-term fix: dismiss the single alert as a reviewed
+# false positive in the code-scanning UI (per-alert, keeps the rule active
+# everywhere) and remove this block. Tracking: revisit after #5596 merges.
+#
+# Why it's a false positive: this app stores no password hashes at rest
+# (decryption of the per-user SQLCipher DB IS authentication, via PBKDF2). The
+# only fast hash of a password is the in-process, per-process-keyed, never-
+# persisted cache verifier in database/encrypted_db.py (_compute_verifier_digest),
+# where a slow KDF would only add login latency without reducing exposure.
+query-filters:
+ - exclude:
+ id: py/weak-sensitive-data-hashing
diff --git a/changelog.d/+login-cached-connection-reverify.security.md b/changelog.d/+login-cached-connection-reverify.security.md
new file mode 100644
index 0000000000..5b6e6f1913
--- /dev/null
+++ b/changelog.d/+login-cached-connection-reverify.security.md
@@ -0,0 +1,19 @@
+Login now verifies your password even when your encrypted database is already
+open. The connection cache is keyed by username alone, so a cache hit proved
+only that *someone* had already opened that user's database — and login's sole
+credential check is whether that open succeeds.
+
+This only affected an account that **already existed and was currently open** —
+the normal state while that user is signed in anywhere. It could **not** be used
+to sign in to an account that does not exist or that has never been opened, and
+the attacker needed no account of their own. The exposure also outlives an
+active browser session: the database stays open after the user closes the
+browser (until the idle timeout — up to 30 days with "remember me") and while a
+research job is running. For any account meeting that condition, knowing only
+the **username** — not the password — was enough to sign in as that user from a
+different session, browser, or IP and read (and write) their data. The attempt
+also counted as a successful login, so it never tripped the account lockout or
+the rate limiter and left nothing in the logs that looked like an attack.
+
+The cache now records which password opened the connection and re-checks it on
+every login, falling back to a real key-validating open when it does not match.
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index 4dc80da591..8a39a288dd 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -3,6 +3,8 @@ Encrypted database management using SQLCipher.
Handles per-user encrypted databases with browser-friendly authentication.
"""
+import hmac
+import secrets
import os
import threading
import time
@@ -153,6 +155,18 @@ class DatabaseManager:
def __init__(self):
self.connections: Dict[str, Engine] = {}
+ # username -> (salt, digest) proving which password opened the cached
+ # engine. `connections` is keyed by username ALONE, so a cache hit
+ # says nothing about the credential presented on THIS call; without a
+ # verifier, returning the cached engine silently accepts any password.
+ # See _password_matches_cached().
+ #
+ # A fast keyed digest is the right primitive here: this is an
+ # in-process equality check, not at-rest storage, and the plaintext
+ # password already lives in memory in session_password_store, so a
+ # slow KDF would add cost without reducing exposure.
+ self._password_verifiers: Dict[str, tuple[bytes, bytes]] = {}
+ self._verifier_key = secrets.token_bytes(32)
self._connections_lock = threading.RLock()
# Per-user locks serializing the cold-open (engine build + migration)
# so two concurrent first-opens of one user never run alembic against
@@ -752,13 +766,108 @@ class DatabaseManager:
if not self.has_encryption and db_path.exists():
_best_effort_chmod(db_path, 0o600, warn=True)
- # Store connection AFTER migrations complete
- with self._connections_lock:
- self.connections[username] = engine
+ # Store connection AFTER migrations complete. This password just proved
+ # itself by creating the database; publish the engine and its verifier
+ # together so the cache is never briefly trusted without one.
+ self._cache_connection(username, engine, password)
logger.info(f"Created encrypted database for user {username}")
return engine
+ def _compute_verifier_digest(self, salt: bytes, password: str) -> bytes:
+ """Keyed digest binding ``password`` to a per-entry ``salt``.
+
+ A fast keyed HMAC, deliberately not a slow KDF: this is an in-process
+ equality check, never persisted, and the plaintext password already
+ lives in memory in session_password_store, so a KDF would add cost
+ without reducing exposure.
+
+ NOTE: CodeQL py/weak-sensitive-data-hashing flags the hash below as
+ weak password hashing. It is a reviewed FALSE POSITIVE: this app stores
+ no password hashes at rest (SQLCipher's PBKDF2 is the real KDF on the
+ cold-open path); this keyed digest only proves, in memory, that the SAME
+ password opened the cached engine, so a slow KDF here would add login
+ latency without reducing exposure. The rule is temporarily excluded in
+ .github/codeql/codeql-config.yml (see the TEMPORARY note there); the
+ preferred long-term fix is a per-alert dismissal in code scanning.
+ """
+ return hmac.new(
+ self._verifier_key, salt + password.encode("utf-8"), "sha256"
+ ).digest()
+
+ def _make_verifier(self, password: str) -> tuple[bytes, bytes]:
+ """Build a ``(salt, digest)`` verifier for ``password``. Takes no lock."""
+ salt = secrets.token_bytes(16)
+ return salt, self._compute_verifier_digest(salt, password)
+
+ def _cache_connection(
+ self, username: str, engine: Engine, password: str
+ ) -> None:
+ """Publish an engine and the verifier for the password that opened it,
+ atomically.
+
+ Called only on paths that have ALREADY proved the password by opening
+ (or creating) the SQLCipher database with it. Storing the engine and
+ its verifier under a single lock keeps the invariant "a cached
+ connection always has a matching verifier" true by construction, so a
+ concurrent open can never observe a connection with a missing or stale
+ verifier.
+ """
+ verifier = self._make_verifier(password)
+ with self._connections_lock:
+ self.connections[username] = engine
+ self._password_verifiers[username] = verifier
+
+ def _record_password_verifier(self, username: str, password: str) -> None:
+ """Arm the verifier for a connection cached by other means.
+
+ Prefer :meth:`_cache_connection` when publishing the engine too — it
+ stores both atomically. This standalone form arms a verifier against an
+ already-cached engine. Caller must not hold ``_connections_lock``.
+ """
+ verifier = self._make_verifier(password)
+ with self._connections_lock:
+ self._password_verifiers[username] = verifier
+
+ def _verifier_matches(self, username: str, password: str) -> bool:
+ """Lock-free verifier comparison. **Caller must hold _connections_lock.**
+
+ Fails CLOSED: a missing verifier returns False so the caller falls
+ through to a real key-validating open. Returning True on a missing
+ verifier would reopen exactly the hole this closes.
+ """
+ entry = self._password_verifiers.get(username)
+ if entry is None:
+ return False
+ salt, expected = entry
+ return hmac.compare_digest(
+ self._compute_verifier_digest(salt, password), expected
+ )
+
+ def _cached_engine_trusted(self, username: str, password: str) -> bool:
+ """May the cached engine for ``username`` be returned to a caller
+ presenting ``password``? **Caller must hold _connections_lock.**
+
+ Unencrypted mode has no credential to verify — the cold path opens the
+ plain-SQLite database with any password too — so the verifier is
+ meaningless there and would only force needless cold opens against the
+ placeholder passwords the app uses (session_context /
+ database_middleware). Trust the cache directly. Encrypted mode requires
+ a verifier match.
+ """
+ if not self.has_encryption:
+ return True
+ return self._verifier_matches(username, password)
+
+ def _password_matches_cached(self, username: str, password: str) -> bool:
+ """Does ``password`` match the one that opened the cached engine?
+
+ Fails CLOSED (see :meth:`_verifier_matches`). Takes the lock; prefer
+ :meth:`_verifier_matches` when already holding it.
+ """
+ with self._connections_lock:
+ return self._verifier_matches(username, password)
+
def _get_init_lock(self, username: str) -> threading.Lock:
"""Return the per-user cold-open lock, creating it on first use.
@@ -796,10 +905,24 @@ class DatabaseManager:
"Invalid encryption key: password cannot be None or empty"
)
- # Check if already open
+ # Check if already open.
+ #
+ # `connections` is keyed by username ALONE, so a hit proves only that
+ # SOMEONE opened this user's database -- not that the caller supplied
+ # the right password. Returning the engine on a bare hit made login
+ # accept ANY password for any user with a live cached connection,
+ # which is the normal state whenever they are logged in anywhere.
+ # Verify the credential against the one that actually opened it, and
+ # fall through to a real (key-validating) open when it does not match.
+ # Look up the engine and check its verifier under ONE lock acquisition
+ # so the engine cannot be evicted between the lookup and the verify
+ # (which would hand back a disposed, de-registered engine).
with self._connections_lock:
- if username in self.connections:
- return self.connections[username]
+ cached = self.connections.get(username)
+ if cached is not None and self._cached_engine_trusted(
+ username, password
+ ):
+ return cached
# Serialize the cold-open (engine build + migration) per user so two
# concurrent first-opens never run alembic against the same database
@@ -808,10 +931,14 @@ class DatabaseManager:
init_lock = self._get_init_lock(username)
with init_lock:
# Re-check: another thread may have completed the cold-open while
- # we were waiting for the per-user lock.
+ # we were waiting for the per-user lock. One lock acquisition, as
+ # above, so the engine cannot be evicted between lookup and verify.
with self._connections_lock:
- if username in self.connections:
- return self.connections[username]
+ cached = self.connections.get(username)
+ if cached is not None and self._cached_engine_trusted(
+ username, password
+ ):
+ return cached
engine = self._open_user_database_cold(
username, password, open_start
)
@@ -1011,9 +1138,11 @@ class DatabaseManager:
f"Database initialisation failed for {username}: {safe_msg}"
) from None
- # Store connection AFTER migrations complete
- with self._connections_lock:
- self.connections[username] = engine
+ # Store connection AFTER migrations complete. This password just
+ # proved itself against SQLCipher; publish the engine and its
+ # verifier together so the cache is never briefly trusted without
+ # one.
+ self._cache_connection(username, engine, password)
# NOTE: the phase-2 RAG index re-key does NOT run here. It re-enters
# open_user_database() (via get_user_db_session on a session-cache
@@ -1058,7 +1187,32 @@ class DatabaseManager:
return None
def get_session(self, username: str) -> Optional[Session]:
- """Create a new session for a user's database."""
+ """Bind a Session to ``username``'s ALREADY-open engine. Post-auth accessor.
+
+ SECURITY INVARIANT -- this intentionally takes NO password and performs
+ NO credential check, unlike ``open_user_database`` /
+ ``create_thread_safe_session_for_metrics`` (which gate their cache hit
+ through ``_cached_engine_trusted``). That is correct ONLY because this
+ is a post-authentication accessor, never an authentication entry point:
+
+ * It NEVER opens a database -- a cache miss returns ``None``. The
+ engine it hands back was published to ``connections`` solely by a
+ credential-verified create/open, so no unverified password can ever
+ reach the cache via this method.
+ * Every caller supplies a server-trusted ``username`` -- the signed
+ Flask-session identity (``session["username"]`` / ``g.current_user``)
+ or an internal server value (settings-snapshot thread, log drain)
+ -- and most also gate on ``is_user_connected`` (the never-open-on-
+ miss property above is the load-bearing guarantee, not that gate).
+ The username is never an attacker-supplied login attempt paired with
+ an unverified password, which is the shape that made the cached-
+ connection bypass exploitable (see ``open_user_database``).
+
+ DO NOT add a lazy open-on-miss here, and DO NOT call this from an
+ auth-decision path: either turns this accessor into an unauthenticated
+ bypass. Credential-taking entry points must go through
+ ``open_user_database`` instead.
+ """
with self._connections_lock:
if username not in self.connections:
# Use debug level for this common scenario to reduce log noise
@@ -1106,6 +1260,9 @@ class DatabaseManager:
f"Failed to dispose engine for {username}",
)
del self.connections[username]
+ # Drop the verifier with the connection it described, so a
+ # stale entry can never outlive the engine it was recorded for.
+ self._password_verifiers.pop(username, None)
# Deliberately do NOT pop _init_locks[username] here. A
# concurrent open_user_database may already hold a reference to
# this user's lock (fetched via _get_init_lock) and be about to
@@ -1127,6 +1284,7 @@ class DatabaseManager:
except Exception:
logger.debug(f"Error disposing engine for {username}")
self.connections.clear()
+ self._password_verifiers.clear()
self._init_locks.clear()
def check_database_integrity(self, username: str) -> bool:
@@ -1206,6 +1364,20 @@ class DatabaseManager:
# Use centralized rekey function
set_sqlcipher_rekey(conn, new_password, db_path=db_path)
+ # Evict the cached engine and its verifier NOW, while still inside
+ # the try. open_user_database() above cold-opened with old_password
+ # and cached that engine together with a verifier for old_password.
+ # The rekey just invalidated that engine's key (its creator closure
+ # still derives the OLD hex key, so any freshly pooled connection is
+ # mis-keyed) yet the cached verifier still matches old_password -- so
+ # until this eviction a concurrent open_user_database(old_password)
+ # would pass the verifier check and be handed the stale-key engine.
+ # change_password holds no lock across the rekey, so evict here
+ # rather than waiting for the finally. close_user_database is
+ # idempotent (no-ops when the user is not cached), so the
+ # finally-close below stays a backstop and is a no-op once this ran.
+ self.close_user_database(username)
+
logger.info(f"Password changed for user {username}")
return True
@@ -1267,8 +1439,9 @@ class DatabaseManager:
Args:
username: The username
- password: The user's password (encryption key), used only
- to open the user database on cache miss.
+ password: The user's password (encryption key). Verified against
+ the cached connection's recorded verifier on a cache hit, and
+ used to open the user database on a cache miss or mismatch.
Returns:
A SQLAlchemy Session bound to the per-user QueuePool engine.
@@ -1278,12 +1451,23 @@ class DatabaseManager:
if not db_path.exists():
raise ValueError(f"No database found for user {username}")
+ # Trust the cached engine only when the presented password matches the
+ # one that opened it -- the same fail-closed rule as
+ # open_user_database. Returning a session on a bare cache hit here
+ # would be a second instance of exactly the cached-connection password
+ # bypass this change closes; falling through to open_user_database on a
+ # mismatch re-validates the key against SQLCipher.
with self._connections_lock:
engine = self.connections.get(username)
+ if engine is not None and not self._cached_engine_trusted(
+ username, password
+ ):
+ engine = None
if engine is None:
- # Cache miss — open the user database. This is idempotent:
- # after the first call it just returns the cached engine.
+ # Cache miss (or a rejected cache hit) — open the user database.
+ # This is idempotent: after the first call it just returns the
+ # cached engine.
engine = self.open_user_database(username, password)
if engine is None:
raise ValueError(f"Failed to open database for user {username}")
diff --git a/tests/database/test_encrypted_db_coverage.py b/tests/database/test_encrypted_db_coverage.py
index 2e13cbbfe2..baa8b94587 100644
--- a/tests/database/test_encrypted_db_coverage.py
+++ b/tests/database/test_encrypted_db_coverage.py
@@ -52,6 +52,12 @@ def _unencrypted_manager():
# __init__ is bypassed here; mirror its per-user init-lock dict so the
# close_*/open paths that reference mgr._init_locks don't AttributeError.
mgr._init_locks = {}
+ # Likewise mirror the cached-connection password-verifier state so the
+ # close_*/open paths that read/clear it don't AttributeError.
+ import secrets
+
+ mgr._password_verifiers = {}
+ mgr._verifier_key = secrets.token_bytes(32)
mgr.has_encryption = False
import os
diff --git a/tests/database/test_encrypted_db_manager.py b/tests/database/test_encrypted_db_manager.py
index c8e07a8c08..bee9a56465 100644
--- a/tests/database/test_encrypted_db_manager.py
+++ b/tests/database/test_encrypted_db_manager.py
@@ -298,6 +298,11 @@ class TestDatabaseOpening:
mock_engine = MagicMock()
manager.connections["testuser"] = mock_engine
+ # A cached engine is now trusted only when a verifier proves which
+ # password opened it (see the cached-connection password bypass
+ # fix). Record the matching verifier so this exercises the intended
+ # cache-reuse path rather than the fail-closed fallback.
+ manager._record_password_verifier("testuser", "password")
result = manager.open_user_database("testuser", "password")
@@ -875,6 +880,9 @@ class TestThreadSafeSessionForMetrics:
mock_engine = MagicMock()
manager.connections["testuser"] = mock_engine
+ # The cached engine is trusted on a metrics-session cache hit only
+ # when the presented password matches the recorded verifier.
+ manager._record_password_verifier("testuser", "password")
with patch.object(
manager, "_get_user_db_path", return_value=db_file
@@ -928,8 +936,10 @@ class TestThreadSafeSessionForMetrics:
conn.commit()
# Inject the engine so create_thread_safe_session_for_metrics
- # finds it on cache hit.
+ # finds it on cache hit, with a verifier matching the password the
+ # writer threads present ("unused") so the cache hit is trusted.
manager.connections["testuser"] = engine
+ manager._record_password_verifier("testuser", "unused")
try:
with patch.object(
diff --git a/tests/security/test_change_password_evicts_stale_engine.py b/tests/security/test_change_password_evicts_stale_engine.py
new file mode 100644
index 0000000000..18e289f121
--- /dev/null
+++ b/tests/security/test_change_password_evicts_stale_engine.py
@@ -0,0 +1,172 @@
+"""Regression coverage for the change_password stale-cached-engine window.
+
+``change_password`` cold-opens the user's database with the OLD password
+(``open_user_database`` caches that engine together with a verifier for the old
+password), rekeys the SQLCipher file to the NEW password, and then closes the
+connection. Before the fix the close happened ONLY in the ``finally`` block, so
+between the rekey and the finally the cache held an engine whose creator closure
+still derives the now-invalid OLD key while its verifier still matched the OLD
+password. In that window a concurrent ``open_user_database(username, old)`` would
+pass the verifier check and be handed the stale-key engine, and ``change_password``
+holds no lock across the rekey.
+
+The fix evicts the connection (and its verifier) immediately AFTER the rekey,
+INSIDE the ``try``, keeping the finally-close as an idempotent backstop.
+
+This test pins that the eviction is performed by the in-try close, NOT merely by
+the finally. It neutralises the finally-close and proves the stale engine/verifier
+are already gone, then proves the old password can no longer open the database and
+the new password can. Because the finally is neutralised, a build that relied on
+the finally alone would leave the stale engine cached and fail here.
+
+Surfaced by a multi-agent review of PR #5596.
+"""
+
+import uuid
+
+import pytest
+
+from local_deep_research.database import encrypted_db
+from local_deep_research.database.encrypted_db import DatabaseManager
+
+
+def manager(tmp_path, monkeypatch):
+ """A DatabaseManager writing to an isolated data directory."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ mgr = DatabaseManager()
+ mgr.data_dir = tmp_path
+ yield mgr
+ # Dispose the real SQLCipher engines these tests open (StaticPool under
+ # TESTING=1 holds one live connection per engine indefinitely otherwise).
+ mgr.close_all_databases()
+
+
+class _LoggerProxy:
+ """Delegates to the real loguru logger but reports every ``info`` message.
+
+ Used to observe WHEN change_password emits its "Password changed" success
+ line, which is logged after the in-try eviction but before the finally-close
+ -- letting the close spy tell the two closes apart.
+ """
+
+ def __init__(self, real, on_info):
+ self._real = real
+ self._on_info = on_info
+
+ def info(self, message, *args, **kwargs):
+ self._on_info(message)
+ return self._real.info(message, *args, **kwargs)
+
+ def __getattr__(self, name): # warning/debug/opt/... pass straight through
+ return getattr(self._real, name)
+
+
+def test_change_password_evicts_stale_engine_in_try_not_only_finally(
+ manager, monkeypatch
+):
+ if not manager.has_encryption:
+ pytest.skip("SQLCipher not available; rekey path is a no-op")
+
+ username = f"chgpwwin_{uuid.uuid4().hex[:8]}"
+ old = "OldCorrectHorse1!" # noqa: S105
+ new = "NewCorrectHorse2!" # noqa: S105
+
+ engine = manager.create_user_database(username, old)
+ assert engine is not None
+ assert manager.is_user_connected(username)
+
+ state = {
+ "rekeyed": False,
+ "success_logged": False,
+ "intry_close": False,
+ "intry_engine_present": None,
+ "intry_verifier_present": None,
+ "gone_after_intry": None,
+ "finally_neutralized": False,
+ }
+
+ # Flag the exact moment the rekey completes: everything after this and
+ # before the "Password changed" log is the in-try region the fix targets.
+ real_rekey = encrypted_db.set_sqlcipher_rekey
+
+ def spy_rekey(conn, new_password, **kwargs):
+ real_rekey(conn, new_password, **kwargs)
+ state["rekeyed"] = True
+
+ monkeypatch.setattr(encrypted_db, "set_sqlcipher_rekey", spy_rekey)
+
+ # The success line is logged AFTER the in-try close but BEFORE the finally.
+ def on_info(message):
+ if "Password changed" in str(message):
+ state["success_logged"] = True
+
+ monkeypatch.setattr(
+ encrypted_db, "logger", _LoggerProxy(encrypted_db.logger, on_info)
+ )
+
+ # Spy the close so we can (a) capture the state at the in-try eviction and
+ # (b) NEUTRALISE the finally-close, forcing the in-try close to be the only
+ # thing that could have removed the stale engine/verifier.
+ real_close = manager.close_user_database
+
+ def spy_close(user):
+ if state["rekeyed"] and not state["success_logged"]:
+ # The in-try eviction (post-rekey, pre-success-log). The stale
+ # engine + old verifier must still be cached right now -- that is
+ # the very window being closed -- and must be gone once we evict.
+ state["intry_close"] = True
+ state["intry_engine_present"] = user in manager.connections
+ state["intry_verifier_present"] = (
+ user in manager._password_verifiers
+ )
+ real_close(user)
+ state["gone_after_intry"] = (
+ user not in manager.connections
+ and user not in manager._password_verifiers
+ )
+ return
+ if state["rekeyed"] and state["success_logged"]:
+ # The finally backstop. Neutralise it: if the in-try close did its
+ # job the stale state is already gone; if the code relied on the
+ # finally alone, skipping it here leaves the stale engine cached and
+ # the assertions below fail.
+ state["finally_neutralized"] = True
+ return
+ # The pre-rekey close at the top of change_password: run normally.
+ real_close(user)
+
+ monkeypatch.setattr(manager, "close_user_database", spy_close)
+
+ assert manager.change_password(username, old, new) is True
+
+ # 1. The eviction happened INSIDE the try, right after the rekey...
+ assert state["intry_close"], (
+ "change_password must evict the cached engine in-try after the rekey, "
+ "not only in the finally"
+ )
+ # 2. ...and at that instant the stale-key engine + old verifier were still
+ # cached, i.e. the window is real and this close is what closes it.
+ assert state["intry_engine_present"] is True
+ assert state["intry_verifier_present"] is True
+ assert state["gone_after_intry"] is True
+ # 3. The finally ran but we neutralised it, so anything still gone below is
+ # attributable to the in-try close, not the finally backstop.
+ assert state["finally_neutralized"] is True
+
+ # 4. Stale engine and old verifier are gone even with the finally disabled.
+ assert username not in manager.connections
+ assert username not in manager._password_verifiers
+
+ # 5. The old password can no longer open the re-keyed database, and the new
+ # password can. (These re-open, so restore the real close first.)
+ monkeypatch.setattr(manager, "close_user_database", real_close)
+ monkeypatch.setattr(encrypted_db, "set_sqlcipher_rekey", real_rekey)
+
+ assert manager.open_user_database(username, old) is None, (
+ "the old password must not open the re-keyed database"
+ )
+ reopened = manager.open_user_database(username, new)
+ assert reopened is not None
+ assert manager._password_matches_cached(username, new)
+ assert not manager._password_matches_cached(username, old)
diff --git a/tests/security/test_login_cached_connection_password.py b/tests/security/test_login_cached_connection_password.py
new file mode 100644
index 0000000000..e6201deeb6
--- /dev/null
+++ b/tests/security/test_login_cached_connection_password.py
@@ -0,0 +1,125 @@
+"""Login must verify the password even when the user's DB is already open.
+
+``DatabaseManager.connections`` is keyed by username ALONE. A cache hit
+therefore proves only that *someone* opened that user's database -- not that
+the caller supplied the right password. ``open_user_database`` used to return
+the cached engine on a bare hit, and the login route's only credential check
+is whether that call returns non-None:
+
+ engine = db_manager.open_user_database(username, password)
+
+So while any session for a username was live -- the normal state whenever that
+user is logged in anywhere -- knowing only the USERNAME was enough to
+authenticate as them. It also called ``record_success()``, so it never tripped
+the lockout counter or the rate limiter: there was nothing to brute-force and
+nothing in the logs resembling an attack.
+
+The cold-open path always validated the key against SQLCipher, which is why
+the same wrong password was correctly rejected once the connection closed.
+These tests pin both halves so the cache path can never diverge from it again.
+"""
+
+import uuid
+
+import pytest
+
+from local_deep_research.database.encrypted_db import DatabaseManager
+
+
+def manager(tmp_path, monkeypatch):
+ """A DatabaseManager writing to an isolated data directory."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ mgr = DatabaseManager()
+ mgr.data_dir = tmp_path
+ yield mgr
+ # Dispose the real SQLCipher engines these tests open (StaticPool under
+ # TESTING=1 holds one live connection per engine indefinitely otherwise).
+ # Matches the established pattern in tests/auth_tests/test_encrypted_db.py.
+ mgr.close_all_databases()
+
+
+def user(manager):
+ """A registered user whose database is created and left OPEN.
+
+ Leaving it cached is the whole point: it is the state that made the
+ bypass reachable.
+ """
+ username = f"cachetest_{uuid.uuid4().hex[:8]}"
+ password = "CorrectHorseBattery1!" # noqa: S105
+ engine = manager.create_user_database(username, password)
+ assert engine is not None, "setup failed: could not create the user DB"
+ assert manager.is_user_connected(username), (
+ "setup failed: the connection should be cached after creation"
+ )
+ return username, password
+
+
+def test_wrong_password_rejected_while_connection_is_cached(manager, user):
+ """The bypass itself."""
+ username, _ = user
+
+ engine = manager.open_user_database(username, "totally-wrong-password")
+
+ assert engine is None, (
+ "a wrong password opened the database because the connection was "
+ "cached -- the cache hit skipped credential verification entirely"
+ )
+
+
+def test_correct_password_still_uses_the_cache(manager, user):
+ """The fix must not turn every login into a cold open."""
+ username, password = user
+
+ first = manager.open_user_database(username, password)
+ second = manager.open_user_database(username, password)
+
+ assert first is not None
+ assert second is first, (
+ "the correct password should return the cached engine, not rebuild it"
+ )
+
+
+def test_wrong_password_rejected_when_connection_is_cold(manager, user):
+ """Control: the cold path was always correct. If this ever fails, the
+ test is lying about what it proves."""
+ username, _ = user
+ manager.close_user_database(username)
+ assert not manager.is_user_connected(username)
+
+ assert (
+ manager.open_user_database(username, "totally-wrong-password") is None
+ )
+
+
+def test_correct_password_works_after_close(manager, user):
+ """A real close-then-reopen must still succeed -- the verifier is dropped
+ with the connection, and the reopen re-proves the password."""
+ username, password = user
+ manager.close_user_database(username)
+
+ assert manager.open_user_database(username, password) is not None
+
+
+def test_verifier_is_dropped_when_the_connection_closes(manager, user):
+ """No verifier may outlive the engine it described."""
+ username, _ = user
+ assert username in manager._password_verifiers
+
+ manager.close_user_database(username)
+
+ assert username not in manager._password_verifiers
+
+
+def test_cache_is_unusable_without_a_verifier(manager, user):
+ """Fail closed.
+
+ If a connection is cached but no verifier was recorded (a path that
+ forgot to call _record_password_verifier), the cache must not be trusted.
+ Returning True there would reopen exactly this hole.
+ """
+ username, password = user
+ manager._password_verifiers.pop(username, None)
+
+ assert manager._password_matches_cached(username, password) is False
diff --git a/tests/security/test_login_cached_connection_password_extra.py b/tests/security/test_login_cached_connection_password_extra.py
new file mode 100644
index 0000000000..8a86e919a0
--- /dev/null
+++ b/tests/security/test_login_cached_connection_password_extra.py
@@ -0,0 +1,271 @@
+"""Extra regression coverage for the cached-connection password verifier.
+
+Companion to ``test_login_cached_connection_password.py``. That file pins the
+core bypass and the fail-closed contract; this one pins the surrounding
+behaviours a reviewer worried about the fix would want proven:
+
+* a rejected wrong-password attempt on a warm cache must not disturb the
+ legitimate user's cached engine/verifier (a mismatch that evicted the live
+ engine would turn every wrong guess into a DoS against the real session);
+* the phase-2 RAG re-key that re-enters ``open_user_database`` mid-login with
+ the same password must reuse the cache, not trigger a second cold open;
+* changing a password must invalidate the old verifier and arm the new one,
+ and a *failed* change must leave no stale verifier/engine behind;
+* two threads racing a first open with a wrong password must never be handed
+ an engine;
+* the metrics-session path fails closed on a wrong password just like login;
+* unencrypted mode (no credential to verify) must still reuse the cache
+ instead of thrashing cold opens.
+
+These cases were surfaced by a multi-agent review of PR #5596.
+"""
+
+import threading
+import uuid
+
+import pytest
+
+from local_deep_research.database.encrypted_db import DatabaseManager
+
+
+def manager(tmp_path, monkeypatch):
+ """A DatabaseManager writing to an isolated data directory."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ mgr = DatabaseManager()
+ mgr.data_dir = tmp_path
+ yield mgr
+ # Dispose the real SQLCipher engines these tests open (StaticPool under
+ # TESTING=1 holds one live connection per engine indefinitely otherwise).
+ # Matches the established pattern in tests/auth_tests/test_encrypted_db.py.
+ mgr.close_all_databases()
+
+
+def user(manager):
+ """A registered user whose database is created and left OPEN (cached)."""
+ username = f"cacheextra_{uuid.uuid4().hex[:8]}"
+ password = "CorrectHorseBattery1!" # noqa: S105
+ engine = manager.create_user_database(username, password)
+ assert engine is not None, "setup failed: could not create the user DB"
+ assert manager.is_user_connected(username), (
+ "setup failed: the connection should be cached after creation"
+ )
+ return username, password
+
+
+def test_wrong_password_leaves_legit_cached_connection_intact(manager, user):
+ """A rejected wrong-password attempt must not evict or replace the
+ legitimate cached engine, and the correct password must still return that
+ same engine object afterwards."""
+ username, password = user
+ original = manager.connections[username]
+
+ rejected = manager.open_user_database(username, "totally-wrong-password")
+
+ assert rejected is None
+ assert manager.is_user_connected(username), (
+ "the wrong-password attempt must not have closed the legit connection"
+ )
+ assert manager.connections[username] is original, (
+ "the wrong-password attempt must not have replaced the cached engine"
+ )
+ assert manager._password_matches_cached(username, password), (
+ "the legitimate verifier must survive a rejected attempt"
+ )
+ assert manager.open_user_database(username, password) is original, (
+ "the correct password must still return the same cached engine"
+ )
+
+
+def test_phase2_rekey_reentry_reuses_cached_engine(manager, monkeypatch):
+ """The phase-2 RAG re-key re-enters open_user_database() mid-login with the
+ same password. That re-entry must hit the freshly-populated cache, not do a
+ second cold open, and its verifier check must match."""
+ username = f"rekey_{uuid.uuid4().hex[:8]}"
+ password = "CorrectHorseBattery1!" # noqa: S105
+ manager.create_user_database(username, password)
+ manager.close_user_database(username)
+
+ cold_passwords = []
+ original_cold = manager._open_user_database_cold
+
+ def counting_cold(u, p, start):
+ cold_passwords.append(p)
+ return original_cold(u, p, start)
+
+ monkeypatch.setattr(manager, "_open_user_database_cold", counting_cold)
+
+ reentry = {}
+
+ def fake_rekey(u, db_password):
+ # Exactly what legacy_rekey does: re-enter with the same password.
+ reentry["engine"] = manager.open_user_database(u, db_password)
+ reentry["verifier_matched"] = manager._password_matches_cached(
+ u, db_password
+ )
+
+ monkeypatch.setattr(
+ "local_deep_research.vector_stores.legacy_rekey.rekey_user_indexes",
+ fake_rekey,
+ )
+
+ engine = manager.open_user_database(username, password)
+
+ assert reentry, "the phase-2 re-key hook did not run on the cold open"
+ assert len(cold_passwords) == 1, (
+ "the re-key re-entry must reuse the cache, not trigger a 2nd cold open"
+ )
+ assert reentry["engine"] is engine, (
+ "the re-key re-entry must get the same cached engine"
+ )
+ assert reentry["verifier_matched"] is True
+
+
+def test_password_change_invalidates_old_verifier_and_arms_new(manager):
+ """After change_password, the old password must be rejected (even while the
+ new connection is warm) and the new password accepted."""
+ username = f"chgpw_{uuid.uuid4().hex[:8]}"
+ old = "OldCorrectHorse1!" # noqa: S105
+ new = "NewCorrectHorse2!" # noqa: S105
+ manager.create_user_database(username, old)
+
+ assert manager.change_password(username, old, new) is True
+
+ # change_password closes the connection; the old verifier must be gone.
+ assert username not in manager._password_verifiers
+ assert manager.open_user_database(username, old) is None, (
+ "the old password must not open the re-keyed database"
+ )
+ engine = manager.open_user_database(username, new)
+ assert engine is not None
+ assert manager._password_matches_cached(username, new)
+ assert not manager._password_matches_cached(username, old)
+ # Old password rejected while the NEW connection is warm (the cache path).
+ assert manager.open_user_database(username, old) is None
+ assert manager.connections[username] is engine, (
+ "the rejected old-password attempt must not replace the new engine"
+ )
+
+
+def test_failed_password_change_leaves_no_stale_state(manager):
+ """A change_password with the wrong current password must fail and leave no
+ stale verifier or connection behind."""
+ username = f"chgpwfail_{uuid.uuid4().hex[:8]}"
+ password = "CorrectHorseBattery1!" # noqa: S105
+ manager.create_user_database(username, password)
+ manager.close_user_database(username)
+ manager.open_user_database(username, password)
+
+ assert manager.change_password(username, "wrong-old", "Another3!") is False
+ assert not manager.is_user_connected(username)
+ assert username not in manager._password_verifiers
+ # The real password still works after the failed change.
+ assert manager.open_user_database(username, password) is not None
+
+
+def test_concurrent_first_open_never_returns_engine_for_wrong_password(
+ manager,
+):
+ """Two threads racing the very first open of a user -- one with the correct
+ password, one with a wrong one -- must never hand the wrong-password caller
+ an engine, regardless of interleaving on the per-user init lock."""
+ username = f"race_{uuid.uuid4().hex[:8]}"
+ password = "CorrectHorseBattery1!" # noqa: S105
+ # Create then close so the first concurrent open is a genuine cold open.
+ manager.create_user_database(username, password)
+ manager.close_user_database(username)
+
+ results = {}
+ errors = {}
+ barrier = threading.Barrier(2)
+
+ def attempt(key, pw):
+ barrier.wait(timeout=30)
+ try:
+ results[key] = manager.open_user_database(username, pw)
+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below
+ # A bare `results[key] = manager.open_user_database(...)` would
+ # let an unexpected exception in this thread vanish (Thread
+ # swallows it) and turn into an opaque KeyError on `results[key]`
+ # below instead of the real failure.
+ errors[key] = exc
+
+ threads = [
+ threading.Thread(target=attempt, args=("good", password)),
+ threading.Thread(target=attempt, args=("bad", "totally-wrong")),
+ ]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=60)
+
+ # Fail fast rather than hang the whole suite if a future lock-ordering
+ # regression deadlocks the racing opens.
+ assert not any(t.is_alive() for t in threads), (
+ "open_user_database deadlocked under a concurrent wrong/right race"
+ )
+ assert not errors, f"open_user_database raised in a racing thread: {errors}"
+ assert results["good"] is not None, "the correct password must succeed"
+ assert results["bad"] is None, (
+ "the wrong password must never be handed an engine, even while racing "
+ "a legitimate concurrent open"
+ )
+
+
+def test_metrics_session_is_fail_closed_on_wrong_password(manager, user):
+ """create_thread_safe_session_for_metrics must not hand out a session on a
+ cached engine for a wrong password -- it is the same cache-hit-returns-
+ engine shape as login and must fail closed the same way.
+
+ A wrong password falls through to a real open, which rejects it; the
+ correct password binds a session to the cached engine.
+ """
+ username, password = user
+ cached = manager.connections[username]
+
+ with pytest.raises(ValueError):
+ manager.create_thread_safe_session_for_metrics(
+ username, "totally-wrong-password"
+ )
+ # The rejected attempt must not have disturbed the legit cached engine.
+ assert manager.connections[username] is cached
+
+ session = manager.create_thread_safe_session_for_metrics(username, password)
+ try:
+ assert session.bind is cached, (
+ "the correct password must reuse the cached engine"
+ )
+ finally:
+ session.close()
+
+
+def test_unencrypted_mode_reuses_cached_engine(tmp_path, monkeypatch):
+ """Unencrypted mode must reuse the cached engine across the different
+ placeholder 'passwords' the app uses, not thrash cold opens.
+
+ There is no credential to verify in unencrypted mode (the cold path opens
+ the plain-SQLite DB with any password), so the verifier check is
+ short-circuited (see _cached_engine_trusted); otherwise the placeholder
+ passwords used by session_context/database_middleware would mismatch and
+ force repeated cold opens that orphan engines.
+ """
+ monkeypatch.setenv("LDR_BOOTSTRAP_ALLOW_UNENCRYPTED", "true")
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ mgr = DatabaseManager()
+ mgr.has_encryption = False
+ mgr.data_dir = tmp_path
+
+ try:
+ username = f"unenc_{uuid.uuid4().hex[:8]}"
+ engine = mgr.create_user_database(username, "RealUserPassword123!")
+ assert engine is not None
+
+ # The three strings the app actually uses for the same unencrypted DB.
+ assert (
+ mgr.open_user_database(username, "RealUserPassword123!") is engine
+ )
+ assert mgr.open_user_database(username, "unencrypted-mode") is engine
+ assert mgr.open_user_database(username, "dummy") is engine
+ finally:
+ mgr.close_all_databases()
diff --git a/tests/security/test_login_cached_connection_password_lifecycle.py b/tests/security/test_login_cached_connection_password_lifecycle.py
new file mode 100644
index 0000000000..148ebfdd0f
--- /dev/null
+++ b/tests/security/test_login_cached_connection_password_lifecycle.py
@@ -0,0 +1,270 @@
+"""Lifecycle coverage for the cached-connection password verifier.
+
+Companion to ``test_login_cached_connection_password.py`` and
+``test_login_cached_connection_password_extra.py``. Those two files pin the
+core bypass, the fail-closed contract, non-destructive rejection, the
+phase-2 rekey re-entry, password-change, concurrency, and the metrics-session
+path. This file fills the remaining lifecycle gaps:
+
+1. A composed fail-closed-then-heal sequence driven THROUGH the public
+ ``open_user_database`` API (not the private ``_password_matches_cached``
+ helper): dropping the verifier for a cached engine must force a real
+ cold-reopen on the very next call, and that cold-reopen must RE-ARM the
+ verifier so a subsequent call is trusted again.
+2. ``close_all_databases`` clears both ``connections`` and
+ ``_password_verifiers``.
+3. Multi-user isolation: two users' cached engines and verifiers never cross
+ -- user A's password can never open user B's cache entry, and evicting
+ A's verifier does not disturb B's.
+4. The verifier is re-armed on every cold-open success, not just the first
+ one (create -> close -> open must both return a working engine and leave
+ the verifier trusting that same password).
+5. ``is_user_connected`` reflects only liveness (cached vs. not), never the
+ password argument -- it takes no password at all, but the tests here pin
+ that its answer tracks close/open regardless of what password is used to
+ reopen.
+"""
+
+import uuid
+
+import pytest
+
+from local_deep_research.database.encrypted_db import DatabaseManager
+
+
+def manager(tmp_path, monkeypatch):
+ """A DatabaseManager writing to an isolated data directory."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ mgr = DatabaseManager()
+ mgr.data_dir = tmp_path
+ yield mgr
+ # Dispose the real SQLCipher engines these tests open (StaticPool under
+ # TESTING=1 holds one live connection per engine indefinitely otherwise).
+ # Matches the established pattern in tests/auth_tests/test_encrypted_db.py.
+ mgr.close_all_databases()
+
+
+def _make_user(manager, prefix, password="CorrectHorseBattery1!"): # noqa: S107
+ """Create-and-leave-cached a fresh user, returning (username, password)."""
+ username = f"{prefix}_{uuid.uuid4().hex[:8]}"
+ engine = manager.create_user_database(username, password)
+ assert engine is not None, "setup failed: could not create the user DB"
+ assert manager.is_user_connected(username), (
+ "setup failed: the connection should be cached after creation"
+ )
+ return username, password
+
+
+def user(manager):
+ """A registered user whose database is created and left OPEN (cached)."""
+ return _make_user(manager, "lifecycle")
+
+
+def test_dropped_verifier_heals_through_public_api(manager, user):
+ """Composed fail-closed-then-heal driven through open_user_database().
+
+ Dropping the verifier for a live cached engine (simulating any bug or
+ code path that lost track of it) must not let the correct password
+ silently reuse the now-unproven cache entry. open_user_database() must
+ fall through to a real cold reopen -- and that cold reopen must succeed
+ and re-publish a fresh verifier, so the NEXT call is trusted again
+ without a further cold open.
+ """
+ username, password = user
+
+ # Simulate a verifier loss on an otherwise-live connection.
+ manager._password_verifiers.pop(username, None)
+
+ # Call 1: the public API, with the CORRECT password, on a cached engine
+ # with no verifier. Must fail closed on the cache and fall through to a
+ # real cold reopen rather than returning the (now unverifiable) cached
+ # engine or refusing outright.
+ healed_engine = manager.open_user_database(username, password)
+
+ assert healed_engine is not None, (
+ "the correct password must still succeed via a cold reopen even "
+ "though the cached engine's verifier was lost"
+ )
+ # The cold-reopen path always disposes and rebuilds the engine (see
+ # _open_user_database_cold), so this need not be the same object that
+ # was cached before the verifier was dropped, but it must be live and
+ # cached now.
+ assert manager.is_user_connected(username)
+ assert manager.connections[username] is healed_engine
+
+ # The heal must have re-armed the verifier immediately -- no further
+ # cold open should be required.
+ assert username in manager._password_verifiers, (
+ "the cold reopen must re-publish a verifier for the healed engine"
+ )
+
+ # Call 2: the public API again. This must now be a warm cache hit that
+ # trusts the verifier (no dropped-verifier fallback this time) and
+ # returns the SAME engine object rebuilt in call 1.
+ second = manager.open_user_database(username, password)
+ assert second is healed_engine, (
+ "after healing, the cache must be reused rather than cold-opening again"
+ )
+ assert manager._password_matches_cached(username, password) is True, (
+ "the re-armed verifier must accept the same password that healed it"
+ )
+
+ # And the safety property still holds post-heal: a wrong password must
+ # still be rejected against the newly-armed verifier.
+ assert manager.open_user_database(username, "still-wrong") is None
+ assert manager.connections[username] is healed_engine, (
+ "a rejected wrong-password attempt after healing must not disturb "
+ "the healed engine"
+ )
+
+
+def test_close_all_databases_clears_connections_and_verifiers(manager):
+ """close_all_databases must wipe both maps, not just one."""
+ userA = _make_user(manager, "closeall_a")
+ userB = _make_user(manager, "closeall_b")
+
+ assert manager.connections
+ assert manager._password_verifiers
+
+ manager.close_all_databases()
+
+ assert manager.connections == {}, (
+ "close_all_databases must clear every cached engine"
+ )
+ assert manager._password_verifiers == {}, (
+ "close_all_databases must clear every cached verifier -- a leftover "
+ "verifier with no matching engine is dead weight, and if a future "
+ "bug ever re-added the engine under the same username without going "
+ "through _cache_connection, a stale verifier here would silently "
+ "authorize it"
+ )
+
+ # Both users must be fully logged out from the manager's point of view.
+ assert not manager.is_user_connected(userA[0])
+ assert not manager.is_user_connected(userB[0])
+
+
+def test_multi_user_isolation(manager):
+ """Two users open concurrently (both left cached); their engines and
+ verifiers must never cross.
+
+ Deliberately DIFFERENT passwords for A and B -- reusing the same
+ password across users would make a cross-user open trivially succeed
+ for the wrong reason (both passwords are "correct"), not prove
+ isolation.
+ """
+ userA, passwordA = _make_user(manager, "isoA", "AliceCorrectHorse1!")
+ userB, passwordB = _make_user(manager, "isoB", "BobDifferentHorse2!")
+
+ engineA = manager.connections[userA]
+ engineB = manager.connections[userB]
+ assert engineA is not engineB
+
+ # Each user's own correct password returns only their own engine.
+ assert manager.open_user_database(userA, passwordA) is engineA
+ assert manager.open_user_database(userB, passwordB) is engineB
+
+ # User A's password must never open user B's cache entry, and vice
+ # versa -- even though both usernames have live cached connections.
+ assert manager.open_user_database(userB, passwordA) is None, (
+ "user A's password must not open user B's cached database"
+ )
+ assert manager.open_user_database(userA, passwordB) is None, (
+ "user B's password must not open user A's cached database"
+ )
+
+ # The rejected cross-user attempts must not have disturbed either
+ # legitimate cached engine.
+ assert manager.connections[userA] is engineA
+ assert manager.connections[userB] is engineB
+ assert manager._password_matches_cached(userA, passwordA)
+ assert manager._password_matches_cached(userB, passwordB)
+
+ # Dropping A's verifier must not affect B's verifier or cache entry at
+ # all -- the maps are keyed per-user and must not interact.
+ manager._password_verifiers.pop(userA, None)
+
+ assert userB in manager._password_verifiers
+ assert manager._password_matches_cached(userB, passwordB) is True
+ assert manager.connections[userB] is engineB
+ assert manager.is_user_connected(userB)
+
+ # And B's state is untouched by A's verifier being gone: B's correct
+ # password still returns B's cached engine without a cold open.
+ assert manager.open_user_database(userB, passwordB) is engineB
+
+
+def test_verifier_rearmed_on_cold_open_after_close(manager, user):
+ """create -> close -> open(correct) must return a working engine AND
+ leave _password_matches_cached True -- pinning that _cache_connection
+ actually ran on the cold-open path (not just at creation time)."""
+ username, password = user
+
+ manager.close_user_database(username)
+ assert not manager.is_user_connected(username)
+ assert username not in manager._password_verifiers
+
+ engine = manager.open_user_database(username, password)
+
+ assert engine is not None
+ assert manager.is_user_connected(username)
+ assert manager._password_matches_cached(username, password) is True, (
+ "the cold-open path must re-arm the verifier, not merely return an "
+ "engine"
+ )
+
+ # The engine returned must actually be usable (a real, working
+ # SQLCipher-backed connection), not a stale/disposed reference.
+ with engine.connect() as conn:
+ from sqlalchemy import text
+
+ result = conn.execute(text("SELECT 1")).scalar()
+ assert result == 1
+
+ # And the cache must genuinely be warm now: a second call with the same
+ # password returns the identical engine object without another cold
+ # open.
+ assert manager.open_user_database(username, password) is engine
+
+
+def test_is_user_connected_reflects_liveness_only(manager, user):
+ """is_user_connected must track cached-vs-not, and must be completely
+ unaffected by any password argument passed elsewhere -- it takes no
+ password parameter at all, and its answer must not depend on whether the
+ most recent open_user_database call used the right or wrong password."""
+ username, password = user
+
+ assert manager.is_user_connected(username) is True
+
+ manager.close_user_database(username)
+ assert manager.is_user_connected(username) is False
+
+ # A rejected wrong-password open on a not-yet-cached user must not make
+ # is_user_connected report True.
+ assert (
+ manager.open_user_database(username, "totally-wrong-password") is None
+ )
+ assert manager.is_user_connected(username) is False
+
+ # Reopening with the correct password makes it live again.
+ engine = manager.open_user_database(username, password)
+ assert engine is not None
+ assert manager.is_user_connected(username) is True
+
+ # Now that it's cached, a rejected wrong-password attempt must leave it
+ # connected (the legit connection survives) -- liveness is unaffected by
+ # a failed credential check either way.
+ assert manager.open_user_database(username, "still-wrong") is None
+ assert manager.is_user_connected(username) is True
+
+ # And an unknown user (never created) must simply read False -- no
+ # password argument involved at all.
+ assert (
+ manager.is_user_connected(f"never-existed-{uuid.uuid4().hex[:8]}")
+ is False
+ )
+
+ manager.close_user_database(username)
+ assert manager.is_user_connected(username) is False
diff --git a/tests/security/test_login_cached_connection_password_lockout.py b/tests/security/test_login_cached_connection_password_lockout.py
new file mode 100644
index 0000000000..0e3f238c5a
--- /dev/null
+++ b/tests/security/test_login_cached_connection_password_lockout.py
@@ -0,0 +1,289 @@
+"""Route-level proof that PR #5596 restores account-lockout accounting.
+
+Pre-fix, ``open_user_database`` returned the cached engine for ANY password
+whenever a connection was already warm (see ``encrypted_db.py``). The login
+route (``web/auth/routes.py``) treats a non-None engine as a successful
+login and calls ``lockout_mgr.record_success(username)`` -- which *clears*
+the failure counter. So pre-fix, a wrong password against a warm cached
+connection did not just bypass authentication: it actively evaded account
+lockout, clearing any accumulated failure count on every attempt. A
+credential-stuffing run against a logged-in victim could never trip the
+lockout threshold.
+
+The companion ``test_login_cached_connection_password_route.py`` pins the
+authentication outcome (never a 302 / no session minted). This file pins
+the *lockout accounting* side effect of that same code path, asserting
+against the real module-level ``AccountLockoutManager`` singleton the route
+actually uses.
+
+Reproduces the multi-agent review's lockout-evasion finding for PR #5596.
+"""
+
+import uuid
+
+import pytest
+
+
+def app_client(tmp_path, monkeypatch):
+ """A real app + a live module-level db_manager pointed at a temp data dir.
+
+ Same pattern as test_login_cached_connection_password_route.py: the
+ login route reads the module-level ``db_manager`` singleton (so the
+ warm-cache state must live on that exact instance) AND the module-level
+ account-lockout singleton (so the lockout assertions are against what
+ the route itself mutates, not a private copy).
+ """
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ monkeypatch.setenv("LDR_TESTING_WITH_MOCKS", "true")
+ # NOTE: `LDR_RATE_LIMITING_ENABLED` (used by the companion route test) is
+ # a *different* knob entirely -- it controls the adaptive search-engine
+ # rate limiter, not the Flask HTTP rate limiter guarding /auth/login (see
+ # settings/env_registry.py:is_rate_limiting_enabled's own docstring
+ # warning about this exact name collision, issue #3905). The login route
+ # is also wrapped in `login_limit` ("5 per 15 minutes" per IP by
+ # default), which we WOULD hit partway through the lockout-threshold
+ # loop below (masking record_failure() calls behind 429s instead of
+ # 401s) without disabling it via the canonical var here.
+ monkeypatch.setenv("LDR_DISABLE_RATE_LIMITING", "true")
+
+ from local_deep_research.database.auth_db import init_auth_database
+ from local_deep_research.database.encrypted_db import db_manager
+ from local_deep_research.security.account_lockout import (
+ get_account_lockout_manager,
+ )
+ from local_deep_research.web.app_factory import create_app
+ import local_deep_research.web.auth.routes as auth_routes
+
+ if not db_manager.has_encryption:
+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")
+
+ # Everything that mutates the module-level singleton lives inside
+ # try/finally from here on, INCLUDING setup -- mirroring the companion
+ # route fixture. init_auth_database()/create_app() can raise, and a
+ # setup-time raise before the try would leave db_manager.data_dir pointed
+ # at this test's (soon-deleted) tmp_path for every later test that touches
+ # the singleton (_get_user_db_path reads the persistent self.data_dir, not
+ # the env, so the leak is real). registered_users/lockout_mgr are pre-bound
+ # so the finally can run even if setup raises before they'd be assigned.
+ original_data_dir = db_manager.data_dir
+ registered_users = []
+ lockout_mgr = None
+ try:
+ db_manager.data_dir = tmp_path / "encrypted_databases"
+ init_auth_database()
+
+ app, _ = create_app()
+ app.config["TESTING"] = True
+ app.config["WTF_CSRF_ENABLED"] = False
+ app.config["SESSION_COOKIE_SECURE"] = False
+
+ # Keep the synchronous test off the real post-login worker threads.
+ monkeypatch.setattr(
+ auth_routes, "_perform_post_login_tasks", lambda _u, _p: None
+ )
+
+ lockout_mgr = get_account_lockout_manager()
+
+ yield app, db_manager, lockout_mgr, registered_users
+ finally:
+ # Belt-and-suspenders isolation: tests/conftest.py's autouse
+ # reset_all_singletons fixture already replaces the lockout
+ # singleton (account_lockout._manager = None) around every test, but
+ # explicitly clear the state for the users THIS test touched too, in
+ # case that ordering ever changes.
+ if lockout_mgr is not None:
+ for username in registered_users:
+ lockout_mgr._state.pop(username, None)
+ db_manager.close_all_databases()
+ db_manager.data_dir = original_data_dir
+
+
+def _register(client, username, password):
+ return client.post(
+ "/auth/register",
+ data={
+ "username": username,
+ "password": password,
+ "confirm_password": password,
+ "acknowledge": "true",
+ },
+ follow_redirects=False,
+ )
+
+
+def _login(client, username, password):
+ return client.post(
+ "/auth/login",
+ data={"username": username, "password": password},
+ follow_redirects=False,
+ )
+
+
+def _register_and_warm(app, db_manager, registered_users, prefix, password):
+ """Register a fresh user, leaving their connection cached (warm)."""
+ username = f"{prefix}_{uuid.uuid4().hex[:8]}"
+ registered_users.append(username)
+ client = app.test_client()
+ reg = _register(client, username, password)
+ assert reg.status_code in (200, 302), (
+ f"registration failed: {reg.status_code} / {reg.get_data(as_text=True)[:500]}"
+ )
+ assert db_manager.is_user_connected(username), (
+ "the connection must be cached (warm) after registration for this "
+ "test to be meaningful"
+ )
+ return username
+
+
+def test_warm_cache_wrong_password_increments_lockout_failure_count(
+ app_client,
+):
+ """A wrong password against a warm connection must take the
+ record_failure() branch, not record_success()."""
+ app, db_manager, lockout_mgr, registered_users = app_client
+ good = "V!ctimPassw0rd123" # noqa: S105
+ bad = "attacker-does-not-know-this" # noqa: S105
+
+ username = _register_and_warm(
+ app, db_manager, registered_users, "lockout_wrong", good
+ )
+
+ assert lockout_mgr.is_locked(username) is False
+ before = lockout_mgr._state.get(username, {}).get("count", 0)
+
+ attacker = app.test_client()
+ resp = _login(attacker, username, bad)
+ assert resp.status_code != 302, (
+ "wrong password on a warm cache must not authenticate"
+ )
+
+ entry = lockout_mgr._state.get(username)
+ assert entry is not None, (
+ "a wrong password against a warm cached connection must create/ "
+ "increment a lockout failure entry -- pre-fix, the cached-connection "
+ "bypass reached record_success() instead, which pops any entry "
+ "rather than creating one, so this would be None"
+ )
+ assert entry["count"] == before + 1, (
+ "the failure count must increment by exactly one per wrong-password "
+ "attempt against the warm cache"
+ )
+ assert lockout_mgr.is_locked(username) is False, (
+ "a single failed attempt must not itself trigger a lockout "
+ "(threshold is well above 1)"
+ )
+
+
+def test_repeated_warm_cache_wrong_passwords_eventually_lock_account(
+ app_client,
+):
+ """Pre-fix, repeated wrong-password attempts against a warm connection
+ could never lock the account (each attempt cleared the counter via
+ record_success()). Post-fix, they must accumulate and lock at
+ threshold."""
+ app, db_manager, lockout_mgr, registered_users = app_client
+ good = "V!ctimPassw0rd123" # noqa: S105
+ bad = "attacker-does-not-know-this" # noqa: S105
+
+ username = _register_and_warm(
+ app, db_manager, registered_users, "lockout_repeat", good
+ )
+
+ threshold = lockout_mgr.threshold
+ assert lockout_mgr.is_locked(username) is False
+
+ last_resp = None
+ for attempt in range(1, threshold + 1):
+ assert db_manager.is_user_connected(username), (
+ "the connection must stay warm/cached across attempts for this "
+ "test to be meaningful -- a wrong password must never evict the "
+ "legitimate cached engine"
+ )
+ attacker = app.test_client()
+ last_resp = _login(attacker, username, bad)
+ assert last_resp.status_code != 302, (
+ f"wrong password must never authenticate (attempt {attempt})"
+ )
+
+ assert lockout_mgr.is_locked(username) is True, (
+ f"after {threshold} wrong-password attempts against a warm cached "
+ "connection, the account must be locked -- pre-fix this could never "
+ "happen because every attempt hit record_success() and reset the "
+ "counter to zero"
+ )
+ # Once locked, the route itself must refuse further attempts with 429
+ # regardless of password correctness.
+ locked_resp = _login(app.test_client(), username, good)
+ assert locked_resp.status_code == 429, (
+ "a locked account must be refused even with the CORRECT password"
+ )
+
+
+def test_correct_login_clears_failure_count_and_is_not_locked(app_client):
+ """A correct login (whether cold or against a warm connection) must
+ call record_success() and leave the account unlocked, with a clean
+ failure count."""
+ app, db_manager, lockout_mgr, registered_users = app_client
+ good = "V!ctimPassw0rd123" # noqa: S105
+ bad = "attacker-does-not-know-this" # noqa: S105
+
+ username = _register_and_warm(
+ app, db_manager, registered_users, "lockout_success", good
+ )
+
+ # Accumulate a few failures first (but stay below threshold) so we can
+ # observe them being cleared.
+ for _ in range(3):
+ _login(app.test_client(), username, bad)
+ assert lockout_mgr._state.get(username, {}).get("count", 0) == 3
+ assert lockout_mgr.is_locked(username) is False
+
+ ok = _login(app.test_client(), username, good)
+ assert ok.status_code == 302, "the correct password must authenticate"
+
+ assert lockout_mgr.is_locked(username) is False
+ assert username not in lockout_mgr._state, (
+ "a successful login must clear the failure-count entry entirely "
+ "(record_success pops the state), not merely avoid incrementing it"
+ )
+
+
+def test_register_logout_relogin_end_to_end(app_client):
+ """Sanity: register -> logout -> re-login with the correct password
+ still works end to end through the real route stack."""
+ app, db_manager, lockout_mgr, registered_users = app_client
+ good = "V!ctimPassw0rd123" # noqa: S105
+
+ username = f"lockout_e2e_{uuid.uuid4().hex[:8]}"
+ registered_users.append(username)
+
+ # Use the SAME client throughout so the session cookie set at
+ # registration carries through to the logout/re-login calls below.
+ client = app.test_client()
+ reg = _register(client, username, good)
+ assert reg.status_code in (200, 302), (
+ f"registration failed: {reg.status_code} / {reg.get_data(as_text=True)[:500]}"
+ )
+ assert db_manager.is_user_connected(username), (
+ "the connection must be cached (warm) after registration"
+ )
+ with client.session_transaction() as sess:
+ assert sess.get("username") == username, (
+ "registration must also log the user in"
+ )
+
+ logout_resp = client.post("/auth/logout", follow_redirects=False)
+ assert logout_resp.status_code in (200, 302)
+ with client.session_transaction() as sess:
+ assert sess.get("username") is None, "logout must clear the session"
+
+ relogin = _login(client, username, good)
+ assert relogin.status_code == 302, (
+ "re-login with the correct password must succeed after logout"
+ )
+ with client.session_transaction() as sess:
+ assert sess.get("username") == username
+
+ assert lockout_mgr.is_locked(username) is False
+ assert username not in lockout_mgr._state
diff --git a/tests/security/test_login_cached_connection_password_route.py b/tests/security/test_login_cached_connection_password_route.py
new file mode 100644
index 0000000000..4506bf006a
--- /dev/null
+++ b/tests/security/test_login_cached_connection_password_route.py
@@ -0,0 +1,136 @@
+"""End-to-end proof, through the real /auth/login route, that a warm cached
+connection no longer lets a wrong password authenticate.
+
+The companion unit tests exercise ``DatabaseManager`` directly. The *impact* of
+the bug, though, lived entirely in the login route treating any non-None engine
+as authenticated (``web/auth/routes.py``: ``engine = db_manager.open_user_database(...)``
+then ``record_success`` + session creation). This test drives the actual HTTP
+endpoint with a genuinely cached connection -- the state that made the bypass
+reachable -- so the route wiring can never silently diverge from the fix.
+
+Reproduces the multi-agent review's end-to-end repro for PR #5596.
+"""
+
+import uuid
+
+import pytest
+
+
+def app_client(tmp_path, monkeypatch):
+ """A real app + a live module-level db_manager pointed at a temp data dir.
+
+ The login/history/settings blueprints all share the module-level
+ ``db_manager`` singleton, so the attacker's cross-blueprint reads only work
+ if that same instance holds the warm connection -- hence we use the real
+ singleton and just isolate its data dir, restoring it afterwards.
+ """
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ monkeypatch.setenv("LDR_TESTING_WITH_MOCKS", "true")
+ monkeypatch.setenv("LDR_RATE_LIMITING_ENABLED", "false")
+
+ from local_deep_research.database.auth_db import init_auth_database
+ from local_deep_research.database.encrypted_db import db_manager
+ from local_deep_research.web.app_factory import create_app
+ import local_deep_research.web.auth.routes as auth_routes
+
+ if not db_manager.has_encryption:
+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")
+
+ # Everything that touches the singleton lives inside try/finally from
+ # here on, INCLUDING setup (init_auth_database/create_app can raise) --
+ # not just the yield. A setup-time raise before try/finally would leave
+ # db_manager.data_dir pointed at this test's (soon-deleted) tmp_path for
+ # every later test that touches the singleton.
+ original_data_dir = db_manager.data_dir
+ try:
+ db_manager.data_dir = tmp_path / "encrypted_databases"
+ init_auth_database()
+
+ app, _ = create_app()
+ app.config["TESTING"] = True
+ app.config["WTF_CSRF_ENABLED"] = False
+ app.config["SESSION_COOKIE_SECURE"] = False
+
+ # Keep the synchronous test off the real post-login worker threads.
+ monkeypatch.setattr(
+ auth_routes, "_perform_post_login_tasks", lambda _u, _p: None
+ )
+
+ yield app, db_manager
+ finally:
+ db_manager.close_all_databases()
+ db_manager.data_dir = original_data_dir
+
+
+def _register(client, username, password):
+ return client.post(
+ "/auth/register",
+ data={
+ "username": username,
+ "password": password,
+ "confirm_password": password,
+ "acknowledge": "true",
+ },
+ follow_redirects=False,
+ )
+
+
+def test_warm_cache_wrong_password_is_rejected_end_to_end(app_client):
+ app, db_manager = app_client
+ username = f"victim_{uuid.uuid4().hex[:8]}"
+ good = "V!ctimPassw0rd123" # noqa: S105
+ bad = "attacker-does-not-know-this" # noqa: S105
+
+ victim = app.test_client()
+ reg = _register(victim, username, good)
+ assert reg.status_code in (200, 302), (
+ f"registration failed: {reg.status_code}"
+ )
+ assert db_manager.is_user_connected(username), (
+ "the victim's connection must be cached for this test to be meaningful"
+ )
+
+ # Attacker: brand-new client, no cookies, knows only the username.
+ attacker = app.test_client()
+ resp = attacker.post(
+ "/auth/login",
+ data={"username": username, "password": bad},
+ follow_redirects=False,
+ )
+ assert resp.status_code != 302, (
+ "wrong password on a warm cache must NOT be a successful login "
+ "(302 redirect) -- this is the bypass"
+ )
+ with attacker.session_transaction() as sess:
+ assert sess.get("username") is None, (
+ "no session may be minted for a wrong password"
+ )
+ hist = attacker.get("/history/api", follow_redirects=False)
+ assert hist.status_code == 401, (
+ "the attacker must not be able to read the victim's history "
+ "(login_required returns 401 for an unauthenticated /api request)"
+ )
+
+ # Positive control: the correct password still authenticates end-to-end.
+ legit = app.test_client()
+ ok = legit.post(
+ "/auth/login",
+ data={"username": username, "password": good},
+ follow_redirects=False,
+ )
+ assert ok.status_code == 302
+ with legit.session_transaction() as sess:
+ assert sess.get("username") == username
+ assert legit.get("/history/api", follow_redirects=False).status_code == 200
+
+ # Cold control: with the connection closed, a wrong password is still
+ # rejected (the cold path was always correct).
+ db_manager.close_user_database(username)
+ cold_attacker = app.test_client()
+ cold = cold_attacker.post(
+ "/auth/login",
+ data={"username": username, "password": bad},
+ follow_redirects=False,
+ )
+ assert cold.status_code != 302
diff --git a/tests/security/test_password_verifier_primitive.py b/tests/security/test_password_verifier_primitive.py
new file mode 100644
index 0000000000..95acc9eca8
--- /dev/null
+++ b/tests/security/test_password_verifier_primitive.py
@@ -0,0 +1,369 @@
+"""Unit coverage for the password-verifier PRIMITIVE used by the
+cached-connection fix in PR #5596.
+
+Companion to ``test_login_cached_connection_password.py`` /
+``test_login_cached_connection_password_extra.py``, which exercise the
+verifier through the full ``DatabaseManager.open_user_database`` /
+``create_user_database`` flow (real SQLCipher opens). This file instead pins
+down the primitive itself -- ``_compute_verifier_digest``, ``_make_verifier``,
+``_verifier_matches``, ``_password_matches_cached``,
+``_record_password_verifier`` and ``_cached_engine_trusted`` -- in isolation,
+with no database I/O and no SQLCipher dependency, so it runs fast and stays
+green in environments without SQLCipher installed.
+
+Each ``DatabaseManager`` under test is built via ``__new__`` so
+``DatabaseManager.__init__`` (which probes for SQLCipher and can raise
+``RuntimeError`` when it isn't installed and unencrypted mode isn't
+explicitly allowed) never runs. Only the handful of attributes the verifier
+methods actually touch are set: ``_password_verifiers``, ``_verifier_key``,
+``_connections_lock``, ``connections`` and ``has_encryption``.
+"""
+
+import hmac
+import secrets
+import threading
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.database.encrypted_db import DatabaseManager
+
+
+def make_manager(has_encryption: bool = True) -> DatabaseManager:
+ """Build a bare ``DatabaseManager`` with only the verifier-related state
+ initialised, bypassing ``__init__`` (and therefore the SQLCipher probe)
+ entirely."""
+ mgr = DatabaseManager.__new__(DatabaseManager)
+ mgr.connections = {}
+ mgr._password_verifiers = {}
+ mgr._verifier_key = secrets.token_bytes(32)
+ mgr._connections_lock = threading.RLock()
+ mgr.has_encryption = has_encryption
+ return mgr
+
+
+# ---------------------------------------------------------------------------
+# 1. A recorded verifier matches its own password and rejects any other.
+# ---------------------------------------------------------------------------
+
+
+def test_verifier_matches_own_password_and_rejects_others():
+ mgr = make_manager()
+ username = "user_own_password"
+ password = "CorrectHorseBattery1!" # noqa: S105
+
+ mgr._record_password_verifier(username, password)
+
+ with mgr._connections_lock:
+ assert mgr._verifier_matches(username, password) is True
+ assert mgr._verifier_matches(username, "totally-wrong") is False
+ # A single trailing/near-miss character must still be rejected.
+ assert mgr._verifier_matches(username, password[:-1]) is False
+ assert mgr._verifier_matches(username, password + "x") is False
+ assert mgr._verifier_matches(username, "") is False
+
+
+# ---------------------------------------------------------------------------
+# 2. Same password, different usernames -> different (salt, digest) pairs,
+# each still matches its own password (unlinkability).
+# ---------------------------------------------------------------------------
+
+
+def test_same_password_different_usernames_are_unlinkable():
+ mgr = make_manager()
+ password = "SharedPassword1!" # noqa: S105
+
+ mgr._record_password_verifier("alice", password)
+ mgr._record_password_verifier("bob", password)
+
+ salt_a, digest_a = mgr._password_verifiers["alice"]
+ salt_b, digest_b = mgr._password_verifiers["bob"]
+
+ assert isinstance(salt_a, bytes) and len(salt_a) == 16
+ assert isinstance(salt_b, bytes) and len(salt_b) == 16
+ assert salt_a != salt_b, "per-entry salts must differ (unlinkability)"
+ assert digest_a != digest_b, (
+ "digests for the same password must differ across users because "
+ "the salts differ"
+ )
+
+ with mgr._connections_lock:
+ assert mgr._verifier_matches("alice", password) is True
+ assert mgr._verifier_matches("bob", password) is True
+ # Cross-check: neither entry is somehow tied to the other's salt.
+ cross = hmac.new(
+ mgr._verifier_key, salt_b + password.encode("utf-8"), "sha256"
+ ).digest()
+ assert cross == digest_b
+ assert cross != digest_a
+
+
+def test_make_verifier_produces_fresh_salt_each_call():
+ mgr = make_manager()
+ salt1, digest1 = mgr._make_verifier("SamePassword1!")
+ salt2, digest2 = mgr._make_verifier("SamePassword1!")
+ assert salt1 != salt2, "two calls must not reuse a salt"
+ assert digest1 != digest2
+
+
+# ---------------------------------------------------------------------------
+# 3. Unicode, very long, whitespace- and case-distinct passwords are treated
+# as DISTINCT and each still matches correctly.
+# ---------------------------------------------------------------------------
+
+
+UNUSUAL_PASSWORDS = {
+ "accented": "pässwörd Ñoño Café",
+ "emoji": "correct-horse-battery-staple🔒🐴🔋📎",
+ "cjk": "正确马电池订书机安全密码",
+ "mixed_script": "Пароль123密码🔥",
+ "very_long": "x" * 100_000,
+ "long_unicode": "é" * 20_000,
+ "case_lower": "password1!",
+ "case_title": "Password1!",
+ "case_upper": "PASSWORD1!",
+ "no_trailing_ws": "Password1!",
+ "trailing_space": "Password1! ",
+ "leading_space": " Password1!",
+ "trailing_tab": "Password1!\t",
+ "trailing_newline": "Password1!\n",
+ "empty": "",
+ "whitespace_only": " ",
+}
+
+
+def test_unusual_passwords_each_match_only_their_own_username():
+ mgr = make_manager()
+
+ for name, password in UNUSUAL_PASSWORDS.items():
+ mgr._record_password_verifier(f"user_{name}", password)
+
+ with mgr._connections_lock:
+ # Every password matches its own recorded verifier.
+ for name, password in UNUSUAL_PASSWORDS.items():
+ assert mgr._verifier_matches(f"user_{name}", password) is True, (
+ f"{name!r} should match its own verifier"
+ )
+
+ # Passwords that differ only by case, or only by leading/trailing
+ # whitespace, must be treated as fully distinct -- no verifier for
+ # one should match another's password.
+ confusable_groups = [
+ ["case_lower", "case_title", "case_upper"],
+ [
+ "no_trailing_ws",
+ "trailing_space",
+ "leading_space",
+ "trailing_tab",
+ "trailing_newline",
+ ],
+ ["empty", "whitespace_only"],
+ ]
+ for group in confusable_groups:
+ for owner in group:
+ for other in group:
+ if owner == other:
+ continue
+ assert (
+ mgr._verifier_matches(
+ f"user_{owner}", UNUSUAL_PASSWORDS[other]
+ )
+ is False
+ ), (
+ f"user_{owner}'s verifier must not accept "
+ f"{other}'s password ({UNUSUAL_PASSWORDS[other]!r})"
+ )
+
+ # A very long password with a single trailing character changed must
+ # not match (rules out any truncation in the digest computation).
+ truncated_long = UNUSUAL_PASSWORDS["very_long"][:-1]
+ assert mgr._verifier_matches("user_very_long", truncated_long) is False
+ appended_long = UNUSUAL_PASSWORDS["very_long"] + "y"
+ assert mgr._verifier_matches("user_very_long", appended_long) is False
+
+
+# ---------------------------------------------------------------------------
+# 4. Fail-closed: no verifier recorded (or popped) -> False, never True.
+# ---------------------------------------------------------------------------
+
+
+def test_fail_closed_when_no_verifier_was_ever_recorded():
+ mgr = make_manager()
+ with mgr._connections_lock:
+ assert mgr._verifier_matches("never_registered", "anything") is False
+ assert mgr._verifier_matches("never_registered", "") is False
+ assert mgr._password_matches_cached("never_registered", "anything") is False
+
+
+def test_fail_closed_after_verifier_is_popped():
+ mgr = make_manager()
+ username = "user_popped"
+ password = "CorrectHorseBattery1!" # noqa: S105
+ mgr._record_password_verifier(username, password)
+
+ # Sanity: it matches before the pop.
+ assert mgr._password_matches_cached(username, password) is True
+
+ mgr._password_verifiers.pop(username, None)
+
+ with mgr._connections_lock:
+ assert mgr._verifier_matches(username, password) is False
+ assert mgr._password_matches_cached(username, password) is False
+
+
+# ---------------------------------------------------------------------------
+# 5. Re-recording replaces the verifier: new salt/digest, old password no
+# longer matches once re-recorded under a new password.
+# ---------------------------------------------------------------------------
+
+
+def test_rerecording_replaces_verifier_and_invalidates_old_password():
+ mgr = make_manager()
+ username = "user_rerecord"
+ old_password = "OldPassword1!" # noqa: S105
+ new_password = "NewPassword2!" # noqa: S105
+
+ mgr._record_password_verifier(username, old_password)
+ old_salt, old_digest = mgr._password_verifiers[username]
+
+ mgr._record_password_verifier(username, new_password)
+ new_salt, new_digest = mgr._password_verifiers[username]
+
+ assert (new_salt, new_digest) != (old_salt, old_digest), (
+ "re-recording must produce a fresh salt/digest pair"
+ )
+
+ with mgr._connections_lock:
+ assert mgr._verifier_matches(username, new_password) is True
+ assert mgr._verifier_matches(username, old_password) is False
+
+
+def test_rerecording_same_password_still_rotates_salt():
+ """Even re-recording the SAME password must not silently keep the old
+ salt/digest -- _record_password_verifier always calls _make_verifier."""
+ mgr = make_manager()
+ username = "user_same_pw_rerecord"
+ password = "SamePassword1!" # noqa: S105
+
+ mgr._record_password_verifier(username, password)
+ salt1, digest1 = mgr._password_verifiers[username]
+
+ mgr._record_password_verifier(username, password)
+ salt2, digest2 = mgr._password_verifiers[username]
+
+ assert salt1 != salt2
+ assert digest1 != digest2
+ assert mgr._verifier_matches(username, password) is True
+
+
+# ---------------------------------------------------------------------------
+# 6. _cached_engine_trusted: unencrypted mode always trusts; encrypted mode
+# defers to the verifier (including its fail-closed behaviour).
+# ---------------------------------------------------------------------------
+
+
+def test_cached_engine_trusted_unencrypted_mode_ignores_password():
+ mgr = make_manager(has_encryption=False)
+ username = "user_unencrypted"
+ # No verifier is ever recorded in this test -- unencrypted mode must not
+ # need one.
+ with mgr._connections_lock:
+ assert mgr._cached_engine_trusted(username, "any-password") is True
+ assert mgr._cached_engine_trusted(username, "") is True
+ assert mgr._cached_engine_trusted(username, "unencrypted-mode") is True
+ assert mgr._cached_engine_trusted("some-other-user", "dummy") is True
+
+
+def test_cached_engine_trusted_encrypted_mode_defers_to_verifier():
+ mgr = make_manager(has_encryption=True)
+ username = "user_encrypted"
+ password = "CorrectHorseBattery1!" # noqa: S105
+ mgr._record_password_verifier(username, password)
+
+ with mgr._connections_lock:
+ assert mgr._cached_engine_trusted(username, password) is True
+ assert mgr._cached_engine_trusted(username, "wrong-password") is False
+
+ # And fails closed once the verifier is gone, same as _verifier_matches.
+ mgr._password_verifiers.pop(username, None)
+ with mgr._connections_lock:
+ assert mgr._cached_engine_trusted(username, password) is False
+
+
+# ---------------------------------------------------------------------------
+# 7. _verifier_matches compares digests with hmac.compare_digest
+# (constant-time), not a short-circuiting `==`.
+# ---------------------------------------------------------------------------
+
+
+def test_verifier_matches_uses_hmac_compare_digest():
+ mgr = make_manager()
+ username = "user_constant_time"
+ password = "CorrectHorseBattery1!" # noqa: S105
+ mgr._record_password_verifier(username, password)
+ salt, expected_digest = mgr._password_verifiers[username]
+
+ with patch.object(hmac, "compare_digest", wraps=hmac.compare_digest) as spy:
+ with mgr._connections_lock:
+ match_result = mgr._verifier_matches(username, password)
+ mismatch_result = mgr._verifier_matches(username, "wrong")
+
+ assert match_result is True
+ assert mismatch_result is False
+ # Called exactly once per _verifier_matches invocation -- both the
+ # matching and the mismatching comparison must go through
+ # hmac.compare_digest rather than a data-dependent `==`.
+ assert spy.call_count == 2
+
+ match_args = spy.call_args_list[0].args
+ computed_for_match = mgr._compute_verifier_digest(salt, password)
+ assert match_args[0] == computed_for_match
+ assert match_args[1] == expected_digest
+
+ mismatch_args = spy.call_args_list[1].args
+ computed_for_mismatch = mgr._compute_verifier_digest(salt, "wrong")
+ assert mismatch_args[0] == computed_for_mismatch
+ assert mismatch_args[1] == expected_digest
+
+
+def test_verifier_matches_never_uses_plain_equality_shortcut():
+ """Guard against a regression to `computed == expected`: patch
+ hmac.compare_digest to always return False and confirm the verifier
+ result follows the patched function rather than the underlying bytes
+ equality (which would still be True for a genuinely matching password).
+ """
+ mgr = make_manager()
+ username = "user_forced_false"
+ password = "CorrectHorseBattery1!" # noqa: S105
+ mgr._record_password_verifier(username, password)
+
+ with patch.object(hmac, "compare_digest", return_value=False):
+ with mgr._connections_lock:
+ assert mgr._verifier_matches(username, password) is False
+
+
+# ---------------------------------------------------------------------------
+# Extra: independence between test cases / fresh manager per test is assumed
+# throughout via the `make_manager()` factory (no shared fixture state).
+# ---------------------------------------------------------------------------
+
+
[email protected]("has_encryption", [True, False])
+def test_fresh_managers_do_not_share_verifier_keys(has_encryption):
+ """Sanity check that each manager gets its own random verifier key, so
+ a digest computed by one manager is meaningless to another."""
+ mgr1 = make_manager(has_encryption=has_encryption)
+ mgr2 = make_manager(has_encryption=has_encryption)
+ assert mgr1._verifier_key != mgr2._verifier_key
+
+ username = "user_cross_manager"
+ password = "CorrectHorseBattery1!" # noqa: S105
+ mgr1._record_password_verifier(username, password)
+ salt, digest = mgr1._password_verifiers[username]
+ mgr2._password_verifiers[username] = (salt, digest)
+
+ with mgr2._connections_lock:
+ assert mgr2._verifier_matches(username, password) is False, (
+ "a verifier recorded under one manager's key must not validate "
+ "under another manager's key"
+ )