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): revoke session on logout via server-side session id validation (#5532)

LearningCircuit79902acefe5e
diff --git a/changelog.d/+session-id-revocation.security.md b/changelog.d/+session-id-revocation.security.md
new file mode 100644
index 0000000000..6d107ab2b8
--- /dev/null
+++ b/changelog.d/+session-id-revocation.security.md
@@ -0,0 +1,5 @@
+Logging out now revokes the session cookie immediately. The auth path
+(HTTP and WebSocket) validates the cookie's server-side session id, so a
+session that has been logged out can no longer be reused — even after the
+same user logs back in. Idle/expired sessions are now also rejected
+(sliding-expiry).
diff --git a/pyproject.toml b/pyproject.toml
index e1f2afbac5..9dd7c18ce0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -202,6 +202,7 @@ markers = [
"asyncio: marks async tests that use asyncio",
"connected: marks the connected pytest suite (real per-user encrypted SQLCipher DBs; heavier scenarios run out of the default unit suite).",
"fd_canary: heavy file-descriptor-leak regression tests (#3816). CPU-bound real-event-loop spins that exceeded the legacy 60s timeout under coverage + '-n auto' contention, and whose FD-count assertions are noisy under parallel execution; run in a dedicated serial, no-coverage CI step instead of the parallel suite.",
+ "real_session_check: opt out of the autouse _legacy_bare_username_auth shim so the real server-side session-id check is exercised. For tests that must prove a destroyed/invalid session is rejected.",
]
# Global timeout for all tests - fail fast instead of hanging.
# "thread" (not "signal") because SIGALRM was firing inside weakref/GC on
diff --git a/src/local_deep_research/web/auth/decorators.py b/src/local_deep_research/web/auth/decorators.py
index f8f62aa1e2..ffef69ef0f 100644
--- a/src/local_deep_research/web/auth/decorators.py
+++ b/src/local_deep_research/web/auth/decorators.py
@@ -11,6 +11,7 @@ from sqlalchemy.orm import Session
from ...database.encrypted_db import db_manager
from ...security.url_validator import URLValidator
+from .session_manager import session_manager
def _safe_redirect_to_login():
@@ -45,6 +46,26 @@ def _is_api_path(path: str) -> bool:
return "/api/" in path or path.endswith("/api")
+def _server_session_valid(username: str) -> bool:
+ """Return True if the cookie's ``session_id`` maps to a live server-side
+ session for ``username``.
+
+ This is what makes ``destroy_session`` (called on logout / password
+ change) actually revoke a cookie: without it the auth path only checks
+ ``is_user_connected(username)``, which flips back to True the moment the
+ legitimate user logs in again, so a previously captured cookie would be
+ accepted. ``validate_session`` also enforces the idle / absolute timeout
+ and refreshes ``last_access`` as a side effect (sliding expiry).
+
+ A missing ``session_id`` (or one absent from the in-memory store — e.g.
+ destroyed, expired, or lost across a server restart) returns False.
+ """
+ session_id = session.get("session_id")
+ if not session_id:
+ return False
+ return session_manager.validate_session(session_id) == username
+
+
def login_required(f):
"""
Decorator to require authentication for a route.
@@ -61,8 +82,21 @@ def login_required(f):
return jsonify({"error": "Authentication required"}), 401
return _safe_redirect_to_login()
- # Check if we have an active database connection
username = session["username"]
+
+ # Validate the server-side session so a revoked (logged-out) or
+ # expired cookie is actually rejected — see _server_session_valid.
+ if not _server_session_valid(username):
+ logger.debug(
+ f"Rejecting request for {username}: server-side session "
+ f"missing, revoked, or expired"
+ )
+ session.clear()
+ if _is_api_path(request.path):
+ return jsonify({"error": "Authentication required"}), 401
+ return _safe_redirect_to_login()
+
+ # Check if we have an active database connection
if not db_manager.is_user_connected(username):
# Use debug level to reduce log noise for persistent sessions
logger.debug(
@@ -103,6 +137,18 @@ def inject_current_user():
"""
g.current_user = current_user()
if g.current_user:
+ # Revoke logged-out / expired server-side sessions before any DB
+ # work, so a captured cookie can't ride a subsequent fresh login.
+ # Mirrors login_required (see _server_session_valid).
+ if not _server_session_valid(g.current_user):
+ logger.debug(
+ f"Clearing revoked/invalid server-side session for user "
+ f"{g.current_user}"
+ )
+ session.clear()
+ g.current_user = None
+ g.db_session = None
+ return
# Check connectivity
if not db_manager.is_user_connected(g.current_user):
# For API/auth routes, allow the request to continue
diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.py
index 79f087bc42..b0f4e1fc09 100644
--- a/src/local_deep_research/web/services/socket_service.py
+++ b/src/local_deep_research/web/services/socket_service.py
@@ -8,6 +8,7 @@ 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
@@ -305,17 +306,26 @@ 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
+ ):
+ self.__log_info(
+ f"Rejected WebSocket connection for {username}: "
+ f"server-side session missing, revoked, or expired"
+ )
+ return False
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
# open it using the password the user authenticated with at login.
- session_id = session.get("session_id")
- password = (
- session_password_store.get_session_password(
- username, session_id
- )
- if session_id
- else None
+ # session_id is guaranteed present/valid by the check above.
+ password = session_password_store.get_session_password(
+ username, session_id
)
if not password:
self.__log_info(
diff --git a/tests/auth_tests/test_auth_decorators.py b/tests/auth_tests/test_auth_decorators.py
index 3dd852c62e..ddce52c37d 100644
--- a/tests/auth_tests/test_auth_decorators.py
+++ b/tests/auth_tests/test_auth_decorators.py
@@ -11,6 +11,24 @@ from local_deep_research.web.auth.decorators import (
login_required,
)
+# These tests seed a real server-side session and assert the decorator's real
+# behaviour, so opt out of the autouse legacy-auth shim in tests/conftest.py.
+pytestmark = pytest.mark.real_session_check
+
+
+def _seed_server_session(store, username="testuser"):
+ """Register a live server-side session and stash its id in ``store``.
+
+ ``login_required`` / ``inject_current_user`` validate the cookie's
+ ``session_id`` against session_manager (so logout actually revokes a
+ cookie), so authenticated-branch tests must seed a real session, not
+ just a bare username.
+ """
+ from local_deep_research.web.auth.session_manager import session_manager
+
+ store["session_id"] = session_manager.create_session(username)
+ store["username"] = username
+
@pytest.fixture
def app():
@@ -89,7 +107,7 @@ class TestAuthDecorators:
)
with client.session_transaction() as sess:
- sess["username"] = "testuser"
+ _seed_server_session(sess)
response = client.get("/protected")
assert response.status_code == 200
@@ -134,7 +152,7 @@ class TestAuthDecorators:
# Test logged in scenario
with client.session_transaction() as sess:
- sess["username"] = "testuser"
+ _seed_server_session(sess)
response = client.get("/user-info")
assert response.status_code == 200
@@ -168,7 +186,7 @@ class TestAuthDecorators:
# Test logged in
with app.test_request_context("/"):
# Set session data directly within request context
- session["username"] = "testuser"
+ _seed_server_session(session)
inject_current_user()
assert g.current_user == "testuser"
# Session is now created lazily, not eagerly in inject_current_user
@@ -189,7 +207,7 @@ class TestAuthDecorators:
monkeypatch.setattr(decorators, "db_manager", MockDbManager())
with client.session_transaction() as sess:
- sess["username"] = "testuser"
+ _seed_server_session(sess)
response = client.get("/protected")
assert response.status_code == 302
diff --git a/tests/conftest.py b/tests/conftest.py
index 0d02358f24..096a8f2b18 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -6,7 +6,7 @@ import types
import shutil
import uuid
from pathlib import Path
-from unittest.mock import Mock
+from unittest.mock import Mock, patch
import pytest
from loguru import logger
@@ -250,6 +250,46 @@ def cleanup_database_connections():
dispose_auth_engine()
[email protected](autouse=True)
+def _legacy_bare_username_auth(request):
+ """Keep the legacy test idiom authenticating.
+
+ Many route tests authenticate by putting a bare ``username`` in the session
+ (via ``session_transaction`` or by patching the decorator's ``session``
+ object) with a mocked ``db_manager``, and never create a server-side
+ session. After the session-id revocation fix, ``login_required`` /
+ ``inject_current_user`` validate the cookie's ``session_id`` via
+ ``session_manager`` and would reject those requests. This autouse fixture
+ relaxes the decorator's server-side-session gate so the legacy
+ "username present == authenticated" behaviour is restored without editing
+ each test.
+
+ ``_server_session_valid`` is only ever called *after* the caller has already
+ confirmed a username is present, so accepting unconditionally is exactly the
+ pre-revocation contract — and works regardless of how the test built its
+ session (real Flask session, patched ``decorators.session`` fake, etc.).
+
+ Tests that must prove a destroyed / invalid session IS rejected opt out with
+ ``@pytest.mark.real_session_check`` so they exercise the real gate. The
+ fixture only relaxes the HTTP decorator path (``_server_session_valid``);
+ the WebSocket handshake validates ``session_manager`` directly and is
+ unaffected, so the socket revocation test keeps using the real check.
+ """
+ if request.node.get_closest_marker("real_session_check"):
+ # Security tests: leave the real server-side-session check in place.
+ yield
+ return
+
+ def _accept(_username):
+ return True
+
+ with patch(
+ "local_deep_research.web.auth.decorators._server_session_valid",
+ _accept,
+ ):
+ yield
+
+
@pytest.fixture
def app(temp_data_dir, monkeypatch):
"""Create a Flask app configured for testing."""
diff --git a/tests/security/test_login_required_boundaries.py b/tests/security/test_login_required_boundaries.py
index 02519f7b27..a4248a6ea9 100644
--- a/tests/security/test_login_required_boundaries.py
+++ b/tests/security/test_login_required_boundaries.py
@@ -25,6 +25,11 @@ from flask import Blueprint, Flask, jsonify
from local_deep_research.web.auth.decorators import login_required
+# Exercise the REAL server-side session-id check; opt out
+# of the autouse legacy-auth shim in tests/conftest.py. The authenticated-path
+# fixtures below seed a real server-side session via session_manager.
+pytestmark = pytest.mark.real_session_check
+
@pytest.fixture
def app():
@@ -127,9 +132,13 @@ def authenticated_client(client, patch_db_manager):
e.g. the post-rejection branch swallowing valid requests — would
not be caught by any existing test.
"""
+ from local_deep_research.web.auth.session_manager import session_manager
+
patch_db_manager.is_user_connected.return_value = True
+ session_id = session_manager.create_session("test-user")
with client.session_transaction() as sess:
sess["username"] = "test-user"
+ sess["session_id"] = session_id
return client
@@ -255,11 +264,18 @@ class TestAuthenticatedButDisconnectedDb:
@pytest.fixture
def session_without_db(self, client, patch_db_manager):
- # is_user_connected stays False (autouse default), but seed the
- # session so we hit the second decorator branch, not the first.
+ # is_user_connected stays False (autouse default), but seed a live
+ # server-side session so we pass the session-id check and hit the
+ # DB-connection branch, not the earlier auth branches.
+ from local_deep_research.web.auth.session_manager import (
+ session_manager,
+ )
+
patch_db_manager.is_user_connected.return_value = False
+ session_id = session_manager.create_session("test-user")
with client.session_transaction() as sess:
sess["username"] = "test-user"
+ sess["session_id"] = session_id
return client
def test_api_path_returns_json_401_db_required(self, session_without_db):
diff --git a/tests/security/test_session_username_hardening.py b/tests/security/test_session_username_hardening.py
index 87e4ac8ac0..6744a0dbd2 100644
--- a/tests/security/test_session_username_hardening.py
+++ b/tests/security/test_session_username_hardening.py
@@ -9,6 +9,12 @@ the key exists; direct access fails fast if the decorator is ever removed.
import inspect
import textwrap
+import pytest
+
+# Static source-analysis suite (never runs login_required), but opt out of the
+# legacy-auth shim anyway so it can never mask the real session-id check.
+pytestmark = pytest.mark.real_session_check
+
def _get_function_source(func):
"""Get dedented source of a function for AST analysis."""
diff --git a/tests/web/auth/test_decorators.py b/tests/web/auth/test_decorators.py
index f0d8a60e2a..571da73463 100644
--- a/tests/web/auth/test_decorators.py
+++ b/tests/web/auth/test_decorators.py
@@ -10,8 +10,33 @@ Tests cover:
"""
from unittest.mock import Mock, patch
+
+import pytest
from flask import Blueprint, Flask, session, g
+# These tests seed a real server-side session and assert the decorator's real
+# behaviour, so opt out of the autouse legacy-auth shim in tests/conftest.py.
+pytestmark = pytest.mark.real_session_check
+
+
+def _seed_server_session(store, username="testuser"):
+ """Register a live server-side session and stash its id in ``store``.
+
+ ``login_required`` / ``inject_current_user`` now validate the cookie's
+ ``session_id`` against the in-memory session_manager (so that logout
+ actually revokes a cookie). Tests that want to exercise the *authenticated*
+ branches must therefore seed a real session, not just a bare username.
+
+ ``store`` is either a Flask ``session_transaction`` proxy or the request
+ ``session`` object — both support item assignment.
+ """
+ from local_deep_research.web.auth.session_manager import session_manager
+
+ session_id = session_manager.create_session(username)
+ store["username"] = username
+ store["session_id"] = session_id
+ return session_id
+
class TestLoginRequiredDecorator:
"""Tests for login_required decorator."""
@@ -99,7 +124,7 @@ class TestLoginRequiredDecorator:
with app.test_client() as client:
with client.session_transaction() as sess:
- sess["username"] = "testuser"
+ _seed_server_session(sess)
response = client.get("/api/test")
assert response.status_code == 401
assert response.json["error"] == "Database connection required"
@@ -123,7 +148,7 @@ class TestLoginRequiredDecorator:
with app.test_client() as client:
with client.session_transaction() as sess:
- sess["username"] = "testuser"
+ _seed_server_session(sess)
response = client.get("/api/test")
assert response.status_code == 200
@@ -184,7 +209,7 @@ class TestLoginRequiredDecorator:
with app.test_client() as client:
with client.session_transaction() as sess:
- sess["username"] = "testuser"
+ _seed_server_session(sess)
response = client.get("/news/api/feed")
assert response.status_code == 401
assert response.json["error"] == "Database connection required"
@@ -325,7 +350,7 @@ class TestInjectCurrentUser:
)
with app.test_request_context():
- session["username"] = "testuser"
+ _seed_server_session(session)
inject_current_user()
assert g.current_user == "testuser"
# Session is now created lazily, not eagerly in inject_current_user
@@ -358,7 +383,7 @@ class TestInjectCurrentUser:
)
with app.test_request_context():
- session["username"] = "testuser"
+ _seed_server_session(session)
inject_current_user()
assert g.current_user == "testuser"
assert g.db_session is None
@@ -379,7 +404,7 @@ class TestInjectCurrentUser:
)
with app.test_request_context("/dashboard"):
- session["username"] = "testuser"
+ _seed_server_session(session)
inject_current_user()
# Session should be cleared
assert g.current_user is None
@@ -401,7 +426,7 @@ class TestInjectCurrentUser:
)
with app.test_request_context("/api/test"):
- session["username"] = "testuser"
+ _seed_server_session(session)
inject_current_user()
# g.current_user should still be set for API routes
assert g.current_user == "testuser"
@@ -422,7 +447,7 @@ class TestInjectCurrentUser:
)
with app.test_request_context("/auth/login"):
- session["username"] = "testuser"
+ _seed_server_session(session)
inject_current_user()
# g.current_user should still be set for auth routes
assert g.current_user == "testuser"
diff --git a/tests/web/auth/test_decorators_coverage.py b/tests/web/auth/test_decorators_coverage.py
index aa823d7194..1461dbb67a 100644
--- a/tests/web/auth/test_decorators_coverage.py
+++ b/tests/web/auth/test_decorators_coverage.py
@@ -7,6 +7,25 @@ from flask import Flask
MODULE = "local_deep_research.web.auth.decorators"
+# These tests seed a real server-side session and assert the decorator's real
+# behaviour, so opt out of the autouse legacy-auth shim in tests/conftest.py.
+pytestmark = pytest.mark.real_session_check
+
+
+def _seed_server_session(store, username="testuser"):
+ """Register a live server-side session and stash its id in ``store``.
+
+ ``login_required`` / ``inject_current_user`` now validate the cookie's
+ ``session_id`` against session_manager (so logout actually revokes a
+ cookie), so tests exercising the authenticated branches must seed a real
+ session, not just a bare username. ``store`` is a Flask session proxy or
+ ``session_transaction`` proxy — both support item assignment.
+ """
+ from local_deep_research.web.auth.session_manager import session_manager
+
+ store["session_id"] = session_manager.create_session(username)
+ store["username"] = username
+
@pytest.fixture()
def app():
@@ -86,7 +105,7 @@ class TestLoginRequiredNoDbConnection:
mock_db.is_user_connected.return_value = False
with client.session_transaction() as sess:
- sess["username"] = "testuser"
+ _seed_server_session(sess)
resp = client.get("/api/data")
@@ -104,7 +123,7 @@ class TestLoginRequiredNoDbConnection:
mock_db.is_user_connected.return_value = False
with client.session_transaction() as sess:
- sess["username"] = "testuser"
+ _seed_server_session(sess)
client.get("/page")
@@ -120,7 +139,7 @@ class TestLoginRequiredAuthenticated:
mock_db.is_user_connected.return_value = True
with client.session_transaction() as sess:
- sess["username"] = "testuser"
+ _seed_server_session(sess)
resp = client.get("/page")
@@ -159,7 +178,7 @@ class TestInjectCurrentUser:
mock_db.get_session.return_value = mock_session
from flask import g, session
- session["username"] = "testuser"
+ _seed_server_session(session)
inject_current_user()
@@ -177,7 +196,7 @@ class TestInjectCurrentUser:
mock_db.is_user_connected.return_value = False
from flask import g, session
- session["username"] = "testuser"
+ _seed_server_session(session)
inject_current_user()
@@ -195,7 +214,7 @@ class TestInjectCurrentUser:
mock_db.is_user_connected.return_value = False
from flask import g, session
- session["username"] = "testuser"
+ _seed_server_session(session)
inject_current_user()
@@ -213,7 +232,7 @@ class TestInjectCurrentUser:
mock_db.get_session.side_effect = RuntimeError("db error")
from flask import g, session
- session["username"] = "testuser"
+ _seed_server_session(session)
inject_current_user()
@@ -230,7 +249,7 @@ class TestInjectCurrentUser:
mock_db.is_user_connected.return_value = False
from flask import g, session
- session["username"] = "testuser"
+ _seed_server_session(session)
inject_current_user()
diff --git a/tests/web/auth/test_decorators_extended.py b/tests/web/auth/test_decorators_extended.py
index c2fc995ad1..92c0d097e2 100644
--- a/tests/web/auth/test_decorators_extended.py
+++ b/tests/web/auth/test_decorators_extended.py
@@ -11,6 +11,7 @@ Tests cover:
from unittest.mock import MagicMock, patch
+import pytest
from flask import Blueprint, Flask, g, session
from local_deep_research.web.auth.decorators import (
@@ -21,6 +22,10 @@ from local_deep_research.web.auth.decorators import (
login_required,
)
+# These tests seed a real server-side session and assert the decorator's real
+# behaviour, so opt out of the autouse legacy-auth shim in tests/conftest.py.
+pytestmark = pytest.mark.real_session_check
+
def _make_app():
"""Create a minimal Flask app with an auth blueprint for url_for('auth.login')."""
@@ -38,6 +43,21 @@ def _make_app():
return app
+def _seed_server_session(store, username):
+ """Register a live server-side session and stash its id in ``store``.
+
+ ``login_required`` / ``inject_current_user`` validate the cookie's
+ ``session_id`` against session_manager (so logout actually revokes a
+ cookie), so tests exercising the authenticated branches must seed a real
+ session, not just a bare username. ``store`` is a Flask session proxy or
+ ``session_transaction`` proxy — both support item assignment.
+ """
+ from local_deep_research.web.auth.session_manager import session_manager
+
+ store["session_id"] = session_manager.create_session(username)
+ store["username"] = username
+
+
# ---------------------------------------------------------------------------
# login_required
# ---------------------------------------------------------------------------
@@ -112,7 +132,7 @@ class TestLoginRequired:
with app.test_client() as client:
with client.session_transaction() as sess:
- sess["username"] = "alice"
+ _seed_server_session(sess, "alice")
resp = client.get("/page")
assert resp.status_code == 302
@@ -138,7 +158,7 @@ class TestLoginRequired:
with app.test_client() as client:
with client.session_transaction() as sess:
- sess["username"] = "alice"
+ _seed_server_session(sess, "alice")
resp = client.get("/api/items")
assert resp.status_code == 401
@@ -160,7 +180,7 @@ class TestLoginRequired:
with app.test_client() as client:
with client.session_transaction() as sess:
- sess["username"] = "alice"
+ _seed_server_session(sess, "alice")
resp = client.get("/protected")
assert resp.status_code == 200
@@ -242,7 +262,7 @@ class TestInjectCurrentUser:
mock_db.get_session.return_value = mock_session_obj
with app.test_request_context():
- session["username"] = "dave"
+ _seed_server_session(session, "dave")
inject_current_user()
assert g.current_user == "dave"
# Session is now created lazily, not eagerly in inject_current_user
@@ -270,7 +290,7 @@ class TestInjectCurrentUser:
mock_db.is_user_connected.return_value = False
with app.test_request_context("/dashboard"):
- session["username"] = "eve"
+ _seed_server_session(session, "eve")
inject_current_user()
# Session should have been cleared
assert g.current_user is None
@@ -288,7 +308,7 @@ class TestInjectCurrentUser:
mock_db.is_user_connected.return_value = False
with app.test_request_context("/api/test"):
- session["username"] = "frank"
+ _seed_server_session(session, "frank")
inject_current_user()
# current_user should still be set for API routes
assert g.current_user == "frank"
@@ -304,7 +324,7 @@ class TestInjectCurrentUser:
mock_db.get_session.side_effect = RuntimeError("connection lost")
with app.test_request_context():
- session["username"] = "grace"
+ _seed_server_session(session, "grace")
inject_current_user()
assert g.current_user == "grace"
assert g.db_session is None
diff --git a/tests/web/auth/test_session_revocation.py b/tests/web/auth/test_session_revocation.py
new file mode 100644
index 0000000000..d2e7aaf61e
--- /dev/null
+++ b/tests/web/auth/test_session_revocation.py
@@ -0,0 +1,227 @@
+"""Regression tests for session-id revocation (part a): logout must revoke a
+captured session cookie.
+
+Before the fix, ``login_required`` / ``inject_current_user`` only checked
+``session["username"]`` and ``db_manager.is_user_connected(username)``. Neither
+reads the cookie's ``session_id``, so ``destroy_session`` on logout had no
+request-path effect: a captured cookie became valid again the moment the
+legitimate user logged back in (``is_user_connected`` flips back to True).
+
+These tests pin the behaviour that a ``session_id`` destroyed via
+``destroy_session`` is rejected even while ``is_user_connected`` is True, that a
+live session still passes, and that multi-device sessions stay independent.
+"""
+
+from unittest.mock import patch
+
+import pytest
+from flask import Blueprint, Flask, g, session
+
+
+# These tests must exercise the REAL server-side session check, so opt out of
+# the autouse legacy-auth shim in tests/conftest.py.
+pytestmark = pytest.mark.real_session_check
+
+MODULE = "local_deep_research.web.auth.decorators"
+
+
+def _make_app():
+ """Minimal Flask app with a stub auth.login endpoint and two protected
+ routes (one page, one API) using the real ``login_required`` decorator."""
+ app = Flask(__name__)
+ app.secret_key = "test-secret"
+ app.config["TESTING"] = True
+
+ auth = Blueprint("auth", __name__, url_prefix="/auth")
+
+ @auth.route("/login")
+ def login():
+ return "Login Page"
+
+ app.register_blueprint(auth)
+
+ from local_deep_research.web.auth.decorators import login_required
+
+ @app.route("/page")
+ @login_required
+ def page():
+ return "secret page"
+
+ @app.route("/api/data")
+ @login_required
+ def api_data():
+ return {"ok": True}
+
+ return app
+
+
+def app():
+ return _make_app()
+
+
+def client(app):
+ return app.test_client()
+
+
+class TestLoginRequiredRevocation:
+ """login_required must honour a destroyed server-side session."""
+
+ def test_destroyed_session_rejected_even_while_user_connected(
+ self, app, client
+ ):
+ """A cookie whose session_id was destroyed via destroy_session is
+ rejected even though is_user_connected(username) is True — simulating
+ the legitimate user having logged back in (connection kept open)."""
+ from local_deep_research.web.auth.session_manager import (
+ session_manager,
+ )
+
+ with patch(f"{MODULE}.db_manager") as mock_db:
+ # The legitimate user is logged in again → connection is live.
+ mock_db.is_user_connected.return_value = True
+
+ session_id = session_manager.create_session("victim")
+ with client.session_transaction() as sess:
+ sess["username"] = "victim"
+ sess["session_id"] = session_id
+
+ # Attacker still holds the (now logged-out) cookie.
+ session_manager.destroy_session(session_id)
+
+ resp = client.get("/api/data")
+
+ assert resp.status_code == 401
+ assert resp.get_json()["error"] == "Authentication required"
+
+ def test_destroyed_session_on_page_redirects_and_clears(self, app, client):
+ """Page routes redirect to login and clear the stale cookie."""
+ from local_deep_research.web.auth.session_manager import (
+ session_manager,
+ )
+
+ with patch(f"{MODULE}.db_manager") as mock_db:
+ mock_db.is_user_connected.return_value = True
+
+ session_id = session_manager.create_session("victim")
+ with client.session_transaction() as sess:
+ sess["username"] = "victim"
+ sess["session_id"] = session_id
+
+ session_manager.destroy_session(session_id)
+
+ resp = client.get("/page")
+ assert resp.status_code == 302
+ assert "/auth/login" in resp.location
+
+ # Cookie must have been cleared by the decorator.
+ with client.session_transaction() as sess:
+ assert "username" not in sess
+ assert "session_id" not in sess
+
+ def test_missing_session_id_is_rejected(self, app, client):
+ """A cookie with a username but no server-side session_id (e.g. forged,
+ or minted before this fix) is rejected."""
+ with patch(f"{MODULE}.db_manager") as mock_db:
+ mock_db.is_user_connected.return_value = True
+
+ with client.session_transaction() as sess:
+ sess["username"] = "victim" # no session_id
+
+ resp = client.get("/api/data")
+
+ assert resp.status_code == 401
+ assert resp.get_json()["error"] == "Authentication required"
+
+ def test_live_session_still_passes(self, app, client):
+ """A valid, undestroyed server-side session is accepted."""
+ from local_deep_research.web.auth.session_manager import (
+ session_manager,
+ )
+
+ with patch(f"{MODULE}.db_manager") as mock_db:
+ mock_db.is_user_connected.return_value = True
+
+ session_id = session_manager.create_session("alice")
+ with client.session_transaction() as sess:
+ sess["username"] = "alice"
+ sess["session_id"] = session_id
+
+ resp = client.get("/api/data")
+
+ assert resp.status_code == 200
+ assert resp.get_json() == {"ok": True}
+
+ def test_multi_device_sessions_are_independent(self, app, client):
+ """Destroying one device's session (each login mints its own
+ session_id) must not invalidate another device's live session."""
+ from local_deep_research.web.auth.session_manager import (
+ session_manager,
+ )
+
+ with patch(f"{MODULE}.db_manager") as mock_db:
+ mock_db.is_user_connected.return_value = True
+
+ phone_sid = session_manager.create_session("alice")
+ laptop_sid = session_manager.create_session("alice")
+
+ # Log out the phone only.
+ session_manager.destroy_session(phone_sid)
+
+ # Laptop cookie is still live.
+ with client.session_transaction() as sess:
+ sess["username"] = "alice"
+ sess["session_id"] = laptop_sid
+
+ resp = client.get("/api/data")
+
+ assert resp.status_code == 200
+
+
+class TestInjectCurrentUserRevocation:
+ """inject_current_user must not repopulate g.current_user for a destroyed
+ session — otherwise a captured cookie still gets in via that path."""
+
+ def test_destroyed_session_clears_g_current_user(self, app):
+ from local_deep_research.web.auth.decorators import inject_current_user
+ from local_deep_research.web.auth.session_manager import (
+ session_manager,
+ )
+
+ with (
+ app.test_request_context("/page"),
+ patch(f"{MODULE}.db_manager") as mock_db,
+ ):
+ mock_db.is_user_connected.return_value = True
+
+ session_id = session_manager.create_session("victim")
+ session["username"] = "victim"
+ session["session_id"] = session_id
+ session_manager.destroy_session(session_id)
+
+ inject_current_user()
+
+ assert g.current_user is None
+ assert g.db_session is None
+ assert "username" not in session
+
+ def test_live_session_sets_g_current_user(self, app):
+ from local_deep_research.web.auth.decorators import inject_current_user
+ from local_deep_research.web.auth.session_manager import (
+ session_manager,
+ )
+
+ with (
+ app.test_request_context("/page"),
+ patch(f"{MODULE}.db_manager") as mock_db,
+ ):
+ mock_db.is_user_connected.return_value = True
+
+ session_id = session_manager.create_session("alice")
+ session["username"] = "alice"
+ session["session_id"] = session_id
+
+ inject_current_user()
+
+ assert g.current_user == "alice"
diff --git a/tests/web/services/test_socket_service_coverage.py b/tests/web/services/test_socket_service_coverage.py
index f69837465f..55d5a8fea2 100644
--- a/tests/web/services/test_socket_service_coverage.py
+++ b/tests/web/services/test_socket_service_coverage.py
@@ -272,9 +272,11 @@ 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,
):
+ mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = False
mock_store.get_session_password.return_value = None
result = service._SocketIOService__handle_connect(mock_request)
@@ -293,10 +295,12 @@ 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(f"{MODULE}.join_room"),
):
+ mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = False
mock_store.get_session_password.return_value = "pw"
result = service._SocketIOService__handle_connect(mock_request)
@@ -315,10 +319,12 @@ 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.object(service, "_SocketIOService__log_error"),
):
+ mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = False
mock_store.get_session_password.return_value = "pw"
mock_db.open_user_database.side_effect = ValueError("bad key")
@@ -333,11 +339,16 @@ class TestHandleConnect:
mock_request.sid = "connect_client_999"
with (
- patch(f"{MODULE}.session", {"username": "alice"}),
+ patch(
+ 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}.join_room"),
patch.object(service, "_SocketIOService__log_info") as mock_log,
):
+ mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = True
result = service._SocketIOService__handle_connect(mock_request)
@@ -358,11 +369,16 @@ class TestHandleConnect:
mock_request.sid = "connect_client_999"
with (
- patch(f"{MODULE}.session", {"username": "alice"}),
+ patch(
+ 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}.join_room") as mock_join,
patch.object(service, "_SocketIOService__log_info"),
):
+ mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = True
service._SocketIOService__handle_connect(mock_request)
diff --git a/tests/web/services/test_socket_service_extra_coverage.py b/tests/web/services/test_socket_service_extra_coverage.py
index 4ca74310fd..20d56f67f2 100644
--- a/tests/web/services/test_socket_service_extra_coverage.py
+++ b/tests/web/services/test_socket_service_extra_coverage.py
@@ -42,10 +42,17 @@ class TestHandleConnect:
mock_request.sid = "client-123"
with (
- patch(f"{MODULE}.session", {"username": "alice"}),
+ patch(
+ 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,
):
+ mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = False
+ mock_store.get_session_password.return_value = None
assert svc._SocketIOService__handle_connect(mock_request) is False
def test_accepts_authenticated(self):
@@ -54,10 +61,15 @@ class TestHandleConnect:
mock_request.sid = "client-123"
with (
- patch(f"{MODULE}.session", {"username": "alice"}),
+ patch(
+ 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}.join_room"),
):
+ mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = True
assert svc._SocketIOService__handle_connect(mock_request) is True
diff --git a/tests/web_services/test_socket_service.py b/tests/web_services/test_socket_service.py
index debfb06aa7..2ad747c869 100644
--- a/tests/web_services/test_socket_service.py
+++ b/tests/web_services/test_socket_service.py
@@ -765,6 +765,9 @@ class TestSocketIOServiceErrorHandling:
"local_deep_research.web.services.socket_service.session",
{"username": "alice", "session_id": "sess-1"},
),
+ patch(
+ "local_deep_research.web.services.socket_service.session_manager"
+ ) as mock_sm,
patch(
"local_deep_research.web.services.socket_service.db_manager"
) as mock_db,
@@ -772,6 +775,7 @@ class TestSocketIOServiceErrorHandling:
"local_deep_research.web.services.socket_service.session_password_store"
) as mock_store,
):
+ mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = False
mock_store.get_session_password.return_value = None
assert (
@@ -788,6 +792,9 @@ class TestSocketIOServiceErrorHandling:
"local_deep_research.web.services.socket_service.session",
{"username": "alice", "session_id": "sess-1"},
),
+ patch(
+ "local_deep_research.web.services.socket_service.session_manager"
+ ) as mock_sm,
patch(
"local_deep_research.web.services.socket_service.db_manager"
) as mock_db,
@@ -796,6 +803,7 @@ class TestSocketIOServiceErrorHandling:
) as mock_store,
patch("local_deep_research.web.services.socket_service.join_room"),
):
+ mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = False
mock_store.get_session_password.return_value = "pw"
assert (
@@ -808,8 +816,11 @@ class TestSocketIOServiceErrorHandling:
with (
patch(
"local_deep_research.web.services.socket_service.session",
- {"username": "alice"},
+ {"username": "alice", "session_id": "sess-1"},
),
+ patch(
+ "local_deep_research.web.services.socket_service.session_manager"
+ ) as mock_sm,
patch(
"local_deep_research.web.services.socket_service.db_manager"
) as mock_db,
@@ -818,6 +829,7 @@ class TestSocketIOServiceErrorHandling:
) as mock_logger,
patch("local_deep_research.web.services.socket_service.join_room"),
):
+ mock_sm.validate_session.return_value = "alice"
mock_db.is_user_connected.return_value = True
assert (
service._SocketIOService__handle_connect(mock_request) is True
@@ -826,6 +838,37 @@ class TestSocketIOServiceErrorHandling:
call_args = mock_logger.info.call_args[0][0]
assert mock_request.sid in call_args
+ def test_connect_handler_rejects_destroyed_session(
+ self, service, mock_request
+ ):
+ """Session-id revocation: a cookie whose server-side session was
+ destroyed (logout) is rejected at the WebSocket handshake even while
+ is_user_connected(username) is True (i.e. the legitimate user has since
+ logged back in). Uses the real session_manager so the
+ destroy -> validate path is exercised end to end."""
+ from local_deep_research.web.auth.session_manager import (
+ session_manager,
+ )
+
+ session_id = session_manager.create_session("alice")
+ session_manager.destroy_session(session_id)
+
+ with (
+ patch(
+ "local_deep_research.web.services.socket_service.session",
+ {"username": "alice", "session_id": session_id},
+ ),
+ patch(
+ "local_deep_research.web.services.socket_service.db_manager"
+ ) as mock_db,
+ ):
+ mock_db.is_user_connected.return_value = True
+ assert (
+ service._SocketIOService__handle_connect(mock_request) is False
+ )
+ # Rejected at the session check, before any DB work.
+ mock_db.is_user_connected.assert_not_called()
+
class TestSocketIOServiceRun:
"""Tests for run method.