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): disconnect sockets and drop subscriptions on logout (#5535)

LearningCircuit778688295e40
diff --git a/changelog.d/5535.security.md b/changelog.d/5535.security.md
new file mode 100644
index 0000000000..f75bf6c6f8
--- /dev/null
+++ b/changelog.d/5535.security.md
@@ -0,0 +1 @@
+Live WebSocket connections are now torn down whenever the session behind them ends — logging out, changing your password, a session expiring, or an idle connection being reclaimed — instead of only at handshake. A socket can no longer keep receiving your events (including `settings_changed` events that carry secret values) after its session is gone. Teardown is scoped per session, so logging out of one tab no longer disconnects your other tabs or devices, and every connect/subscribe/unsubscribe is re-checked against a still-valid session as defense in depth. In particular, a stale or captured cookie can no longer open a brand-new socket and join your event room after its own session was logged out or expired, even while another of your sessions (or an in-flight research run) keeps your database connection open.
diff --git a/src/local_deep_research/web/auth/connection_cleanup.py b/src/local_deep_research/web/auth/connection_cleanup.py
index 43ffa61539..fcba3162d6 100644
--- a/src/local_deep_research/web/auth/connection_cleanup.py
+++ b/src/local_deep_research/web/auth/connection_cleanup.py
@@ -115,6 +115,25 @@ def _pop_per_user_locks(username: str) -> None:
logger.warning(f"Failed to pop _faiss_write_locks for {username}")
+def _disconnect_all_user_sockets(username: str) -> None:
+ """Best-effort disconnect of ALL of ``username``'s live sockets.
+
+ Called from the idle-connection sweep, where the user has no active
+ session at all — so every one of their still-open sockets (authorised
+ once at handshake and never re-checked) should be severed. Lazy-imported
+ to keep this module's startup import graph shallow and to tolerate
+ non-web contexts (the socket server may not exist).
+ """
+ try:
+ from ...web.services.socket_service import SocketIOService
+
+ SocketIOService().disconnect_user(username)
+ except ValueError:
+ pass # No socket server in this context.
+ except Exception:
+ logger.warning(f"Failed to disconnect sockets for idle user {username}")
+
+
def _count_open_fds() -> int:
"""Count open file descriptors for the current process."""
proc_fd = Path("/proc/self/fd")
@@ -185,6 +204,11 @@ def cleanup_idle_connections(session_manager, db_manager):
logger.debug(f"Closed idle connection for {username}")
except Exception:
logger.warning(f"Connection cleanup failed for {username}")
+ # This user has no active session at all (that's why we're closing
+ # their DB), so tear down every one of their still-open sockets — a
+ # socket authorised at handshake is never re-checked and would
+ # otherwise keep receiving the user's events after the session lapsed.
+ _disconnect_all_user_sockets(username)
# Pop lock-dict entries regardless of whether close succeeded.
# The lock-dict cleanup is independent of DB-engine teardown;
# putting it inside the try above would skip pop on the very
diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.py
index 1c1500c2a3..b79168c61d 100644
--- a/src/local_deep_research/web/auth/routes.py
+++ b/src/local_deep_research/web/auth/routes.py
@@ -161,6 +161,70 @@ def _cleanup_user_session(
session_password_store.clear_all_for_user(username)
+def _get_socket_service():
+ """Return the SocketIOService singleton, or None if not initialised.
+
+ Socket teardown on logout / password change is best-effort: a non-web
+ context (tests, CLI) has no socket server, and a teardown failure must
+ never break the auth flow. Lazy import avoids pulling the socket stack
+ into module import.
+ """
+ try:
+ from ..services.socket_service import SocketIOService
+
+ return SocketIOService()
+ except ValueError:
+ # Socket.IO service not initialised (e.g. non-web context) — there
+ # are no sockets to tear down.
+ logger.debug(
+ "Skipping socket teardown: Socket.IO service not initialized"
+ )
+ return None
+ except Exception:
+ # Any other failure (lazy import error, construction failure, ...)
+ # must not break logout / password-change either.
+ logger.opt(exception=True).warning(
+ "Failed to resolve socket service for auth teardown"
+ )
+ return None
+
+
+def _disconnect_user_sockets(username: str) -> None:
+ """Disconnect ALL of ``username``'s live sockets and drop subscriptions.
+
+ A Socket.IO connection is authorised once at handshake and then keeps
+ delivering that user's events (including ``settings_changed``, which
+ carries plaintext secrets) for its whole lifetime. Used by the
+ password-change flow, which destroys every session for the user, so all
+ of their sockets must go. For single-session logout use
+ ``_disconnect_session_sockets`` instead so other tabs / devices survive.
+ """
+ svc = _get_socket_service()
+ if svc is None:
+ return
+ try:
+ svc.disconnect_user(username)
+ except Exception:
+ logger.exception(f"Failed to disconnect sockets for {username}")
+
+
+def _disconnect_session_sockets(session_id: str) -> None:
+ """Disconnect only the sockets belonging to ``session_id``.
+
+ Used by single-session logout: it tears down the sockets of the session
+ being logged out without disconnecting the user's other still-valid
+ sessions (rooms are per-session as well as per-user). Best-effort —
+ socket teardown must never break logout.
+ """
+ svc = _get_socket_service()
+ if svc is None:
+ return
+ try:
+ svc.disconnect_session(session_id)
+ except Exception:
+ logger.exception("Failed to disconnect sockets for session")
+
+
@auth_bp.route("/csrf-token", methods=["GET"])
def get_csrf_token():
"""
@@ -713,15 +777,24 @@ def logout():
# LOGOUT CLEANUP ORDER (order matters):
# 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
+ # 2. Invalidate the server-side 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
+ # password and reopen the DB in the close→clear window. This also
+ # makes the socket connect gate (__session_authorizes ->
+ # validate_session) reject any NEW socket from this moment on.
+ # 3. Disconnect this session's live WebSocket connections — sockets are
+ # authorised once at handshake and never re-checked, so without this
+ # a socket connected before logout keeps receiving the user's events.
+ # Scoped to THIS session so the user's other tabs / devices stay
+ # connected. MUST run AFTER step 2 so the socket connect gate
+ # above already rejects new sockets before we tear down the
+ # existing ones.
+ # 4. 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.
+ # 5. Drop per-user lock-dict entries.
+ # 6. Clear the Flask session dict.
try:
from ...scheduler.background import (
get_background_job_scheduler,
@@ -738,9 +811,23 @@ def logout():
# 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.
+ # logout. Disconnecting this session's live WebSocket connections
+ # right after — rather than deferring it to after the DB close and
+ # lock cleanup below — matters too: sockets are authorised once at
+ # handshake and never re-checked, so without this a socket connected
+ # before logout keeps receiving the user's events. Scoped to THIS
+ # session so the user's other tabs / devices stay connected. This
+ # MUST run AFTER _cleanup_user_session so the socket connect gate
+ # (__session_authorizes -> validate_session) already rejects new
+ # sockets before we tear down the existing ones — this closes the
+ # reconnect-in-teardown-window race: were the sockets disconnected
+ # first, a socket connecting in the gap would still pass the gate,
+ # join user_room, and survive logout. _disconnect_session_sockets
+ # only needs the session_id string (a local), so it still works
+ # after the session has been destroyed.
if session_id:
_cleanup_user_session(username, session_id=session_id)
+ _disconnect_session_sockets(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
@@ -963,6 +1050,10 @@ def change_password():
username, session_id=None, new_password=new_password
)
+ # 3a. Disconnect live WebSocket connections so a socket authorised
+ # under the old session stops receiving this user's events.
+ _disconnect_user_sockets(username)
+
# 4. Clear Flask session dict
session.clear()
diff --git a/src/local_deep_research/web/auth/session_manager.py b/src/local_deep_research/web/auth/session_manager.py
index 342e69b1b7..f85b3341ea 100644
--- a/src/local_deep_research/web/auth/session_manager.py
+++ b/src/local_deep_research/web/auth/session_manager.py
@@ -15,10 +15,25 @@ from ...security import get_security_default
class SessionManager:
- """Manages user sessions and database connection lifecycle."""
+ """Manages user sessions and database connection lifecycle.
+
+ Note: session state is in-memory and per-process (no Redis or other
+ shared store). In multi-worker deployments (e.g. gunicorn with more
+ than one worker) each worker holds its own ``sessions`` dict, and a
+ worker restart drops all sessions it held. ``validate_session`` only
+ ever sees sessions created by *this* process — including for callers
+ like the socket connect-time session gate, which now relies on this
+ lookup. See ``security/account_lockout.py`` and
+ ``research_library/routes/rag_routes.py`` for the same caveat
+ elsewhere in the codebase.
+ """
def __init__(self):
self.sessions: Dict[str, dict] = {}
+ # WARNING: never call logger.* while holding _lock. The synchronous
+ # frontend_progress_sink can re-enter emit_to_subscribers ->
+ # touch_session -> _lock on the same thread and self-deadlock (this is
+ # a plain Lock, not an RLock).
self._lock = threading.Lock()
# Load session timeouts from security settings
session_hours = get_security_default(
@@ -84,6 +99,22 @@ class SessionManager:
session_data["last_access"] = now
return str(session_data["username"])
+ def touch_session(self, session_id: str) -> None:
+ """Refresh a session's ``last_access`` without enforcing the timeout.
+
+ Called on socket activity: a user actively watching a long research
+ run makes no HTTP requests, so the request-path idle-timeout refresh
+ (in ``validate_session``) never fires and the session would silently
+ expire mid-run. Unlike ``validate_session`` this never deletes an
+ expired session — it only bumps ``last_access`` for one still present.
+ """
+ if not session_id:
+ return
+ with self._lock:
+ session_data = self.sessions.get(session_id)
+ if session_data is not None:
+ session_data["last_access"] = datetime.datetime.now(UTC)
+
def destroy_session(self, session_id: str):
"""Destroy a session and clean up."""
with self._lock:
@@ -111,7 +142,7 @@ class SessionManager:
return len(to_delete)
def cleanup_expired_sessions(self):
- """Remove all expired sessions."""
+ """Remove all expired sessions and disconnect their live sockets."""
now = datetime.datetime.now(UTC)
expired = []
@@ -130,6 +161,41 @@ class SessionManager:
if expired:
logger.info(f"Cleaned up {len(expired)} expired sessions")
+ # Tear down any sockets still attached to these now-dead sessions.
+ # A socket is authorised once at handshake and then frozen, so
+ # without this an expired session's tab keeps receiving the user's
+ # events. Done AFTER releasing the lock (disconnect reaches into
+ # the socket server) and best-effort — socket teardown must never
+ # break session cleanup.
+ self._disconnect_expired_sockets(expired)
+
+ @staticmethod
+ def _disconnect_expired_sockets(session_ids: list[str]) -> None:
+ """Best-effort disconnect of the sockets for expired session ids.
+
+ Lazy-imports the socket service to avoid an import cycle
+ (``socket_service`` imports this module) and to tolerate its absence
+ in non-web contexts (CLI, tests). Each session is torn down
+ independently so one failure can't strand the rest.
+ """
+ try:
+ from ..services.socket_service import SocketIOService
+
+ socket_service = SocketIOService()
+ except ValueError:
+ return # No socket server in this context.
+ except Exception:
+ logger.opt(exception=True).warning(
+ "Failed to resolve socket service for expired-session teardown"
+ )
+ return
+ for session_id in session_ids:
+ try:
+ socket_service.disconnect_session(session_id)
+ except Exception:
+ logger.opt(exception=True).warning(
+ "Failed to disconnect sockets for an expired session"
+ )
def get_active_sessions_count(self) -> int:
"""Get count of active sessions."""
diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.py
index b0f4e1fc09..a7e7671190 100644
--- a/src/local_deep_research/web/services/socket_service.py
+++ b/src/local_deep_research/web/services/socket_service.py
@@ -8,7 +8,6 @@ from loguru import logger
from ...constants import ResearchStatus
from ...database.encrypted_db import db_manager
from ...database.session_passwords import session_password_store
-from ..auth.session_manager import session_manager
from ..routes.globals import get_active_research_snapshot
@@ -147,6 +146,11 @@ class SocketIOService:
self.__logging_enabled = True
# Protects access to shared state.
self.__lock = Lock()
+ # sid -> session_id, so socket activity (a user watching a live
+ # research run makes no HTTP requests) can refresh that session's idle
+ # timer and keep it from silently expiring. Best-effort, not
+ # lock-critical.
+ self.__sid_sessions = {}
# Register events.
@self.__socketio.on("connect")
@@ -209,6 +213,19 @@ class SocketIOService:
"""
return f"user:{username}"
+ @staticmethod
+ def session_room(session_id: str) -> str:
+ """Socket.IO room name scoping a socket to a single login session.
+
+ A user can have several concurrent sessions (tabs / devices), each
+ with its own ``session_id``. Every socket joins this per-session room
+ in addition to the per-user room, so a single session's sockets can be
+ torn down (logout of one tab, session expiry) without disconnecting
+ the user's other still-valid sessions. Kept next to ``user_room`` so
+ the connect handler and teardown paths share one definition.
+ """
+ return f"session:{session_id}"
+
def emit_socket_event(self, event, data, room=None):
"""
Emit a socket event to clients.
@@ -268,6 +285,8 @@ class SocketIOService:
else:
subscriptions = None
if subscriptions is not None:
+ from ..auth.session_manager import session_manager
+
for sid in subscriptions:
try:
self.__socketio.emit(full_event, data, room=sid)
@@ -275,6 +294,19 @@ class SocketIOService:
self.__log_exception(
f"Error emitting to subscriber {sid}"
)
+ # Receiving live progress over the socket is activity:
+ # refresh the watcher's session idle timer so a long run
+ # doesn't expire the session and log them out on their next
+ # HTTP request. Own try/except so a refresh failure can't
+ # strand delivery to the remaining subscribers.
+ try:
+ sid_session = self.__sid_sessions.get(sid)
+ if sid_session:
+ session_manager.touch_session(sid_session)
+ except Exception:
+ self.__log_exception(
+ f"Error refreshing session for subscriber {sid}"
+ )
# When no targeted subscribers exist yet, drop the event.
# The catch-up snapshot in __handle_subscribe replays the
# latest progress on subscribe, so early-arriving events
@@ -298,6 +330,206 @@ class SocketIOService:
f"Removed {len(removed)} subscription(s) for research {research_id}"
)
+ def __disconnect_room(self, room: str, description: str) -> int:
+ """Disconnect every socket in ``room`` and drop their subscriptions.
+
+ Shared teardown for ``disconnect_user`` (per-username room) and
+ ``disconnect_session`` (per-session room).
+
+ A Socket.IO connection is authorised once at handshake and then keeps
+ delivering events for its whole lifetime — the ``user:<username>``
+ room even carries ``settings_changed`` events that include plaintext
+ secrets. Logout, password change, and session expiry destroy the HTTP
+ session but do NOT close these sockets on their own, so this severs
+ them explicitly.
+
+ Safe to call from the HTTP request thread: ``async_mode="threading"``
+ is a single in-process server, so the request thread can reach into
+ the Socket.IO server directly. Best-effort and exception-safe — a
+ teardown failure must never break the caller (logout etc.).
+
+ ``description`` is used only for logging. Returns the number of sids
+ disconnect was attempted for (0 if the room is empty or the server
+ internals are unavailable) — this includes sids whose individual
+ ``disconnect()`` call raised.
+ """
+ try:
+ server = self.__socketio.server
+ except AttributeError:
+ return 0
+
+ # Snapshot the room membership before disconnecting, since disconnect
+ # mutates the room. get_participants yields (sid, eio_sid) tuples for
+ # the default namespace.
+ try:
+ sids = [
+ sid for sid, _ in server.manager.get_participants("/", room)
+ ]
+ except Exception:
+ # Unconditional warning — NOT the __logging_enabled-gated
+ # __log_exception. This reads semi-internal python-socketio
+ # state (server.manager.get_participants), so a dependency
+ # upgrade that changes its shape must always surface here,
+ # rather than silently leaving secret-carrying sockets live.
+ logger.opt(exception=True).warning(
+ f"Failed to enumerate sockets for room {room} via "
+ "server.manager.get_participants — python-socketio "
+ "internals may have changed; socket teardown for this room "
+ "did not happen"
+ )
+ return 0
+
+ if not sids:
+ return 0
+
+ # Drop these sids from every research subscription set so no further
+ # emit_to_subscribers reaches them, pruning now-empty entries. Done
+ # under the lock and BEFORE disconnecting so the disconnect handler
+ # (which also takes the lock) never contends with us.
+ with self.__lock:
+ empty_keys = []
+ for research_id, subscribed in self.__socket_subscriptions.items():
+ subscribed.difference_update(sids)
+ if not subscribed:
+ empty_keys.append(research_id)
+ for key in empty_keys:
+ del self.__socket_subscriptions[key]
+
+ # Disconnect each socket so nothing further is delivered to it.
+ for sid in sids:
+ try:
+ server.disconnect(sid, namespace="/")
+ except Exception:
+ self.__log_exception(f"Failed to disconnect socket {sid}")
+ # server.disconnect raised, so the "disconnect" event (and
+ # __handle_disconnect's pruning) never fires for this sid —
+ # prune its __sid_sessions entry here too, or it lingers.
+ with self.__lock:
+ self.__sid_sessions.pop(sid, None)
+
+ # Belt and suspenders: empty the room so any in-flight room emit is
+ # dropped even if a disconnect above raced.
+ try:
+ self.__socketio.close_room(room, namespace="/")
+ except Exception:
+ self.__log_exception(f"Failed to close room {room}")
+
+ self.__log_info(f"Disconnected {len(sids)} socket(s) for {description}")
+ return len(sids)
+
+ def disconnect_user(self, username: str) -> int:
+ """Disconnect ALL of ``username``'s sockets and drop their subscriptions.
+
+ Use for the all-sessions cases: password change (every session is
+ destroyed) and idle-DB-close (the user has no active session left).
+ For single-session logout use ``disconnect_session`` so the user's
+ other tabs / devices survive.
+
+ Returns the number of sids disconnect was attempted for (includes
+ sids whose disconnect raised).
+ """
+ return self.__disconnect_room(
+ self.user_room(username), f"user {username}"
+ )
+
+ def disconnect_session(self, session_id: str) -> int:
+ """Disconnect only the sockets belonging to ``session_id``.
+
+ Use for single-session teardown (logout of one tab, session expiry)
+ so the user's other still-valid sessions keep their sockets. The
+ per-session room is joined at connect alongside the per-user room.
+
+ Returns the number of sids disconnect was attempted for (includes
+ sids whose disconnect raised).
+ """
+ return self.__disconnect_room(
+ self.session_room(session_id), f"session {session_id[:8]}..."
+ )
+
+ def __session_authorizes(self, username: str) -> bool:
+ """Return True if this socket's Flask session is still a live server
+ session for ``username``.
+
+ Defense-in-depth for socket actions: handshake auth is validated once
+ and then frozen (Flask-SocketIO copies the session at connect), so a
+ socket can outlive the session that authorised it (logout race,
+ idle/expiry teardown). Re-checking the session id against the
+ ``SessionManager`` on every subscribe/unsubscribe means such a socket
+ cannot act on a destroyed session even if it somehow survived. Fails
+ closed on a missing id or any validation error.
+ """
+ try:
+ session_id = session.get("session_id")
+ if not session_id:
+ return False
+ # Lazy import avoids an import cycle (session_manager is imported
+ # by the auth routes, which pull in this package).
+ from ..auth.session_manager import session_manager
+
+ return session_manager.validate_session(session_id) == username
+ except Exception:
+ logger.opt(exception=True).warning(
+ "Failed to validate session for socket action"
+ )
+ return False
+
+ def __revoke_socket(self, request) -> None:
+ """Disconnect a socket whose session failed re-validation.
+
+ Rejecting the action is not enough: ``validate_session`` DELETES an
+ expired session from the ``SessionManager`` inline, so the periodic
+ ``cleanup_expired_sessions`` sweep can no longer see it, and a
+ multi-session user keeps the idle-DB sweep from firing. The socket
+ would otherwise linger in ``user_room`` receiving events (including
+ ``settings_changed``, which carries plaintext secrets) indefinitely.
+ So sever it here.
+
+ ``__session_authorizes`` fails for two different reasons and they
+ must NOT be handled the same way:
+
+ - The session id is dead (missing/expired — ``validate_session``
+ returns ``None``): the whole session is gone, so use
+ ``disconnect_session`` to tear down all of that now-dead session's
+ sockets and drop their subscriptions (it releases ``__lock`` before
+ calling ``server.disconnect``, so re-entering
+ ``__handle_disconnect`` for the current socket cannot deadlock).
+ - The session id is still LIVE but belongs to a DIFFERENT user than
+ this socket claimed (a mismatch, not an expiry — this should only
+ be reachable via a forged/stale session cookie, since Flask's
+ signed cookie makes it hard to present someone else's session id).
+ Calling ``disconnect_session`` here would tear down that OTHER
+ user's whole session — collateral damage to an innocent user. Only
+ this one socket is suspect, so sever just ``request.sid``.
+
+ If the socket carries no session id to scope by, sever just this
+ sid. Best-effort — never raise back into the event handler.
+ """
+ session_id = session.get("session_id")
+ try:
+ if not session_id:
+ # No session id to scope by — sever just this socket.
+ self.__socketio.server.disconnect(request.sid, namespace="/")
+ return
+
+ # Lazy import avoids an import cycle (session_manager is imported
+ # by the auth routes, which pull in this package).
+ from ..auth.session_manager import session_manager
+
+ actual_username = session_manager.validate_session(session_id)
+ if actual_username is None:
+ # Dead/expired session — safe to tear down all of its
+ # sockets.
+ self.disconnect_session(session_id)
+ else:
+ # Live session, but not this socket's — it belongs to a
+ # different user. Sever only this socket, not the other
+ # user's session.
+ self.__socketio.server.disconnect(request.sid, namespace="/")
+ except Exception:
+ self.__log_exception(
+ f"Failed to revoke socket {request.sid} on invalid session"
+ )
+
def __handle_connect(self, request):
"""Handle client connection"""
username = session.get("username")
@@ -306,19 +538,23 @@ class SocketIOService:
f"Rejected unauthenticated WebSocket connection from {request.sid}"
)
return False
- # Validate the server-side session so a revoked (logged-out) or
- # expired cookie is rejected here too, keeping the socket handshake
- # consistent with login_required / inject_current_user.
- session_id = session.get("session_id")
- if (
- not session_id
- or session_manager.validate_session(session_id) != username
- ):
+ # Re-validate the session id at connect, not just on subscribe.
+ # Flask-SocketIO freezes the handshake session, and db_manager's
+ # per-user engine is keyed by username (shared across all of a
+ # user's sessions) — so a stale/captured cookie whose own session
+ # was logged out or idle-expired can otherwise open a NEW socket
+ # and join user_room (receiving settings_changed, which carries
+ # plaintext secrets) as long as ANOTHER session or an in-flight
+ # research run keeps that user's DB connection open. Gate the
+ # connection on the specific session id still being live.
+ if not self.__session_authorizes(username):
self.__log_info(
f"Rejected WebSocket connection for {username}: "
- f"server-side session missing, revoked, or expired"
+ f"session is no longer valid"
)
return False
+ # session_id is guaranteed present/valid by __session_authorizes above.
+ session_id = session.get("session_id")
if not db_manager.is_user_connected(username):
# Cookie is valid but the per-user DB engine isn't open yet (race vs first
# XHR after page load, gunicorn worker restart, or idle eviction). Lazily
@@ -347,6 +583,14 @@ class SocketIOService:
# connected client. Flask-SocketIO auto-removes the socket from the
# room on disconnect.
join_room(self.user_room(username))
+ # Also join a per-session room so a single session's sockets can be
+ # torn down (logout of one tab, session expiry) without disconnecting
+ # the user's other still-valid sessions. session_id is set at login;
+ # a session without one simply skips this finer-grained scoping.
+ session_id = session.get("session_id")
+ if session_id:
+ join_room(self.session_room(session_id))
+ self.__sid_sessions[request.sid] = session_id
self.__log_info(f"Client connected: {request.sid} (user: {username})")
return True
@@ -360,6 +604,7 @@ class SocketIOService:
# __socket_subscriptions is keyed by research_id → set of sids,
# so we iterate all entries and discard the disconnecting sid.
with self.__lock:
+ self.__sid_sessions.pop(request.sid, None)
empty_keys = []
for research_id, sids in self.__socket_subscriptions.items():
sids.discard(request.sid)
@@ -401,7 +646,19 @@ class SocketIOService:
# is the ownership boundary: if the research row doesn't exist in
# the user's DB, they don't own it.
username = session.get("username")
- if not username or not self._user_owns_research(username, research_id):
+ # Defense-in-depth: re-validate the socket's session on every action,
+ # not just at handshake, so a socket that outlived its session (logout
+ # race, idle/expiry teardown) cannot act on a destroyed session.
+ if not username or not self.__session_authorizes(username):
+ self.__log_info(
+ f"Rejected subscribe from {request.sid}: no valid session"
+ )
+ # The session is gone (validate_session inline-deletes an expired
+ # one), so rejecting alone would strand this socket in user_room.
+ # Disconnect it and drop its subscriptions.
+ self.__revoke_socket(request)
+ return
+ if not self._user_owns_research(username, research_id):
self.__log_info(
f"Rejected subscribe from {request.sid}: user does not own research {research_id}"
)
@@ -501,7 +758,17 @@ class SocketIOService:
# exfiltration; subscribe is already guarded), but it keeps the
# authz boundary consistent and avoids log spam from spoofed sids.
username = session.get("username")
- if not username or not self._user_owns_research(username, research_id):
+ # Symmetric with subscribe: re-validate the session so a socket that
+ # outlived its session cannot mutate subscription state.
+ if not username or not self.__session_authorizes(username):
+ self.__log_info(
+ f"Rejected unsubscribe from {request.sid}: no valid session"
+ )
+ # As in subscribe: a failed re-validation means the session is
+ # gone, so sever the stranded socket rather than just rejecting.
+ self.__revoke_socket(request)
+ return
+ if not self._user_owns_research(username, research_id):
self.__log_info(
f"Rejected unsubscribe from {request.sid}: user does not own research {research_id}"
)
diff --git a/tests/chat/test_chat_socket_events.py b/tests/chat/test_chat_socket_events.py
index a121c84547..266f3cb23a 100644
--- a/tests/chat/test_chat_socket_events.py
+++ b/tests/chat/test_chat_socket_events.py
@@ -126,11 +126,16 @@ class TestSocketIOHandlers:
) as mock_socketio_class,
patch(
"src.local_deep_research.web.services.socket_service.session",
- {"username": "alice"},
+ {"username": "alice", "session_id": "sess-alice"},
),
patch.object(
SocketIOService, "_user_owns_research", return_value=True
),
+ patch(
+ "src.local_deep_research.web.auth.session_manager."
+ "session_manager.validate_session",
+ return_value="alice",
+ ),
):
mock_socketio = MagicMock()
mock_socketio_class.return_value = mock_socketio
@@ -165,11 +170,16 @@ class TestSocketIOHandlers:
) as mock_socketio_class,
patch(
"src.local_deep_research.web.services.socket_service.session",
- {"username": "alice"},
+ {"username": "alice", "session_id": "sess-alice"},
),
patch.object(
SocketIOService, "_user_owns_research", return_value=True
),
+ patch(
+ "src.local_deep_research.web.auth.session_manager."
+ "session_manager.validate_session",
+ return_value="alice",
+ ),
):
mock_socketio = MagicMock()
mock_socketio_class.return_value = mock_socketio
@@ -269,11 +279,16 @@ class TestSocketIOHandlers:
) as mock_socketio_class,
patch(
"src.local_deep_research.web.services.socket_service.session",
- {"username": "alice"},
+ {"username": "alice", "session_id": "sess-alice"},
),
patch.object(
SocketIOService, "_user_owns_research", return_value=True
),
+ patch(
+ "src.local_deep_research.web.auth.session_manager."
+ "session_manager.validate_session",
+ return_value="alice",
+ ),
):
mock_socketio = MagicMock()
mock_socketio_class.return_value = mock_socketio
@@ -334,11 +349,16 @@ class TestSocketIOHandlers:
) as mock_socketio_class,
patch(
"src.local_deep_research.web.services.socket_service.session",
- {"username": "alice"},
+ {"username": "alice", "session_id": "sess-alice"},
),
patch.object(
SocketIOService, "_user_owns_research", return_value=True
),
+ patch(
+ "src.local_deep_research.web.auth.session_manager."
+ "session_manager.validate_session",
+ return_value="alice",
+ ),
):
mock_socketio = MagicMock()
# Make emit fail for specific clients
diff --git a/tests/web/auth/test_auth_routes.py b/tests/web/auth/test_auth_routes.py
index 529a2d4a39..fc71fcb895 100644
--- a/tests/web/auth/test_auth_routes.py
+++ b/tests/web/auth/test_auth_routes.py
@@ -536,6 +536,50 @@ class TestLogout:
"testuser"
)
+ def test_disconnects_only_this_session_sockets_on_logout(self):
+ """Logout must tear down only THIS session's live sockets.
+
+ Sockets are authorised once at handshake and never re-checked, so a
+ socket opened before logout would keep receiving the user's events
+ unless logout disconnects it. Logout is single-session, so it must
+ scope teardown to the logged-out session (disconnect_session) and must
+ NOT disconnect the user's other still-valid sessions (disconnect_user
+ would be an availability regression).
+ """
+ app = Flask(__name__)
+ app.secret_key = "test"
+ app.config["WTF_CSRF_ENABLED"] = False
+
+ mock_socket_service = MagicMock()
+
+ with (
+ patch("local_deep_research.web.auth.routes.db_manager"),
+ patch("local_deep_research.web.auth.routes.session_manager"),
+ patch(
+ "local_deep_research.database.session_passwords.session_password_store"
+ ),
+ patch(
+ "local_deep_research.web.services.socket_service.SocketIOService",
+ return_value=mock_socket_service,
+ ),
+ ):
+ 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"
+
+ response = client.post("/auth/logout")
+ assert response.status_code == 302
+
+ mock_socket_service.disconnect_session.assert_called_once_with(
+ "session_123"
+ )
+ # Must NOT nuke the user's other sessions.
+ mock_socket_service.disconnect_user.assert_not_called()
+
def _logout_with_active_research(self, active):
app = Flask(__name__)
app.secret_key = "test"
@@ -756,6 +800,58 @@ class TestChangePassword:
"testuser"
)
+ def test_disconnects_sockets_on_password_change(self):
+ """A password change must also drop the user's live sockets.
+
+ Changing the password destroys all sessions; a socket authorised
+ under the old session must not keep receiving the user's events.
+ """
+ app = Flask(__name__)
+ app.secret_key = "test"
+ app.config["WTF_CSRF_ENABLED"] = False
+
+ mock_socket_service = MagicMock()
+
+ 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"
+ ),
+ patch(
+ "local_deep_research.web.services.socket_service.SocketIOService",
+ return_value=mock_socket_service,
+ ),
+ ):
+ mock_db.change_password.return_value = True
+ 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!",
+ },
+ follow_redirects=False,
+ )
+ assert response.status_code == 302
+
+ mock_socket_service.disconnect_user.assert_called_once_with(
+ "testuser"
+ )
+
def test_returns_401_for_wrong_current_password(self):
"""Should return 401 when current password is incorrect."""
app = Flask(__name__)
diff --git a/tests/web/auth/test_connection_cleanup.py b/tests/web/auth/test_connection_cleanup.py
index c25fc882cd..5c455caf85 100644
--- a/tests/web/auth/test_connection_cleanup.py
+++ b/tests/web/auth/test_connection_cleanup.py
@@ -82,6 +82,34 @@ class TestCleanupIdleConnections:
db.close_user_database.assert_not_called()
+ @patch(
+ "local_deep_research.web.services.socket_service.SocketIOService",
+ )
+ @patch(
+ "local_deep_research.scheduler.background.get_background_job_scheduler",
+ )
+ @patch(
+ "local_deep_research.web.auth.connection_cleanup.get_usernames_with_active_research",
+ return_value=set(),
+ )
+ def test_disconnects_all_sockets_for_idle_user(
+ self, _mock_research, _mock_sched, mock_socket_cls, sm, db
+ ):
+ """Idle-close disconnects ALL of the idle user's sockets.
+
+ The user has no active session at all here, so every one of their
+ still-open sockets (authorised once at handshake and never re-checked)
+ must be severed — disconnect_user, not disconnect_session.
+ """
+ db.get_connected_usernames.return_value = {"alice"}
+ mock_service = MagicMock()
+ mock_socket_cls.return_value = mock_service
+
+ cleanup_idle_connections(sm, db)
+
+ db.close_user_database.assert_called_once_with("alice")
+ mock_service.disconnect_user.assert_called_once_with("alice")
+
@patch(
"local_deep_research.scheduler.background.get_background_job_scheduler",
)
diff --git a/tests/web/auth/test_session_manager.py b/tests/web/auth/test_session_manager.py
index a41b3a6c91..ef9dfa2a5d 100644
--- a/tests/web/auth/test_session_manager.py
+++ b/tests/web/auth/test_session_manager.py
@@ -10,7 +10,7 @@ Tests cover:
import datetime
from datetime import UTC
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
import pytest
@@ -429,6 +429,59 @@ class TestCleanupExpiredSessions:
assert s4 in manager.sessions # still valid regular
+_SOCKET_SERVICE_PATCH = (
+ "local_deep_research.web.services.socket_service.SocketIOService"
+)
+
+
+class TestExpiredSessionSocketTeardown:
+ """cleanup_expired_sessions must also disconnect expired sessions' sockets.
+
+ A socket is authorised once at handshake and then frozen, so without an
+ explicit teardown an expired session's tab keeps receiving the user's
+ events (including settings_changed, which carries secret values).
+ """
+
+ def test_cleanup_disconnects_expired_session_sockets(self, manager):
+ """Each expired session id is passed to disconnect_session."""
+ expired_sid = manager.create_session("alice", remember_me=False)
+ manager.sessions[expired_sid]["last_access"] = datetime.datetime.now(
+ UTC
+ ) - datetime.timedelta(hours=MOCK_SESSION_TIMEOUT_HOURS + 1)
+ # A still-valid session must NOT be torn down.
+ valid_sid = manager.create_session("bob", remember_me=False)
+
+ mock_service = MagicMock()
+ with patch(_SOCKET_SERVICE_PATCH, return_value=mock_service):
+ manager.cleanup_expired_sessions()
+
+ assert expired_sid not in manager.sessions
+ assert valid_sid in manager.sessions
+ mock_service.disconnect_session.assert_called_once_with(expired_sid)
+
+ def test_cleanup_survives_socket_service_uninitialized(self, manager):
+ """If the socket service isn't initialised, cleanup still succeeds."""
+ expired_sid = manager.create_session("alice", remember_me=False)
+ manager.sessions[expired_sid]["last_access"] = datetime.datetime.now(
+ UTC
+ ) - datetime.timedelta(hours=MOCK_SESSION_TIMEOUT_HOURS + 1)
+
+ with patch(_SOCKET_SERVICE_PATCH, side_effect=ValueError("no app")):
+ manager.cleanup_expired_sessions() # must not raise
+
+ assert expired_sid not in manager.sessions
+
+ def test_cleanup_does_not_disconnect_when_nothing_expired(self, manager):
+ """No expired sessions → the socket service is never consulted."""
+ manager.create_session("alice", remember_me=False)
+
+ mock_service = MagicMock()
+ with patch(_SOCKET_SERVICE_PATCH, return_value=mock_service):
+ manager.cleanup_expired_sessions()
+
+ mock_service.disconnect_session.assert_not_called()
+
+
# ===========================================================================
# Active sessions count
# ===========================================================================
@@ -579,3 +632,32 @@ class TestDestroyAllUserSessions:
manager.destroy_all_user_sessions("alice")
count = manager.destroy_all_user_sessions("alice")
assert count == 0
+
+
+class TestTouchSession:
+ """touch_session refreshes the idle timer on socket activity."""
+
+ def test_refreshes_last_access(self, manager):
+ from datetime import UTC
+
+ sid = manager.create_session("alice", remember_me=False)
+ old = datetime.datetime.now(UTC) - datetime.timedelta(hours=1)
+ manager.sessions[sid]["last_access"] = old
+ manager.touch_session(sid)
+ assert manager.sessions[sid]["last_access"] > old
+
+ def test_missing_or_none_session_is_noop(self, manager):
+ manager.touch_session("does-not-exist")
+ manager.touch_session(None)
+ assert "does-not-exist" not in manager.sessions
+
+ def test_does_not_delete_expired_session(self, manager):
+ from datetime import UTC
+
+ sid = manager.create_session("bob", remember_me=False)
+ manager.sessions[sid]["last_access"] = datetime.datetime.now(
+ UTC
+ ) - datetime.timedelta(days=99)
+ manager.touch_session(sid)
+ # Unlike validate_session, touch must NOT delete an expired session.
+ assert sid in manager.sessions
diff --git a/tests/web/services/conftest.py b/tests/web/services/conftest.py
index f2b07943b0..18931a4a8a 100644
--- a/tests/web/services/conftest.py
+++ b/tests/web/services/conftest.py
@@ -50,8 +50,19 @@ def _allow_socket_subscribe(monkeypatch):
module_path = "src.local_deep_research.web.services.socket_service"
+ # __handle_subscribe / __handle_unsubscribe now also re-validate the
+ # socket's session id against the SessionManager (defense-in-depth), so
+ # provide a session_id and make validate_session recognise it.
+ root = module_path.rsplit(".web.services.socket_service", 1)[0]
with (
- patch(f"{module_path}.session", {"username": "test-owner"}),
+ patch(
+ f"{module_path}.session",
+ {"username": "test-owner", "session_id": "test-session"},
+ ),
patch.object(SocketIOService, "_user_owns_research", return_value=True),
+ patch(
+ f"{root}.web.auth.session_manager.session_manager.validate_session",
+ return_value="test-owner",
+ ),
):
yield
diff --git a/tests/web/services/test_socket_service.py b/tests/web/services/test_socket_service.py
index 2b369d76d3..3231e86c0c 100644
--- a/tests/web/services/test_socket_service.py
+++ b/tests/web/services/test_socket_service.py
@@ -586,6 +586,514 @@ class TestSocketIOServiceSingletonBehavior:
SocketIOService._instance = original_instance
+class TestDisconnectUser:
+ """Tests for disconnect_user (socket teardown on logout / password change).
+
+ disconnect_user must tear down every live socket in the user's room so a
+ socket authorised at an earlier handshake stops receiving that user's
+ events after logout, and it must drop those sids from every research
+ subscription set so emit_to_subscribers no longer reaches them.
+ """
+
+ @staticmethod
+ def _make_service(mock_socketio_class, participants):
+ """Build a fresh service whose user room contains ``participants``.
+
+ ``participants`` is a list of sids; get_participants yields
+ (sid, eio_sid) tuples, matching python-socketio's BaseManager.
+ """
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ mock_socketio = MagicMock()
+ mock_socketio.server.manager.get_participants.return_value = [
+ (sid, f"eio-{sid}") for sid in participants
+ ]
+ mock_socketio_class.return_value = mock_socketio
+
+ service = SocketIOService(app=MockFlaskApp())
+ return service, mock_socketio
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ def test_disconnect_user_disconnects_all_sids(self, mock_socketio_class):
+ """Every sid in the user room is disconnected and the room closed."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ original_instance = SocketIOService._instance
+ SocketIOService._instance = None
+ try:
+ service, mock_socketio = self._make_service(
+ mock_socketio_class, ["sid-1", "sid-2"]
+ )
+
+ count = service.disconnect_user("alice")
+
+ assert count == 2
+ mock_socketio.server.manager.get_participants.assert_called_once_with(
+ "/", "user:alice"
+ )
+ mock_socketio.server.disconnect.assert_any_call(
+ "sid-1", namespace="/"
+ )
+ mock_socketio.server.disconnect.assert_any_call(
+ "sid-2", namespace="/"
+ )
+ mock_socketio.close_room.assert_called_once_with(
+ "user:alice", namespace="/"
+ )
+ finally:
+ SocketIOService._instance = original_instance
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ def test_disconnect_user_removes_subscriptions(self, mock_socketio_class):
+ """The user's sids are dropped from every research subscription set."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ original_instance = SocketIOService._instance
+ SocketIOService._instance = None
+ try:
+ service, _ = self._make_service(mock_socketio_class, ["sid-1"])
+
+ subs = service._SocketIOService__socket_subscriptions
+ subs["research_1"] = {"sid-1", "other-sid"}
+ subs["research_2"] = {"sid-1"}
+
+ service.disconnect_user("alice")
+
+ # sid-1 removed from research_1, other subscriber untouched.
+ assert subs["research_1"] == {"other-sid"}
+ # research_2 had only sid-1, so the now-empty key is pruned.
+ assert "research_2" not in subs
+ finally:
+ SocketIOService._instance = original_instance
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ def test_disconnect_user_stops_emit_to_subscribers(
+ self, mock_socketio_class
+ ):
+ """After disconnect, emit_to_subscribers no longer reaches the sid."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ original_instance = SocketIOService._instance
+ SocketIOService._instance = None
+ try:
+ service, mock_socketio = self._make_service(
+ mock_socketio_class, ["sid-1"]
+ )
+
+ subs = service._SocketIOService__socket_subscriptions
+ subs["research_1"] = {"sid-1"}
+
+ service.disconnect_user("alice")
+ mock_socketio.emit.reset_mock()
+
+ service.emit_to_subscribers("progress", "research_1", {"pct": 10})
+
+ # No subscribers remain for research_1, so nothing is emitted to
+ # the disconnected user's sid.
+ for call in mock_socketio.emit.call_args_list:
+ assert call.kwargs.get("room") != "sid-1"
+ finally:
+ SocketIOService._instance = original_instance
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ def test_disconnect_user_no_sockets_is_noop(self, mock_socketio_class):
+ """With no sockets in the room, disconnect_user is a clean no-op."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ original_instance = SocketIOService._instance
+ SocketIOService._instance = None
+ try:
+ service, mock_socketio = self._make_service(mock_socketio_class, [])
+
+ count = service.disconnect_user("nobody")
+
+ assert count == 0
+ mock_socketio.server.disconnect.assert_not_called()
+ mock_socketio.close_room.assert_not_called()
+ finally:
+ SocketIOService._instance = original_instance
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ def test_disconnect_user_continues_when_one_disconnect_fails(
+ self, mock_socketio_class
+ ):
+ """A single failed disconnect doesn't stop the others or close_room."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ original_instance = SocketIOService._instance
+ SocketIOService._instance = None
+ try:
+ service, mock_socketio = self._make_service(
+ mock_socketio_class, ["sid-1", "sid-2"]
+ )
+
+ def flaky_disconnect(sid, namespace=None):
+ if sid == "sid-1":
+ raise RuntimeError("boom")
+
+ mock_socketio.server.disconnect.side_effect = flaky_disconnect
+
+ count = service.disconnect_user("alice")
+
+ assert count == 2
+ mock_socketio.server.disconnect.assert_any_call(
+ "sid-2", namespace="/"
+ )
+ mock_socketio.close_room.assert_called_once_with(
+ "user:alice", namespace="/"
+ )
+ finally:
+ SocketIOService._instance = original_instance
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ def test_disconnect_user_handles_enumeration_failure(
+ self, mock_socketio_class
+ ):
+ """If room enumeration raises, disconnect_user returns 0, not raises."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ original_instance = SocketIOService._instance
+ SocketIOService._instance = None
+ try:
+ mock_socketio = MagicMock()
+ mock_socketio.server.manager.get_participants.side_effect = (
+ RuntimeError("manager unavailable")
+ )
+ mock_socketio_class.return_value = mock_socketio
+
+ service = SocketIOService(app=MockFlaskApp())
+
+ count = service.disconnect_user("alice")
+
+ assert count == 0
+ mock_socketio.server.disconnect.assert_not_called()
+ finally:
+ SocketIOService._instance = original_instance
+
+
+class TestDisconnectSession:
+ """Tests for disconnect_session (single-session teardown).
+
+ disconnect_session must tear down only the sockets of one login session
+ (its per-session room), leaving the user's other sessions connected.
+ """
+
+ @staticmethod
+ def _make_service(mock_socketio_class, participants):
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ mock_socketio = MagicMock()
+ mock_socketio.server.manager.get_participants.return_value = [
+ (sid, f"eio-{sid}") for sid in participants
+ ]
+ mock_socketio_class.return_value = mock_socketio
+
+ service = SocketIOService(app=MockFlaskApp())
+ return service, mock_socketio
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ def test_disconnect_session_targets_only_session_room(
+ self, mock_socketio_class
+ ):
+ """disconnect_session acts on the per-session room, not the user room."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ original_instance = SocketIOService._instance
+ SocketIOService._instance = None
+ try:
+ service, mock_socketio = self._make_service(
+ mock_socketio_class, ["sid-1"]
+ )
+
+ count = service.disconnect_session("sess-A")
+
+ assert count == 1
+ mock_socketio.server.manager.get_participants.assert_called_once_with(
+ "/", "session:sess-A"
+ )
+ mock_socketio.server.disconnect.assert_called_once_with(
+ "sid-1", namespace="/"
+ )
+ mock_socketio.close_room.assert_called_once_with(
+ "session:sess-A", namespace="/"
+ )
+ finally:
+ SocketIOService._instance = original_instance
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ def test_disconnect_session_leaves_other_sessions_subscriptions(
+ self, mock_socketio_class
+ ):
+ """Only the target session's sids are pruned; another session's socket
+ (subscribed to the same research) keeps its subscription."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ original_instance = SocketIOService._instance
+ SocketIOService._instance = None
+ try:
+ # Only session A's socket (sid-A) is in the session:sess-A room.
+ service, _ = self._make_service(mock_socketio_class, ["sid-A"])
+
+ subs = service._SocketIOService__socket_subscriptions
+ # sid-B belongs to another still-valid session of the same user.
+ subs["research_1"] = {"sid-A", "sid-B"}
+
+ service.disconnect_session("sess-A")
+
+ # sid-A dropped, the other session's sid-B survives.
+ assert subs["research_1"] == {"sid-B"}
+ finally:
+ SocketIOService._instance = original_instance
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ def test_disconnect_session_no_sockets_is_noop(self, mock_socketio_class):
+ """With no sockets in the session room, disconnect_session is a no-op."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ original_instance = SocketIOService._instance
+ SocketIOService._instance = None
+ try:
+ service, mock_socketio = self._make_service(mock_socketio_class, [])
+
+ count = service.disconnect_session("sess-empty")
+
+ assert count == 0
+ mock_socketio.server.disconnect.assert_not_called()
+ mock_socketio.close_room.assert_not_called()
+ finally:
+ SocketIOService._instance = original_instance
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ def test_disconnect_session_stops_emit_to_subscribers(
+ self, mock_socketio_class
+ ):
+ """After session teardown, emit_to_subscribers no longer reaches the
+ expired session's sid (mirrors what happens on session expiry)."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ original_instance = SocketIOService._instance
+ SocketIOService._instance = None
+ try:
+ service, mock_socketio = self._make_service(
+ mock_socketio_class, ["sid-A"]
+ )
+ subs = service._SocketIOService__socket_subscriptions
+ subs["research_1"] = {"sid-A"}
+
+ service.disconnect_session("sess-A")
+ mock_socketio.emit.reset_mock()
+
+ service.emit_to_subscribers("progress", "research_1", {"pct": 10})
+
+ for call in mock_socketio.emit.call_args_list:
+ assert call.kwargs.get("room") != "sid-A"
+ finally:
+ SocketIOService._instance = original_instance
+
+
+class TestSubscribeSessionRevalidation:
+ """Defense-in-depth: subscribe/unsubscribe re-validate the session.
+
+ A socket authorised at handshake is frozen; if its session is later
+ destroyed (logout, expiry) the socket must not be able to act on it.
+ """
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ def test_subscribe_rejected_and_disconnected_when_session_destroyed(
+ self, mock_socketio_class
+ ):
+ """Subscribe on a destroyed session is rejected AND the socket is
+ disconnected (not merely rejected), so it can't linger in user_room."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ original_instance = SocketIOService._instance
+ SocketIOService._instance = None
+ try:
+ mock_socketio = MagicMock()
+ # The socket's per-session room still holds it.
+ mock_socketio.server.manager.get_participants.return_value = [
+ ("ghost-sid", "eio-ghost")
+ ]
+ mock_socketio_class.return_value = mock_socketio
+ service = SocketIOService(app=MockFlaskApp())
+
+ mock_request = MagicMock()
+ mock_request.sid = "ghost-sid"
+
+ # Override the autouse fixture's happy-path validate_session: the
+ # session backing this socket has been destroyed. session_id comes
+ # from the autouse fixture ("test-session").
+ with patch(
+ "local_deep_research.web.auth.session_manager."
+ "session_manager.validate_session",
+ return_value=None,
+ ):
+ service._SocketIOService__handle_subscribe(
+ {"research_id": "r1"}, mock_request
+ )
+
+ assert "r1" not in service._SocketIOService__socket_subscriptions
+ mock_socketio.server.disconnect.assert_any_call(
+ "ghost-sid", namespace="/"
+ )
+ mock_socketio.close_room.assert_any_call(
+ "session:test-session", namespace="/"
+ )
+ finally:
+ SocketIOService._instance = original_instance
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ def test_unsubscribe_rejected_and_disconnected_when_session_destroyed(
+ self, mock_socketio_class
+ ):
+ """Unsubscribe on a destroyed session is rejected (state untouched)
+ AND the stranded socket is disconnected."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ original_instance = SocketIOService._instance
+ SocketIOService._instance = None
+ try:
+ mock_socketio = MagicMock()
+ mock_socketio.server.manager.get_participants.return_value = [
+ ("ghost-sid", "eio-ghost")
+ ]
+ mock_socketio_class.return_value = mock_socketio
+ service = SocketIOService(app=MockFlaskApp())
+
+ subs = service._SocketIOService__socket_subscriptions
+ subs["r1"] = {"legit-sid"}
+
+ mock_request = MagicMock()
+ mock_request.sid = "ghost-sid"
+
+ with patch(
+ "local_deep_research.web.auth.session_manager."
+ "session_manager.validate_session",
+ return_value=None,
+ ):
+ service._SocketIOService__handle_unsubscribe(
+ {"research_id": "r1"}, mock_request
+ )
+
+ # Rejected before any mutation — legit subscriber untouched.
+ assert subs["r1"] == {"legit-sid"}
+ # But the offending socket is severed.
+ mock_socketio.server.disconnect.assert_any_call(
+ "ghost-sid", namespace="/"
+ )
+ finally:
+ SocketIOService._instance = original_instance
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ def test_subscribe_disconnects_orphan_from_inline_expiry_delete(
+ self, mock_socketio_class
+ ):
+ """Regression: validate_session inline-deletes an expired session, so
+ rejecting the subscribe without disconnecting would strand the socket
+ forever (cleanup_expired_sessions can no longer see the deleted
+ session). The handler must disconnect the socket during the subscribe,
+ and a later cleanup pass must not be relied upon.
+
+ Uses a REAL SessionManager so the inline expiry-delete actually runs.
+ """
+ import datetime
+ from datetime import UTC, timedelta
+
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+ from local_deep_research.web.auth.session_manager import SessionManager
+
+ original_instance = SocketIOService._instance
+ SocketIOService._instance = None
+ try:
+ mock_socketio = MagicMock()
+ mock_socketio.server.manager.get_participants.return_value = [
+ ("orphan-sid", "eio-orphan")
+ ]
+ mock_socketio_class.return_value = mock_socketio
+ service = SocketIOService(app=MockFlaskApp())
+
+ # Real manager; create a session then force it past its timeout.
+ with patch(
+ "local_deep_research.web.auth.session_manager."
+ "get_security_default",
+ return_value=1,
+ ):
+ manager = SessionManager()
+ manager.session_timeout = timedelta(seconds=1)
+ session_token = manager.create_session("alice", remember_me=False)
+ manager.sessions[session_token]["last_access"] = (
+ datetime.datetime.now(UTC) - timedelta(hours=1)
+ )
+
+ mock_request = MagicMock()
+ mock_request.sid = "orphan-sid"
+
+ with (
+ patch(
+ "local_deep_research.web.services.socket_service.session",
+ {"username": "alice", "session_id": session_token},
+ ),
+ patch(
+ "local_deep_research.web.auth.session_manager."
+ "session_manager",
+ manager,
+ ),
+ ):
+ service._SocketIOService__handle_subscribe(
+ {"research_id": "r1"}, mock_request
+ )
+
+ # validate_session inline-deleted the expired session ...
+ assert session_token not in manager.sessions
+ # ... the subscribe was rejected ...
+ assert "r1" not in service._SocketIOService__socket_subscriptions
+ # ... and the orphaned socket was disconnected + its room closed.
+ mock_socketio.server.disconnect.assert_any_call(
+ "orphan-sid", namespace="/"
+ )
+ mock_socketio.close_room.assert_any_call(
+ SocketIOService.session_room(session_token), namespace="/"
+ )
+
+ # cleanup_expired_sessions is NOT relied upon: the session is
+ # already gone, so a later sweep has nothing left to disconnect.
+ mock_socketio.server.disconnect.reset_mock()
+ manager.cleanup_expired_sessions()
+ mock_socketio.server.disconnect.assert_not_called()
+ finally:
+ SocketIOService._instance = original_instance
+
+
class TestSocketServiceDisconnectCleanup:
"""Tests for thread cleanup on socket disconnect.
diff --git a/tests/web/services/test_socket_service_coverage.py b/tests/web/services/test_socket_service_coverage.py
index 55d5a8fea2..e7f232d96e 100644
--- a/tests/web/services/test_socket_service_coverage.py
+++ b/tests/web/services/test_socket_service_coverage.py
@@ -272,9 +272,16 @@ class TestHandleConnect:
f"{MODULE}.session",
{"username": "alice", "session_id": "sess-1"},
),
- patch(f"{MODULE}.session_manager") as mock_sm,
+ patch(
+ "local_deep_research.web.auth.session_manager.session_manager"
+ ) as mock_sm,
patch(f"{MODULE}.db_manager") as mock_db,
patch(f"{MODULE}.session_password_store") as mock_store,
+ patch.object(
+ service,
+ "_SocketIOService__session_authorizes",
+ return_value=True,
+ ),
):
mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = False
@@ -295,10 +302,17 @@ class TestHandleConnect:
f"{MODULE}.session",
{"username": "alice", "session_id": "sess-1"},
),
- patch(f"{MODULE}.session_manager") as mock_sm,
+ patch(
+ "local_deep_research.web.auth.session_manager.session_manager"
+ ) as mock_sm,
patch(f"{MODULE}.db_manager") as mock_db,
patch(f"{MODULE}.session_password_store") as mock_store,
patch(f"{MODULE}.join_room"),
+ patch.object(
+ service,
+ "_SocketIOService__session_authorizes",
+ return_value=True,
+ ),
):
mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = False
@@ -319,10 +333,17 @@ class TestHandleConnect:
f"{MODULE}.session",
{"username": "alice", "session_id": "sess-1"},
),
- patch(f"{MODULE}.session_manager") as mock_sm,
+ patch(
+ "local_deep_research.web.auth.session_manager.session_manager"
+ ) as mock_sm,
patch(f"{MODULE}.db_manager") as mock_db,
patch(f"{MODULE}.session_password_store") as mock_store,
patch.object(service, "_SocketIOService__log_error"),
+ patch.object(
+ service,
+ "_SocketIOService__session_authorizes",
+ return_value=True,
+ ),
):
mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = False
@@ -343,10 +364,17 @@ class TestHandleConnect:
f"{MODULE}.session",
{"username": "alice", "session_id": "sess-1"},
),
- patch(f"{MODULE}.session_manager") as mock_sm,
+ patch(
+ "local_deep_research.web.auth.session_manager.session_manager"
+ ) as mock_sm,
patch(f"{MODULE}.db_manager") as mock_db,
patch(f"{MODULE}.join_room"),
patch.object(service, "_SocketIOService__log_info") as mock_log,
+ patch.object(
+ service,
+ "_SocketIOService__session_authorizes",
+ return_value=True,
+ ),
):
mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = True
@@ -373,18 +401,63 @@ class TestHandleConnect:
f"{MODULE}.session",
{"username": "alice", "session_id": "sess-1"},
),
- patch(f"{MODULE}.session_manager") as mock_sm,
+ patch(
+ "local_deep_research.web.auth.session_manager.session_manager"
+ ) as mock_sm,
patch(f"{MODULE}.db_manager") as mock_db,
patch(f"{MODULE}.join_room") as mock_join,
patch.object(service, "_SocketIOService__log_info"),
+ patch.object(
+ service,
+ "_SocketIOService__session_authorizes",
+ return_value=True,
+ ),
):
mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = True
service._SocketIOService__handle_connect(mock_request)
- mock_join.assert_called_once_with(SocketIOService.user_room("alice"))
+ # A per-session room is also joined alongside the per-user room (see
+ # test_handle_connect_joins_per_session_room), so assert membership
+ # rather than exclusivity here.
+ mock_join.assert_any_call(SocketIOService.user_room("alice"))
+ mock_join.assert_any_call(SocketIOService.session_room("sess-1"))
assert SocketIOService.user_room("alice") == "user:alice"
+ def test_handle_connect_joins_per_session_room(self):
+ """A socket whose session carries a session_id also joins the
+ per-session room, so a single session can be torn down (logout of one
+ tab, session expiry) without disconnecting the user's other sessions."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ service = _make_service()
+ mock_request = MagicMock()
+ mock_request.sid = "connect_client_777"
+
+ with (
+ patch(
+ f"{MODULE}.session",
+ {"username": "alice", "session_id": "sess-1"},
+ ),
+ patch(f"{MODULE}.db_manager") as mock_db,
+ patch(f"{MODULE}.join_room") as mock_join,
+ patch.object(service, "_SocketIOService__log_info"),
+ patch.object(
+ service,
+ "_SocketIOService__session_authorizes",
+ return_value=True,
+ ),
+ ):
+ mock_db.is_user_connected.return_value = True
+ service._SocketIOService__handle_connect(mock_request)
+
+ joined = {call.args[0] for call in mock_join.call_args_list}
+ assert SocketIOService.user_room("alice") in joined
+ assert SocketIOService.session_room("sess-1") in joined
+ assert SocketIOService.session_room("sess-1") == "session:sess-1"
+
class TestHandleSubscribeEdgeCases:
"""Edge cases in __handle_subscribe."""
@@ -631,3 +704,40 @@ class TestLoggingMethods:
service._SocketIOService__log_info("active message")
mock_logger.info.assert_called_once_with("active message")
+
+
+class TestSessionAuthorizesFailsClosed:
+ """__session_authorizes fails closed (returns False) on any error,
+ including a RuntimeError raised by the Flask session proxy itself
+ (e.g. accessed outside a request context) rather than by
+ session_manager.validate_session."""
+
+ def setup_method(self):
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ self._orig = SocketIOService._instance
+
+ def teardown_method(self):
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ SocketIOService._instance = self._orig
+
+ def test_returns_false_when_session_get_raises_runtime_error(self):
+ """session.get() raising RuntimeError (e.g. outside request context)
+ is caught by the same except as validate_session errors, so the
+ socket action is rejected instead of the exception propagating."""
+ service = _make_service()
+
+ mock_session = MagicMock()
+ mock_session.get.side_effect = RuntimeError(
+ "Working outside of request context"
+ )
+
+ with patch(f"{MODULE}.session", mock_session):
+ result = service._SocketIOService__session_authorizes("alice")
+
+ assert result is False
diff --git a/tests/web/services/test_socket_service_extra_coverage.py b/tests/web/services/test_socket_service_extra_coverage.py
index 20d56f67f2..3de7632ac8 100644
--- a/tests/web/services/test_socket_service_extra_coverage.py
+++ b/tests/web/services/test_socket_service_extra_coverage.py
@@ -16,6 +16,7 @@ def _get_service_with_patched_init():
svc = object.__new__(SocketIOService)
svc._SocketIOService__socket_subscriptions = {}
+ svc._SocketIOService__sid_sessions = {}
svc._SocketIOService__lock = __import__("threading").Lock()
svc._SocketIOService__socketio = MagicMock()
svc._SocketIOService__logging_enabled = True
@@ -46,14 +47,41 @@ class TestHandleConnect:
f"{MODULE}.session",
{"username": "alice", "session_id": "sess-1"},
),
- patch(f"{MODULE}.session_manager") as mock_sm,
patch(f"{MODULE}.db_manager") as mock_db,
- patch(f"{MODULE}.session_password_store") as mock_store,
+ patch(
+ "local_deep_research.web.auth.session_manager.session_manager"
+ ) as mock_sm,
+ patch(f"{MODULE}.session_password_store") as mock_pw,
):
mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = False
- mock_store.get_session_password.return_value = None
+ mock_pw.get_session_password.return_value = None
+ assert svc._SocketIOService__handle_connect(mock_request) is False
+
+ def test_rejects_stale_session_even_when_db_open(self):
+ """A cookie whose own session was destroyed must not open a new
+ socket, even though the user's shared DB connection is still open
+ (another session, or an in-flight research run)."""
+ svc = _get_service_with_patched_init()
+ mock_request = MagicMock()
+ mock_request.sid = "client-123"
+
+ with (
+ patch(
+ f"{MODULE}.session",
+ {"username": "alice", "session_id": "stale-sess"},
+ ),
+ patch(f"{MODULE}.db_manager") as mock_db,
+ patch(
+ "local_deep_research.web.auth.session_manager.session_manager"
+ ) as mock_sm,
+ patch(f"{MODULE}.join_room") as mock_join,
+ ):
+ # Session destroyed → validate_session no longer maps it to alice.
+ mock_sm.validate_session.return_value = None
+ mock_db.is_user_connected.return_value = True
assert svc._SocketIOService__handle_connect(mock_request) is False
+ mock_join.assert_not_called()
def test_accepts_authenticated(self):
svc = _get_service_with_patched_init()
@@ -65,8 +93,10 @@ class TestHandleConnect:
f"{MODULE}.session",
{"username": "alice", "session_id": "sess-1"},
),
- patch(f"{MODULE}.session_manager") as mock_sm,
patch(f"{MODULE}.db_manager") as mock_db,
+ patch(
+ "local_deep_research.web.auth.session_manager.session_manager"
+ ) as mock_sm,
patch(f"{MODULE}.join_room"),
):
mock_sm.validate_session.return_value = "alice"
diff --git a/tests/web/test_socket_subscribe_ownership.py b/tests/web/test_socket_subscribe_ownership.py
index f262ac9cf7..c535778d75 100644
--- a/tests/web/test_socket_subscribe_ownership.py
+++ b/tests/web/test_socket_subscribe_ownership.py
@@ -126,7 +126,14 @@ def test_unsubscribe_rejected_when_user_does_not_own_research():
) as mock_socketio_class,
patch(
"src.local_deep_research.web.services.socket_service.session",
- {"username": "alice"},
+ {"username": "alice", "session_id": "sess-alice"},
+ ),
+ # Session is valid (defense-in-depth check passes) so this test
+ # exercises the ownership rejection specifically.
+ patch(
+ "src.local_deep_research.web.auth.session_manager."
+ "session_manager.validate_session",
+ return_value="alice",
),
# Ownership check returns False → non-owner trying to unsubscribe.
patch.object(
@@ -175,7 +182,12 @@ def test_unsubscribe_allowed_when_user_owns_research():
) as mock_socketio_class,
patch(
"src.local_deep_research.web.services.socket_service.session",
- {"username": "alice"},
+ {"username": "alice", "session_id": "sess-alice"},
+ ),
+ patch(
+ "src.local_deep_research.web.auth.session_manager."
+ "session_manager.validate_session",
+ return_value="alice",
),
patch.object(SocketIOService, "_user_owns_research", return_value=True),
):
diff --git a/tests/web_services/conftest.py b/tests/web_services/conftest.py
index 19ca24fef1..2ca3e0386f 100644
--- a/tests/web_services/conftest.py
+++ b/tests/web_services/conftest.py
@@ -33,9 +33,20 @@ def _allow_socket_subscribe():
module_path = "src.local_deep_research.web.services.socket_service"
+ # __handle_subscribe / __handle_unsubscribe now also re-validate the
+ # socket's session id against the SessionManager (defense-in-depth), so
+ # provide a session_id and make validate_session recognise it.
+ root = module_path.rsplit(".web.services.socket_service", 1)[0]
with (
- patch(f"{module_path}.session", {"username": "test-owner"}),
+ patch(
+ f"{module_path}.session",
+ {"username": "test-owner", "session_id": "test-session"},
+ ),
patch.object(SocketIOService, "_user_owns_research", return_value=True),
+ patch(
+ f"{root}.web.auth.session_manager.session_manager.validate_session",
+ return_value="test-owner",
+ ),
):
yield
diff --git a/tests/web_services/test_socket_service.py b/tests/web_services/test_socket_service.py
index 2ad747c869..b4dd655832 100644
--- a/tests/web_services/test_socket_service.py
+++ b/tests/web_services/test_socket_service.py
@@ -766,7 +766,7 @@ class TestSocketIOServiceErrorHandling:
{"username": "alice", "session_id": "sess-1"},
),
patch(
- "local_deep_research.web.services.socket_service.session_manager"
+ "local_deep_research.web.auth.session_manager.session_manager"
) as mock_sm,
patch(
"local_deep_research.web.services.socket_service.db_manager"
@@ -793,7 +793,7 @@ class TestSocketIOServiceErrorHandling:
{"username": "alice", "session_id": "sess-1"},
),
patch(
- "local_deep_research.web.services.socket_service.session_manager"
+ "local_deep_research.web.auth.session_manager.session_manager"
) as mock_sm,
patch(
"local_deep_research.web.services.socket_service.db_manager"
@@ -802,6 +802,11 @@ class TestSocketIOServiceErrorHandling:
"local_deep_research.web.services.socket_service.session_password_store"
) as mock_store,
patch("local_deep_research.web.services.socket_service.join_room"),
+ patch.object(
+ service,
+ "_SocketIOService__session_authorizes",
+ return_value=True,
+ ),
):
mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = False
@@ -819,7 +824,7 @@ class TestSocketIOServiceErrorHandling:
{"username": "alice", "session_id": "sess-1"},
),
patch(
- "local_deep_research.web.services.socket_service.session_manager"
+ "local_deep_research.web.auth.session_manager.session_manager"
) as mock_sm,
patch(
"local_deep_research.web.services.socket_service.db_manager"
@@ -828,6 +833,11 @@ class TestSocketIOServiceErrorHandling:
"local_deep_research.web.services.socket_service.logger"
) as mock_logger,
patch("local_deep_research.web.services.socket_service.join_room"),
+ patch.object(
+ service,
+ "_SocketIOService__session_authorizes",
+ return_value=True,
+ ),
):
mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = True