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(chat): guard user key against missing session scope (#6250)

Abarnaa Sree N8ffa2d96a42b
diff --git a/changelog.d/6250.bugfix.md b/changelog.d/6250.bugfix.md
new file mode 100644
index 0000000000..d5ca516e2c
--- /dev/null
+++ b/changelog.d/6250.bugfix.md
@@ -0,0 +1 @@
+Guard chat rate-limit user keys against requests without session middleware.
diff --git a/src/local_deep_research/web/routers/chat.py b/src/local_deep_research/web/routers/chat.py
index 385d647c23..65e477eca2 100644
--- a/src/local_deep_research/web/routers/chat.py
+++ b/src/local_deep_research/web/routers/chat.py
@@ -134,7 +134,10 @@ def _chat_user_key(request: Request) -> str:
DoS each other for legitimate chat use. Falls back to the client IP for
any unauthenticated request that somehow reaches a limited route.
"""
- return request.session.get("username") or _get_client_ip(request)
+ username = (
+ request.session.get("username") if "session" in request.scope else None
+ )
+ return username or _get_client_ip(request)
async def _json_object_body(request: Request):
diff --git a/tests/chat/test_chat_route_helpers.py b/tests/chat/test_chat_route_helpers.py
index b81f079c5d..b55660181f 100644
--- a/tests/chat/test_chat_route_helpers.py
+++ b/tests/chat/test_chat_route_helpers.py
@@ -10,6 +10,8 @@ tests/web/auth/test_password_utils_gaps.py named here previously does not
survive the FastAPI port.)
"""
+from starlette.requests import Request
+
class TestParseIntParam:
"""Tests for the _parse_int_param helper function."""
@@ -70,3 +72,40 @@ class TestParseIntParam:
result = _parse_int_param("3.14", default=10)
assert result == 10
+
+
+class TestChatUserKey:
+ """Tests for the _chat_user_key helper function."""
+
+ def test_chat_user_key_falls_back_to_client_ip_without_session(self):
+ """Test that requests without session scope use the client IP."""
+ from local_deep_research.web.routers.chat import _chat_user_key
+
+ request = Request(
+ {
+ "type": "http",
+ "method": "GET",
+ "path": "/",
+ "headers": [],
+ "client": ("192.168.1.10", 12345),
+ }
+ )
+
+ assert _chat_user_key(request) == "192.168.1.10"
+
+ def test_chat_user_key_uses_username_from_session(self):
+ """Test that a session username is used when session scope exists."""
+ from local_deep_research.web.routers.chat import _chat_user_key
+
+ request = Request(
+ {
+ "type": "http",
+ "method": "GET",
+ "path": "/",
+ "headers": [],
+ "client": ("192.168.1.10", 12345),
+ "session": {"username": "alice"},
+ }
+ )
+
+ assert _chat_user_key(request) == "alice"