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(web): render branded pages for browser 404 and 413 errors (#5424)

LearningCircuit5ee5fc5e6340
diff --git a/changelog.d/5424.bugfix.md b/changelog.d/5424.bugfix.md
new file mode 100644
index 0000000000..e9065c47f5
--- /dev/null
+++ b/changelog.d/5424.bugfix.md
@@ -0,0 +1 @@
+404 and 413 errors on a browser navigation (a mistyped URL, a stale bookmark) now render a branded, standalone error page with a link back home, instead of an unstyled "Not found" / "Request too large" body. Any non-/api path gets the branded page regardless of the request's Accept header. API requests are unaffected and keep their JSON error responses -- including an oversized upload, since both real upload routes live under /api/. The page does not extend the app shell, so it never discloses the app version or internal routes to an unauthenticated caller.
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index 986fa0700f..1ce7efd39c 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -45,6 +45,119 @@ from .template_config import (
templates,
)
+# ---------------------------------------------------------------------------
+# Branded error pages (404 / 413)
+# ---------------------------------------------------------------------------
+
+#: Title/message copy for each status code the branded error page covers.
+#: Ports the copy from PR #5424 (Flask's ``app_factory.py::
+#: register_error_handlers``, retired by the FastAPI migration in #3299).
+_BRANDED_ERROR_COPY: dict[int, tuple[str, str]] = {
+ 404: (
+ "Page not found",
+ "The page you're looking for doesn't exist or may have moved.",
+ ),
+ 413: (
+ "Request too large",
+ "The file or request you sent is larger than the allowed limit.",
+ ),
+}
+
+
+def _render_branded_error_page(request: Request, status_code: int):
+ """Render ``templates/pages/error.html`` for a browser-facing error.
+
+ Ports the defensive design of the Flask handler this replaces (PR
+ #5424): rendering depends on session data, CSRF token generation, and
+ Jinja globals (``url_for``, the frontend-constants injection in
+ ``template_config.py``'s ``_LDRTemplates.TemplateResponse``) that are
+ not guaranteed to be populated in every environment this can run in —
+ most notably, a minimal test harness may not populate ``scope["app"]``
+ at all (no ``url_for``), or may not install ``SessionMiddleware`` at
+ all (no ``scope["session"]``). A template that itself raises must
+ never turn a 404/413 into an unhandled 500, so any failure here is
+ swallowed and logged at debug; callers fall back to the previous
+ plain-text/JSON response.
+
+ Returns the rendered ``Response`` on success, or ``None`` on any
+ failure.
+ """
+ title, message = _BRANDED_ERROR_COPY.get(
+ status_code, ("Something went wrong", "Please try again.")
+ )
+ from ..security.egress.policy import DEFAULT_EGRESS_SCOPE
+
+ # If a session is present -- real or a caller-supplied placeholder
+ # dict (see BodySizeLimitMiddleware._send_413) -- render against a
+ # *copy* of the scope with a snapshotted "session", never the live
+ # SessionMiddleware ``Session`` object. `_LDRTemplates.
+ # TemplateResponse` (template_config.py:41) does
+ # `getattr(request, "session", None)` unconditionally, and
+ # Starlette's `Request.session` property calls
+ # `session.mark_accessed()` purely by being *read* -- which alone
+ # makes SessionMiddleware add `Vary: Cookie` to the response, before
+ # any of the "not in context" guards below even run. A plain dict
+ # has no `mark_accessed`, so touching the copy here can never mark
+ # the real session accessed or modified, which is what keeps this
+ # from ever adding Set-Cookie/Vary either.
+ #
+ # If there is no session at all (no key in scope -- SessionMiddleware
+ # never ran on this scope, e.g. a minimal test harness, or a caller
+ # that has not populated one), leave `request` untouched: the
+ # `getattr` above then raises the same ``AssertionError`` it always
+ # did, caught by this function's own `except` below, and rendering
+ # falls back to the plain-text/JSON response exactly as before this
+ # session-copy was introduced -- there is no live session object to
+ # protect in that case, so there is nothing to fix.
+ real_session = request.scope.get("session")
+ if hasattr(real_session, "get"):
+ scope = dict(request.scope)
+ scope["session"] = dict(real_session)
+ render_request = Request(scope)
+ else:
+ render_request = request
+
+ try:
+ return templates.TemplateResponse(
+ request=render_request,
+ name="pages/error.html",
+ context={
+ "request": render_request,
+ "status_code": status_code,
+ "error_title": title,
+ "error_message": message,
+ # error.html is a standalone page (does not extend
+ # base.html) and never reads any of these four keys, so
+ # any value satisfies the template — but *_LDRTemplates.
+ # TemplateResponse* treats a missing key as "go compute
+ # the real one": CSRF-token generation (:51, mutates the
+ # session copy above -- harmless, but would still cost a
+ # `secrets.token_hex` call), a flash-message pop (:58,
+ # would drain the *copy*, which is why the real pending
+ # flashes still reach the next real page), and — worst —
+ # an egress-scope DB lookup for any logged-in user (:145)
+ # on every 404/413, including ones DatabaseMiddleware
+ # never opens a session for (the session copy still has
+ # ``username``, so only supplying this explicitly avoids
+ # the DB round trip). Supplying all four here
+ # short-circuits every "not in context" guard so none of
+ # that work ever runs for an error page.
+ "csrf_token": "",
+ "get_flashed_messages": lambda *_a, **_k: [],
+ "egress_scope": DEFAULT_EGRESS_SCOPE,
+ "has_encryption": False,
+ },
+ status_code=status_code,
+ )
+ except Exception:
+ logger.opt(exception=True).debug(
+ "Failed to render branded error page for status {}; falling "
+ "back to a plain response",
+ status_code,
+ )
+ return None
+
+
# ---------------------------------------------------------------------------
# Secret key (same logic as Flask app_factory)
# ---------------------------------------------------------------------------
@@ -723,15 +836,58 @@ class BodySizeLimitMiddleware:
max_large_json_body_size, max_json_body_size
)
- async def _send_413(self, scope, send):
+ async def _send_413(self, scope, receive, send):
path = scope.get("path", "")
# Same negotiation as main's 413 errorhandler (_is_api_path).
if "/api/" in path or path.endswith("/api"):
body = b'{"error": "Request too large"}'
content_type = b"application/json"
- else:
- body = b"Request too large"
- content_type = b"text/plain; charset=utf-8"
+ await send(
+ {
+ "type": "http.response.start",
+ "status": 413,
+ "headers": [
+ (b"content-type", content_type),
+ (b"content-length", str(len(body)).encode()),
+ ],
+ }
+ )
+ await send({"type": "http.response.body", "body": body})
+ return
+
+ # Only the declared-length rejection (the fast path in __call__,
+ # before `self.app` — and therefore SessionMiddleware — ever
+ # runs) reaches this with no "session" key in `scope` at all;
+ # `setdefault` supplies an empty placeholder there, without
+ # adding keys to the original scope, so the branded page still
+ # renders instead of falling back to plain text for that path.
+ # On the streamed (chunked) path, this runs from `__call__`'s
+ # `except _RequestBodyTooLarge` handler AFTER `self.app(...)`
+ # was entered, so SessionMiddleware has already populated
+ # `scope["session"]` with the real, live ``Session`` and
+ # `setdefault` is a no-op — `_render_branded_error_page` renders
+ # against its own detached copy of that live session either way,
+ # so nothing here needs to know which case it is.
+ # `_render_branded_error_page` already catches every exception
+ # itself and returns ``None`` on failure — `dict(scope)` and
+ # `Request(...)` do no work that can raise — so there is nothing
+ # left here to catch; rendering failures keep the plain-text
+ # fallback via that ``None`` return. Unmatched and decorated
+ # routes can skip the outer global rate-limit check, so rendering
+ # here must not rely on an endpoint's rate-limit decorator having
+ # run.
+ req_scope = dict(scope)
+ req_scope.setdefault("session", {})
+ response = _render_branded_error_page(Request(req_scope), 413)
+ if response is not None:
+ # Response.__call__ never reads `receive` for a non-streaming
+ # response (only sends http.response.start/body), so the real
+ # `receive` is safe to pass through unused.
+ await response(scope, receive, send)
+ return
+
+ body = b"Request too large"
+ content_type = b"text/plain; charset=utf-8"
await send(
{
"type": "http.response.start",
@@ -796,7 +952,7 @@ class BodySizeLimitMiddleware:
except ValueError:
break
if declared > effective_max:
- await self._send_413(scope, send)
+ await self._send_413(scope, receive, send)
return
break
@@ -829,7 +985,7 @@ class BodySizeLimitMiddleware:
f"Rejected over-limit request body on {scope.get('path', '')} "
f"(> {effective_max} bytes)"
)
- await self._send_413(scope, send)
+ await self._send_413(scope, receive, send)
class SecureCookieMiddleware:
@@ -1165,12 +1321,18 @@ def _register_exception_handlers(app: FastAPI) -> None:
# Browser navigations get HTML; only API callers get JSON. Without
# the branch, a user who mistypes a URL is shown a raw
# ``{"error": "Not found"}`` body in the browser's JSON viewer.
- # Flask branched the same way — app_factory.py's
+ # Flask branched the same way — the retired app_factory.py's
# ``@app.errorhandler(404)`` returned ``make_response("Not found",
# 404)``, which Flask serves as text/html — and the 401 handler
# directly above already makes this distinction. This one did not.
if _is_api_request(request):
return JSONResponse({"error": "Not found"}, status_code=404)
+ # Branded page (PR #5424), falling back to the old fixed plain-text
+ # body if rendering fails for any reason — see
+ # _render_branded_error_page's docstring.
+ page = _render_branded_error_page(request, 404)
+ if page is not None:
+ return page
return HTMLResponse("Not found", status_code=404)
# Catch-all so unhandled exceptions get logged with traceback rather than
@@ -1198,16 +1360,8 @@ def _register_exception_handlers(app: FastAPI) -> None:
# Flask ``after_request`` covered every response including
# unhandled 500s; this reuses SecurityHeadersMiddleware.
# cache_headers() so the two can't drift apart).
- # NOTE: unlike the 404 handler above, this deliberately does NOT
- # branch on _is_api_request(). Flask's @app.errorhandler(500) did
- # (returning "Server error" as text/html for non-API paths), but the
- # JSON body here is a pinned contract — tests/web/
- # test_exception_handler_contract.py::Test500Contract and
- # test_middleware_order_and_headers.py both assert it — and a raw
- # JSON 500 is far less user-visible than a raw JSON 404, which users
- # hit routinely by mistyping a URL or following a stale link.
- # Changing it buys little and churns a contract two suites depend
- # on. Revisit alongside a real styled error page.
+ # Preserve the fixed JSON 500 response for both browser and API
+ # callers. Branding 404/413 does not change this error envelope.
return JSONResponse(
{"error": "Server error"},
status_code=500,
diff --git a/src/local_deep_research/web/templates/pages/error.html b/src/local_deep_research/web/templates/pages/error.html
new file mode 100644
index 0000000000..4ba577e1ed
--- /dev/null
+++ b/src/local_deep_research/web/templates/pages/error.html
@@ -0,0 +1,111 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>{{ error_title|default('Error') }} - Deep Research System</title>
+ <link rel="icon" type="image/png" href="/static/favicon.png">
+
+ {# Standalone layout: shared template context may contain private values.
+ Do not extend the app shell or interpolate its version/session data. #}
+
+ <!-- Vite HMR for development -->
+ {{ vite_hmr() }}
+
+ <!-- SafeLogger must load before app.js which uses it at init -->
+ <script src="/static/js/security/safe-logger.js"></script>
+ <!-- Load all vendor dependencies and styles through Vite -->
+ {{ vite_asset('js/app.js') }}
+
+ <!-- Keep local styles -->
+ <link rel="stylesheet" href="/static/css/styles.css">
+
+ <style>
+ body {
+ min-height: 100vh;
+ background: var(--bg-primary);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 2rem;
+ margin: 0;
+ box-sizing: border-box;
+ }
+
+ .ldr-error-page {
+ width: 100%;
+ max-width: 480px;
+ padding: 3rem 2.5rem;
+ text-align: center;
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-color);
+ border-radius: 12px;
+ box-shadow: var(--card-shadow, none);
+ box-sizing: border-box;
+ }
+
+ .ldr-error-page .ldr-error-icon {
+ display: block;
+ font-size: 2.5rem;
+ color: var(--text-muted);
+ opacity: 0.6;
+ margin-bottom: 1.25rem;
+ }
+
+ .ldr-error-page .ldr-error-code {
+ margin: 0 0 0.5rem 0;
+ font-size: 0.85rem;
+ font-weight: 600;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--accent-primary);
+ }
+
+ .ldr-error-page h1 {
+ margin: 0 0 0.75rem 0;
+ font-size: 1.4rem;
+ color: var(--text-primary);
+ }
+
+ .ldr-error-page p {
+ margin: 0 0 1.75rem 0;
+ color: var(--text-secondary);
+ line-height: 1.6;
+ }
+
+ .ldr-error-page .btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.5rem;
+ padding: 0.875rem 2rem;
+ background: var(--accent-primary);
+ color: white;
+ border: none;
+ border-radius: 8px;
+ font-size: 1rem;
+ font-weight: 500;
+ cursor: pointer;
+ transition: all 0.2s;
+ text-decoration: none;
+ }
+
+ .ldr-error-page .btn:hover {
+ background: var(--accent-secondary);
+ transform: translateY(-1px);
+ box-shadow: 0 4px 12px rgba(110, 79, 246, 0.3);
+ }
+ </style>
+</head>
+<body>
+ <div class="ldr-error-page" data-error-page data-status-code="{{ status_code }}">
+ <i aria-hidden="true" class="fas fa-exclamation-circle ldr-error-icon"></i>
+ <p class="ldr-error-code">Error {{ status_code }}</p>
+ <h1>{{ error_title|default('Something went wrong') }}</h1>
+ <p>{{ error_message|default('Please try again, or head back to the main page.') }}</p>
+ <a class="btn" href="/">
+ <i aria-hidden="true" class="fas fa-home"></i> Back to Deep Research
+ </a>
+ </div>
+</body>
+</html>
diff --git a/tests/chat/test_chat_security.py b/tests/chat/test_chat_security.py
index 96a249e73b..fc77b53584 100644
--- a/tests/chat/test_chat_security.py
+++ b/tests/chat/test_chat_security.py
@@ -274,7 +274,9 @@ class TestSessionIdValidation:
# response body must never echo system file paths.
assert response.status_code in [404, 400]
body_text = response.data.decode("utf-8", errors="replace")
- assert "etc" not in body_text.lower()
+ # Branded HTML can contain unrelated words and asset names.
+ # Check for the sensitive path, not the broad substring "etc".
+ assert "etc/passwd" not in body_text.lower()
assert "passwd" not in body_text.lower()
# httpx's TestClient applies RFC 3986 dot-segment removal to
diff --git a/tests/security/test_security_headers_fastapi.py b/tests/security/test_security_headers_fastapi.py
index 0c5846c822..b29d89e832 100644
--- a/tests/security/test_security_headers_fastapi.py
+++ b/tests/security/test_security_headers_fastapi.py
@@ -160,8 +160,16 @@ class TestHeadersOnRemainingResponsePaths:
},
)
assert resp.status_code == 413
- assert resp.text == "Request too large"
- assert resp.headers["content-type"].startswith("text/plain")
+ # This is the declared-length path (the Content-Length above is
+ # declared, not sent -- see OVER_CAP_CONTENT_LENGTH), so it is
+ # rejected before `self.app` -- and therefore SessionMiddleware --
+ # ever runs. `_send_413` (fastapi_app.py) fabricates its own
+ # empty-session scope regardless, so `request.session` doesn't
+ # raise, and the standalone `pages/error.html` page (PR #5424)
+ # renders successfully here rather than falling back to the
+ # plain-text body used when rendering isn't possible.
+ assert "data-error-page" in resp.text
+ assert resp.headers["content-type"].startswith("text/html")
_assert_exact_headers(resp, "413 (non-API branch)")
assert resp.headers.get("cache-control") == EXPECTED_NO_STORE
diff --git a/tests/web/routers/test_redirect_static.py b/tests/web/routers/test_redirect_static.py
index fa0f3bdef9..3ba6b13a15 100644
--- a/tests/web/routers/test_redirect_static.py
+++ b/tests/web/routers/test_redirect_static.py
@@ -118,6 +118,16 @@ def test_rejected_path_renders_through_the_app_404_handler(client):
document in the browser -- a third 404 shape on top of the two
``tests/web/test_exception_handler_contract.py`` pins.
+ Since PR #5424 the shared 404 handler renders the branded
+ ``pages/error.html`` page for browser navigations; the fixed
+ ``"Not found"`` text survives only as the fallback for when that
+ render fails (see ``fastapi_app.py::_render_branded_error_page``),
+ which the real-app client here cannot exercise. The positive control
+ is therefore the branded page's stable ``data-error-page`` /
+ ``data-status-code`` markers, matching how
+ ``test_exception_handler_contract.py`` and the real-app tests in
+ ``test_exception_handler_matrix.py`` pin the same handler.
+
An empty captured path is used because HTTP clients normalise the dot
segments the other cases rely on before the request is sent.
"""
@@ -129,4 +139,5 @@ def test_rejected_path_renders_through_the_app_404_handler(client):
assert resp.status_code == 404
assert resp.headers["content-type"].startswith("text/html")
- assert resp.text == "Not found"
+ assert "data-error-page" in resp.text
+ assert 'data-status-code="404"' in resp.text
diff --git a/tests/web/test_body_size_limit.py b/tests/web/test_body_size_limit.py
index 02804ddf6c..71d8aa2366 100644
--- a/tests/web/test_body_size_limit.py
+++ b/tests/web/test_body_size_limit.py
@@ -99,8 +99,51 @@ class TestDeclaredContentLength:
assert status == 200
assert app.ran is True
- def test_non_api_path_gets_plain_text_413(self):
- """Mirrors main's 413 errorhandler content negotiation."""
+ def test_non_api_path_gets_branded_html_413(self):
+ """Mirrors main's 413 errorhandler content negotiation.
+
+ PR #5424 upgraded the non-API path's body from the plain
+ "Request too large" string to the branded pages/error.html page
+ (see fastapi_app.py::_render_branded_error_page); the plain text
+ is now only the fallback if rendering that page fails -- see
+ ``test_render_failure_falls_back_to_plain_text_413`` below. This
+ test's own name used to say "plain_text", which is what this
+ exact body is NOT: it asserts on ``data-error-page`` HTML markers.
+ """
+ mw = BodySizeLimitMiddleware(_App(), max_body_size=100)
+ scope = _scope(
+ path="/settings/save_settings",
+ headers=[(b"content-length", b"101")],
+ )
+
+ status, body = _run(mw, scope, [b""])
+
+ assert status == 413
+ text = body.decode("utf-8")
+ assert "data-error-page" in text
+ assert 'data-status-code="413"' in text
+
+ def test_render_failure_falls_back_to_plain_text_413(self, monkeypatch):
+ """When rendering the branded page raises, the 413 must still be
+ a well-formed plain-text response, not an unhandled 500.
+
+ ``_render_branded_error_page``'s own ``except Exception``
+ (fastapi_app.py) is the only thing standing between a broken
+ template/Jinja global and an unhandled exception on every
+ oversized non-API request; nothing pinned that swallow before
+ this test. Not a regression guard (this fallback already worked
+ on head, unrelated to PR #5424's tidy-round session-handling
+ fix) -- coverage against it quietly being dropped later.
+ """
+ from local_deep_research.web import template_config
+
+ def _boom(*args, **kwargs):
+ raise RuntimeError("template render exploded")
+
+ monkeypatch.setattr(
+ template_config.templates, "TemplateResponse", _boom
+ )
+
mw = BodySizeLimitMiddleware(_App(), max_body_size=100)
scope = _scope(
path="/settings/save_settings",
diff --git a/tests/web/test_content_negotiation_census.py b/tests/web/test_content_negotiation_census.py
index 93a94885de..2161d05202 100644
--- a/tests/web/test_content_negotiation_census.py
+++ b/tests/web/test_content_negotiation_census.py
@@ -714,8 +714,10 @@ class TestBodyLimit413NegotiatesOnPathOnly:
status, ctype = _drive_413(NON_API_JSON_POST, BROWSER_ACCEPT)
assert status == 413
- assert ctype.startswith("text/plain"), (
- "a browser on a non-api path should get text, not JSON"
+ # PR #5424: a browser on a non-api path now gets the branded
+ # pages/error.html page (text/html), not plain text or JSON.
+ assert ctype.startswith("text/html"), (
+ "a browser on a non-api path should get HTML, not JSON"
)
def test_the_route_really_has_no_api_segment(self):
@@ -734,7 +736,8 @@ class TestBodyLimit413NegotiatesOnPathOnly:
"of _is_api_request's first mechanism that omits the second. "
"It never reads the Accept header, so a programmatic client "
"sending Accept: application/json to a non-/api/ JSON route "
- "gets text/plain and its json() call fails. Fix by calling "
+ "gets the branded text/html error page (PR #5424) instead of "
+ "JSON, and its json() call fails. Fix by calling "
"_is_api_request instead of duplicating half of it."
),
)
diff --git a/tests/web/test_exception_handler_contract.py b/tests/web/test_exception_handler_contract.py
index 7f4d7eb730..fc13c878f3 100644
--- a/tests/web/test_exception_handler_contract.py
+++ b/tests/web/test_exception_handler_contract.py
@@ -27,6 +27,8 @@ Unit-level ``to_dict()`` sanitization is covered in
the registered handlers through real ASGI request/response cycles.
"""
+import importlib
+
import pytest
from fastapi import FastAPI, HTTPException, Request
from fastapi.testclient import TestClient
@@ -139,35 +141,44 @@ class Test404Contract:
assert resp.json() == {"error": "Not found"}
def test_browser_404_returns_html_matching_flask(self, real_client):
- # This assertion previously pinned the opposite: the port served the
- # same JSON body to browsers and API callers alike, and the pin
- # existed so that changing it would be "a conscious decision". This
- # is that decision. Serving `{"error": "Not found"}` to a top-level
- # browser navigation renders the raw body in the browser's JSON
- # viewer, which is what a user sees after a typo or a stale
- # bookmark. Flask branched on API-vs-browser and returned
- # `make_response("Not found", 404)` as text/html
- # (web/app_factory.py's `@app.errorhandler(404)`), and the 401
- # handler in this app already made the same distinction — the 404
- # handler was the odd one out. Parity restored.
+ # This assertion previously pinned a bare "Not found" text/html
+ # body, itself a deliberate step up from the original JSON-for-
+ # everyone behavior. PR #5424 goes one step further: instead of
+ # unstyled "Not found", browser navigations now get a branded,
+ # STANDALONE `pages/error.html` page (a way back to the app) --
+ # it deliberately does NOT extend base.html, so it carries no
+ # sidebar/route map and no {{ version }} for an unauthenticated
+ # caller to read off a mistyped URL — the plain-text body was
+ # itself only a fallback for when rendering that page fails (see
+ # fastapi_app.py::_render_branded_error_page). Serving
+ # `{"error": "Not found"}` — or bare "Not found" — to a top-level
+ # browser navigation is what a user sees after a typo or a stale
+ # bookmark; this asserts on the stable `data-error-page` /
+ # `data-status-code` markers from error.html rather than prose,
+ # matching how PR #5424's own test suite pinned it.
resp = real_client.get(
"/definitely-not-a-page-xyzzy", headers={"Accept": "text/html"}
)
assert resp.status_code == 404
assert resp.headers["content-type"].startswith("text/html")
- assert resp.text == "Not found"
+ assert "data-error-page" in resp.text
+ assert 'data-status-code="404"' in resp.text
def test_browser_404_body_does_not_reflect_request_path(self, real_client):
# The HTML branch must stay a fixed constant. A reflected path in an
# HTML response body is a live XSS channel, not merely a leak as it
- # would be in JSON.
+ # would be in JSON. Check for the request-path fragment itself
+ # rather than the bare words "script"/"alert" -- the branded,
+ # standalone pages/error.html page (PR #5424) legitimately contains
+ # "<script" (its own Vite/HMR bootstrap tags), so a bare-word check
+ # would be a false positive independent of any real reflection.
resp = real_client.get(
"/not-a-page-<script>alert(1)</script>",
headers={"Accept": "text/html"},
)
assert resp.status_code == 404
- assert "script" not in resp.text
- assert "alert" not in resp.text
+ assert "not-a-page" not in resp.text
+ assert "<script>alert(1)</script>" not in resp.text
def test_404_body_does_not_reflect_request_path(self, real_client):
# Reflected-path 404 pages are an XSS/leak channel; body is fixed.
@@ -182,6 +193,30 @@ class Test404Contract:
# ---------------------------------------------------------------------------
[email protected]("status_code", [404, 413])
+def test_branded_error_pages_omit_app_version(
+ real_client, monkeypatch, status_code
+):
+ """Shared template context must not leak through rendered HTML comments."""
+ version_module = importlib.import_module("local_deep_research.__version__")
+ private_version = "private-build-marker-for-error-page"
+ monkeypatch.setattr(version_module, "__version__", private_version)
+ headers = {"Accept": "text/html"}
+ if status_code == 413:
+ # Only a declared size: no oversized body is allocated or sent.
+ headers["Content-Length"] = str(1 << 40)
+
+ response = real_client.get(
+ "/missing-branded-version-probe", headers=headers
+ )
+
+ assert response.status_code == status_code
+ assert response.headers["content-type"].startswith("text/html")
+ assert "data-error-page" in response.text
+ assert f'data-status-code="{status_code}"' in response.text
+ assert private_version not in response.text
+
+
class Test405Contract:
def test_405_json_detail_and_allow_header(self, real_client):
# GET on a POST-only route; GET is CSRF-safe so the request
diff --git a/tests/web/test_exception_handler_matrix.py b/tests/web/test_exception_handler_matrix.py
index 91de54b09f..34eec05a8c 100644
--- a/tests/web/test_exception_handler_matrix.py
+++ b/tests/web/test_exception_handler_matrix.py
@@ -62,6 +62,7 @@ import pytest
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
+from starlette.middleware.sessions import SessionMiddleware
from local_deep_research.web.exceptions import WebAPIException
from local_deep_research.web.fastapi_app import (
@@ -281,6 +282,38 @@ def real_client():
return TestClient(app, raise_server_exceptions=False)
[email protected](scope="module")
+def sessioned_client():
+ """Real handlers, WITH ``SessionMiddleware`` installed -- unlike
+ ``matrix_client``, which deliberately omits it so
+ ``_render_branded_error_page`` falls back to plain text (see the
+ fallback tests above). Two test-only routes drive session state
+ directly, the same "real handler registration on a throwaway app"
+ technique ``_matrix_app()`` uses, since no anonymous real route both
+ queues a flash and is reachable without authentication.
+ """
+ from local_deep_research.web.dependencies.flash import (
+ flash,
+ get_flashed_messages,
+ )
+
+ app = _matrix_app()
+ app.add_middleware(
+ SessionMiddleware, secret_key="test-only-secret-key-not-for-prod"
+ )
+
+ @app.get("/__set_flash__")
+ async def _set_flash(request: Request):
+ flash(request, "Settings saved.", "success")
+ return {"ok": True}
+
+ @app.get("/__peek_flash__")
+ async def _peek_flash(request: Request):
+ return {"flashes": get_flashed_messages(request, with_categories=True)}
+
+ return TestClient(app, raise_server_exceptions=False)
+
+
BROWSER = {"Accept": "text/html,application/xhtml+xml,*/*;q=0.8"}
API = {"Accept": "application/json"}
@@ -547,9 +580,60 @@ class Test404HandlerMatrix:
assert browser.status_code == api.status_code == 404
assert browser.headers["content-type"].startswith("text/html")
- assert browser.text == "Not found"
+ # Real app -> the standalone `pages/error.html` page (PR #5424)
+ # renders successfully here, not the bare "Not found" fallback text
+ # used when rendering isn't possible (see the throwaway-app tests
+ # above, which pin that fallback body because their bare `FastAPI()`
+ # app has no SessionMiddleware, so `request.session` raises inside
+ # `_LDRTemplates.TemplateResponse` and the render is swallowed).
+ assert "data-error-page" in browser.text
assert api.json() == {"error": "Not found"}
+ def test_anonymous_non_api_404_sets_no_session_cookie(
+ self, sessioned_client
+ ):
+ """Regression guard for PR #5424's tidy-round fix.
+
+ ``_LDRTemplates.TemplateResponse`` (template_config.py) mints and
+ stores a CSRF token in the session -- and merely *reading*
+ ``request.session`` marks it accessed, which makes
+ SessionMiddleware add ``Vary: Cookie`` -- unless the render
+ context already supplies ``csrf_token``/the other injected keys.
+ Before the fix, a visitor who mistyped a URL or hit a stale
+ bookmark got a session established (Set-Cookie) and a
+ cache-fragmenting ``Vary: Cookie`` on what should be a stateless
+ miss. On head (9afa3c45f) this failed: anonymous GET /page/... got
+ both ``Set-Cookie: session=...`` and ``Vary: Cookie``.
+ """
+ c = sessioned_client
+ c.cookies.clear()
+ resp = c.get("/page/no-such-thing", headers=BROWSER)
+ assert resp.status_code == 404
+ assert "data-error-page" in resp.text # positive control
+ assert "set-cookie" not in resp.headers
+ assert "cookie" not in resp.headers.get("vary", "").lower()
+
+ def test_pending_flash_survives_a_404(self, sessioned_client):
+ """Regression guard: a 404 must not consume unrelated flashes.
+
+ A flash queued before an unrelated navigation miss (e.g. "Settings
+ saved" followed by a mistyped/stale link) must still reach the
+ NEXT real page. Before the fix, rendering the branded error page
+ called ``get_flashed_messages()``, which POPS ``_flashes`` off the
+ session -- on head (9afa3c45f) the flash queued here did not
+ survive the intervening 404: ``/__peek_flash__`` came back empty.
+ """
+ c = sessioned_client
+ c.cookies.clear()
+ assert c.get("/__set_flash__").status_code == 200
+
+ miss = c.get("/page/no-such-thing", headers=BROWSER)
+ assert miss.status_code == 404
+ assert "data-error-page" in miss.text # positive control
+
+ peeked = c.get("/__peek_flash__")
+ assert peeked.json() == {"flashes": [["success", "Settings saved."]]}
+
# ---------------------------------------------------------------------------
# Catch-all Exception handler
@@ -910,7 +994,7 @@ class TestSecurityHeadersOnErrorResponses:
# a future reflected-content mistake would become exploitable.
resp = real_client.get("/no-such-page-xyzzy", headers=BROWSER)
assert resp.status_code == 404
- assert resp.text == "Not found"
+ assert "data-error-page" in resp.text
for header, expected in EXPECTED_ERROR_HEADERS.items():
assert expected in resp.headers.get(header, ""), (
f"{header} missing from the browser 404"
diff --git a/tests/web/test_middleware_stack_contracts.py b/tests/web/test_middleware_stack_contracts.py
index 5fb537fad8..6d92feae00 100644
--- a/tests/web/test_middleware_stack_contracts.py
+++ b/tests/web/test_middleware_stack_contracts.py
@@ -562,8 +562,15 @@ class TestShortCircuitSkipsInnerMiddleware:
"""
resp = self._oversized(client)
assert resp.status_code == 413
- assert resp.text == "Request too large"
- assert resp.headers["content-type"].startswith("text/plain")
+ # This is the declared-length path -- SessionMiddleware never runs
+ # here at all (see the skip-list assertion above). `_send_413`
+ # (fastapi_app.py) fabricates its own empty-session scope
+ # regardless, so `request.session` doesn't raise, and the
+ # standalone `pages/error.html` page (PR #5424) renders
+ # successfully here rather than falling back to the plain-text
+ # body used when rendering isn't possible.
+ assert "data-error-page" in resp.text
+ assert resp.headers["content-type"].startswith("text/html")
missing = [h for h in _ALL_STAMPED_HEADERS if h not in resp.headers]
assert missing == [], (
"the 413 produced by BodySizeLimitMiddleware lost headers that "