~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): stop reinstating user credentials via the log-queue drain after logout (#5538)
LearningCircuitdd6a0545f6cb
diff --git a/changelog.d/+log-queue-credential-hygiene.security.md b/changelog.d/+log-queue-credential-hygiene.security.mdnew file mode 100644index 0000000000..8818059c69--- /dev/null+++ b/changelog.d/+log-queue-credential-hygiene.security.md@@ -0,0 +1,23 @@+Hardened background log persistence so it can no longer reopen a user's+encrypted database or reinstate their connected state after logout. Queued+log entries no longer carry the user's password, the log-queue drain now+writes only while the user's database is already open (post-logout backlog+entries are dropped), and the drain thread clears any cached credential on+every iteration. In-flight logging for active research is unaffected.++Logout also no longer closes a user's database while their research is+still running — closing it mid-run made the log-queue drain silently drop+that job's logs. The connection now stays open for the rest of the run,+plus up to one idle-connection sweep afterward (a few minutes), which is+also when `is_user_connected` stops reporting the account as reachable.+This is safe only together with the server-side session-id revocation on+the request/socket auth path (#5532); this PR must ship with, or after,+that change, not before it.++Changing your password no longer pauses other users' in-progress research.+The database re-encryption is now gated per-user rather than process-wide,+so only your own new research is briefly held back while the re-encryption+runs; everyone else's active research keeps progressing. The queue+processor additionally re-checks your session immediately before reopening+your encrypted database, so a logout that lands in that instant can no+longer bring the decrypted database back or resume a queued research.diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.pyindex 802fc591a3..838247696d 100644--- a/src/local_deep_research/utilities/log_utils.py+++ b/src/local_deep_research/utilities/log_utils.py@@ -178,10 +178,12 @@ def _report_silent_exception(Note: takes the exception's TYPE NAME as a plain string (not theexception object). The caller does ``type(exc).__name__`` and passesthe result. This is deliberate — CodeQL's taint analyzer treats any- function frame holding a ``BaseException`` captured from a password-- bearing call site as tainted, and flags every stderr write inside- that frame. Receiving only a type-name string severs the flow at- the boundary.+ function frame holding a ``BaseException`` captured from a+ credential-adjacent call site as tainted, and flags every stderr+ write inside that frame. Receiving only a type-name string severs the+ flow at the boundary. (The log-queue drain no longer carries or+ resolves a plaintext password at all, so no credential value can+ reach this frame in the first place.)"""if os.environ.get("LDR_APP_DEBUG", "").lower() not in ("1", "true", "yes"):return@@ -199,8 +201,9 @@ def _report_silent_exception(ctx = " ".join(parts)# CodeQL's py/clear-text-logging-sensitive-data may flag this stderr# write because the function frame is reachable from- # _write_log_to_database which holds user_password locally. The data- # actually written is only plain strings — `where` (literal),+ # _write_log_to_database, which is part of the credential-adjacent+ # logging path (though it no longer holds any password locally). The+ # data actually written is only plain strings — `where` (literal),# `exc_type_name` (`type(exc).__name__`), and `username/research_id/level`# repr'd from the queue entry. No password value ever reaches the# formatter; the helper signature deliberately accepts only typed@@ -213,14 +216,37 @@ def _report_silent_exception(sys.stderr.flush()+def _clear_daemon_thread_credentials() -> None:+ """Drop any DB session / cached credential held by the current thread.++ Invoked at the end of every log-queue drain iteration. The queue+ daemon is a long-lived ``daemon=True`` thread whose credentials the+ dead-thread sweeper (``cleanup_dead_threads``) can never reclaim,+ because the thread stays alive for the whole process. Clearing here+ guarantees the ``log-queue-processor`` thread never retains a+ plaintext credential in ``thread_local_session``'s+ ``_thread_credentials``.++ Best-effort: must never raise, or a single cleanup hiccup would crash+ the daemon and silently stop all subsequent log persistence.+ """+ try:+ from ..database.thread_local_session import cleanup_current_thread++ cleanup_current_thread()+ except Exception:+ pass # noqa: silent-exception — cleanup must not kill the log daemon++def _process_log_queue():"""Process logs from the queue in a dedicated daemon thread.- Safe to run off the main thread: ``_write_log_to_database`` uses- ``get_user_db_session`` which yields a thread-local SQLAlchemy session,- and the underlying SQLite engines are opened with- ``check_same_thread=False``.+ Safe to run off the main thread: ``_write_log_to_database`` binds a+ session to the user's already-open engine, and the underlying SQLite+ engines are opened with ``check_same_thread=False``. It never reopens+ a closed database, so a post-logout backlog can't resurrect a user's+ connection from this thread."""while not _stop_queue.is_set():try:@@ -233,7 +259,18 @@ def _process_log_queue():# Write to database if we have app contextif has_app_context():- _write_log_to_database(log_entry)+ try:+ _write_log_to_database(log_entry)+ finally:+ # Belt-and-suspenders credential hygiene. This daemon+ # is a long-lived ``daemon=True`` thread, so the+ # dead-thread credential sweeper+ # (``cleanup_dead_threads``) never reclaims it. Clear+ # any per-thread DB session / cached credential at the+ # end of every drain iteration so the+ # ``log-queue-processor`` thread can never accumulate a+ # plaintext credential in ``_thread_credentials``.+ _clear_daemon_thread_credentials()else:# If no app context, put it back in queue for latertry:@@ -258,32 +295,61 @@ def _process_log_queue():def _write_log_to_database(log_entry: dict) -> None:+ """Persist one queued log entry into the user's already-open database.++ The queue drain must NEVER reopen a closed database. A log entry that+ was queued while a user was active can be drained by the background+ daemon *after* that user has logged out; reopening their encrypted DB+ here would silently re-add the connection (``is_user_connected`` would+ flip back to True) and re-cache their credentials — resurrecting+ session state with no user action and no attacker involved.++ So we gate strictly on an already-open connection+ (``db_manager.is_user_connected``) and bind to the EXISTING engine via+ ``db_manager.get_session`` — which never opens a new database and needs+ no password. Entries for a user with no live connection (e.g. a+ post-logout backlog) are dropped; the full message is still available+ in the stderr/file sinks.++ In-flight logging is preserved: while a user is active — including a+ running research job, which keeps their DB open — the connection stays+ live, so their logs continue to be written normally."""- Write a log entry to the database. Should only be called from main thread.- """- from ..database.session_context import get_user_db_session+ from ..database.encrypted_db import db_manager+ username = log_entry.get("username")+ if not username:+ return++ # Gate on an already-open connection. Do NOT lazily reopen the DB:+ # after logout the connection is gone, and reopening it here would+ # resurrect the user's connected state from a stale queued backlog.+ if not db_manager.is_user_connected(username):+ return++ db_session = Nonetry:- username = log_entry.get("username")- # Captured in the emitting thread (database_sink) from- # ContextVar storage; the queue daemon thread can't read that itself.- pw = log_entry.get("user_password") # gitleaks:allow-- with get_user_db_session(- username, password=pw- ) as db_session: # gitleaks:allow- if db_session:- db_log = ResearchLog(- timestamp=log_entry["timestamp"],- message=log_entry["message"],- module=log_entry["module"],- function=log_entry["function"],- line_no=log_entry["line_no"],- level=log_entry["level"],- research_id=log_entry["research_id"],- )- db_session.add(db_log)- db_session.commit()+ # Binds a session to the ALREADY-open engine. Returns None (never+ # reopens) if the connection was closed in the small race between+ # the is_user_connected check above and this call. We can't use+ # get_user_db_session here: it would resolve+cache a password and+ # lazily reopen the DB, which is exactly the post-logout+ # resurrection this fix removes. The session is explicitly closed+ # in the finally block below, so the QueuePool connection is+ # returned and no FD leaks.+ db_session = db_manager.get_session(username) # noqa: raw-session+ if db_session is not None:+ db_log = ResearchLog(+ timestamp=log_entry["timestamp"],+ message=log_entry["message"],+ module=log_entry["module"],+ function=log_entry["function"],+ line_no=log_entry["line_no"],+ level=log_entry["level"],+ research_id=log_entry["research_id"],+ )+ db_session.add(db_log)+ db_session.commit()except Exception as exc:# noqa: silent-exception — DB errors in the logging path must not propagate or recurse.# Wrap the report itself so a broken-stderr IOError can't escape and@@ -298,6 +364,16 @@ def _write_log_to_database(log_entry: dict) -> None:)except Exception:pass # noqa: silent-exception — broken stderr must not bubble out of logging path+ finally:+ # The session is freshly created per drain, bound to the shared+ # per-user engine — close it so its pooled connection is returned+ # (close() also rolls back any pending transaction from a failed+ # commit). Never let a close error escape the logging path.+ if db_session is not None:+ try:+ db_session.close()+ except Exception:+ pass # noqa: silent-exception — session close failure must not propagatedef database_sink(message: loguru.Message) -> None:@@ -312,11 +388,18 @@ def database_sink(message: loguru.Message) -> None:record = message.recordresearch_id = _get_research_id(record)- # Resolve username + password. The queue daemon thread can't read the- # research thread's ContextVar storage and has no Flask request- # context, so we capture both here in the emitting thread.+ # Resolve the username the log belongs to. The queue daemon thread+ # can't read the research thread's ContextVar storage and has no Flask+ # request context, so we capture the username here in the emitting+ # thread.#- # Source priority:+ # NOTE: we deliberately do NOT capture the user's password here. The+ # queue entry must never carry a plaintext credential: the background+ # drain would otherwise use it to reopen the user's encrypted DB after+ # logout, reinstating their connected state. Instead the drain writes+ # only when the user's DB is already open (see _write_log_to_database).+ #+ # Source priority for the username:# 1. logger.bind(...) extras on the record itself# 2. per-thread research context (set once when the research thread# starts, so every subsequent log call inherits it without@@ -325,12 +408,9 @@ def database_sink(message: loguru.Message) -> None:# tagged research_id via the @log_for_research decorator but# didn't bind username — common for /api/research/<id>/* routes)username = record.get("extra", {}).get("username")- user_password = Nonectx = _get_research_context_fallback()- if ctx:- if not username:- username = ctx.get("username")- user_password = ctx.get("user_password")+ if ctx and not username:+ username = ctx.get("username")# Only consult Flask request state when the log already has a# research_id. ResearchLog is research-scoped by design — auth and# other system DEBUG logs (research_id=None) don't belong there. If@@ -344,11 +424,6 @@ def database_sink(message: loguru.Message) -> None:if not username and has_request_context():username = flask_session.get("username")- # Password is set on g.user_password by the request middleware- # after authentication. The daemon thread can't read this, so- # capture it here in the request thread.- if not user_password and hasattr(g, "user_password"):- user_password = g.user_passwordexcept Exception:pass # noqa: silent-exception — must not fail logging on session lookup@@ -375,7 +450,6 @@ def database_sink(message: loguru.Message) -> None:"level": record["level"].name,"research_id": research_id,"username": username,- "user_password": user_password,}# Check if we're in a background threaddiff --git a/src/local_deep_research/web/auth/connection_cleanup.py b/src/local_deep_research/web/auth/connection_cleanup.pyindex 2c8f95926f..43ffa61539 100644--- a/src/local_deep_research/web/auth/connection_cleanup.py+++ b/src/local_deep_research/web/auth/connection_cleanup.py@@ -61,6 +61,15 @@ def _pop_per_user_locks(username: str) -> None:locks (the locks hold no state worth preserving acrosslogin/logout).+ The per-user research-start gate (``_user_research_start_gates`` in+ web/routes/globals.py) is DELIBERATELY EXCLUDED from this cleanup. It+ is a mutual-exclusion primitive that may be HELD across a multi-second+ SQLCipher rekey; popping a held gate would let a concurrent same-user+ ``check_and_start_research`` create a SECOND gate instance and bypass+ the exclusion the gate provides. It is bounded by the user population,+ so it is safe (and necessary) to leave in place — see the comment at+ its definition in globals.py.+Lazy-imported here to keep this module's import graph shallow:``connection_cleanup`` runs at startup and shouldn't pull in thequeue / backup / library-init / library-RAG modules eagerly.@@ -90,6 +99,12 @@ def _pop_per_user_locks(username: str) -> None:except Exception:logger.warning(f"Failed to pop _user_critical_locks for {username}")+ # NOTE: the per-user research-start gate (_user_research_start_gates in+ # web/routes/globals.py) is deliberately NOT popped here — it may be held+ # across a multi-second rekey and removing a held gate would let a+ # concurrent same-user check_and_start_research create a second gate+ # instance and bypass the exclusion. See the docstring above.+try:from ...research_library.services.library_rag_service import (pop_faiss_locks_for_user,diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.pyindex b99d4346c4..1c1500c2a3 100644--- a/src/local_deep_research/web/auth/routes.py+++ b/src/local_deep_research/web/auth/routes.py@@ -711,22 +711,17 @@ def logout():if username:# LOGOUT CLEANUP ORDER (order matters):- # 1. Unregister from news scheduler — removes password from scheduler's- # user_sessions dict and cancels scheduled jobs. Must happen BEFORE- # close_user_database() because: scheduler jobs fetch the password- # from user_sessions at runtime to call open_user_database(). If we- # close the DB first, a running job that already has the password- # can re-create the engine. Removing the password first ensures- # future job invocations can't authenticate.- # Note: a narrow race remains — a job that already fetched the- # password (but hasn't called open_user_database yet) can still- # recreate an engine. This is benign: the dead-thread sweep will- # clean it up within 60 seconds.- # 2. Close database connection — disposes QueuePool engine and cleans- # up thread engines for this user.- # 3. Destroy Flask session — invalidates session token.- # 4. Clear session password store — removes password from secondary store.- # 5. Clear Flask session dict — removes all session data.+ # 1. Unregister from news scheduler — removes the password from the+ # scheduler's user_sessions dict and cancels scheduled jobs.+ # 2. Destroy the server session AND clear the session password store+ # (via _cleanup_user_session) — BEFORE closing the DB, so the+ # always-running queue processor / scheduler can't read a stale+ # password and reopen the DB in the close→clear window.+ # 3. Close the database connection — unless the user still has research+ # running (closing then would make the log-queue drain silently drop+ # that job's logs; the idle sweeper closes it once the job ends).+ # 4. Drop per-user lock-dict entries.+ # 5. Clear the Flask session dict.try:from ...scheduler.background import (get_background_job_scheduler,@@ -738,8 +733,52 @@ def logout():except Exception:logger.warning("Could not unregister user from scheduler")- # Close database connection- db_manager.close_user_database(username)+ # Destroy the server session and clear the in-memory password store+ # BEFORE closing the DB. The always-running queue processor reads the+ # session password store to reopen a user's DB; clearing it only AFTER+ # close_user_database left a window where a concurrent tick could+ # resurrect the connection (and even resume a queued research) after+ # logout.+ if session_id:+ _cleanup_user_session(username, session_id=session_id)++ # Close the DB connection — but not while the user still has research+ # running. A running job keeps producing logs, and the log-queue drain+ # no longer reopens a closed DB, so closing here would silently drop+ # that job's log rows. The idle-connection sweeper (which also protects+ # active research) closes the connection once the job finishes.+ #+ # The active-research check and the close run under this user's+ # ``user_research_start_gate`` — the SAME per-user gate+ # ``check_and_start_research`` acquires to register a new research+ # thread, and that ``change_password`` holds across its close ->+ # PRAGMA rekey -> close. Holding it here closes two check-then-act+ # races that the bare check+close left open:+ # (a) a concurrent same-user ``change_password`` rekey (from another+ # tab) could otherwise have its in-flight engine disposed by this+ # close mid-rekey; sharing the gate serialises the two so the+ # close waits for the rekey (or vice versa).+ # (b) a research STARTING in the gap between the check and the close+ # could otherwise have its freshly-opened DB closed underneath it+ # and silently lose logs; holding the gate means a concurrent+ # ``check_and_start_research`` for this user either registers+ # before our check (so we see it active and skip the close) or+ # blocks until after our close (and then reopens its own engine).+ # Lock ordering is preserved: the gate is taken BEFORE ``_lock`` (via+ # ``get_usernames_with_active_research``) and before the DB layer's+ # ``_connections_lock`` (via ``close_user_database``) — the same+ # gate -> _lock / gate -> _connections_lock order used everywhere else,+ # so no deadlock. logout holds no other gate, and the close is fast+ # (WAL checkpoint + dispose, not a multi-second rekey), so this adds+ # only negligible same-user contention.+ from ..routes.globals import (+ get_usernames_with_active_research,+ user_research_start_gate,+ )++ with user_research_start_gate(username):+ if username not in get_usernames_with_active_research():+ db_manager.close_user_database(username)# Drop per-user lock-dict entries (library-init, backup,# queue-processor critical sections). Matches the cleanup@@ -750,10 +789,6 @@ def logout():_pop_per_user_locks(username)- # Clear session- if session_id:- _cleanup_user_session(username, session_id=session_id)-session.clear()logger.info(f"User {username} logged out")@@ -830,11 +865,63 @@ def change_password():password_requirements=PasswordValidator.get_requirements(),), 400- # Attempt password change- success = db_manager.change_password(- username, current_password, new_password+ # Do NOT rekey the encrypted DB while a research job is running. The rekey+ # (close -> PRAGMA rekey -> close) needs exclusive access, and a running+ # job holds a session bound to the pre-rekey engine with the now-invalid+ # old password — it can't recover, and a concurrent rekey risks corrupting+ # the whole encrypted DB. Unlike logout's DB close, the destructive rekey+ # can't be deferred, so reject until research finishes.+ #+ # The check and the rekey run under this user's ``user_research_start_gate``+ # — the SAME per-user gate ``check_and_start_research`` (routes/globals.py)+ # acquires to register and start a new research thread for this user.+ # Without holding it, a job could start in the gap between the check below+ # and the rekey actually happening, undetected by the check but still+ # racing the rekey. Holding the gate across both closes that TOCTOU window:+ # no research can start FOR THIS USER while we hold it.+ #+ # This is a PER-USER gate, NOT the process-global ``_lock`` (routes/globals.py):+ # the SQLCipher ``PRAGMA rekey`` can take seconds, and that global lock is+ # taken on every research progress/log update, so holding it across the+ # rekey would freeze EVERY user's active research for the duration. The+ # per-user gate blocks only this user's new research.+ #+ # RESIDUAL (concurrent same-user writers): the gate serialises the rekey+ # against this user's NEW research starts, and the active-research check+ # below rejects the rekey outright while this user has a research WORKER+ # running (so that worker's metrics/log writers are excluded too). It does+ # NOT serialise same-user background writers that open/write the user's+ # engine WITHOUT going through check_and_start_research — the news-scheduler+ # job (get_user_db_session) and the async log-drain+ # (_write_log_to_database). Those can still INSERT concurrently with the+ # PRAGMA rekey. Fully serialising them would require a per-user read/write+ # lock taken on the metrics/log hot path inside the database layer+ # (encrypted_db.py) — a cross-layer lock the web-layer gate can't provide+ # without a fragile import cycle, and a change with real deadlock/perf risk.+ # Given the narrow window (a manual, rare, single-user action) this is left+ # as a documented residual rather than hardened here.+ from ..routes.globals import (+ get_usernames_with_active_research,+ user_research_start_gate,)+ with user_research_start_gate(username):+ if username in get_usernames_with_active_research():+ flash(+ "Cannot change your password while research is in progress. "+ "Wait for it to finish or cancel it, then try again.",+ "error",+ )+ return render_template(+ "auth/change_password.html",+ password_requirements=PasswordValidator.get_requirements(),+ ), 409++ # Attempt password change (the rekey) — holds only this user's gate.+ success = db_manager.change_password(+ username, current_password, new_password+ )+if success:# The rekey is the ONLY step needed. The auth database stores no# password hash — login works by attempting to decrypt the user'sdiff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex a19e0f2a41..6e4f90d779 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -287,6 +287,37 @@ class QueueProcessorV2:password = session_password_store.get_session_password(username, session_id)+ if password:+ # TOCTOU guard against post-logout DB resurrection.+ # Between the read above and open_user_database() below the+ # user can log out: logout clears the session password store+ # (auth/routes.py step 2) and THEN closes the DB. Re-opening+ # here with the captured password would resurrect the user's+ # decrypted database — and even resume a queued research —+ # after logout. Re-read the store immediately before the+ # open; if the credential is gone the user has logged out,+ # so abort the direct start (``password`` becomes None and+ # the block below is skipped). Keeping this re-check adjacent+ # to the open shrinks the residual window to a negligible+ # remainder — the store clear and the DB open live in+ # different subsystems and are not jointly lockable without a+ # fragile cross-subsystem lock. Otherwise adopt the freshest+ # credential (never the stale captured one) for both the open+ # and _start_research_directly. On abort we fall through to+ # the queue-mode path below, which re-reads fresh and no-ops+ # cleanly when the user is logged out.+ current_password = (+ session_password_store.get_session_password(+ username, session_id+ )+ )+ if current_password is None:+ logger.info(+ f"Aborting direct-start DB open for {username}: "+ "session credential cleared since read (logout?); "+ "leaving research queued"+ )+ password = current_passwordif password:try:# Open database and check settings + active countdiff --git a/src/local_deep_research/web/routes/globals.py b/src/local_deep_research/web/routes/globals.pyindex 10e6697024..a773a4e396 100644--- a/src/local_deep_research/web/routes/globals.py+++ b/src/local_deep_research/web/routes/globals.py@@ -8,6 +8,7 @@ dicts directly."""import threading+from contextlib import contextmanagerfrom sqlalchemy.orm import Session@@ -22,6 +23,33 @@ _termination_flags: dict[int, bool] = {}# so a single lock is simpler and eliminates any deadlock risk from lock ordering._lock = threading.RLock()+# Per-user gate serialising a user's password-change rekey against that user's+# own newly-starting research threads. Deliberately NOT the process-global+# ``_lock`` above: the SQLCipher ``PRAGMA rekey`` can take seconds, and holding+# ``_lock`` across it would freeze EVERY user's research (every log-append /+# progress-update / status read takes ``_lock``). Keyed by username;+# ``check_and_start_research`` acquires the gate for the research's owner, and+# ``change_password`` (web/auth/routes.py) holds it across its "is research+# active?" check + rekey, so a rekey blocks only the SAME user's new-research+# registration. A dedicated small lock guards the dict so gate lookups never+# touch ``_lock`` — keeping the two consistently orderable: a caller always+# takes a gate BEFORE ``_lock``, never the reverse.+#+# INTENTIONALLY NEVER POPPED. This is a per-user mutual-exclusion primitive+# that may be HELD across a multi-second SQLCipher ``PRAGMA rekey`` (see+# ``change_password`` in web/auth/routes.py). A gate that may be held across a+# long operation cannot be safely removed from its registry: if a logout / idle+# sweep popped a gate while one tab holds it across the rekey, a concurrent+# same-user ``check_and_start_research`` would find no entry, CREATE A SECOND+# ``threading.Lock`` instance, acquire it uncontended, and start a worker that+# writes the user's DB concurrently with the in-flight rekey — defeating the+# exact exclusion this gate exists to provide. Any lookup-then-acquire scheme+# has this lookup->acquire gap, so the only correct policy is to never remove+# the gate. The dict is bounded by the user population (one small+# ``threading.Lock`` per distinct username), so it does not grow unbounded.+_user_research_start_gates: dict[str, threading.Lock] = {}+_user_research_start_gates_lock = threading.Lock()+# ===================================================================# active_research accessors@@ -90,6 +118,41 @@ def set_active_research(research_id, data):_active_research[research_id] = data+def _get_user_research_start_gate(username: str) -> threading.Lock:+ """Return the per-user research-start gate, creating it on first use."""+ with _user_research_start_gates_lock:+ gate = _user_research_start_gates.get(username)+ if gate is None:+ gate = threading.Lock()+ _user_research_start_gates[username] = gate+ return gate+++@contextmanager+def user_research_start_gate(username):+ """Hold the per-user research-start gate across a check-then-act sequence.++ ``check_and_start_research`` acquires this same per-user gate before it+ registers and starts a new research thread for a user. A caller that holds+ the gate across its own "is this user researching?" check *and* the action+ that check gates (that user's password-change rekey) therefore closes the+ TOCTOU window for THAT user only: no new research can start for this user+ until the gate is released, because starting one requires the same gate.++ Unlike the process-global ``_lock`` this does NOT block other users'+ research — essential because the rekey it guards can take seconds and+ ``_lock`` is taken on every progress/log update.++ ``username`` of ``None`` yields without acquiring anything: there is no user+ to gate, and real research always carries an owning username.+ """+ if username is None:+ yield+ return+ with _get_user_research_start_gate(username):+ yield++def check_and_start_research(research_id, data) -> bool:"""Atomically register a research entry iff no live thread exists.@@ -101,18 +164,36 @@ def check_and_start_research(research_id, data) -> bool:The entire check-and-start is done under the single shared lock, sotwo concurrent callers with the same *research_id* cannot both passthe liveness check and end up with two live threads for the same ID.++ Registration is additionally wrapped in the research owner's per-user+ ``user_research_start_gate``, so a new thread cannot register (and start+ writing to the pre-rekey engine) while that user's password-change rekey+ is in flight — see ``change_password`` in web/auth/routes.py."""thread = data.get("thread") if isinstance(data, dict) else Noneif thread is None:raise ValueError("data must contain a 'thread' entry")- with _lock:- entry = _active_research.get(research_id)- if entry is not None:- existing = entry.get("thread")- if existing is not None and existing.is_alive():- return False- thread.start()- _active_research[research_id] = data+ # Owning username drives the per-user rekey gate below. Every real research+ # start passes settings["username"] (via start_research_process); a+ # missing/None username degrades to no gating (nothing to serialise+ # against, since the rekey gate is keyed by username).+ username = None+ if isinstance(data, dict):+ settings = data.get("settings")+ if isinstance(settings, dict):+ username = settings.get("username")+ # Serialise against an in-flight password-change rekey for this user. The+ # gate is per-user, so this never stalls other users' research; the inner+ # ``_lock`` still provides the atomic check-and-start for research_id.+ with user_research_start_gate(username):+ with _lock:+ entry = _active_research.get(research_id)+ if entry is not None:+ existing = entry.get("thread")+ if existing is not None and existing.is_alive():+ return False+ thread.start()+ _active_research[research_id] = datareturn Truediff --git a/tests/security/test_egress_url_edgecases_followup.py b/tests/security/test_egress_url_edgecases_followup.pyindex 97f163f9fc..23c1996fcd 100644--- a/tests/security/test_egress_url_edgecases_followup.py+++ b/tests/security/test_egress_url_edgecases_followup.py@@ -434,6 +434,7 @@ class TestDenialLogCarriesUrl:from local_deep_research.security.egress import policy as policy_modfrom local_deep_research.utilities.log_utils import database_sink+ from local_deep_research.database.encrypted_db import db_managerbound = MagicMock()with patch.object(policy_mod, "logger") as mock_logger:@@ -463,30 +464,28 @@ class TestDenialLogCarriesUrl:mock_thread = Mock()mock_thread.name = "MainThread"mock_session = MagicMock()- mock_cm = MagicMock()- mock_cm.__enter__ = Mock(return_value=mock_session)- mock_cm.__exit__ = Mock(return_value=None)+ # The connected user's DB is already open; database_sink's+ # direct-write path binds to the existing connection (no reopen,+ # no password).with patch("local_deep_research.utilities.log_utils.has_app_context",return_value=True,):with patch(- "local_deep_research.utilities.log_utils.g",- SimpleNamespace(),+ "local_deep_research.utilities.log_utils.threading.current_thread",+ return_value=mock_thread,):- with patch(- "local_deep_research.utilities.log_utils.threading.current_thread",- return_value=mock_thread,- ):- with patch(- "local_deep_research.database.session_context.get_user_db_session",- return_value=mock_cm,+ with patch.object(+ db_manager, "is_user_connected", return_value=True+ ) as mock_conn:+ with patch.object(+ db_manager, "get_session", return_value=mock_session) as mock_get_session:database_sink(mock_message)- mock_get_session.assert_called_once()- assert mock_get_session.call_args.args[0] == "triager"+ mock_conn.assert_called_once_with("triager")+ mock_get_session.assert_called_once_with("triager")persisted = mock_session.add.call_args[0][0]assert persisted.research_id == "rid-denial"assert persisted.message == messagediff --git a/tests/utilities/test_log_utils.py b/tests/utilities/test_log_utils.pyindex b553fd5082..1a31647880 100644--- a/tests/utilities/test_log_utils.py+++ b/tests/utilities/test_log_utils.py@@ -222,10 +222,11 @@ class TestDatabaseSink:database_sink(mock_message)def test_writes_to_database_in_main_thread(self):- """Should write to database when in main thread with app context."""- from types import SimpleNamespace-+ """Should write to the DB when in main thread with app context and+ the user's DB is already open — binding to the existing connection,+ never reopening it (no password is used)."""from local_deep_research.utilities.log_utils import database_sink+ from local_deep_research.database.encrypted_db import db_managerimport local_deep_research.utilities.log_utils as modulemock_message = Mock()@@ -243,32 +244,30 @@ class TestDatabaseSink:mock_thread.name = "MainThread"mock_session = MagicMock()- mock_cm = MagicMock()- mock_cm.__enter__ = Mock(return_value=mock_session)- mock_cm.__exit__ = Mock(return_value=None)-- mock_g = SimpleNamespace()with patch.object(module, "has_app_context", return_value=True):- with patch.object(module, "g", mock_g):+ with patch.object(+ threading, "current_thread", return_value=mock_thread+ ):with patch.object(- threading, "current_thread", return_value=mock_thread- ):- with patch(- "local_deep_research.database.session_context.get_user_db_session",- return_value=mock_cm,+ db_manager, "is_user_connected", return_value=True+ ) as mock_conn:+ with patch.object(+ db_manager, "get_session", return_value=mock_session) as mock_get_session:- database_sink(mock_message)-- # Should write to database- mock_get_session.assert_called_once()- assert mock_get_session.call_args.args[0] == "testuser"- assert (- mock_get_session.call_args.kwargs["password"]- is None- )- mock_session.add.assert_called_once()- mock_session.commit.assert_called_once()+ with patch.object(+ db_manager, "open_user_database"+ ) as mock_open:+ database_sink(mock_message)++ # Gated on the already-open connection, bound to it.+ mock_conn.assert_called_once_with("testuser")+ mock_get_session.assert_called_once_with("testuser")+ # The drain must never reopen the DB.+ mock_open.assert_not_called()+ mock_session.add.assert_called_once()+ mock_session.commit.assert_called_once()+ mock_session.close.assert_called_once()def test_handles_database_error_gracefully(self):"""Should not raise on database errors when writing."""@@ -396,10 +395,12 @@ class TestDatabaseSink:call_args = mock_queue.put_nowait.call_args[0][0]assert call_args["research_id"] == "record-uuid"- def test_captures_user_password_from_thread_context(self):- """Should snapshot user_password from per-thread research context onto- the queue entry, so the daemon can decrypt the per-user SQLCipher DB- from a thread that can't read the research thread's ContextVar."""+ def test_captures_username_but_never_password_into_queue_entry(self):+ """The username is still captured from the per-thread research+ context so the daemon can attribute the row, but the queue entry+ must NEVER carry a plaintext password. Carrying it would let the+ background drain reopen the user's encrypted DB after logout and+ reinstate their connected state (post-logout resurrection)."""from local_deep_research.utilities.log_utils import database_sinkimport local_deep_research.utilities.log_utils as module@@ -429,7 +430,9 @@ class TestDatabaseSink:call_args = mock_queue.put_nowait.call_args[0][0]assert call_args["username"] == "alice"- assert call_args["user_password"] == "pw-from-thread-ctx"+ # No plaintext credential anywhere in the queue entry.+ assert "user_password" not in call_args+ assert "pw-from-thread-ctx" not in call_args.values()def test_skips_persistence_when_no_research_or_username(self):"""Logs without a research_id AND without a username must be dropped@@ -983,6 +986,8 @@ class TestFlushLogQueue:from local_deep_research.utilities.log_utils import flush_log_queueimport local_deep_research.utilities.log_utils as module+ from local_deep_research.database.encrypted_db import db_manager+log_entries = [{"timestamp": datetime.now(),@@ -991,8 +996,8 @@ class TestFlushLogQueue:"function": "f","line_no": 1,"level": "INFO",- "research_id": None,- "username": None,+ "research_id": "rid-1",+ "username": "alice",},{"timestamp": datetime.now(),@@ -1001,29 +1006,28 @@ class TestFlushLogQueue:"function": "f","line_no": 2,"level": "INFO",- "research_id": None,- "username": None,+ "research_id": "rid-1",+ "username": "alice",},]mock_session = MagicMock()- mock_cm = MagicMock()- mock_cm.__enter__ = Mock(return_value=mock_session)- mock_cm.__exit__ = Mock(return_value=None)with patch.object(module, "_log_queue") as mock_queue:mock_queue.empty.side_effect = [False, False, True]mock_queue.get_nowait.side_effect = log_entries + [queue.Empty()]- with patch(- "local_deep_research.database.session_context.get_user_db_session",- return_value=mock_cm,+ with patch.object(+ db_manager, "is_user_connected", return_value=True):- flush_log_queue()+ with patch.object(+ db_manager, "get_session", return_value=mock_session+ ):+ flush_log_queue()- # Should have written 2 logs- assert mock_session.add.call_count == 2- assert mock_session.commit.call_count == 2+ # Should have written 2 logs+ assert mock_session.add.call_count == 2+ assert mock_session.commit.call_count == 2def test_handles_empty_queue(self):"""Should handle empty queue gracefully."""@@ -1092,104 +1096,195 @@ class TestConfigLogger:config_logger("test_app")+class _FakeDBManager:+ """Minimal stand-in for the encrypted ``db_manager`` singleton.++ Mirrors the real resurrection hazard: ``get_session`` yields a session+ only for an already-open connection (like the real one, which returns+ None when the user isn't in ``connections``), while+ ``open_user_database`` is the buggy path that RE-ADDS a connection.+ A correct drain must never call ``open_user_database`` for a+ logged-out user, so ``is_user_connected`` must stay False.+ """++ def __init__(self, connected):+ self._connections = set(connected)+ self.open_called = 0+ self.get_session_calls = []+ self.last_session = None++ def is_user_connected(self, username):+ return username in self._connections++ def get_session(self, username):+ self.get_session_calls.append(username)+ if username not in self._connections:+ # Real get_session returns None for a closed DB — never reopens.+ return None+ self.last_session = MagicMock()+ return self.last_session++ def open_user_database(self, username, password=None):+ # The resurrection path the drain must NOT take: reopening re-adds+ # the connection so is_user_connected would flip back to True.+ self.open_called += 1+ self._connections.add(username)+ return MagicMock()++class TestWriteLogToDatabase:"""Tests for _write_log_to_database function."""- def test_writes_research_log(self):- """Should write ResearchLog to database."""- from local_deep_research.utilities.log_utils import (- _write_log_to_database,- )-- log_entry = {+ @staticmethod+ def _entry(username="alice", research_id="test-uuid", level="INFO"):+ return {"timestamp": datetime.now(),"message": "Test message","module": "test_module","function": "test_func","line_no": 42,- "level": "INFO",- "research_id": "test-uuid",- "username": "testuser",+ "level": level,+ "research_id": research_id,+ "username": username,}- mock_session = MagicMock()- mock_cm = MagicMock()- mock_cm.__enter__ = Mock(return_value=mock_session)- mock_cm.__exit__ = Mock(return_value=None)+ def test_writes_research_log_when_user_connected(self):+ """A connected user's entry is written by binding to the EXISTING+ open connection — no reopen, no password. This is also the+ research-in-progress case: a running research job keeps the user's+ DB open, so in-flight logs must still be persisted."""+ from local_deep_research.utilities.log_utils import (+ _write_log_to_database,+ )++ fake = _FakeDBManager(connected={"alice"})+ with patch(+ "local_deep_research.database.encrypted_db.db_manager", fake+ ):+ _write_log_to_database(self._entry(username="alice"))++ assert fake.get_session_calls == ["alice"]+ assert fake.open_called == 0 # never reopened+ session = fake.last_session+ session.add.assert_called_once()+ session.commit.assert_called_once()+ session.close.assert_called_once()++ def test_drops_entry_and_never_reopens_when_user_not_connected(self):+ """A backlog entry drained AFTER logout (connection closed) must be+ dropped: the DB must not be reopened and ``is_user_connected`` must+ stay False. Asserts no post-logout resurrection."""+ from local_deep_research.utilities.log_utils import (+ _write_log_to_database,+ )++ # User already logged out — no live connection.+ fake = _FakeDBManager(connected=set())+ with patch(+ "local_deep_research.database.encrypted_db.db_manager", fake+ ):+ _write_log_to_database(self._entry(username="loggedout"))++ # No resurrection: DB never reopened, connection still closed,+ # and no session was created for the write.+ assert fake.open_called == 0+ assert fake.is_user_connected("loggedout") is False+ assert fake.get_session_calls == []+ assert fake.last_session is None++ def test_drops_entry_with_no_username(self):+ """An entry with no username can't map to any per-user DB — drop it+ without touching the connection registry."""+ from local_deep_research.utilities.log_utils import (+ _write_log_to_database,+ )+ fake = _FakeDBManager(connected={"alice"})with patch(- "local_deep_research.database.session_context.get_user_db_session",- return_value=mock_cm,+ "local_deep_research.database.encrypted_db.db_manager", fake):- _write_log_to_database(log_entry)+ _write_log_to_database(self._entry(username=None))- mock_session.add.assert_called_once()- mock_session.commit.assert_called_once()+ assert fake.get_session_calls == []+ assert fake.open_called == 0- def test_handles_database_error_gracefully(self):- """Should not raise on database errors."""+ def test_does_not_cache_credential_on_drain_thread(self):+ """Draining a connected user's entry must NOT leave a credential+ cached in the thread-local session manager for this thread — the+ drain binds to the existing engine instead of going through the+ password-caching get_metrics_session path."""from local_deep_research.utilities.log_utils import (_write_log_to_database,)+ from local_deep_research.database.thread_local_session import (+ thread_session_manager,+ )- log_entry = {- "timestamp": datetime.now(),- "message": "Test",- "module": "mod",- "function": "f",- "line_no": 1,- "level": "INFO",- "research_id": None,- "username": None,- }+ tid = threading.get_ident()+ thread_session_manager._thread_credentials.pop(tid, None)+ fake = _FakeDBManager(connected={"alice"})with patch(- "local_deep_research.database.session_context.get_user_db_session",- side_effect=Exception("DB error"),+ "local_deep_research.database.encrypted_db.db_manager", fake):- # Should not raise- _write_log_to_database(log_entry)-- def test_passes_user_password_to_get_user_db_session(self):- """The password snapshotted onto the queue entry by database_sink- must be forwarded to get_user_db_session as the password= kwarg.- Without this the daemon thread cannot decrypt the per-user- SQLCipher DB and every research-thread MILESTONE log is silently- dropped."""+ _write_log_to_database(self._entry(username="alice"))++ assert tid not in thread_session_manager._thread_credentials++ def test_handles_database_error_gracefully(self):+ """Should not raise if the write itself fails for a connected user."""from local_deep_research.utilities.log_utils import (_write_log_to_database,)+ from local_deep_research.database.encrypted_db import db_manager- log_entry = {- "timestamp": datetime.now(),- "message": "milestone msg",- "module": "mod",- "function": "f",- "line_no": 1,- "level": "MILESTONE",- "research_id": "rid-1",- "username": "alice",- "user_password": "pw-from-queue", # gitleaks:allow- }+ with patch.object(db_manager, "is_user_connected", return_value=True):+ with patch.object(+ db_manager,+ "get_session",+ side_effect=Exception("DB error"),+ ):+ # Should not raise+ _write_log_to_database(self._entry(username="alice"))- mock_session = MagicMock()- mock_cm = MagicMock()- mock_cm.__enter__ = Mock(return_value=mock_session)- mock_cm.__exit__ = Mock(return_value=None)++class TestClearDaemonThreadCredentials:+ """Tests for the belt-and-suspenders per-drain credential cleanup."""++ def test_clears_cached_credential_for_current_thread(self):+ """After a drain iteration the daemon thread must retain no+ credential in ``_thread_credentials`` — the long-lived daemon is+ never reclaimed by the dead-thread sweeper, so it clears its own+ entry every iteration."""+ from local_deep_research.utilities.log_utils import (+ _clear_daemon_thread_credentials,+ )+ from local_deep_research.database.thread_local_session import (+ thread_session_manager,+ )++ tid = threading.get_ident()+ thread_session_manager._thread_credentials[tid] = (+ "alice",+ "secret-pw", # gitleaks:allow+ )+ try:+ _clear_daemon_thread_credentials()+ assert tid not in thread_session_manager._thread_credentials+ finally:+ thread_session_manager._thread_credentials.pop(tid, None)++ def test_never_raises(self):+ """Cleanup failures must be swallowed — a hiccup must not crash the+ log daemon and stop all subsequent log persistence."""+ from local_deep_research.utilities import log_utilswith patch(- "local_deep_research.database.session_context.get_user_db_session",- return_value=mock_cm,- ) as mock_get_session:- _write_log_to_database(log_entry)-- mock_get_session.assert_called_once()- call_args = mock_get_session.call_args- # username is positional (first arg).- assert call_args.args[0] == "alice"- # password must be passed as the kwarg the daemon uses for- # SQLCipher decryption.- assert call_args.kwargs.get("password") == "pw-from-queue"+ "local_deep_research.database.thread_local_session.cleanup_current_thread",+ side_effect=Exception("boom"),+ ):+ # Must not raise.+ log_utils._clear_daemon_thread_credentials()class TestLogQueueProcessorDaemon:diff --git a/tests/utilities/test_log_utils_coverage.py b/tests/utilities/test_log_utils_coverage.pyindex 9bdea7e9be..a09fd9fff6 100644--- a/tests/utilities/test_log_utils_coverage.py+++ b/tests/utilities/test_log_utils_coverage.py@@ -158,8 +158,8 @@ class TestDatabaseSinkUsernameExtraction:def test_no_username_queues_none(self):"""When research_id is set but username isn't, queue entry has- username=None — the daemon's get_user_db_session will then look it- up via session/thread-context fallbacks."""+ username=None — the daemon drops entries it can't attribute to a+ connected user (it never reopens a DB to write them)."""from local_deep_research.utilities.log_utils import database_sinkimport local_deep_research.utilities.log_utils as moddiff --git a/tests/web/auth/test_auth_routes.py b/tests/web/auth/test_auth_routes.pyindex 9b248f026b..529a2d4a39 100644--- a/tests/web/auth/test_auth_routes.py+++ b/tests/web/auth/test_auth_routes.py@@ -10,6 +10,8 @@ Tests cover:- Open redirect prevention"""+import threading+import timefrom pathlib import Pathfrom unittest.mock import MagicMock, patch@@ -534,6 +536,51 @@ class TestLogout:"testuser")+ def _logout_with_active_research(self, active):+ app = Flask(__name__)+ app.secret_key = "test"+ app.config["WTF_CSRF_ENABLED"] = False+ sched = MagicMock()+ sched.is_running = False+ with (+ patch("local_deep_research.web.auth.routes.db_manager") as mock_db,+ patch("local_deep_research.web.auth.routes.session_manager"),+ patch(+ "local_deep_research.database.session_passwords."+ "session_password_store"+ ),+ patch(+ "local_deep_research.scheduler.background."+ "get_background_job_scheduler",+ return_value=sched,+ ),+ patch(+ "local_deep_research.web.routes.globals."+ "get_usernames_with_active_research",+ return_value=active,+ ),+ ):+ from local_deep_research.web.auth.routes import auth_bp++ app.register_blueprint(auth_bp)+ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"+ sess["session_id"] = "session_123"+ client.post("/auth/logout")+ return mock_db++ def test_skips_db_close_when_research_active(self):+ """Logout must NOT close the DB while the user has research running,+ so the log-queue drain doesn't silently drop that job's logs."""+ mock_db = self._logout_with_active_research({"testuser"})+ mock_db.close_user_database.assert_not_called()++ def test_closes_db_when_no_active_research(self):+ """With no active research, logout closes the DB as before."""+ mock_db = self._logout_with_active_research(set())+ mock_db.close_user_database.assert_called_once_with("testuser")+class TestCheckAuth:"""Tests for /check endpoint."""@@ -746,6 +793,265 @@ class TestChangePassword:password_requirements=PasswordValidator.get_requirements(),)+ def test_blocked_while_research_active(self):+ """Must NOT rekey the DB while the user has research running (the+ rekey can't be deferred and would break/corrupt the running job);+ returns 409 and never calls db_manager.change_password."""+ app = Flask(__name__)+ app.secret_key = "test"+ app.config["WTF_CSRF_ENABLED"] = False++ with (+ patch("local_deep_research.web.auth.routes.db_manager") as mock_db,+ patch(+ "local_deep_research.web.auth.routes.render_template"+ ) as mock_render,+ patch(+ "local_deep_research.web.routes.globals."+ "get_usernames_with_active_research",+ return_value={"testuser"},+ ),+ ):+ mock_render.return_value = "Change Password Page"++ from local_deep_research.web.auth.routes import auth_bp++ app.register_blueprint(auth_bp)++ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"++ response = client.post(+ "/auth/change-password",+ data={+ "current_password": "OldPass123",+ "new_password": "NewStrongP4ss!",+ "confirm_password": "NewStrongP4ss!",+ },+ )+ assert response.status_code == 409+ mock_db.change_password.assert_not_called()++ def test_rekey_holds_user_gate_against_new_research(self):+ """TOCTOU hardening: a research thread must not be able to register+ itself (via ``check_and_start_research``, which acquires the owner's+ per-user ``user_research_start_gate``) while the request is between+ its "is research active?" check and the rekey actually completing.++ ``db_manager.change_password`` is faked to take a moment (as the+ real close -> open -> PRAGMA rekey -> close sequence would), and a+ background thread races to call the real+ ``check_and_start_research`` for this user while that's in flight.+ The change_password route holds ``user_research_start_gate(username)``+ across both its check and the rekey, and ``check_and_start_research``+ acquires that SAME per-user gate before registering, so the racer can+ only complete registration AFTER the fake rekey has returned — never+ before. Without that gate, the racer's real+ ``check_and_start_research`` call has nothing stopping it from+ completing immediately, well before the (slow) fake rekey returns,+ which is exactly the corruption-risking race this test guards against.+ """+ from local_deep_research.web.routes import globals as globals_mod++ app = Flask(__name__)+ app.secret_key = "test"+ app.config["WTF_CSRF_ENABLED"] = False++ times = {}+ rekey_started = threading.Event()++ def fake_change_password(username, old_password, new_password):+ rekey_started.set()+ # Brief -- just enough to give the racer thread a real chance+ # to attempt registration while this "rekey" is in flight. The+ # assertion below is ordering-based (enforced by the lock, not+ # by this duration), so this doesn't need to be long.+ time.sleep(0.05)+ times["rekey_about_to_return"] = time.monotonic()+ return True++ def attempt_start_research():+ assert rekey_started.wait(timeout=2), (+ "fake change_password never started"+ )+ thread_stub = threading.Thread(target=lambda: None)+ started = globals_mod.check_and_start_research(+ "toctou-regression-research-id",+ {+ "thread": thread_stub,+ "progress": 0,+ "status": "IN_PROGRESS",+ "log": [],+ "settings": {"username": "testuser"},+ },+ )+ times["racer_registered"] = time.monotonic()+ times["racer_started"] = started++ try:+ with (+ patch(+ "local_deep_research.web.auth.routes.db_manager"+ ) as mock_db,+ patch(+ "local_deep_research.web.auth.routes.render_template"+ ) as mock_render,+ patch("local_deep_research.web.auth.routes.session_manager"),+ patch(+ "local_deep_research.database.session_passwords."+ "session_password_store"+ ),+ ):+ mock_db.change_password.side_effect = fake_change_password+ mock_render.return_value = "Change Password Page"++ from local_deep_research.web.auth.routes import auth_bp++ app.register_blueprint(auth_bp)++ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"++ racer = threading.Thread(target=attempt_start_research)+ racer.start()++ response = client.post(+ "/auth/change-password",+ data={+ "current_password": "OldPass123",+ "new_password": "NewStrongP4ss!",+ "confirm_password": "NewStrongP4ss!",+ },+ follow_redirects=False,+ )+ racer.join(timeout=2)+ finally:+ # Never leave the racer's registration behind for other tests.+ globals_mod.remove_active_research("toctou-regression-research-id")++ assert response.status_code == 302+ assert not racer.is_alive()+ assert times.get("racer_started") is True+ # The racer could only complete registration once the (fake) rekey+ # had already returned -- i.e. the per-user gate serialized them.+ assert times["racer_registered"] >= times["rekey_about_to_return"]++ def test_rekey_does_not_block_other_users_new_research(self):+ """Availability regression guard: the rekey holds only the acting+ user's PER-USER gate, so a DIFFERENT user's research can still+ register (and, by extension, keep logging/progressing) while the+ (slow) rekey runs.++ A process-global lock held across the whole rekey (the ``_lock`` in+ routes/globals.py, taken on every progress/log update) would freeze+ EVERY user's active research for its duration. Here a background thread+ registers research for a DIFFERENT user while the acting user's fake+ (blocking) rekey is in flight; the rekey is wired to return only+ AFTER that other-user registration has happened. Under the old global+ lock the other user's ``check_and_start_research`` would block on the+ same ``_lock`` the route holds — deadlocking against a rekey that+ waits for it — and the racer would never register. Under the per-user+ gate it proceeds immediately.+ """+ from local_deep_research.web.routes import globals as globals_mod++ app = Flask(__name__)+ app.secret_key = "test"+ app.config["WTF_CSRF_ENABLED"] = False++ rekey_started = threading.Event()+ allow_rekey_return = threading.Event()+ times = {}++ def fake_change_password(username, old_password, new_password):+ rekey_started.set()+ # Block until the OTHER user has registered its research. If the+ # gate were process-global this would never be signalled (the+ # other user's registration would be blocked behind this rekey),+ # so the wait would time out and the assertions below would fail.+ assert allow_rekey_return.wait(timeout=2), (+ "other user's research never registered during rekey"+ )+ times["rekey_returned"] = time.monotonic()+ return True++ def other_user_starts_research():+ assert rekey_started.wait(timeout=2), (+ "fake change_password never started"+ )+ thread_stub = threading.Thread(target=lambda: None)+ started = globals_mod.check_and_start_research(+ "other-user-research-id",+ {+ "thread": thread_stub,+ "progress": 0,+ "status": "IN_PROGRESS",+ "log": [],+ "settings": {"username": "otheruser"},+ },+ )+ times["other_registered"] = time.monotonic()+ times["other_started"] = started+ # Registration completed WHILE the rekey is still blocked — let it+ # return now.+ allow_rekey_return.set()++ try:+ with (+ patch(+ "local_deep_research.web.auth.routes.db_manager"+ ) as mock_db,+ patch(+ "local_deep_research.web.auth.routes.render_template"+ ) as mock_render,+ patch("local_deep_research.web.auth.routes.session_manager"),+ patch(+ "local_deep_research.database.session_passwords."+ "session_password_store"+ ),+ ):+ mock_db.change_password.side_effect = fake_change_password+ mock_render.return_value = "Change Password Page"++ from local_deep_research.web.auth.routes import auth_bp++ app.register_blueprint(auth_bp)++ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"++ racer = threading.Thread(target=other_user_starts_research)+ racer.start()++ response = client.post(+ "/auth/change-password",+ data={+ "current_password": "OldPass123",+ "new_password": "NewStrongP4ss!",+ "confirm_password": "NewStrongP4ss!",+ },+ follow_redirects=False,+ )+ racer.join(timeout=3)+ finally:+ # Never leave the racer's registration or the other user's gate+ # behind for other tests. The research-start gate is intentionally+ # never popped in production (it may be held across a rekey), so+ # clear this test's entry directly from the registry.+ globals_mod.remove_active_research("other-user-research-id")+ with globals_mod._user_research_start_gates_lock:+ globals_mod._user_research_start_gates.pop("otheruser", None)++ assert response.status_code == 302+ assert not racer.is_alive()+ assert times.get("other_started") is True+ # The other user registered BEFORE the rekey returned: a different+ # user's new research is NOT blocked by this user's rekey.+ assert times["other_registered"] <= times["rekey_returned"]+def test_renders_page_when_authenticated(self):"""Should render change password page for authenticated user."""app = Flask(__name__)diff --git a/tests/web/auth/test_connection_cleanup.py b/tests/web/auth/test_connection_cleanup.pyindex 199d91ea46..c25fc882cd 100644--- a/tests/web/auth/test_connection_cleanup.py+++ b/tests/web/auth/test_connection_cleanup.py@@ -431,6 +431,49 @@ class TestPopPerUserLocks:# is still popped.assert u not in _user_init_locks+ def test_research_start_gate_identity_stable_across_pop(self):+ """The per-user research-start gate is INTENTIONALLY NOT popped on+ user-close, unlike the four lock dicts above.++ It is a mutual-exclusion primitive that may be HELD across a+ multi-second SQLCipher rekey (see ``change_password``). If+ ``_pop_per_user_locks`` removed a held gate, a concurrent same-user+ ``check_and_start_research`` would find no entry, create a SECOND+ ``threading.Lock`` instance, acquire it uncontended, and start a+ worker that writes the user's DB concurrently with the in-flight+ rekey — bypassing the exclusion the gate exists to provide.++ This pins that the gate's IDENTITY is stable across a logout /+ idle-close: ``_get_user_research_start_gate`` returns the SAME object+ before and after ``_pop_per_user_locks`` for the same username, so+ the gate is never removed-and-recreated behind a held reference.+ """+ from local_deep_research.web.auth.connection_cleanup import (+ _pop_per_user_locks,+ )+ from local_deep_research.web.routes.globals import (+ _get_user_research_start_gate,+ _user_research_start_gates,+ _user_research_start_gates_lock,+ )++ u = "test-gate-identity-user-zzz"+ try:+ gate_before = _get_user_research_start_gate(u)++ # The user-close cleanup must NOT drop the gate.+ _pop_per_user_locks(u)++ gate_after = _get_user_research_start_gate(u)+ # SAME object: the gate was neither removed nor recreated.+ assert gate_after is gate_before+ assert u in _user_research_start_gates+ finally:+ # The gate is never popped in production; clear this test's+ # entry directly so it doesn't leak into other tests.+ with _user_research_start_gates_lock:+ _user_research_start_gates.pop(u, None)+class TestStartConnectionCleanupScheduler:"""Tests for start_connection_cleanup_scheduler()."""diff --git a/tests/web/queue/test_processor_v2_coverage.py b/tests/web/queue/test_processor_v2_coverage.pyindex abe4c94936..dc6d2dbae1 100644--- a/tests/web/queue/test_processor_v2_coverage.py+++ b/tests/web/queue/test_processor_v2_coverage.py@@ -106,6 +106,45 @@ class TestNotifyResearchQueuedFallbackPaths:# Fallback queue path must have been calledmock_qs.add_task_metadata.assert_called_once()+ def test_credential_cleared_between_read_and_open_aborts_direct(self):+ """Fix A (post-logout DB resurrection TOCTOU): if the session password+ is cleared between the initial read and the pre-open re-check (a logout+ landing in that window), the direct-start path must NOT call+ open_user_database — re-opening with the stale captured password would+ resurrect the user's decrypted DB (and could resume a queued research)+ after logout. The research instead falls through to the queue-mode path.+ """+ proc = _make_processor()+ mock_session = MagicMock()+ mock_qs = MagicMock()++ with (+ patch(f"{MODULE}.session_password_store") as mock_store,+ patch(f"{MODULE}.db_manager") as mock_db,+ patch(f"{MODULE}.get_user_db_session") as mock_ctx,+ patch(f"{MODULE}.UserQueueService", return_value=mock_qs),+ patch(f"{MODULE}.logger"),+ ):+ # First read (initial) returns the captured password; the pre-open+ # re-check returns None — the store was cleared by a logout racing+ # in the window between the two reads.+ mock_store.get_session_password.side_effect = ["secret", None]+ mock_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)++ proc.notify_research_queued(+ "alice", "r1", session_id="sess1", query="q"+ )++ # The DB must NOT have been (re)opened with the stale captured password.+ mock_db.open_user_database.assert_not_called()+ # The research still lands in the queue via the fallback path.+ mock_qs.add_task_metadata.assert_called_once_with(+ task_id="r1", task_type="research", priority=0+ )+# ---------------------------------------------------------------------------# _start_research_directly – active-record creation failure