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(auth): send the same 503 body from the middleware and require_auth (#8238)

dodoshell98883d5d640c
diff --git a/changelog.d/+session-unavailable-503-body.bugfix.md b/changelog.d/+session-unavailable-503-body.bugfix.md
new file mode 100644
index 0000000000..48a990edc9
--- /dev/null
+++ b/changelog.d/+session-unavailable-503-body.bugfix.md
@@ -0,0 +1 @@
+A request refused with a 503 because its session could not be validated now gets the same JSON body whichever check refused it: `{"detail": ...}`, plus the legacy `"error"` key under `/api/v1`. Before, the middleware answered `{"error": ...}` on every path. Fixes #8216.
diff --git a/src/local_deep_research/web/auth/session_manager.py b/src/local_deep_research/web/auth/session_manager.py
index 6213bacaab..ab78435f25 100644
--- a/src/local_deep_research/web/auth/session_manager.py
+++ b/src/local_deep_research/web/auth/session_manager.py
@@ -58,6 +58,13 @@ VALIDATED_SESSION_STATE_KEY = "ldr_validated_session"
# durable epoch could not be read. Only the logout route reads it.
UNVALIDATED_LOGOUT_STATE_KEY = "ldr_unvalidated_logout"
+# The ``detail`` of the 503 that refuses a request whose session could not
+# be validated (``SessionValidationUnavailableError``), from either
+# ``DatabaseMiddleware`` or ``require_auth``.
+SESSION_VALIDATION_UNAVAILABLE_DETAIL = (
+ "Service temporarily unavailable, please retry"
+)
+
class SessionValidationUnavailableError(Exception):
"""The session's durable epoch could not be read for THIS check.
diff --git a/src/local_deep_research/web/dependencies/auth.py b/src/local_deep_research/web/dependencies/auth.py
index 6ec9a6da83..debcdb4efe 100644
--- a/src/local_deep_research/web/dependencies/auth.py
+++ b/src/local_deep_research/web/dependencies/auth.py
@@ -23,6 +23,7 @@ from ...database.session_context import get_user_db_session
from ...database.session_passwords import session_password_store
from ...utilities.db_utils import get_settings_manager
from ..auth.session_manager import (
+ SESSION_VALIDATION_UNAVAILABLE_DETAIL,
VALIDATED_SESSION_STATE_KEY,
SessionValidationUnavailableError,
session_manager,
@@ -368,7 +369,7 @@ def require_auth(request: Request) -> str:
# proves nothing about the session and must not log users out.
raise HTTPException(
status_code=503,
- detail="Service temporarily unavailable, please retry",
+ detail=SESSION_VALIDATION_UNAVAILABLE_DETAIL,
headers={"Retry-After": "5"},
) from None
if not session_valid:
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index fc255a3ee7..8d97b4d312 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -1463,6 +1463,25 @@ def _is_api_request(request: Request) -> bool:
return False
+def _http_exception_content(path: str, detail) -> dict:
+ """JSON body for an ``HTTPException`` answered as JSON on ``path``."""
+ if path == "/api/v1" or path.startswith("/api/v1/"):
+ # /api/v1 is the documented programmatic API for external clients,
+ # and main returned {"error": ...} for its auth failures
+ # (web/api.py's `jsonify({"error": "Authentication required"})` /
+ # `{"error": "API access is disabled"}`). Routing those through
+ # HTTPException here would silently change the envelope to
+ # {"detail": ...} for every existing script.
+ #
+ # Both keys are emitted rather than swapping: the frontend's
+ # api.js reads `detail`, and tests/web/test_exception_handler_
+ # contract.py deliberately pins the {"detail": ...} shape for the
+ # rest of the app. This restores main's contract for the external
+ # API without disturbing either.
+ return {"error": detail, "detail": detail}
+ return {"detail": detail}
+
+
def _register_exception_handlers(app: FastAPI) -> None:
"""Register custom exception handlers (ports Flask's error handlers)."""
@@ -1581,27 +1600,8 @@ def _register_exception_handlers(app: FastAPI) -> None:
status_code=302,
headers=exc.headers,
)
- path = request.url.path
- if path == "/api/v1" or path.startswith("/api/v1/"):
- # /api/v1 is the documented programmatic API for external clients,
- # and main returned {"error": ...} for its auth failures
- # (web/api.py's `jsonify({"error": "Authentication required"})` /
- # `{"error": "API access is disabled"}`). Routing those through
- # HTTPException here would silently change the envelope to
- # {"detail": ...} for every existing script.
- #
- # Both keys are emitted rather than swapping: the frontend's
- # api.js reads `detail`, and tests/web/test_exception_handler_
- # contract.py deliberately pins the {"detail": ...} shape for the
- # rest of the app. This restores main's contract for the external
- # API without disturbing either.
- return JSONResponse(
- {"error": exc.detail, "detail": exc.detail},
- status_code=exc.status_code,
- headers=exc.headers,
- )
return JSONResponse(
- {"detail": exc.detail},
+ _http_exception_content(request.url.path, exc.detail),
status_code=exc.status_code,
headers=exc.headers,
)
@@ -2050,10 +2050,16 @@ async def _send_session_validation_unavailable(scope, receive, send) -> None:
The session (and its cookie) is left alone: the epoch read failed
transiently (e.g. EMFILE), which proves nothing about the session, so
- clearing it would log the user out. The request itself is refused.
+ clearing it would log the user out. The request itself is refused,
+ with the body ``require_auth``'s 503 gets from the HTTPException
+ handler, so a client sees one shape whichever of the two refused it.
"""
+ from .auth.session_manager import SESSION_VALIDATION_UNAVAILABLE_DETAIL
+
response = JSONResponse(
- {"error": "Service temporarily unavailable, please retry"},
+ _http_exception_content(
+ scope.get("path", ""), SESSION_VALIDATION_UNAVAILABLE_DETAIL
+ ),
status_code=503,
headers={"Retry-After": "5"},
)
diff --git a/tests/web/auth/test_session_validation_unavailable.py b/tests/web/auth/test_session_validation_unavailable.py
index 93e1be659e..67f3cca74a 100644
--- a/tests/web/auth/test_session_validation_unavailable.py
+++ b/tests/web/auth/test_session_validation_unavailable.py
@@ -22,13 +22,15 @@ shim does not replace ``_server_session_valid``.
"""
import asyncio
+import json
from unittest.mock import AsyncMock, MagicMock
import pytest
-from fastapi import HTTPException
+from fastapi import FastAPI, HTTPException
from starlette.requests import Request
from local_deep_research.web.auth.session_manager import (
+ SESSION_VALIDATION_UNAVAILABLE_DETAIL,
UNVALIDATED_LOGOUT_STATE_KEY,
VALIDATED_SESSION_STATE_KEY,
SessionManager,
@@ -87,11 +89,13 @@ def _seed_server_record(monkeypatch, username: str = USER) -> None:
)
-def _request(session: dict, state: dict | None = None) -> Request:
+def _request(
+ session: dict, state: dict | None = None, path: str = "/api/whatever"
+) -> Request:
scope = {
"type": "http",
"method": "GET",
- "path": "/api/whatever",
+ "path": path,
"headers": [],
"session": session,
}
@@ -177,6 +181,9 @@ def test_middleware_answers_503_without_touching_the_session(
inner.assert_not_called()
assert sent[0]["type"] == "http.response.start"
assert sent[0]["status"] == 503
+ assert json.loads(sent[1]["body"]) == {
+ "detail": SESSION_VALIDATION_UNAVAILABLE_DETAIL
+ }
# Not a logout: the session is exactly as it came in.
assert session == {"username": USER, "session_id": SID}
@@ -371,9 +378,54 @@ def test_require_auth_answers_503_and_keeps_the_session(
auth_dep.require_auth(request)
assert raised.value.status_code == 503
+ assert raised.value.detail == SESSION_VALIDATION_UNAVAILABLE_DETAIL
+ assert raised.value.headers == {"Retry-After": "5"}
assert request.session == {"username": USER, "session_id": SID}
+def _render_http_exception(request: Request, exc: HTTPException):
+ """Answer ``exc`` through the app's real HTTPException handler."""
+ from local_deep_research.web.fastapi_app import (
+ _register_exception_handlers,
+ )
+
+ app = FastAPI()
+ _register_exception_handlers(app)
+ return asyncio.run(app.exception_handlers[HTTPException](request, exc))
+
+
+ ("path", "body"),
+ [
+ ("/api/whatever", {"detail": SESSION_VALIDATION_UNAVAILABLE_DETAIL}),
+ (
+ "/api/v1/quick_summary",
+ {
+ "error": SESSION_VALIDATION_UNAVAILABLE_DETAIL,
+ "detail": SESSION_VALIDATION_UNAVAILABLE_DETAIL,
+ },
+ ),
+ ],
+)
+def test_middleware_and_require_auth_send_the_same_503(
+ fake_session_manager, connected, monkeypatch, path, body
+):
+ # One condition, one envelope: a client must not have to tell which of
+ # the two refused it. /api/v1 keeps its legacy "error" key.
+ _inner, _ensure, _scope, _session, sent = _run_middleware(
+ fake_session_manager, monkeypatch, "GET", path
+ )
+ request = _request({"username": USER, "session_id": SID}, path=path)
+ with pytest.raises(HTTPException) as raised:
+ auth_dep.require_auth(request)
+ response = _render_http_exception(request, raised.value)
+
+ assert sent[0]["status"] == response.status_code == 503
+ assert json.loads(sent[1]["body"]) == json.loads(response.body) == body
+ assert dict(sent[0]["headers"])[b"retry-after"] == b"5"
+ assert response.headers["retry-after"] == "5"
+
+
def test_require_auth_still_rejects_an_invalid_session(
fake_session_manager, connected
):