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): preserve external-link login and CSRF-protect model refresh (#7133)

LearningCircuitc827cd5cbc00
diff --git a/changelog.d/+model-refresh-after-api-key-save.feature.md b/changelog.d/+model-refresh-after-api-key-save.feature.md
index 5f34cd1c39..7cd1decf56 100644
--- a/changelog.d/+model-refresh-after-api-key-save.feature.md
+++ b/changelog.d/+model-refresh-after-api-key-save.feature.md
@@ -1,3 +1,3 @@
-Saving an LLM provider API key on the research page now refreshes just that provider's model catalog immediately (merged into the cached catalog, with stale in-flight responses discarded; the refreshed models expire from the 24h cache together with the other providers' cached models, so the other providers' models are never hidden while only the refreshed provider's models remain cached) instead of leaving its models hidden behind the 24h model cache until a manual refresh. Pasted API keys with surrounding whitespace no longer fail model discovery while working for research. The targeted refresh is a CSRF-protected `POST /settings/api/available-models?refresh_provider=<provider>` (a POST without `refresh_provider` re-discovers every provider); a `GET` carrying `refresh_provider` or `force_refresh=true` returns 405 and never contacts a provider or rewrites the model cache.
+Saving an LLM provider API key on the research page now refreshes just that provider's model catalog immediately (merged into the cached catalog, with stale in-flight responses discarded; the refreshed models expire from the 24h cache together with the other providers' cached models, so the other providers' models are never hidden while only the refreshed provider's models remain cached) instead of leaving its models hidden behind the 24h model cache until a manual refresh. Pasted API keys with surrounding whitespace no longer fail model discovery while working for research. The targeted refresh is a CSRF-protected `POST /settings/api/available-models?refresh_provider=<provider>` (`POST ?force_refresh=true` re-discovers every provider); a `GET` carrying `refresh_provider` or `force_refresh=true` returns 405 and never contacts a provider or rewrites the model cache.
On the research page, overlapping refreshes preserve successful updates for each provider, including when a full catalog reload overlaps a provider refresh, and policy reloads prevent older responses from restoring disabled cloud providers. On the server, refreshes using an API key or endpoint that has since changed cannot overwrite newer cached models.
diff --git a/changelog.d/3299.breaking.md b/changelog.d/3299.breaking.md
index ed7801079b..3237b744dd 100644
--- a/changelog.d/3299.breaking.md
+++ b/changelog.d/3299.breaking.md
@@ -29,8 +29,6 @@ custom API clients should prepare for these compatibility changes:
also use incompatible formats.
- **Startup now fails if LDR cannot read or create its persistent session key.**
Fix the data-directory permissions or key-file contents before upgrading.
-- **Session cookies now use `SameSite=Strict`** instead of `Lax`. Cross-site
- embeds and integrations that depend on cross-site cookie delivery must adjust.
- **Session-authenticated `POST /api/v1/quick_summary`, `/generate_report` and
`/analyze_documents` clients must now send a CSRF token.** v1.x exempted these
endpoints, so tokenless calls worked; fetch the token from
diff --git a/changelog.d/6578.breaking.md b/changelog.d/6578.breaking.md
index 86973c3600..99205473c7 100644
--- a/changelog.d/6578.breaking.md
+++ b/changelog.d/6578.breaking.md
@@ -1 +1 @@
-Refreshing the model list now requires a CSRF-protected `POST /settings/api/available-models`. `GET /settings/api/available-models?force_refresh=true`, which cleared and re-discovered the whole model cache without a CSRF check, now returns 405 (`Allow: POST`) and changes nothing; send a `POST` with the session's CSRF token instead (add `?refresh_provider=<provider>` to refresh a single provider). The research, settings and benchmark pages already refresh this way; plain `GET` model-list reads are unchanged.
+Refreshing the model list now requires a CSRF-protected `POST /settings/api/available-models`. `GET /settings/api/available-models?force_refresh=true`, which cleared and re-discovered the whole model cache without a CSRF check, now returns 405 (`Allow: POST`) and changes nothing, as does a `GET` carrying the new `refresh_provider` parameter.
diff --git a/changelog.d/6668.bugfix.md b/changelog.d/6668.bugfix.md
new file mode 100644
index 0000000000..9205bc6ce4
--- /dev/null
+++ b/changelog.d/6668.bugfix.md
@@ -0,0 +1,13 @@
+Keep users logged in when following links to LDR from other sites by sending
+the session cookie on safe top-level navigation. A chat link carrying `?q=` no
+longer sends anything by itself: the query only pre-fills the chat box of a
+chat without earlier messages, and nothing is sent until you press Send. When
+the browser's `Sec-Fetch-Site` header says that the link came from another
+origin (another site, or another subdomain or port; browsers send the header
+to HTTPS and localhost addresses), the query is not pre-filled at all. The
+login page also drops `?q=` from a chat address that it sends you on to after
+signing in. Typed and bookmarked addresses, and links opened from other apps
+such as mail and chat clients, still pre-fill the chat box when you are
+already signed in. Chat mode on the main page still starts the chat with one
+submit through the protected API, without staging the query in browser storage
+or putting it in the navigation URL.
diff --git a/changelog.d/7133.breaking.md b/changelog.d/7133.breaking.md
new file mode 100644
index 0000000000..cd0b77162f
--- /dev/null
+++ b/changelog.d/7133.breaking.md
@@ -0,0 +1,13 @@
+`GET /settings/api/available-models` now only reads the cached model list. A
+cold, expired or entirely policy-filtered cache returns the usual response with
+an empty `providers` mapping, and an error reading the cache returns a generic
+error (HTTP 500); a `GET` never discovers models, contacts a provider or writes
+the cache. Model discovery uses a CSRF-protected `POST` to the same endpoint:
+without a query it returns the fresh cached models and discovers models only
+when the cache gives none (cold, expired, entirely filtered or unreadable),
+`?force_refresh=true` bypasses the cache and re-discovers every provider, and
+`?refresh_provider=<provider>` re-discovers one provider (every provider when
+the cache gives none) and takes precedence over `force_refresh=true`. API clients
+that loaded the model list with a `GET` must send such a `POST` with the
+session's CSRF token to get models discovered; the research, settings,
+benchmark and news-subscription pages already do.
diff --git a/docs/MIGRATION_GUIDE_v1.md b/docs/MIGRATION_GUIDE_v1.md
index f57b171849..6187078669 100644
--- a/docs/MIGRATION_GUIDE_v1.md
+++ b/docs/MIGRATION_GUIDE_v1.md
@@ -353,16 +353,39 @@ An earlier version of this section said the default was "tightened" from
allowlist when the variable was unset. Nothing about origin policy changed
in this migration; only the transport moved.
-### SameSite cookie attribute changed from `Lax` to `Strict`
-
-If you embed LDR inside another tool via an iframe or rely on OAuth
-redirects, the session cookie may not survive the cross-site navigation.
-LDR itself does not use either pattern.
-
-There is currently **no setting or environment variable to restore `Lax`** —
-`same_site="strict"` is hardcoded where `SessionMiddleware` is installed
-(`web/fastapi_app.py`). If you need `Lax`, open an issue; do not expect a
-config knob to exist.
+### Session cookies explicitly use `SameSite=Lax`
+
+Following a top-level link from another site preserves the authenticated
+session. Cross-site unsafe requests do not carry the cookie, and unsafe
+methods also require the session CSRF token. That token does not help when
+a page's own script makes the request, and a link from another site can open
+any page signed in. So GET routes must not change state, and page-load
+scripts must not turn URL parameters into state-changing requests.
+
+- Model discovery and refresh require POST; ordinary model-list GET requests
+ only read cached models, including when the cache is empty or expired.
+- A `/chat/?q=<text>` link no longer sends anything by itself. Earlier
+ versions could send the query and start a research run as soon as the page
+ loaded. Now `q` only pre-fills the chat box of a new chat, or of a chat with
+ no messages yet, without focusing it, and nothing is sent until the user
+ presses Send; an auto-repeated Enter from a key that was already held down
+ does not send. In addition, when the browser's `Sec-Fetch-Site` header says
+ the link came from another origin (`cross-site` or `same-site`; browsers
+ send the header to HTTPS and localhost origins), the server redirects to the
+ same page without `q`. The login page drops `q` from a chat page in its
+ `next` parameter, whatever the header says, both in the form it renders and
+ in the redirect after signing in. A typed or bookmarked URL, or a link
+ opened from another app such as a mail or chat client, arrives with
+ `Sec-Fetch-Site: none` and keeps `q`, as does any link to a plain-HTTP
+ address other than localhost, where browsers send no `Sec-Fetch-Site`; for
+ a signed-in user such a link pre-fills the chat box. Chat mode on the main
+ page submits its message through the protected API before opening its
+ clean chat URL, so one submit still starts the chat. Queries are not
+ staged in browser storage.
+
+The cookie policy is explicitly set to `same_site="lax"` where
+`SessionMiddleware` is installed (`web/fastapi_app.py`); it is not a setting
+or environment variable.
### Graceful shutdown timeout is bounded (10 s)
diff --git a/docs/api-quickstart.md b/docs/api-quickstart.md
index a2425becbf..f24960968f 100644
--- a/docs/api-quickstart.md
+++ b/docs/api-quickstart.md
@@ -138,8 +138,10 @@ Settings endpoints are under `/settings/api/`:
- `GET /settings/api` - Get all settings
- `GET /settings/api/{key}` - Get specific setting
- `PUT /settings/api/{key}` - Update setting
-- `GET /settings/api/available-models` - Get available LLM providers
-- `POST /settings/api/available-models?refresh_provider=<provider>` - Re-discover one provider's models (CSRF token required; a POST without `refresh_provider` refreshes every provider, and a `GET` with `refresh_provider` or `force_refresh=true` returns 405)
+- `GET /settings/api/available-models` - Read cached LLM providers and models; a cold or expired cache returns an empty model list without discovery (a `GET` with `refresh_provider` or `force_refresh=true` returns 405)
+- `POST /settings/api/available-models` - Reuse cached models or discover them on a cache miss; requires a session CSRF token
+- `POST /settings/api/available-models?force_refresh=true` - Bypass and replace the model cache; requires a session CSRF token
+- `POST /settings/api/available-models?refresh_provider=<provider>` - Re-discover one provider's models, or every provider when the cache is empty; takes precedence over `force_refresh=true`; requires a session CSRF token
- `GET /settings/api/available-search-engines` - Get search engines
### History Endpoints
diff --git a/examples/api_usage/http/advanced/http_api_examples.py b/examples/api_usage/http/advanced/http_api_examples.py
index 837a1a9d92..c85528c3f7 100755
--- a/examples/api_usage/http/advanced/http_api_examples.py
+++ b/examples/api_usage/http/advanced/http_api_examples.py
@@ -234,8 +234,9 @@ class LDRClient:
def get_available_models(self) -> Dict[str, str]:
"""Get available LLM providers and models."""
- response = self.session.get(
- f"{self.base_url}/settings/api/available-models"
+ response = self.session.post(
+ f"{self.base_url}/settings/api/available-models",
+ headers=self._get_headers(),
)
data = response.json()
return data.get("providers", data.get("models", {}))
diff --git a/src/local_deep_research/web/dependencies/csrf.py b/src/local_deep_research/web/dependencies/csrf.py
index 6a933c789a..5a5a483b40 100644
--- a/src/local_deep_research/web/dependencies/csrf.py
+++ b/src/local_deep_research/web/dependencies/csrf.py
@@ -38,15 +38,17 @@ library over hand-rolled security code, a reasonable default instinct):
second cookie) with no integration with Starlette's
`SessionMiddleware`. Our token lives in the session payload
(`request.session["_csrf_token"]`) — i.e. inside the app's existing
- signed, HttpOnly, SameSite=strict session cookie, not a second
+ signed, HttpOnly, SameSite=Lax session cookie, not a second
cookie under a second secret. To be precise about the taxonomy:
that makes this a *session-bound signed double-submit*, not a
server-side synchronizer store — the token rides in the same signed
cookie the session does. The properties that matter follow from the
binding, not from where the bytes are parked: a cross-origin
- attacker can neither read the token (HttpOnly, and SameSite=strict
- keeps the cookie off cross-site requests entirely) nor forge one
- (SECRET_KEY-signed), and the token dies with the session it is in —
+ attacker cannot read the cookie through JavaScript (HttpOnly) or
+ read the token endpoint/page across origins (same-origin policy),
+ nor forge a signed session (SECRET_KEY). Explicit SameSite=Lax also
+ keeps the cookie off cross-site unsafe requests while permitting
+ incoming top-level GET links. The token dies with its session —
`request.session.clear()` at login (session-fixation defence) and at
logout drops it, so the next mint is a fresh token. The library's
cookie is independent of auth state; its own README has route
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index c38316d9cc..c6fcfc2c2f 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -1325,7 +1325,7 @@ class RememberMeMiddleware:
explicit "delete this cookie now" instruction, not persistent session
data. Stripping `Expires`/`Max-Age` from THAT header, the same as any
other non-remember-me cookie, downgrades it to `session=null; path=/;
- httponly; samesite=strict`: no expiry in the past, so the browser does
+ httponly; samesite=lax`: no expiry in the past, so the browser does
not delete the cookie at all — it just keeps sending the literal string
"null" back as the session value for the rest of the browser session.
A revoked/logged-out session would then never actually leave the
@@ -1497,10 +1497,15 @@ def _register_exception_handlers(app: FastAPI) -> None:
# Path AND query. main used Werkzeug's `request.url` (the full
# URL) as `next`, so a deep link survived the login bounce; the
# port truncated it to the path, silently dropping the query.
- # That is not cosmetic: /chat/?q=... auto-submits the query as a
- # research run (static/js/components/chat.js routed-query bootstrap), so a
- # signed-out user following a shared link landed on an empty
- # chat box with their question gone. The consumer side already
+ # That is not cosmetic: a signed-out user following a link such
+ # as /settings/?tab=llm lost everything after the `?`. A chat
+ # page's `q` survives this bounce too, but not the login: the
+ # login page drops it from `next` (routers/auth.py:
+ # _drop_chat_query), because after login the browser follows
+ # our own redirect and the chat page cannot tell that another
+ # site supplied the text. (The chat route also drops `q` before
+ # this bounce when Sec-Fetch-Site marks the link as coming from
+ # another origin.) The consumer side already
# handles this -- URLValidator.get_safe_redirect_path()
# explicitly re-appends query and fragment, and is byte-identical
# to main. quote(safe="/") below encodes the `?` and `&` so the
@@ -1835,14 +1840,12 @@ def _enforce_session_expiry(session) -> None:
so adding a second, redundant deadline only risks the two drifting
apart if an operator changes one setting and not the other.
- Called from ``DatabaseMiddleware.__call__`` — the innermost
- app-level middleware, run immediately before Starlette's router —
- specifically so this runs BEFORE CSRFMiddleware's own session read
- and before any route handler (including ``require_auth`` /
- ``/auth/check``) can act on a session whose signature is still valid
- but whose intended lifetime has passed. Clearing the dict here makes
- an expired session indistinguishable from "never logged in" to every
- downstream consumer, without touching any of those call sites.
+ Called from ``DatabaseMiddleware.__call__`` after CSRFMiddleware and
+ before Starlette's router. CSRF can still inspect a signed but expired
+ session, but no route handler (including ``require_auth`` / ``/auth/check``)
+ can act on one whose intended lifetime has passed. Clearing the dict
+ here makes an expired session indistinguishable from "never logged in"
+ to downstream handlers without touching those call sites.
Existing sessions: does NOT force-log-out non-remember-me sessions
that predate this fix. Their cookie has no stamped deadline yet
@@ -1943,8 +1946,8 @@ class DatabaseMiddleware:
enforces/refreshes the non-remember-me session deadline (regression
#1 — see `_enforce_session_expiry` / `_stamp_session_expiry` above)
since this is the innermost app-level middleware: the last point to
- act on the session before CSRF's own read of it and before any route
- handler runs.
+ act on the session before any route handler runs. CSRFMiddleware runs
+ outside it and reads the session first.
"""
_skip_prefixes = (
@@ -1974,9 +1977,9 @@ class DatabaseMiddleware:
)
# Regression #1: enforce the shorter non-remember-me deadline
- # BEFORE anything downstream (CSRF's session read, the route
- # handler) can act on a session whose itsdangerous signature is
- # still valid but whose intended lifetime has passed. Runs
+ # BEFORE the route handler can act on a session whose itsdangerous
+ # signature is still valid but whose intended lifetime has passed.
+ # CSRFMiddleware already read the session before this point. Runs
# unconditionally (not gated by _skip_prefixes below) — it's a
# cheap in-memory check/clear, not a DB open, and skipping it for
# e.g. static-asset requests would let an idle-but-signature-valid
@@ -2586,9 +2589,20 @@ app.add_middleware(
max_age=get_security_default("security.session_remember_me_days", 30)
* 24
* 3600,
- # "strict" is safe here because LDR has no OAuth redirects or
- # external flows that require cross-site cookie delivery.
- same_site="strict",
+ # Include the login cookie on safe top-level navigation from other sites.
+ # Lax still withholds it from cross-site unsafe requests, and
+ # CSRFMiddleware requires the session token on unsafe methods. But Lax
+ # lets another site's link open any page signed in, so GET routes must
+ # not change state (indexing and model discovery use POST), and a
+ # page-load script must not turn URL parameters into a state-changing
+ # request, which would carry the page's own CSRF token. chat.js only
+ # pre-fills `?q=` into a chat without messages, without focus, and never
+ # sends it by itself; the chat page also redirects `?q=` away from links
+ # that Sec-Fetch-Site marks as coming from another origin
+ # (web/routers/chat.py), and the login page drops it from a chat `next`
+ # (web/routers/auth.py). The main form submits its chat message through
+ # the protected API before opening the chat, without browser staging.
+ same_site="lax",
https_only=False, # Handled dynamically by SecureCookieMiddleware
)
diff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.py
index 7b3d2c52ec..f77dffd6df 100644
--- a/src/local_deep_research/web/routers/auth.py
+++ b/src/local_deep_research/web/routers/auth.py
@@ -35,7 +35,15 @@ from ..auth.session_manager import (
) # singleton from session_manager module
from ..server_config import load_server_config
-from urllib.parse import urlparse
+import posixpath
+from urllib.parse import (
+ unquote,
+ unquote_plus,
+ urljoin,
+ urlparse,
+ urlsplit,
+ urlunsplit,
+)
from ...security.url_validator import URLValidator
from ...security.account_lockout import get_account_lockout_manager
@@ -139,6 +147,54 @@ def _disconnect_session_sockets(session_id: str) -> None:
logger.exception("Failed to disconnect sockets for session")
+# chat.js pre-fills the chat box from this query parameter of a chat URL.
+_CHAT_QUERY_PARAM = "q"
+
+
+def _opens_chat_page(path: str) -> bool:
+ """Whether a redirect to ``path`` would load the chat page.
+
+ The browser removes dot segments (``%2e`` included) from a redirect
+ target and the server percent-decodes the path before routing, so the
+ check uses the decoded path without dot segments. ``/chat`` counts too:
+ the router redirects it to ``/chat/`` and keeps the query. Ignoring
+ letter case can only make the check match more paths.
+ """
+ decoded = posixpath.normpath("/" + unquote(path).lstrip("/")).lower()
+ return decoded == "/chat" or decoded.startswith("/chat/")
+
+
+def _drop_chat_query(target: str, base_url: str) -> str:
+ """Remove ``q`` from a login ``next`` that leads to the chat page.
+
+ A link from another site can open
+ ``/auth/login?next=/chat/?q=<text>``. After the login POST the browser
+ follows this app's own redirect, so the chat page sees a same-origin
+ navigation, ``_drop_foreign_chat_query`` (chat.py) keeps ``q``, and
+ chat.js would pre-fill the linked text. So the login page drops ``q``
+ from such a target, both in the form it renders and in the redirect
+ after login. The rest of ``next`` is kept as written, and any other
+ target is returned unchanged. This runs alongside, not instead of,
+ ``URLValidator.get_safe_redirect_path``.
+ """
+ try:
+ parts = urlsplit(target)
+ resolved_path = urlsplit(urljoin(base_url, target)).path
+ except ValueError:
+ # Unparseable (for example "http://["). get_safe_redirect_path
+ # raises on the same input, so it never redirects anywhere.
+ return target
+ if not parts.query or not _opens_chat_page(resolved_path):
+ return target
+ kept = [
+ item
+ for item in parts.query.split("&")
+ # Decode the name the way chat.js's URLSearchParams does.
+ if unquote_plus(item.split("=", 1)[0]) != _CHAT_QUERY_PARAM
+ ]
+ return urlunsplit(parts._replace(query="&".join(kept)))
+
+
@router.get("/login")
def login_page(request: Request, next: Annotated[str, Query()] = ""):
"""Login page (GET only)."""
@@ -152,7 +208,7 @@ def login_page(request: Request, next: Annotated[str, Query()] = ""):
{
"has_encryption": db_manager.has_encryption,
"allow_registrations": config.get("allow_registrations", True),
- "next_page": next,
+ "next_page": _drop_chat_query(next, str(request.base_url)),
},
)
@@ -309,7 +365,9 @@ def login(
safe_path = URLValidator.get_safe_redirect_path(next, str(request.base_url))
if safe_path:
- safe_path = safe_path.replace("\\", "/")
+ safe_path = _drop_chat_query(
+ safe_path.replace("\\", "/"), str(request.base_url)
+ )
parsed = urlparse(safe_path)
if not parsed.scheme and not parsed.netloc:
return RedirectResponse(url=safe_path, status_code=302)
diff --git a/src/local_deep_research/web/routers/chat.py b/src/local_deep_research/web/routers/chat.py
index 326f940808..dfde1d3c8b 100644
--- a/src/local_deep_research/web/routers/chat.py
+++ b/src/local_deep_research/web/routers/chat.py
@@ -20,8 +20,9 @@ import threading
import unicodedata
import uuid
from datetime import datetime, timedelta, UTC
+from urllib.parse import quote
-from fastapi import APIRouter, Depends, Request
+from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import JSONResponse
from loguru import logger
from sqlalchemy import update as sa_update
@@ -312,11 +313,53 @@ def _cleanup_chat_send_rows(
# Page Routes
# ============================================================================
+# Sec-Fetch-Site values that mean another origin started the navigation.
+# "same-site" is still another origin, such as a sibling subdomain or
+# another port on the same host.
+_FOREIGN_FETCH_SITES = frozenset({"cross-site", "same-site"})
+
+
+def _drop_foreign_chat_query(request: Request) -> None:
+ """Redirect a chat link from another origin to the same page without ``q``.
+
+ chat.js pre-fills the chat box from ``?q=`` and never sends that text
+ by itself. The SameSite=Lax session cookie lets a link from another site
+ open the page signed in, so when the browser says that another origin
+ started the navigation, the text is not even pre-filled. Browsers send
+ ``Sec-Fetch-Site`` to HTTPS and localhost origins. ``same-origin`` and
+ ``none`` (a typed or bookmarked URL, or a link opened from another app
+ such as a mail or chat client) keep ``q``, and so does a request without
+ the header. After a login the browser arrives here through this app's
+ own redirect, so the login page drops a chat ``q`` from its ``next``
+ itself (``routers/auth.py::_drop_chat_query``).
+
+ Declared as ``chat_page``'s first dependency parameter, ahead of
+ ``username``. FastAPI solves dependencies in parameter order, so this
+ runs before ``require_auth``: a signed-out user is sent on to the login
+ page without ``q`` as well.
+ """
+ if "q" not in request.query_params:
+ return
+ site = request.headers.get("sec-fetch-site", "").strip().lower()
+ if site not in _FOREIGN_FETCH_SITES:
+ return
+ session_id = request.path_params.get("session_id")
+ location = "/chat/" + (quote(session_id, safe="") if session_id else "")
+ remaining = request.url.remove_query_params("q").query
+ if remaining:
+ location += "?" + remaining
+ raise HTTPException(status_code=303, headers={"Location": location})
+
@router.get("/chat/", include_in_schema=False)
@router.get("/chat/{session_id}", include_in_schema=False)
def chat_page(
request: Request,
+ # A parameter, not a decorator ``dependencies=[...]`` entry, so every
+ # dependency of this route stays in its signature (where the
+ # cross-user isolation census reads auth). It must stay ahead of
+ # ``username``: dependencies run in parameter order.
+ _foreign_query_dropped: Annotated[None, Depends(_drop_foreign_chat_query)],
username: Annotated[str, Depends(require_auth)],
session_id: str | None = None,
):
diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.py
index d94a3482f2..6db1410e59 100644
--- a/src/local_deep_research/web/routers/settings.py
+++ b/src/local_deep_research/web/routers/settings.py
@@ -3128,20 +3128,27 @@ def api_get_ui_elements(
async def api_get_available_models(
request: Request, username: Annotated[str, Depends(require_auth)]
):
- """Get available LLM models from various providers.
-
- ``GET`` returns the cached catalog; only when the cache yields no
- usable rows from the last 24 hours does it discover the providers and
- cache the result. A refresh calls providers with the user's stored API
- keys and rewrites their cached ``ProviderModel`` rows, so it is a
- state change accepted only on the CSRF-protected ``POST``:
- ``?refresh_provider=<p>`` re-discovers that provider (or every
- provider, when the cache has no usable rows), and a ``POST`` without a
- target re-discovers every provider. A ``GET`` carrying
- ``refresh_provider`` or ``force_refresh=true`` answers 405
- (``Allow: POST``) without touching the cache or any provider; on a
- ``POST`` the legacy ``force_refresh`` flag is ignored, so it never
- widens a targeted refresh.
+ """Read cached models on GET; discover or refresh only on POST.
+
+ ``GET`` returns only the policy-filtered model cache: a cold, expired
+ or filtered cache answers with an empty model list, and a ``GET`` never
+ performs provider-specific credential lookups, contacts a provider or
+ writes the cache. It still loads the strict settings snapshot for policy.
+ Discovery calls providers with the user's stored API keys and rewrites
+ their cached ``ProviderModel`` rows, so it is a state change accepted
+ only on the CSRF-protected ``POST``:
+
+ * a ``POST`` without a refresh query returns the fresh cached rows and
+ discovers every provider only on a cache miss;
+ * ``POST ?force_refresh=true`` bypasses and replaces the whole cache;
+ * ``POST ?refresh_provider=<p>`` re-discovers that provider (or every
+ provider, when the cache has no usable rows). A target takes
+ precedence over ``force_refresh=true``, so a targeted refresh is never
+ widened into a full one.
+
+ A ``GET`` carrying ``refresh_provider`` or ``force_refresh=true``
+ answers 405 (``Allow: POST``) without touching the cache or any
+ provider.
Discovery runs on its own executor and does not continue the provider
loop after cancellation.
@@ -3152,8 +3159,7 @@ async def api_get_available_models(
force_refresh_requested = (
request.query_params.get("force_refresh", "false").lower() == "true"
)
- # Refused here, on the event loop, so a 405 never waits for a discovery
- # worker.
+ # Refused here, on the event loop, so a 405 never waits for a worker.
if request.method != "POST" and (
force_refresh_requested or request.query_params.get("refresh_provider")
):
@@ -3164,10 +3170,13 @@ async def api_get_available_models(
)
cancelled = threading.Event()
try:
- # Not run_db_sync: discovery can wait out one provider timeout after
- # another, and a client disconnect does not cancel this request. On
- # the default executor it would hold the workers that every
- # authenticated request needs to check its user database.
+ # Cache-only reads must not queue behind slow provider discovery.
+ if request.method != "POST":
+ return await run_db_sync(
+ _get_available_models, request, username, cancelled
+ )
+ # Discovery can wait out one provider timeout after another. Keep
+ # those calls off the workers used by authenticated DB requests.
return await run_model_discovery_sync(
_get_available_models, request, username, cancelled
)
@@ -3188,7 +3197,9 @@ def _get_available_models(
raise asyncio.CancelledError
check_cancelled()
- is_refresh_request = request.method == "POST"
+ # Only the CSRF-protected POST may discover providers or write the model
+ # cache. Any other method reads the policy-filtered cache and stops there.
+ discovery_allowed = request.method == "POST"
endpoint_start = time.perf_counter()
try:
# request comes from FastAPI parameter
@@ -3204,15 +3215,20 @@ def _get_available_models(
normalize_provider(
request.query_params.get("refresh_provider", "") or ""
)
- if is_refresh_request
+ if discovery_allowed
else None
)
- # The forced (full) refresh: a POST without a target. The legacy
- # force_refresh flag only matters on GET, where it was refused
- # above; on a POST it neither selects nor widens anything, so a
- # targeted POST stays targeted.
- force_refresh = is_refresh_request and not refresh_provider
+ # The forced (full) refresh: POST ?force_refresh=true without a
+ # target. A POST without the flag stays cache-first (it discovers
+ # only on a cache miss), and a target takes precedence over the
+ # flag, so a targeted POST stays targeted.
+ force_refresh = (
+ discovery_allowed
+ and not refresh_provider
+ and request.query_params.get("force_refresh", "false").lower()
+ == "true"
+ )
# Resolve the egress policy BEFORE the model cache is read or any
# provider is discovered/contacted. Fails closed (PolicyDeniedError).
@@ -3351,7 +3367,20 @@ def _get_available_models(
raise
except Exception:
logger.warning("Error reading cached models from database")
- # Continue to fetch fresh data
+ if not discovery_allowed:
+ raise
+ # A CSRF-protected POST may recover by fetching fresh data.
+
+ # Even an ordinary cache miss can populate or replace persisted rows.
+ # GET must never reach model listing, credential lookup or cache writes.
+ # Return the same response shape for cold, expired or filtered caches.
+ if not discovery_allowed:
+ _log_available_models_duration(endpoint_start, cache_hit=False)
+ return {
+ "provider_options": provider_options,
+ "benchmark_provider_options": benchmark_provider_options,
+ "providers": providers,
+ }
if refresh_provider and not cache_had_rows:
# Cold cache (fresh install, or every row older than 24h): a
diff --git a/src/local_deep_research/web/static/js/components/chat.js b/src/local_deep_research/web/static/js/components/chat.js
index 86960ee56d..178d496fb7 100644
--- a/src/local_deep_research/web/static/js/components/chat.js
+++ b/src/local_deep_research/web/static/js/components/chat.js
@@ -284,10 +284,25 @@
setupEventListeners();
setupTextareaAutoResize();
- // A routed `?q=` is a one-shot bootstrap action. Snapshot user
- // interaction before hydration so a manual Send during a slow restore
- // wins even if that request fails (and clears isProcessing) before the
- // restore settles.
+ // Older revisions staged a query in tab storage. It could survive
+ // an interrupted navigation and a later change of account. Discard
+ // that obsolete value without reading, parsing or displaying it.
+ try {
+ window.sessionStorage.removeItem('pendingChatQuery');
+ } catch {
+ _log.warn('Chat: could not clear obsolete startup state');
+ }
+ // Read `?q=` before the restore too: restoring the most recent
+ // session rewrites the URL. Consume it at once, so a reload neither
+ // restores it over a newer draft nor keeps it in the address bar.
+ const routedQuery = new URLSearchParams(window.location.search).get('q') || '';
+ if (routedQuery) {
+ window.history.replaceState({}, '', window.location.pathname);
+ }
+ // The routed draft is a one-shot bootstrap action. Snapshot user interaction
+ // before hydration so a manual Send during a slow restore wins even if
+ // that request fails (and clears isProcessing) before the restore
+ // settles.
const interactionGenerationAtInit = sessionInteractionGeneration;
// Check for existing session ID from meta tag
@@ -295,6 +310,9 @@
if (sessionMeta && sessionMeta.content) {
sessionId = sessionMeta.content;
await loadSession(sessionId);
+ } else if (routedQuery) {
+ // A linked question opens a new chat, not the most recent one.
+ showWelcomeScreen();
} else {
// No session ID in URL - try to load the most recent session
await loadMostRecentSession();
@@ -307,23 +325,27 @@
// poll fallback.
setupSocketReconnectHandler();
- // Auto-send initial query from URL parameter (e.g., from main page chat mode)
- const urlParams = new URLSearchParams(window.location.search);
- const initialQuery = urlParams.get('q');
- if (initialQuery) {
- // Always consume the one-shot query. A manual Send may already own
- // the composer; leaving `?q=` behind would replay it on a later
- // reload after that research finishes.
- window.history.replaceState({}, '', window.location.pathname);
- if (
- !isProcessing &&
- sessionInteractionGeneration === interactionGenerationAtInit
- ) {
- // handleSend creates a session when a fresh `/chat/?q=...`
- // bootstrap has no recent conversation to restore.
- // eslint-disable-next-line require-atomic-updates -- one-shot init flow
- chatInput.value = initialQuery;
- handleSend();
+ const ownsComposer = (
+ !isProcessing &&
+ sessionInteractionGeneration === interactionGenerationAtInit
+ );
+
+ // A URL query is only a draft. `?q=` may
+ // come from another site's link, which the SameSite=Lax cookie lets
+ // arrive signed in, and the server drops such a `q` only when the
+ // browser sends Sec-Fetch-Site. So a draft never joins a conversation
+ // that already has messages, whose earlier turns would become context
+ // for it, and text from the URL does not take focus. The main form
+ // already submits its user's message before opening this page.
+ if (routedQuery && ownsComposer && !chatInput.value.trim()) {
+ if (chatMessages.querySelector('.ldr-chat-message, .ldr-chat-steps-group')) {
+ resetToNewChat({ replaceHistory: true });
+ }
+ chatInput.value = routedQuery;
+ // Run the input listeners: enable Send and resize the textarea.
+ chatInput.dispatchEvent(new Event('input'));
+ if (document.activeElement === chatInput) {
+ chatInput.blur();
}
}
@@ -349,6 +371,10 @@
chatInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
+ // Only a new key press sends. An auto-repeating Enter (a key
+ // held down, perhaps since before this page loaded) must not
+ // send a draft the user has not looked at.
+ if (e.repeat) return;
handleSend();
}
});
@@ -1277,6 +1303,17 @@
* Start a new chat.
*/
function startNewChat() {
+ resetToNewChat();
+ chatInput.focus();
+ }
+
+ /**
+ * Show an empty new chat without moving focus.
+ *
+ * @param {{replaceHistory?: boolean}} [options] replace the current
+ * history entry instead of adding one (used while the page loads).
+ */
+ function resetToNewChat({ replaceHistory = false } = {}) {
sessionLoadGeneration++;
completionHandled = true;
resetActiveResearchState();
@@ -1291,8 +1328,11 @@
showWelcomeScreen();
updateTitle('New Chat');
hideSessionButtons();
- window.history.pushState({}, '', '/chat/');
- chatInput.focus();
+ if (replaceHistory) {
+ window.history.replaceState({}, '', '/chat/');
+ } else {
+ window.history.pushState({}, '', '/chat/');
+ }
}
/**
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index d12f722573..3fc2085ac9 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -2222,15 +2222,18 @@
};
// Fetch from API if cache is invalid or refresh is forced.
- // refreshProvider targets a single provider's catalog (used
- // after its API key was saved); forceRefresh re-discovers
- // every provider (a POST without a target). Both refreshes
- // call providers with the user's stored keys and rewrite the
- // cached rows, so the server accepts them only as a
- // CSRF-protected POST (a GET with refresh_provider or
- // force_refresh=true answers 405).
+ // Discovery calls providers with the user's stored keys and
+ // rewrites the cached rows, so every load is a CSRF-protected
+ // POST: a GET only reads the server's model cache (empty when
+ // cold) and answers 405 with refresh_provider or
+ // force_refresh=true. A plain POST reuses the server's fresh
+ // cache and discovers only on a miss; forceRefresh re-discovers
+ // every provider; refreshProvider targets a single provider's
+ // catalog (used after its API key was saved).
const params = new URLSearchParams();
- if (!forceRefresh && refreshProvider) {
+ if (forceRefresh) {
+ params.set('force_refresh', 'true');
+ } else if (refreshProvider) {
params.set('refresh_provider', refreshProvider);
}
const url = params.toString()
@@ -2238,9 +2241,9 @@
: URLS.SETTINGS_API.AVAILABLE_MODELS;
const csrfToken = window.api?.getCsrfToken?.()
|| document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
- const modelRequest = (forceRefresh || refreshProvider)
- ? fetch(url, { method: 'POST', headers: { 'X-CSRFToken': csrfToken } })
- : fetch(url);
+ const modelRequest = fetch(url, {
+ method: 'POST', headers: { 'X-CSRFToken': csrfToken }
+ });
modelRequest
.then(response => {
@@ -3642,7 +3645,7 @@
loadingOverlay.remove();
};
- // Handle Chat Mode - create session and redirect
+ // Handle Chat Mode - submit the user's message before opening its chat.
// (mode was resolved up front, before the validation guards.)
if (mode === 'chat') {
if (!query) {
@@ -3651,42 +3654,73 @@
return;
}
- const csrfToken = window.api ? window.api.getCsrfToken() : '';
- fetch('/api/chat/sessions', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify({ initial_query: query })
- })
- .then(async response => {
- const data = await response.json();
- if (!response.ok) {
- const message = nonBlankString(data && data.detail)
+ // Keep both writes bound to the login that rendered this page.
+ // This helper only repeats a middleware-rejected CSRF request;
+ // it never retries a message whose handler may have run.
+ const sendChatRequest = window.api?.fetchWithCsrfRecovery;
+ if (typeof sendChatRequest !== 'function') {
+ showAlert('Failed to start chat. Reload this page and try again.', 'error');
+ finishResearchSubmit();
+ return;
+ }
+ let createdChatId = null;
+ let messageAttempted = false;
+ const postChat = async (url, body, fallbackMessage) => {
+ const response = await sendChatRequest(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': window.api.getCsrfToken(),
+ },
+ body: JSON.stringify(body),
+ });
+ const data = await response.json().catch(() => null);
+ if (!response.ok || !data?.success) {
+ const message = nonBlankString(data?.detail)
? data.detail
- : nonBlankString(data && data.error)
+ : nonBlankString(data?.error)
? data.error
- : nonBlankString(data && data.message)
+ : nonBlankString(data?.message)
? data.message
- : 'Failed to create chat session';
- throw new Error(message);
+ : fallbackMessage;
+ const error = new Error(message);
+ error.status = response.status;
+ throw error;
}
return data;
- })
- .then(data => {
- if (data.success && data.session_id) {
- window.location.href = `/chat/${data.session_id}?q=${encodeURIComponent(query)}`;
- } else {
- throw new Error(
- data.error || data.detail || data.message ||
- 'Failed to create chat session'
- );
- }
+ };
+ postChat('/api/chat/sessions', { initial_query: query }, 'Failed to create chat session')
+ .then(async data => {
+ if (typeof data.session_id !== 'string' || !data.session_id) {
+ throw new Error('Failed to create chat session');
+ }
+ const id = encodeURIComponent(data.session_id);
+ createdChatId = data.session_id;
+ messageAttempted = true;
+ await postChat(`/api/chat/sessions/${id}/messages`, {
+ content: query,
+ trigger_research: true,
+ }, 'Failed to send chat message');
+ // The message and any running research now live in encrypted
+ // storage. chat.js restores them without sending again. No
+ // query is staged in browser storage or the navigation URL.
+ window.location.href = `/chat/${id}`;
})
.catch(error => {
- SafeLogger.error('Error creating chat session:', error);
+ SafeLogger.error('Error starting chat:', error);
showAlert('Failed to start chat: ' + error.message, 'error');
+ if (messageAttempted && createdChatId
+ && (!error.status || error.status < 400 || error.status >= 500)) {
+ // A lost response can hide a committed message. Offer a
+ // read-only recovery instead of automatically posting again.
+ const recovery = document.createElement('p');
+ recovery.append('Your chat may have started. ');
+ const link = document.createElement('a');
+ link.href = `/chat/${encodeURIComponent(createdChatId)}`;
+ link.textContent = 'Open chat';
+ recovery.append(link, ' to check before trying again.');
+ document.getElementById('research-alert')?.appendChild(recovery);
+ }
})
.finally(finishResearchSubmit);
return;
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index 37d6cd78b7..7f9d98aae6 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -4408,14 +4408,15 @@
SafeLogger.log('Fetching model providers from API');
// Create a promise and store it
- const url = URLS.SETTINGS_API.AVAILABLE_MODELS;
+ const url = URLS.SETTINGS_API.AVAILABLE_MODELS
+ + (forceRefresh ? '?force_refresh=true' : '');
const csrfToken = window.api?.getCsrfToken?.()
|| document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
const requestGeneration = ++nextModelProvidersRequestGeneration;
- const request = (forceRefresh
- ? fetch(url, { method: 'POST', headers: { 'X-CSRFToken': csrfToken } })
- : fetch(url))
+ const request = fetch(url, {
+ method: 'POST', headers: { 'X-CSRFToken': csrfToken }
+ })
.then(response => {
if (!response.ok) {
throw new Error(`API returned status: ${response.status}`);
diff --git a/src/local_deep_research/web/templates/pages/benchmark.html b/src/local_deep_research/web/templates/pages/benchmark.html
index 050d123018..55e1b0342c 100644
--- a/src/local_deep_research/web/templates/pages/benchmark.html
+++ b/src/local_deep_research/web/templates/pages/benchmark.html
@@ -2165,7 +2165,7 @@ function setupEvaluationModelDropdown() {
window.modelsLoading = true;
const requestVersion = ++evaluationModelsRequestVersion;
- fetch('/settings/api/available-models', {
+ fetch('/settings/api/available-models?force_refresh=true', {
method: 'POST', headers: { 'X-CSRFToken': csrfToken }
})
.then(response => response.json())
@@ -2311,10 +2311,11 @@ const loadEvaluationModelsFromAPI = debounce(function(forceRefresh = false, refr
window.modelsLoading = true;
const requestVersion = ++evaluationModelsRequestVersion;
- const url = '/settings/api/available-models';
- const modelRequest = forceRefresh
- ? fetch(url, { method: 'POST', headers: { 'X-CSRFToken': csrfToken } })
- : fetch(url);
+ const url = '/settings/api/available-models'
+ + (forceRefresh ? '?force_refresh=true' : '');
+ const modelRequest = fetch(url, {
+ method: 'POST', headers: { 'X-CSRFToken': csrfToken }
+ });
modelRequest
.then(response => response.json())
diff --git a/src/local_deep_research/web/templates/pages/news-subscription-form.html b/src/local_deep_research/web/templates/pages/news-subscription-form.html
index 76776b6a52..68a0bda19f 100644
--- a/src/local_deep_research/web/templates/pages/news-subscription-form.html
+++ b/src/local_deep_research/web/templates/pages/news-subscription-form.html
@@ -390,7 +390,9 @@ async function loadModelsForProvider(provider) {
try {
// Fetch available models
const response = await fetch('/settings/api/available-models', {
- credentials: 'same-origin'
+ method: 'POST',
+ credentials: 'same-origin',
+ headers: { 'X-CSRFToken': getCSRFToken() }
});
const data = await response.json();
@@ -441,7 +443,9 @@ async function loadProviders() {
try {
const response = await fetch('/settings/api/available-models', {
- credentials: 'same-origin'
+ method: 'POST',
+ credentials: 'same-origin',
+ headers: { 'X-CSRFToken': getCSRFToken() }
});
const data = await response.json();
diff --git a/tests/chat/test_chat_page_routes.py b/tests/chat/test_chat_page_routes.py
index 0a85a25396..e7bd04e469 100644
--- a/tests/chat/test_chat_page_routes.py
+++ b/tests/chat/test_chat_page_routes.py
@@ -6,10 +6,16 @@ These tests verify:
- Page routes require login
- Page renders with and without session_id
- Invalid session_id is handled gracefully
+- A link from another origin cannot carry ``?q=`` into the page
"""
import json
+import pytest
+
+# Sec-Fetch-Site values for a navigation that another origin started.
+FOREIGN_SITES = ("cross-site", "same-site")
+
class TestChatPageRoutes:
"""Tests for chat page rendering endpoints."""
@@ -68,3 +74,73 @@ class TestChatPageRoutes:
"/login" in response.headers.get("location", "")
or response.status_code == 401
)
+
+
+class TestChatPageLinkQuery:
+ """chat.js only pre-fills the chat box from ``?q=``; nothing is sent
+ until the user presses Send.
+
+ The SameSite=Lax session cookie lets a link from another site open the
+ chat page signed in, so the route also redirects ``q`` away when the
+ browser sends ``Sec-Fetch-Site`` saying another origin started the
+ navigation.
+ """
+
+ @pytest.mark.parametrize("site", FOREIGN_SITES)
+ @pytest.mark.parametrize(
+ ("path", "expected"),
+ [
+ ("/chat/?q=linked+text&mode=quick", "/chat/?mode=quick"),
+ ("/chat/some-session-id?q=linked+text", "/chat/some-session-id"),
+ ("/chat/a%20b?q=", "/chat/a%20b"),
+ ],
+ )
+ def test_foreign_link_loses_q_before_the_login_check(
+ self, client, site, path, expected
+ ):
+ """Signed out, this redirect still comes before the login bounce,
+ so the bounce's ``next`` does not carry this link's ``q``. (A link
+ straight to ``/auth/login?next=/chat/?q=...`` skips this route; the
+ login page drops a chat ``q`` itself:
+ tests/web/test_redirect_and_url_generation.py.)"""
+ response = client.get(
+ path, headers={"Sec-Fetch-Site": site}, follow_redirects=False
+ )
+ assert response.status_code == 303
+ assert response.headers["location"] == expected
+
+ def test_signed_in_foreign_link_opens_the_page_without_q(
+ self, authenticated_client
+ ):
+ response = authenticated_client.get(
+ "/chat/?q=linked+text",
+ headers={"Sec-Fetch-Site": "cross-site"},
+ follow_redirects=False,
+ )
+ assert response.status_code == 303
+ assert response.headers["location"] == "/chat/"
+
+ # External links still open the chat signed in (#6668).
+ page = authenticated_client.get(
+ response.headers["location"],
+ headers={"Sec-Fetch-Site": "cross-site"},
+ follow_redirects=False,
+ )
+ assert page.status_code == 200
+ assert b'id="chat-input"' in page.data
+
+ @pytest.mark.parametrize("site", [None, "same-origin", "none"])
+ def test_same_origin_typed_or_unmarked_navigation_keeps_q(
+ self, authenticated_client, site
+ ):
+ """``none`` is a typed or bookmarked URL, or a link opened from
+ another app such as a mail or chat client; no header at all is what
+ a plain-HTTP origin other than localhost gets. Each keeps ``q``, so
+ the text is pre-filled and nothing more: chat.js sends nothing until
+ the user presses Send."""
+ headers = {"Sec-Fetch-Site": site} if site else {}
+ response = authenticated_client.get(
+ "/chat/?q=linked+text", headers=headers, follow_redirects=False
+ )
+ assert response.status_code == 200
+ assert b'id="chat-input"' in response.data
diff --git a/tests/js/components/chat-migration-runtime.test.js b/tests/js/components/chat-migration-runtime.test.js
index ba96245ab6..5c4dc034f4 100644
--- a/tests/js/components/chat-migration-runtime.test.js
+++ b/tests/js/components/chat-migration-runtime.test.js
@@ -6,6 +6,8 @@
*/
const SESSION_ID = 'session-1';
+// Discard stale values written by older chat-startup implementations.
+const CHAT_HANDOFF_KEY = 'pendingChatQuery';
const jsonResponse = (payload, status = 200) => ({
ok: status >= 200 && status < 300,
@@ -144,6 +146,7 @@ afterEach(() => {
window.chatComponent?.startNewChat();
vi.restoreAllMocks();
vi.useRealTimers();
+ sessionStorage.removeItem(CHAT_HANDOFF_KEY);
document.head.replaceChildren();
document.body.replaceChildren();
delete window.api;
@@ -462,26 +465,36 @@ it('creates the first chat session before posting its owned message', async () =
});
});
-it('consumes the routed q parameter only after restoring its target session', async () => {
- const researchId = 'routed-query-research';
- const routedQuery = 'What changed in the FastAPI migration?';
- history.replaceState(
- {},
- '',
- `/chat/${SESSION_ID}?q=${encodeURIComponent(routedQuery)}`,
+// Every request chat.js made so far, as "METHOD url", in order.
+function requestLog() {
+ return globalThis.fetch.mock.calls.map(
+ ([url, options]) => `${options?.method || 'GET'} ${String(url)}`,
);
+}
+
+// Let any send that init scheduled reach fetch before the assertions.
+async function settleInit() {
+ await new Promise(resolve => setTimeout(resolve, 0));
+}
+
+it('restores an already-started chat without replaying legacy staged text', async () => {
+ const researchId = 'started-research';
+ const submittedQuery = 'Question already saved by the main form';
+ const staleQuery = 'Private question left by another account';
+ history.replaceState({}, '', `/chat/${SESSION_ID}`);
+ sessionStorage.setItem(CHAT_HANDOFF_KEY, JSON.stringify({
+ sessionId: SESSION_ID,
+ query: staleQuery,
+ }));
await loadChat({
- messages: [],
- fetchRoute: (url, options) => {
- if (url === `/api/chat/sessions/${SESSION_ID}/messages`
- && options?.method === 'POST') {
- return jsonResponse({
- success: true,
- research_id: researchId,
- });
- }
- return null;
- },
+ messages: [{
+ id: 'submitted-message',
+ role: 'user',
+ message_type: 'chat',
+ content: submittedQuery,
+ created_at: '2026-10-18T09:00:00Z',
+ }],
+ inProgress: researchId,
});
await vi.waitFor(() => {
@@ -490,49 +503,199 @@ it('consumes the routed q parameter only after restoring its target session', as
expect.any(Function),
);
});
- expect(globalThis.fetch).toHaveBeenCalledWith(
- `/api/chat/sessions/${SESSION_ID}/messages`,
- {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': 'csrf-chat',
- },
- body: JSON.stringify({
- content: routedQuery,
- trigger_research: true,
- }),
- },
- );
+ expect(requestLog()).toEqual([
+ `GET /api/chat/sessions/${SESSION_ID}`,
+ `GET /api/chat/sessions/${SESSION_ID}/messages`,
+ ]);
expect(document.querySelector('.ldr-chat-message-user').textContent)
- .toContain(routedQuery);
+ .toContain(submittedQuery);
+ expect(document.getElementById('chat-messages').textContent).not.toContain(staleQuery);
+ expect(document.getElementById('chat-input').value).toBe('');
+ expect(sessionStorage.getItem(CHAT_HANDOFF_KEY)).toBeNull();
expect(window.location.pathname).toBe(`/chat/${SESSION_ID}`);
- expect(window.location.search).toBe('');
window.chatComponent.startNewChat();
history.replaceState({}, '', '/');
});
-it('creates a fresh session for q when no recent chat exists', async () => {
- const initialQuery = 'Start a fresh migrated chat';
- const createdSessionId = 'query-created-session';
- const researchId = 'query-created-research';
+it.each([false, true])('discards a prior account\'s legacy query on bare chat (recent session: %s)', async (hasRecentSession) => {
+ const privateQuery = 'Account A private question from an interrupted navigation';
+ const currentAnswer = 'Account B answer in its most recent conversation';
+ history.replaceState({}, '', '/chat/');
+ sessionStorage.setItem(CHAT_HANDOFF_KEY, JSON.stringify({
+ sessionId: 'account-a-session',
+ query: privateQuery,
+ }));
+ await loadChat({
+ sessionMeta: false,
+ messages: [{
+ id: 'account-b-answer',
+ role: 'assistant',
+ message_type: 'chat',
+ content: currentAnswer,
+ created_at: '2026-10-18T09:00:00Z',
+ }],
+ fetchRoute: (url) => {
+ if (url === '/api/chat/sessions?limit=1') {
+ return jsonResponse({
+ success: true,
+ sessions: hasRecentSession ? [{ id: SESSION_ID }] : [],
+ });
+ }
+ return null;
+ },
+ });
+ await settleInit();
+
+ expect(requestLog()).toEqual(hasRecentSession ? [
+ 'GET /api/chat/sessions?limit=1',
+ `GET /api/chat/sessions/${SESSION_ID}`,
+ `GET /api/chat/sessions/${SESSION_ID}/messages`,
+ ] : ['GET /api/chat/sessions?limit=1']);
+ expect(document.getElementById('chat-input').value).toBe('');
+ expect(document.getElementById('chat-messages').textContent)
+ .not.toContain(privateQuery);
+ expect(sessionStorage.getItem(CHAT_HANDOFF_KEY)).toBeNull();
+ if (hasRecentSession) {
+ // Discarding the old account's query must not reset B's conversation.
+ expect(document.querySelector('.ldr-chat-message-assistant').textContent)
+ .toContain(currentAnswer);
+ expect(window.location.pathname).toBe(`/chat/${SESSION_ID}`);
+ } else {
+ expect(document.querySelector('.ldr-chat-message')).toBeNull();
+ expect(window.location.pathname).toBe('/chat/');
+ }
+});
+
+it('restores persisted chat when browser storage access is denied', async () => {
+ history.replaceState({}, '', `/chat/${SESSION_ID}`);
+ vi.spyOn(window, 'sessionStorage', 'get').mockImplementation(() => {
+ throw new globalThis.DOMException('Browser storage is denied', 'SecurityError');
+ });
+
+ await loadChat({ messages: [] });
+ await settleInit();
+
+ expect(requestLog()).toEqual([
+ `GET /api/chat/sessions/${SESSION_ID}`,
+ `GET /api/chat/sessions/${SESSION_ID}/messages`,
+ ]);
+ expect(document.getElementById('chat-input').value).toBe('');
+ expect(document.querySelector('.ldr-chat-message')).toBeNull();
+ expect(document.getElementById('chat-input').dataset.initComplete).toBe('true');
+});
+
+it('does not read or display a legacy query when storage cleanup is denied', async () => {
+ const privateQuery = 'Private query that this account must never read';
+ history.replaceState({}, '', `/chat/${SESSION_ID}`);
+ sessionStorage.setItem(CHAT_HANDOFF_KEY, JSON.stringify({
+ sessionId: SESSION_ID,
+ query: privateQuery,
+ }));
+ const storageRead = vi.spyOn(globalThis.Storage.prototype, 'getItem');
+ vi.spyOn(globalThis.Storage.prototype, 'removeItem').mockImplementation(() => {
+ throw new globalThis.DOMException('Browser storage cleanup is denied', 'SecurityError');
+ });
+
+ await loadChat({ messages: [] });
+ await settleInit();
+
+ expect(storageRead).not.toHaveBeenCalledWith(CHAT_HANDOFF_KEY);
+ expect(requestLog()).toEqual([
+ `GET /api/chat/sessions/${SESSION_ID}`,
+ `GET /api/chat/sessions/${SESSION_ID}/messages`,
+ ]);
+ expect(document.getElementById('chat-input').value).toBe('');
+ expect(document.getElementById('chat-messages').textContent)
+ .not.toContain(privateQuery);
+ expect(document.getElementById('chat-input').dataset.initComplete).toBe('true');
+});
+
+it('hydrates an already-completed first message and answer without resending on reload', async () => {
+ const query = 'Question already submitted by the main form';
+ const answer = 'Completed answer saved before the chat page opened';
+ const completedMessages = [{
+ id: 'submitted-query',
+ role: 'user',
+ message_type: 'query',
+ content: query,
+ research_id: 'completed-before-navigation',
+ created_at: '2026-10-18T09:00:00Z',
+ }, {
+ id: 'completed-answer',
+ role: 'assistant',
+ message_type: 'response',
+ content: answer,
+ research_id: 'completed-before-navigation',
+ created_at: '2026-10-18T09:00:01Z',
+ }];
+ sessionStorage.setItem(CHAT_HANDOFF_KEY, JSON.stringify({
+ sessionId: SESSION_ID,
+ query: 'Obsolete staged text must not replace the completed result',
+ }));
+
+ for (const navigation of ['initial navigation', 'reload']) {
+ if (navigation === 'reload') {
+ window.chatComponent.startNewChat();
+ vi.resetModules();
+ }
+ history.replaceState({}, '', `/chat/${SESSION_ID}`);
+ await loadChat({ messages: completedMessages });
+ await settleInit();
+
+ expect(requestLog()).toEqual([
+ `GET /api/chat/sessions/${SESSION_ID}`,
+ `GET /api/chat/sessions/${SESSION_ID}/messages`,
+ ]);
+ const userMessages = document.querySelectorAll('.ldr-chat-message-user');
+ const assistantMessages = document.querySelectorAll('.ldr-chat-message-assistant');
+ expect(userMessages).toHaveLength(1);
+ expect(userMessages[0].textContent).toContain(query);
+ expect(assistantMessages).toHaveLength(1);
+ expect(assistantMessages[0].textContent).toContain(answer);
+ expect(document.getElementById('chat-input').value).toBe('');
+ expect(document.querySelector('.ldr-chat-message-thinking')).toBeNull();
+ expect(window.socket.subscribeToResearch).not.toHaveBeenCalled();
+ expect(sessionStorage.getItem(CHAT_HANDOFF_KEY)).toBeNull();
+ expect(window.location.pathname).toBe(`/chat/${SESSION_ID}`);
+ expect(window.location.search).toBe('');
+ }
+});
+
+const PRIOR_CONVERSATION = [{
+ id: 'prior-answer',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'An earlier answer in this conversation',
+ created_at: '2026-10-01T12:00:00Z',
+}];
+
+it('opens a linked q as a new draft instead of the most recent chat', async () => {
+ // Under SameSite=Lax another site's link reaches this page signed in.
+ // Its query must wait for the user's own Send, and must not join the
+ // most recent conversation, whose earlier turns would become context.
+ const linkedQuery = 'Query chosen by a link from another site';
+ const createdSessionId = 'user-sent-session';
history.replaceState(
{},
'',
- `/chat/?q=${encodeURIComponent(initialQuery)}`,
+ `/chat/?q=${encodeURIComponent(linkedQuery)}`,
);
await loadChat({
sessionMeta: false,
+ messages: PRIOR_CONVERSATION,
fetchRoute: (url, options) => {
if (url === '/api/chat/sessions?limit=1') {
- return jsonResponse({ success: true, sessions: [] });
+ return jsonResponse({
+ success: true,
+ sessions: [{ id: SESSION_ID, title: 'Recent chat' }],
+ });
}
if (url === '/api/chat/sessions' && options?.method === 'POST') {
return jsonResponse({
success: true,
session_id: createdSessionId,
- session: { title: 'Fresh routed query' },
+ session: { title: 'Linked query' },
});
}
if (url === `/api/chat/sessions/${createdSessionId}/generate-title`) {
@@ -540,51 +703,235 @@ it('creates a fresh session for q when no recent chat exists', async () => {
}
if (url === `/api/chat/sessions/${createdSessionId}/messages`
&& options?.method === 'POST') {
- return jsonResponse({ success: true, research_id: researchId });
+ return jsonResponse({
+ success: true,
+ research_id: 'user-sent-research',
+ });
}
return null;
},
});
+ await settleInit();
+
+ // The most recent chat is not even looked up.
+ expect(requestLog()).toEqual([]);
+ expect(document.querySelector('.ldr-chat-message')).toBeNull();
+ const input = document.getElementById('chat-input');
+ expect(input.value).toBe(linkedQuery);
+ expect(document.activeElement).not.toBe(input);
+ expect(document.getElementById('send-btn').disabled).toBe(false);
+ expect(window.location.pathname).toBe('/chat/');
+ expect(window.location.search).toBe('');
+ // One press of Send then starts a new chat as usual.
+ document.getElementById('send-btn').click();
await vi.waitFor(() => {
expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
- researchId,
+ 'user-sent-research',
expect.any(Function),
);
});
- expect(globalThis.fetch).toHaveBeenCalledWith(
- '/api/chat/sessions',
- expect.objectContaining({
- method: 'POST',
- body: JSON.stringify({ initial_query: initialQuery }),
- }),
- );
+ expect(requestLog().filter(entry => entry.startsWith('POST '))).toEqual([
+ 'POST /api/chat/sessions',
+ `POST /api/chat/sessions/${createdSessionId}/generate-title`,
+ `POST /api/chat/sessions/${createdSessionId}/messages`,
+ ]);
expect(globalThis.fetch).toHaveBeenCalledWith(
`/api/chat/sessions/${createdSessionId}/messages`,
expect.objectContaining({
- method: 'POST',
body: JSON.stringify({
- content: initialQuery,
+ content: linkedQuery,
trigger_research: true,
}),
}),
);
- expect(window.location.pathname).toBe(`/chat/${createdSessionId}`);
- expect(window.location.search).toBe('');
window.chatComponent.startNewChat();
history.replaceState({}, '', '/');
});
-it('consumes q without replaying it after a manual Send during hydration', async () => {
- const queuedQuery = 'Do not replay this queued query';
- const manualQuery = 'Manual question owns the composer';
- const delayedSession = deferred();
+it('moves a linked q out of a restored conversation into a new draft', async () => {
+ const linkedQuery = 'Query linked to a conversation with history';
+ history.replaceState(
+ {},
+ '',
+ `/chat/${SESSION_ID}?q=${encodeURIComponent(linkedQuery)}`,
+ );
+ await loadChat({ messages: PRIOR_CONVERSATION });
+ await settleInit();
+
+ expect(requestLog()).toEqual([
+ `GET /api/chat/sessions/${SESSION_ID}`,
+ `GET /api/chat/sessions/${SESSION_ID}/messages`,
+ ]);
+ // The restored conversation is set aside for an empty new chat.
+ expect(document.querySelector('.ldr-chat-message')).toBeNull();
+ expect(document.getElementById('chat-title').textContent).toBe('New Chat');
+ expect(window.location.pathname).toBe('/chat/');
+ expect(window.location.search).toBe('');
+ const input = document.getElementById('chat-input');
+ expect(input.value).toBe(linkedQuery);
+ expect(document.activeElement).not.toBe(input);
+
+ history.replaceState({}, '', '/');
+});
+
+it('keeps a linked q in an empty restored session without focusing it', async () => {
+ const linkedQuery = 'Query for a session with no messages yet';
history.replaceState(
{},
'',
- `/chat/${SESSION_ID}?q=${encodeURIComponent(queuedQuery)}`,
+ `/chat/${SESSION_ID}?q=${encodeURIComponent(linkedQuery)}`,
+ );
+ await loadChat({ messages: [] });
+ await settleInit();
+
+ expect(requestLog()).toEqual([
+ `GET /api/chat/sessions/${SESSION_ID}`,
+ `GET /api/chat/sessions/${SESSION_ID}/messages`,
+ ]);
+ const input = document.getElementById('chat-input');
+ expect(input.value).toBe(linkedQuery);
+ expect(document.activeElement).not.toBe(input);
+ expect(window.location.pathname).toBe(`/chat/${SESSION_ID}`);
+ expect(window.location.search).toBe('');
+
+ history.replaceState({}, '', '/');
+});
+
+it('only pre-fills a linked q when the session in its path does not load', async () => {
+ // A user who already has chats is reachable through an unknown session id:
+ // the failed restore leaves no session, which used to make the routed q
+ // create one and start a research run.
+ const linkedQuery = 'Query linked with an unknown session id';
+ history.replaceState(
+ {},
+ '',
+ `/chat/${SESSION_ID}?q=${encodeURIComponent(linkedQuery)}`,
+ );
+ await loadChat({
+ fetchRoute: (url) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}`) {
+ return jsonResponse(
+ { success: false, error: 'Session not found' },
+ 404,
+ );
+ }
+ return null;
+ },
+ });
+ await settleInit();
+
+ expect(requestLog()).toEqual([`GET /api/chat/sessions/${SESSION_ID}`]);
+ expect(document.querySelector('.ldr-chat-message-user')).toBeNull();
+ const input = document.getElementById('chat-input');
+ expect(input.value).toBe(linkedQuery);
+ expect(document.activeElement).not.toBe(input);
+ expect(window.location.search).toBe('');
+
+ history.replaceState({}, '', '/');
+});
+
+it('discards another account\'s legacy query instead of drafting it in this session', async () => {
+ history.replaceState({}, '', `/chat/${SESSION_ID}`);
+ sessionStorage.setItem(CHAT_HANDOFF_KEY, JSON.stringify({
+ sessionId: 'another-session',
+ query: 'Meant for another chat',
+ }));
+ await loadChat({ messages: [] });
+ await settleInit();
+
+ expect(requestLog()).toEqual([
+ `GET /api/chat/sessions/${SESSION_ID}`,
+ `GET /api/chat/sessions/${SESSION_ID}/messages`,
+ ]);
+ expect(document.getElementById('chat-input').value).toBe('');
+ expect(document.getElementById('chat-messages').textContent)
+ .not.toContain('Meant for another chat');
+ expect(sessionStorage.getItem(CHAT_HANDOFF_KEY)).toBeNull();
+
+ history.replaceState({}, '', '/');
+});
+
+it.each([404, 503])('discards legacy staged text when session restoration returns %s', async (status) => {
+ const handedOffQuery = 'Main-page query whose session failed to load';
+ history.replaceState({}, '', `/chat/${SESSION_ID}`);
+ sessionStorage.setItem(CHAT_HANDOFF_KEY, JSON.stringify({
+ sessionId: SESSION_ID,
+ query: handedOffQuery,
+ }));
+ await loadChat({
+ fetchRoute: (url) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}`) {
+ return jsonResponse({ success: false, error: 'Unavailable' }, status);
+ }
+ return null;
+ },
+ });
+ await settleInit();
+
+ expect(requestLog()).toEqual([`GET /api/chat/sessions/${SESSION_ID}`]);
+ expect(document.getElementById('chat-input').value).toBe('');
+ expect(document.getElementById('chat-messages').textContent).not.toContain(handedOffQuery);
+ expect(sessionStorage.getItem(CHAT_HANDOFF_KEY)).toBeNull();
+
+ history.replaceState({}, '', '/');
+});
+
+it('sends only on a new Enter press, not on an auto-repeated one', async () => {
+ await loadChat({
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages`
+ && options?.method === 'POST') {
+ return jsonResponse({ success: true, research_id: 'enter-research' });
+ }
+ return null;
+ },
+ });
+ const input = document.getElementById('chat-input');
+ input.value = 'Typed question';
+ input.dispatchEvent(new Event('input'));
+ const messagePosts = () => requestLog().filter(
+ entry => entry === `POST /api/chat/sessions/${SESSION_ID}/messages`,
);
+
+ const held = new KeyboardEvent('keydown', {
+ key: 'Enter',
+ repeat: true,
+ cancelable: true,
+ });
+ input.dispatchEvent(held);
+ await settleInit();
+ expect(messagePosts()).toEqual([]);
+ // Still no newline from the held key.
+ expect(held.defaultPrevented).toBe(true);
+ expect(input.value).toBe('Typed question');
+
+ input.dispatchEvent(new KeyboardEvent('keydown', {
+ key: 'Enter',
+ cancelable: true,
+ }));
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ 'enter-research',
+ expect.any(Function),
+ );
+ });
+ expect(messagePosts()).toHaveLength(1);
+});
+
+it.each(['legacy storage', 'URL q'])('keeps a failed manual Send authoritative over %s during hydration', async (source) => {
+ const queuedQuery = 'Do not replay this queued query';
+ const manualQuery = 'Manual question owns the composer';
+ const delayedSession = deferred();
+ const queryString = source === 'URL q' ? `?q=${encodeURIComponent(queuedQuery)}` : '';
+ history.replaceState({}, '', `/chat/${SESSION_ID}${queryString}`);
+ if (source === 'legacy storage') {
+ sessionStorage.setItem(CHAT_HANDOFF_KEY, JSON.stringify({
+ sessionId: SESSION_ID,
+ query: queuedQuery,
+ }));
+ }
buildChatDom();
window.api = {
getCsrfToken: vi.fn(() => 'csrf-chat'),
@@ -619,6 +966,9 @@ it('consumes q without replaying it after a manual Send during hydration', async
{ headers: { 'X-CSRFToken': 'csrf-chat' } },
);
});
+ // Both bootstrap sources are consumed before the restore can settle.
+ expect(sessionStorage.getItem(CHAT_HANDOFF_KEY)).toBeNull();
+ expect(window.location.search).toBe('');
const input = document.getElementById('chat-input');
input.value = manualQuery;
@@ -631,12 +981,13 @@ it('consumes q without replaying it after a manual Send during hydration', async
delayedSession.resolve(jsonResponse({
success: true,
- session: { id: SESSION_ID, title: 'Delayed routed session' },
+ session: { id: SESSION_ID, title: 'Delayed hand-off session' },
}));
await vi.waitFor(() => {
expect(document.getElementById('chat-input').dataset.initComplete)
.toBe('true');
});
+ await settleInit();
const messagePosts = globalThis.fetch.mock.calls.filter(
([url, options]) => (
@@ -649,8 +1000,13 @@ it('consumes q without replaying it after a manual Send during hydration', async
content: manualQuery,
trigger_research: true,
}));
+ expect(input.value).toBe('');
+ expect(input.value).not.toContain(queuedQuery);
expect(document.getElementById('chat-messages').textContent)
.not.toContain(queuedQuery);
+ expect(document.getElementById('chat-messages').textContent)
+ .toContain('Manual send failed before hydration settled');
+ expect(window.location.pathname).toBe(`/chat/${SESSION_ID}`);
expect(window.location.search).toBe('');
window.chatComponent.startNewChat();
diff --git a/tests/js/components/research-api-runtime.test.js b/tests/js/components/research-api-runtime.test.js
index 1f61a29a42..b4c1fda106 100644
--- a/tests/js/components/research-api-runtime.test.js
+++ b/tests/js/components/research-api-runtime.test.js
@@ -8,25 +8,33 @@ import '@js/config/urls.js';
import '@js/utils/alert-helpers.js';
import '@js/security/xss-protection.js';
import '@js/utils/form-validation.js';
+import '@js/services/api.js';
import { API_KEY_PROVIDERS } from '../helpers/api-key-providers.js';
const AVAILABLE_MODELS = '/settings/api/available-models';
-// The manual full model refresh: a CSRF-protected POST without a query.
+// Every model load is a CSRF-protected POST: a GET only reads the server's
+// cache. A POST without a query is cache-first, so the manual full refresh
+// adds force_refresh=true.
+const FULL_REFRESH_URL = `${AVAILABLE_MODELS}?force_refresh=true`;
const FULL_REFRESH_REQUEST = { method: 'POST', headers: { 'X-CSRFToken': 'research-csrf' } };
const AVAILABLE_ENGINES = '/settings/api/available-search-engines';
const SETTINGS = '/settings/api';
const START_RESEARCH = '/api/start_research';
const CHAT_SESSIONS = '/api/chat/sessions';
+const AUTH_CONTEXT = 'a'.repeat(64);
+const chatFetchWithCsrfRecovery = window.api.fetchWithCsrfRecovery;
const dropdowns = new Map();
const responseOverrides = new Map();
let fetchMock;
let initialSnapshot;
-function response(body, { ok = true, status = 200 } = {}) {
+function response(body, { ok = true, status = 200, headers = {} } = {}) {
return Promise.resolve({
ok,
status,
+ headers: new globalThis.Headers(headers),
+ redirected: false,
json: vi.fn().mockResolvedValue(body),
text: vi.fn().mockResolvedValue(''),
});
@@ -192,7 +200,17 @@ beforeAll(async () => {
}));
buildForm();
- window.api = { getCsrfToken: vi.fn(() => 'research-csrf') };
+ document.head.replaceChildren();
+ for (const [name, content] of [['csrf-token', 'research-csrf'], ['auth-context', AUTH_CONTEXT]]) {
+ const meta = document.createElement('meta');
+ meta.name = name;
+ meta.content = content;
+ document.head.appendChild(meta);
+ }
+ window.api = {
+ getCsrfToken: vi.fn(() => document.querySelector('meta[name="csrf-token"]').content),
+ fetchWithCsrfRecovery: chatFetchWithCsrfRecovery,
+ };
window.ui = { showAlert: vi.fn(), showMessage: vi.fn() };
window.RESEARCH_STATUS = { QUEUED: 'queued', IN_PROGRESS: 'in_progress' };
window.setupCustomDropdown = vi.fn((input, _list, getOptions, onSelect) => {
@@ -243,6 +261,8 @@ beforeAll(async () => {
});
beforeEach(() => {
+ document.querySelector('meta[name="csrf-token"]').content = 'research-csrf';
+ document.querySelector('meta[name="auth-context"]').content = AUTH_CONTEXT;
responseOverrides.clear();
fetchMock.mockClear();
fetchMock.mockImplementation(routeFetch);
@@ -790,7 +810,18 @@ it('does not claim a rejected provider save succeeded', async () => {
});
const provider = document.getElementById('model_provider');
provider.disabled = false;
+ // research.js is loaded once for this file, so its provider list is
+ // whatever the last applied catalog advertised. concurrentModelCatalog()
+ // has no ANTHROPIC_ENDPOINT, and when a test using it ran first, this
+ // value selected nothing and the change handler saw ''. Add the option
+ // like the QwenCloud test does, so the result does not depend on order.
+ if (!provider.querySelector('option[value="ANTHROPIC_ENDPOINT"]')) {
+ const anthropicOption = document.createElement('option');
+ anthropicOption.value = 'ANTHROPIC_ENDPOINT';
+ provider.appendChild(anthropicOption);
+ }
provider.value = 'ANTHROPIC_ENDPOINT';
+ expect(provider.value).toBe('ANTHROPIC_ENDPOINT');
provider.dispatchEvent(new Event('change'));
await vi.waitFor(() => {
@@ -882,11 +913,247 @@ it('surfaces a rejected chat-session detail and leaves the form retryable', asyn
});
expect(document.getElementById('start-research-btn').disabled).toBe(false);
expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
- expect(fetchMock).toHaveBeenCalledWith(CHAT_SESSIONS, expect.objectContaining({
+ const creates = fetchMock.mock.calls.filter(([url]) => url === CHAT_SESSIONS);
+ expect(creates).toHaveLength(1);
+ expect(creates[0][1]).toMatchObject({
method: 'POST',
- headers: expect.objectContaining({ 'X-CSRFToken': 'research-csrf' }),
body: JSON.stringify({ initial_query: 'A current research query' }),
- }));
+ });
+ expect(new globalThis.Headers(creates[0][1].headers).get('X-CSRFToken')).toBe('research-csrf');
+ expect(new globalThis.Headers(creates[0][1].headers).get('X-LDR-Auth-Context')).toBe(AUTH_CONTEXT);
+});
+
+async function withCapturedChatLocation(run) {
+ const ownLocation = Object.getOwnPropertyDescriptor(window, 'location');
+ const startHref = 'http://localhost/';
+ const fakeLocation = { href: startHref, pathname: '/' };
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: fakeLocation,
+ });
+ try {
+ return await run(fakeLocation, startHref);
+ } finally {
+ if (ownLocation) {
+ Object.defineProperty(window, 'location', ownLocation);
+ } else {
+ delete window.location;
+ }
+ }
+}
+
+// Exercise both real main-form POSTs and capture its final navigation.
+async function submitChatAndCaptureNavigation(sessionId) {
+ return withCapturedChatLocation(async (fakeLocation, startHref) => {
+ selectMode('chat');
+ responseOverrides.set(CHAT_SESSIONS, {
+ body: { success: true, session_id: sessionId },
+ });
+ responseOverrides.set(`${CHAT_SESSIONS}/${encodeURIComponent(sessionId)}/messages`, {
+ body: { success: true, research_id: 'started-research' },
+ });
+ submit();
+ await vi.waitFor(() => {
+ expect(fakeLocation.href).not.toBe(startHref);
+ expect(document.getElementById('start-research-btn').disabled)
+ .toBe(false);
+ });
+ return fakeLocation.href;
+ });
+}
+
+it('posts the chat query once with its original login before opening a clean URL', async () => {
+ const setItem = vi.spyOn(window.sessionStorage, 'setItem');
+ try {
+ const target = await submitChatAndCaptureNavigation('created-session');
+ expect(target).toBe('/chat/created-session');
+ expect(setItem).not.toHaveBeenCalled();
+ const writes = fetchMock.mock.calls.filter(([url]) => url.startsWith(CHAT_SESSIONS));
+ expect(writes.map(([url]) => url)).toEqual([
+ CHAT_SESSIONS,
+ `${CHAT_SESSIONS}/created-session/messages`,
+ ]);
+ expect(JSON.parse(writes[0][1].body)).toEqual({ initial_query: 'A current research query' });
+ expect(JSON.parse(writes[1][1].body)).toEqual({
+ content: 'A current research query', trigger_research: true,
+ });
+ for (const [, options] of writes) {
+ expect(options.method).toBe('POST');
+ expect(new globalThis.Headers(options.headers).get('X-CSRFToken')).toBe('research-csrf');
+ expect(new globalThis.Headers(options.headers).get('X-LDR-Auth-Context')).toBe(AUTH_CONTEXT);
+ }
+ } finally {
+ setItem.mockRestore();
+ }
+});
+
+it('starts chat without a storage or URL fallback when browser storage is disabled', async () => {
+ const setItem = vi.spyOn(window.sessionStorage, 'setItem')
+ .mockImplementation(() => {
+ throw new Error('Storage is disabled');
+ });
+ try {
+ const target = await submitChatAndCaptureNavigation('no-storage-session');
+ expect(setItem).not.toHaveBeenCalled();
+ expect(target).toBe('/chat/no-storage-session');
+ } finally {
+ setItem.mockRestore();
+ }
+});
+
+it('holds submit ownership through session creation and message acceptance', async () => {
+ const creation = deferred();
+ const message = deferred();
+ const createdId = 'owned-session';
+ const messageUrl = `${CHAT_SESSIONS}/${createdId}/messages`;
+ fetchMock.mockImplementation((url, options) => {
+ if (url === CHAT_SESSIONS) return creation.promise;
+ if (url === messageUrl) return message.promise;
+ return routeFetch(url, options);
+ });
+ await withCapturedChatLocation(async (location, initialHref) => {
+ selectMode('chat');
+ submit();
+ submit();
+ expect(fetchMock.mock.calls.filter(([url]) => url === CHAT_SESSIONS)).toHaveLength(1);
+ expect(location.href).toBe(initialHref);
+ expect(document.getElementById('start-research-btn').disabled).toBe(true);
+ expect(fetchMock.mock.calls.some(([url]) => url === messageUrl)).toBe(false);
+
+ // The accepted submission retains its original input across both awaits.
+ document.getElementById('query').value = 'A later edit';
+ creation.resolve(await response({ success: true, session_id: createdId }));
+ await vi.waitFor(() => expect(fetchMock.mock.calls.some(([url]) => url === messageUrl)).toBe(true));
+ submit();
+ expect(fetchMock.mock.calls.filter(([url]) => url === messageUrl)).toHaveLength(1);
+ expect(location.href).toBe(initialHref);
+ expect(document.getElementById('start-research-btn').disabled).toBe(true);
+ const sent = fetchMock.mock.calls.find(([url]) => url === messageUrl);
+ expect(JSON.parse(sent[1].body).content).toBe('A current research query');
+
+ message.resolve(await response({ success: true, research_id: 'accepted-research' }));
+ await vi.waitFor(() => {
+ expect(location.href).toBe(`/chat/${createdId}`);
+ expect(document.getElementById('start-research-btn').disabled).toBe(false);
+ });
+ expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
+ });
+});
+
+it.each([
+ [400, false], [401, false], [403, false], [404, false],
+ [409, false], [429, false], [500, true], [200, true],
+])('keeps a rejected message (%s) retryable without replaying it', async (status, uncertain) => {
+ const messageUrl = `${CHAT_SESSIONS}/rejected-session/messages`;
+ responseOverrides.set(CHAT_SESSIONS, { body: { success: true, session_id: 'rejected-session' } });
+ responseOverrides.set(messageUrl, {
+ body: { success: false, detail: 'Chat request rejected' },
+ ok: status >= 200 && status < 300, status,
+ });
+ await withCapturedChatLocation(async (location, initialHref) => {
+ selectMode('chat');
+ submit();
+ await vi.waitFor(() => {
+ expect(document.getElementById('research-alert').textContent).toContain('Chat request rejected');
+ expect(document.getElementById('start-research-btn').disabled).toBe(false);
+ });
+ expect(location.href).toBe(initialHref);
+ expect(document.getElementById('query').value).toBe('A current research query');
+ expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
+ expect(fetchMock.mock.calls.filter(([url]) => url === CHAT_SESSIONS)).toHaveLength(1);
+ expect(fetchMock.mock.calls.filter(([url]) => url === messageUrl)).toHaveLength(1);
+ expect(fetchMock.mock.calls.some(([url]) => url === '/auth/csrf-token')).toBe(false);
+ const recovery = document.querySelector('#research-alert a');
+ if (uncertain) expect(recovery?.getAttribute('href')).toBe('/chat/rejected-session');
+ else expect(recovery).toBeNull();
+ });
+});
+
+it.each(['network', 'invalid-json'])('offers read-only recovery after an uncertain %s message response', async (failure) => {
+ const messageUrl = `${CHAT_SESSIONS}/uncertain-session/messages`;
+ responseOverrides.set(CHAT_SESSIONS, { body: { success: true, session_id: 'uncertain-session' } });
+ fetchMock.mockImplementation((url, options) => {
+ if (url === messageUrl) {
+ if (failure === 'network') return Promise.reject(new Error('Network interrupted'));
+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.reject(new Error('Invalid JSON')) });
+ }
+ return routeFetch(url, options);
+ });
+ await withCapturedChatLocation(async (location, initialHref) => {
+ selectMode('chat');
+ submit();
+ await vi.waitFor(() => {
+ expect(document.querySelector('#research-alert a')?.getAttribute('href')).toBe('/chat/uncertain-session');
+ expect(document.getElementById('start-research-btn').disabled).toBe(false);
+ });
+ expect(location.href).toBe(initialHref);
+ expect(document.getElementById('query').value).toBe('A current research query');
+ expect(fetchMock.mock.calls.filter(([url]) => url === CHAT_SESSIONS)).toHaveLength(1);
+ expect(fetchMock.mock.calls.filter(([url]) => url === messageUrl)).toHaveLength(1);
+ expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
+ });
+});
+
+it('uses a same-login CSRF refresh only before a rejected handler and sends one message', async () => {
+ const id = 'refreshed-session';
+ let creates = 0;
+ fetchMock.mockImplementation((url, options) => {
+ if (url === CHAT_SESSIONS) {
+ creates++;
+ if (creates === 1) return response({ detail: 'CSRF rejected' }, {
+ ok: false, status: 403, headers: { 'X-LDR-CSRF-Rejected': '1' },
+ });
+ return response({ success: true, session_id: id });
+ }
+ if (url === '/auth/csrf-token') return response({
+ auth_context: AUTH_CONTEXT, csrf_token: 'fresh-same-login',
+ });
+ return routeFetch(url, options);
+ });
+ expect(await submitChatAndCaptureNavigation(id)).toBe(`/chat/${id}`);
+ const writes = fetchMock.mock.calls.filter(([url]) => url.startsWith(CHAT_SESSIONS));
+ expect(writes.map(([url]) => url)).toEqual([CHAT_SESSIONS, CHAT_SESSIONS, `${CHAT_SESSIONS}/${id}/messages`]);
+ expect(writes.map(([, options]) => new globalThis.Headers(options.headers).get('X-CSRFToken')))
+ .toEqual(['research-csrf', 'fresh-same-login', 'fresh-same-login']);
+ expect(writes.map(([, options]) => new globalThis.Headers(options.headers).get('X-LDR-Auth-Context')))
+ .toEqual([AUTH_CONTEXT, AUTH_CONTEXT, AUTH_CONTEXT]);
+});
+
+it('does not replay either write under a replacement login during CSRF recovery', async () => {
+ responseOverrides.set(CHAT_SESSIONS, {
+ body: { detail: 'CSRF rejected' }, ok: false, status: 403,
+ headers: { 'X-LDR-CSRF-Rejected': '1' },
+ });
+ responseOverrides.set('/auth/csrf-token', {
+ body: { detail: 'Your sign-in changed' }, ok: false, status: 409,
+ });
+ await withCapturedChatLocation(async (location, initialHref) => {
+ selectMode('chat');
+ submit();
+ await vi.waitFor(() => {
+ expect(document.getElementById('research-alert').textContent).toContain('Your sign-in changed');
+ expect(document.getElementById('start-research-btn').disabled).toBe(false);
+ });
+ expect(location.href).toBe(initialHref);
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([CHAT_SESSIONS, '/auth/csrf-token']);
+ expect(new globalThis.Headers(fetchMock.mock.calls[1][1].headers).get('X-LDR-Auth-Context')).toBe(AUTH_CONTEXT);
+ });
+});
+
+it('fails without sending when the protected request helper is unavailable', async () => {
+ const saved = window.api.fetchWithCsrfRecovery;
+ delete window.api.fetchWithCsrfRecovery;
+ try {
+ selectMode('chat');
+ submit();
+ expect(document.getElementById('research-alert').textContent).toContain('Reload this page');
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(document.getElementById('start-research-btn').disabled).toBe(false);
+ expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
+ } finally {
+ window.api.fetchWithCsrfRecovery = saved;
+ }
});
it('anchors the custom-model hint under ldr-prefixed research markup', async () => {
@@ -938,21 +1205,22 @@ async function concurrentModelRequests() {
// Seed the private cache through the real refresh handler, so each case
// begins with the same catalog even though this runtime is initialized once.
const refreshButton = document.getElementById('model-refresh');
- responseOverrides.set(AVAILABLE_MODELS, {
+ responseOverrides.set(FULL_REFRESH_URL, {
body: concurrentModelCatalog(),
});
refreshButton.click();
await vi.waitFor(() => expect(refreshButton.classList.contains('ldr-loading')).toBe(false));
- // The manual full refresh is a CSRF-protected POST without a query: a
- // GET carrying force_refresh=true answers 405.
- expect(fetchMock).toHaveBeenCalledWith(AVAILABLE_MODELS, FULL_REFRESH_REQUEST);
+ // The manual full refresh is a CSRF-protected POST ?force_refresh=true:
+ // a GET carrying force_refresh=true answers 405, and a POST without it
+ // would reuse the server's cache.
+ expect(fetchMock).toHaveBeenCalledWith(FULL_REFRESH_URL, FULL_REFRESH_REQUEST);
const requests = [];
fetchMock.mockImplementation((url, options = {}) => {
if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
const provider = new URL(url, 'http://localhost').searchParams.get('refresh_provider');
const pending = deferred();
- requests.push({ provider, options, pending });
+ requests.push({ url, provider, options, pending });
return pending.promise;
}
if (options.method === 'PUT') return response({ status: 'ok' });
@@ -974,6 +1242,7 @@ async function concurrentModelRequests() {
refreshButton.click();
await vi.waitFor(() => expect(requests).toHaveLength(count + 1));
expect(requests[count].provider).toBeNull();
+ expect(requests[count].url).toBe(FULL_REFRESH_URL);
expect(requests[count].options).toEqual(FULL_REFRESH_REQUEST);
return requests[count];
},
diff --git a/tests/js/components/research-model-provider.test.js b/tests/js/components/research-model-provider.test.js
index 9970fecf82..53a8ff0e90 100644
--- a/tests/js/components/research-model-provider.test.js
+++ b/tests/js/components/research-model-provider.test.js
@@ -9,15 +9,15 @@
* queued fetches. A separate module runs them in isolation against a clean
* queue.
*
- * The dropdown is populated from GET /settings/api/available-models where
+ * The dropdown is populated from POST /settings/api/available-models where
* each entry carries { value, label, disabled, disabled_reason }. The
* change handlers for the egress-scope select and the local-only checkbox
* must save the new setting first and re-fetch afterwards — otherwise the
* backend reads the OLD policy and the dropdown stays stale. We invalidate
* the client-side 5-minute cache before the re-fetch so it actually
* round-trips the server (the server rebuilds provider_options from the
- * current policy on every request, so the bare cached endpoint is enough
- * — the slow POST refresh path is reserved for cases where the
+ * current policy on every request, so a cache-eligible POST is enough
+ * — the force_refresh=true path is reserved for cases where the
* model *lists* themselves need to be re-discovered).
*/
@@ -87,6 +87,7 @@ function buildForm() {
let fetchMock;
let initAvailableModelsUrl;
+let initAvailableModelsOptions;
beforeAll(async () => {
fetchMock = vi.fn(() =>
@@ -118,10 +119,10 @@ beforeAll(async () => {
// Capture the URL of the synchronous-init /available-models request
// so we can assert the initial read uses the model-list URL. beforeEach calls
// mockClear() which would wipe this otherwise.
- initAvailableModelsUrl =
- fetchMock.mock.calls
- .filter(([u]) => typeof u === 'string' && u.startsWith(AVAILABLE_MODELS))
- .map(([u]) => u)[0] ?? null;
+ [initAvailableModelsUrl, initAvailableModelsOptions] =
+ fetchMock.mock.calls.find(
+ ([u]) => typeof u === 'string' && u.startsWith(AVAILABLE_MODELS)
+ ) ?? [null, null];
await Promise.resolve();
await Promise.resolve();
});
@@ -240,12 +241,15 @@ describe('research form — model provider dropdown', () => {
// beforeEach clears the mock — so we can assert the exact URL
// the mount-time loadModelOptions used. Using the cached
// endpoint is fine because the server rebuilds provider_options
- // from the current policy on every request; POST refresh
+ // from the current policy on every request; force_refresh=true
// would re-discover every provider's models (~1s+ wall clock)
// for no benefit on mount.
expect(initAvailableModelsUrl).not.toBeNull();
expect(initAvailableModelsUrl.startsWith(AVAILABLE_MODELS)).toBe(true);
expect(initAvailableModelsUrl).toBe(AVAILABLE_MODELS);
+ expect(initAvailableModelsOptions).toEqual({
+ method: 'POST', headers: { 'X-CSRFToken': 'test-csrf' },
+ });
});
it('renders disabled <option> with the policy reason appended to the label', async () => {
@@ -306,7 +310,7 @@ describe('research form — model provider dropdown', () => {
// And a re-fetch of the providers list (cache miss because we
// invalidated after the PUT). The URL is the bare cached
// endpoint — the server rebuilds provider_options from the
- // current policy every request, so POST refresh is
+ // current policy every request, so force_refresh=true is
// unnecessary here.
await vi.waitFor(
() => {
@@ -320,7 +324,7 @@ describe('research form — model provider dropdown', () => {
{ timeout: 1000 }
);
- // Ordering: the PUT must appear in the call log BEFORE the GET.
+ // Ordering: the setting PUT must finish before model discovery POST.
const allCalls = fetchMock.mock.calls;
const putIndex = allCalls.findIndex(
([u, init]) =>
@@ -334,13 +338,17 @@ describe('research form — model provider dropdown', () => {
expect(putIndex).toBeGreaterThanOrEqual(0);
expect(getIndex).toBeGreaterThanOrEqual(0);
expect(putIndex).toBeLessThan(getIndex);
+ expect(allCalls[getIndex]).toEqual([
+ AVAILABLE_MODELS,
+ { method: 'POST', headers: { 'X-CSRFToken': 'test-csrf' } },
+ ]);
- // And specifically NOT the slow POST refresh path —
+ // And specifically NOT the slow forced-refresh path —
// its ~1s+ wall-clock cost is what motivated this regression.
const forceRefreshCalls = allCalls.filter(
([u, init]) =>
typeof u === 'string' &&
- u.startsWith(AVAILABLE_MODELS) &&
+ u === `${AVAILABLE_MODELS}?force_refresh=true` &&
init?.method === 'POST'
);
expect(forceRefreshCalls).toHaveLength(0);
@@ -391,11 +399,15 @@ describe('research form — model provider dropdown', () => {
expect(putIndex).toBeGreaterThanOrEqual(0);
expect(getIndex).toBeGreaterThanOrEqual(0);
expect(putIndex).toBeLessThan(getIndex);
+ expect(allCalls[getIndex]).toEqual([
+ AVAILABLE_MODELS,
+ { method: 'POST', headers: { 'X-CSRFToken': 'test-csrf' } },
+ ]);
const forceRefreshCalls = allCalls.filter(
([u, init]) =>
typeof u === 'string' &&
- u.startsWith(AVAILABLE_MODELS) &&
+ u === `${AVAILABLE_MODELS}?force_refresh=true` &&
init?.method === 'POST'
);
expect(forceRefreshCalls).toHaveLength(0);
@@ -779,7 +791,8 @@ it('ignores an older manual model response after a policy refresh completes', as
});
fetchMock.mockImplementation((url, options) => {
if (url.startsWith(AVAILABLE_MODELS)) {
- if (options?.method === 'POST' && !requestedManual) {
+ expect(options).toEqual({ method: 'POST', headers: { 'X-CSRFToken': 'test-csrf' } });
+ if (url === `${AVAILABLE_MODELS}?force_refresh=true` && !requestedManual) {
requestedManual = true;
return manual;
}
@@ -841,7 +854,8 @@ it('clears the model loading state when a superseded request rejects', async ()
let requestedManual = false;
fetchMock.mockImplementation((url, options) => {
if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
- if (options?.method === 'POST' && !requestedManual) {
+ expect(options).toEqual({ method: 'POST', headers: { 'X-CSRFToken': 'test-csrf' } });
+ if (url === `${AVAILABLE_MODELS}?force_refresh=true` && !requestedManual) {
requestedManual = true;
return manual;
}
@@ -927,7 +941,8 @@ it('keeps the loader bounded when a superseded request succeeds', async () => {
let requestedManual = false;
fetchMock.mockImplementation((url, options) => {
if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
- if (options?.method === 'POST' && !requestedManual) {
+ expect(options).toEqual({ method: 'POST', headers: { 'X-CSRFToken': 'test-csrf' } });
+ if (url === `${AVAILABLE_MODELS}?force_refresh=true` && !requestedManual) {
requestedManual = true;
return manual;
}
diff --git a/tests/js/components/research.test.js b/tests/js/components/research.test.js
index b9d3b63a70..3646c08d54 100644
--- a/tests/js/components/research.test.js
+++ b/tests/js/components/research.test.js
@@ -84,7 +84,7 @@ function buildForm() {
}
let fetchMock;
-// Number of GET /available-models requests fired synchronously during init.
+// Number of cache-eligible POST /available-models requests fired during init.
// Both loadModelOptions(false) call sites run synchronously inside
// initializeResearch (before any await), so a synchronous capture right after
// dispatch deterministically distinguishes "loaded once" (1) from the old
@@ -113,7 +113,12 @@ beforeAll(async () => {
})
);
globalThis.fetch = fetchMock;
- window.api = { getCsrfToken: () => 'test-csrf' };
+ window.api = {
+ getCsrfToken: () => 'test-csrf',
+ // The real protected helper is exercised by research-api-runtime;
+ // this fixture isolates the form's model-selection guard.
+ fetchWithCsrfRecovery: (url, options) => fetchMock(url, options),
+ };
window.RESEARCH_STATUS = { QUEUED: 'queued', IN_PROGRESS: 'in_progress' };
buildForm();
@@ -312,7 +317,7 @@ describe('research form — model-required guard', () => {
expect(body.query).toBe('What is quantum computing?');
});
- it('does NOT require a model in chat mode (chat never sends the model field)', () => {
+ it('does NOT require a model in chat mode (chat never sends the model field)', async () => {
document.querySelector('input[name="research_mode"][value="quick"]').checked = false;
document.querySelector('input[name="research_mode"][value="chat"]').checked = true;
document.getElementById('model_hidden').value = ''; // no model selected
@@ -325,6 +330,10 @@ describe('research form — model-required guard', () => {
// research endpoint).
expect(callsTo(CHAT_SESSIONS)).toHaveLength(1);
expect(callsTo(START_RESEARCH)).toHaveLength(0);
+ await vi.waitFor(() => {
+ expect(document.getElementById('start-research-btn').disabled).toBe(false);
+ expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
+ });
});
it('blocks on an empty query even when a model is selected', () => {
diff --git a/tests/js/components/settings-fetch-error-handling.test.js b/tests/js/components/settings-fetch-error-handling.test.js
index fb99c2a347..d127a87695 100644
--- a/tests/js/components/settings-fetch-error-handling.test.js
+++ b/tests/js/components/settings-fetch-error-handling.test.js
@@ -55,8 +55,7 @@ describe('settings request error handling', () => {
];
const excludedPatterns = [
'const response = await fetch(URLS.SETTINGS_API.OLLAMA_STATUS, {',
- "fetch(url, { method: 'POST', headers: { 'X-CSRFToken': csrfToken } })",
- ': fetch(url))',
+ 'const request = fetch(url, {',
'const request = fetch(URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES)',
];
const handledCalls = SETTINGS_SOURCE.match(
@@ -71,7 +70,7 @@ describe('settings request error handling', () => {
expect(SETTINGS_SOURCE).toContain(pattern);
});
expect(handledCalls).toHaveLength(6);
- expect(rawCalls).toHaveLength(4);
+ expect(rawCalls).toHaveLength(3);
});
it('preserves the settings domain success and failure checks', () => {
diff --git a/tests/js/components/settings-refresh-ownership-runtime.test.js b/tests/js/components/settings-refresh-ownership-runtime.test.js
index ac15efcf13..47a65204bf 100644
--- a/tests/js/components/settings-refresh-ownership-runtime.test.js
+++ b/tests/js/components/settings-refresh-ownership-runtime.test.js
@@ -114,6 +114,7 @@ it('keeps the newest overlapping model and search refresh results', async () =>
let captureSearchRefreshes = false;
let currentModels = baselineModels;
let currentEngines = baselineEngines;
+ let expectedCsrfToken = 'csrf-refresh-ownership';
const fetchMock = vi.fn((url, options) => {
if (url === URLS.SETTINGS_API.BASE) {
@@ -128,13 +129,18 @@ it('keeps the newest overlapping model and search refresh results', async () =>
if (url === URLS.SETTINGS_API.BACKUP_STATUS) {
return Promise.resolve(jsonResponse({ enabled: false, count: 0, backups: [] }));
}
- if (url === URLS.SETTINGS_API.AVAILABLE_MODELS && options?.method === 'POST') {
- expect(options.headers['X-CSRFToken']).toBe('csrf-refresh-ownership');
+ if (url === `${URLS.SETTINGS_API.AVAILABLE_MODELS}?force_refresh=true`) {
+ expect(options).toEqual({
+ method: 'POST', headers: { 'X-CSRFToken': expectedCsrfToken },
+ });
const request = deferred();
modelRefreshes.push(request);
return request.promise;
}
if (url === URLS.SETTINGS_API.AVAILABLE_MODELS) {
+ expect(options).toEqual({
+ method: 'POST', headers: { 'X-CSRFToken': expectedCsrfToken },
+ });
return Promise.resolve(jsonResponse(currentModels));
}
if (url === URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES) {
@@ -173,6 +179,13 @@ it('keeps the newest overlapping model and search refresh results', async () =>
const modelRefreshButton = document.getElementById('llm.model-refresh');
expect(modelRefreshButton).not.toBeNull();
+ expect(fetchMock.mock.calls.filter(
+ ([url]) => url === URLS.SETTINGS_API.AVAILABLE_MODELS
+ ).length).toBeGreaterThan(0);
+ expect(modelRefreshes).toHaveLength(0);
+ // Read the current token for each request, including after a token rotation.
+ expectedCsrfToken = 'csrf-refreshed-ownership';
+ document.querySelector('[name="csrf-token"]').content = expectedCsrfToken;
modelRefreshButton.click();
modelRefreshButton.click();
expect(modelRefreshes).toHaveLength(2);
diff --git a/tests/js/pages/benchmark-endpoint-runtime.test.js b/tests/js/pages/benchmark-endpoint-runtime.test.js
index 8af00ca8d1..5e0f13fc8d 100644
--- a/tests/js/pages/benchmark-endpoint-runtime.test.js
+++ b/tests/js/pages/benchmark-endpoint-runtime.test.js
@@ -311,7 +311,10 @@ it('loads and force-refreshes evaluation providers and model options', async ()
harness.loadEvaluationModelsFromAPI();
await vi.advanceTimersByTimeAsync(500);
- expect(fetchMock.mock.calls[0][0]).toBe('/settings/api/available-models');
+ expect(fetchMock.mock.calls[0]).toEqual([
+ '/settings/api/available-models',
+ { method: 'POST', headers: { 'X-CSRFToken': 'csrf-benchmark' } },
+ ]);
expect(window.evaluationModels.openai).toEqual([
{ value: 'initial-model', label: 'initial-model' },
]);
@@ -320,7 +323,7 @@ it('loads and force-refreshes evaluation providers and model options', async ()
await flushPromises();
expect(fetchMock.mock.calls[1]).toEqual([
- '/settings/api/available-models',
+ '/settings/api/available-models?force_refresh=true',
{ method: 'POST', headers: { 'X-CSRFToken': 'csrf-benchmark' } },
]);
expect(harness.getProviders()).toEqual([
@@ -359,7 +362,10 @@ it('starts the initial model request when an empty dropdown asks for options', a
await flushPromises();
expect(fetchMock).toHaveBeenCalledOnce();
- expect(fetchMock).toHaveBeenCalledWith('/settings/api/available-models');
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/settings/api/available-models',
+ { method: 'POST', headers: { 'X-CSRFToken': 'csrf-benchmark' } },
+ );
expect(window.evaluationModels.openai).toEqual([
{ value: 'initial-model', label: 'initial-model' },
]);
@@ -388,7 +394,7 @@ it('does not schedule a fallback request while force refresh is in flight', asyn
expect(fetchMock).toHaveBeenCalledOnce();
expect(fetchMock).toHaveBeenCalledWith(
- '/settings/api/available-models',
+ '/settings/api/available-models?force_refresh=true',
{ method: 'POST', headers: { 'X-CSRFToken': 'csrf-benchmark' } },
);
@@ -425,8 +431,14 @@ it('does not let a deferred initial model response overwrite a force refresh', a
vi.useFakeTimers();
const initialResponse = deferred();
const refreshResponse = deferred();
- const fetchMock = vi.fn((_url, options) => {
- if (options?.method === 'POST') return refreshResponse.promise;
+ const fetchMock = vi.fn((url, options) => {
+ expect(options).toEqual({
+ method: 'POST', headers: { 'X-CSRFToken': 'csrf-benchmark' },
+ });
+ if (url === '/settings/api/available-models?force_refresh=true') {
+ return refreshResponse.promise;
+ }
+ expect(url).toBe('/settings/api/available-models');
return initialResponse.promise;
});
vi.stubGlobal('fetch', fetchMock);
@@ -515,7 +527,7 @@ it('cancels the pending debounced load when refresh is requested immediately', a
expect(fetchMock).toHaveBeenCalledOnce();
expect(fetchMock.mock.calls[0]).toEqual([
- '/settings/api/available-models',
+ '/settings/api/available-models?force_refresh=true',
{ method: 'POST', headers: { 'X-CSRFToken': 'csrf-benchmark' } },
]);
expect(window.evaluationModels.openai[0].value).toBe('manual-model');
diff --git a/tests/js/pages/news-subscription-models-runtime.test.js b/tests/js/pages/news-subscription-models-runtime.test.js
new file mode 100644
index 0000000000..7101d7b5ab
--- /dev/null
+++ b/tests/js/pages/news-subscription-models-runtime.test.js
@@ -0,0 +1,118 @@
+/** Model discovery requests from the checked-in news subscription template. */
+
+import { resolve } from 'node:path';
+
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/news-subscription-form.html',
+);
+const AVAILABLE_MODELS = '/settings/api/available-models';
+const MODEL_PAYLOAD = {
+ provider_options: [
+ { value: 'OLLAMA', label: 'Ollama' },
+ { value: 'OPENAI_ENDPOINT', label: 'Custom endpoint' },
+ {
+ value: 'OPENAI', label: 'OpenAI', disabled: true,
+ disabled_reason: 'Blocked by local-only policy',
+ },
+ ],
+ providers: {
+ ollama_models: [{ value: 'baseline-model', label: 'Baseline model' }],
+ openai_endpoint_models: [{ value: 'endpoint-model', label: 'Endpoint model' }],
+ },
+};
+
+function compileModelsLoader(modelDropdownInstance) {
+ return compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['getCSRFToken', 'loadModelsForProvider', 'loadProviders'],
+ dependencies: { modelDropdownInstance },
+ preamble: `
+ let currentProvider = 'ollama';
+ const defaultModel = 'baseline-model';
+ let modelOptions = [];
+ `,
+ returnExpression: '{ loadProviders, loadModelsForProvider }',
+ });
+}
+
+beforeEach(() => {
+ document.head.insertAdjacentHTML(
+ 'beforeend', '<meta name="csrf-token" content="csrf-news-initial">',
+ );
+ document.body.innerHTML = `
+ <select id="subscription-provider"></select>
+ <input id="subscription-model">
+ <div id="custom-endpoint-container" style="display: none"></div>
+ `;
+ window.updateDropdownOptions = vi.fn();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.updateDropdownOptions;
+ document.head.querySelector('[name="csrf-token"]')?.remove();
+ document.body.replaceChildren();
+});
+
+it('loads providers and initial models using cache-eligible POSTs with CSRF', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true, json: async () => MODEL_PAYLOAD,
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dropdown = { setValue: vi.fn() };
+
+ await compileModelsLoader(dropdown).loadProviders();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ for (const call of fetchMock.mock.calls) {
+ expect(call).toEqual([
+ AVAILABLE_MODELS,
+ {
+ method: 'POST', credentials: 'same-origin',
+ headers: { 'X-CSRFToken': 'csrf-news-initial' },
+ },
+ ]);
+ }
+ const provider = document.getElementById('subscription-provider');
+ expect(provider.value).toBe('OLLAMA');
+ const blockedOption = Array.from(provider.options).find(option => option.value === 'OPENAI');
+ expect(blockedOption.disabled).toBe(true);
+ expect(blockedOption.textContent).toContain('Blocked by local-only policy');
+ expect(window.updateDropdownOptions).toHaveBeenLastCalledWith(
+ document.getElementById('subscription-model'), MODEL_PAYLOAD.providers.ollama_models,
+ );
+ expect(dropdown.setValue).toHaveBeenCalledWith('baseline-model', false);
+});
+
+it('uses the current CSRF token when a provider change loads its models', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true, json: async () => MODEL_PAYLOAD,
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dropdown = { setValue: vi.fn() };
+ await compileModelsLoader(dropdown).loadProviders();
+ fetchMock.mockClear();
+ window.updateDropdownOptions.mockClear();
+ dropdown.setValue.mockClear();
+ document.querySelector('[name="csrf-token"]').content = 'csrf-news-rotated';
+
+ const provider = document.getElementById('subscription-provider');
+ provider.value = 'OPENAI_ENDPOINT';
+ provider.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(() => expect(window.updateDropdownOptions).toHaveBeenCalledWith(
+ document.getElementById('subscription-model'),
+ MODEL_PAYLOAD.providers.openai_endpoint_models,
+ ));
+ expect(fetchMock).toHaveBeenCalledExactlyOnceWith(AVAILABLE_MODELS, {
+ method: 'POST', credentials: 'same-origin',
+ headers: { 'X-CSRFToken': 'csrf-news-rotated' },
+ });
+ expect(document.getElementById('custom-endpoint-container').style.display).toBe('block');
+ expect(dropdown.setValue).not.toHaveBeenCalled();
+});
diff --git a/tests/security/test_cookie_security.py b/tests/security/test_cookie_security.py
index 0b68ced65b..626388c741 100644
--- a/tests/security/test_cookie_security.py
+++ b/tests/security/test_cookie_security.py
@@ -27,7 +27,7 @@ SURVEY — covered elsewhere, deliberately NOT duplicated
works`` / ``test_localhost_http_no_secure_flag_in_production`` — that
``GET /auth/login`` sets a session cookie and that plain HTTP never carries
Secure: ``tests/web/test_session_cookie_behavior.py``
- ::test_unauthenticated_session_cookie_is_strict_and_httponly and
+ ::test_unauthenticated_session_cookie_is_lax_and_httponly and
::test_http_request_does_not_get_secure_session_cookie (same full stack,
same middleware taken out of testing mode).
* ``test_testing_mode_no_secure_flag`` —
diff --git a/tests/security/test_csrf_coverage.py b/tests/security/test_csrf_coverage.py
index 0380c30056..dcf0fe91b4 100644
--- a/tests/security/test_csrf_coverage.py
+++ b/tests/security/test_csrf_coverage.py
@@ -745,20 +745,67 @@ def test_index_all_post_with_a_valid_token_passes_the_middleware():
)
+def test_model_get_reads_the_cache_and_only_a_tokened_post_discovers(
+ authenticated_client,
+):
+ """A legacy GET cannot clear models; a tokened POST reaches discovery.
+
+ The plain GET at the end still builds the provider options from the
+ current policy, but never discovers providers: GET reads only the
+ model cache.
+ """
+ client = authenticated_client
+ path = "/settings/api/available-models"
+ with (
+ patch(
+ "local_deep_research.llm.providers.get_discovered_provider_options",
+ return_value=[],
+ ) as provider_options,
+ patch(
+ "local_deep_research.llm.providers.discover_providers",
+ return_value={},
+ ) as model_providers,
+ ):
+ legacy = client.get(f"{path}?force_refresh=true")
+ assert legacy.status_code == 405, legacy.text
+ assert legacy.headers["allow"] == "POST"
+ provider_options.assert_not_called()
+ model_providers.assert_not_called()
+
+ with _no_token(client):
+ bare = client.post(path)
+ assert _csrf_refused(bare), bare.text
+ provider_options.assert_not_called()
+ model_providers.assert_not_called()
+
+ refreshed = client.post(f"{path}?force_refresh=true")
+ assert refreshed.status_code == 200, refreshed.text
+ assert "provider_options" in refreshed.json()
+ assert provider_options.call_count == 1
+ model_providers.assert_called_once_with()
+
+ cached = client.get(path)
+ assert cached.status_code == 200, cached.text
+ assert provider_options.call_count == 2
+ model_providers.assert_called_once_with()
+
+
@pytest.mark.parametrize(
"query",
["?refresh_provider=openai", "?force_refresh=true", ""],
- ids=["targeted", "force-refresh-flag", "full-without-query"],
+ ids=["targeted", "force-refresh-flag", "cache-first-without-query"],
)
def test_model_refresh_requires_post_and_csrf(authenticated_client, query):
- """A model refresh calls providers with the user's stored keys and
- rewrites their cached ``ProviderModel`` rows (``force_refresh=true``
- used to delete every cached row on a plain GET), so it is a mutation:
- a GET carrying ``refresh_provider`` or ``force_refresh=true`` answers
- 405 with ``Allow: POST`` without reaching discovery, a POST with no
- token is refused by the middleware, and a tokened POST reaches the
- handler. A plain GET read, and a GET with ``force_refresh=false``,
- still reach the handler (controls).
+ """Every POST to the model endpoint can call providers with the user's
+ stored keys and rewrite their cached ``ProviderModel`` rows: a targeted
+ refresh, ``force_refresh=true`` (which used to delete every cached row
+ on a plain GET), and a cache miss on a POST without a query. So each is
+ a mutation: a GET carrying ``refresh_provider`` or
+ ``force_refresh=true`` answers 405 with ``Allow: POST`` without
+ reaching discovery, a POST with no token is refused by the middleware,
+ and a tokened POST reaches the handler. A plain GET read, and a GET
+ with ``force_refresh=false``, still reach the handler (controls); they
+ read only the model cache.
"""
client = authenticated_client
path = "/settings/api/available-models"
diff --git a/tests/security/test_followup_and_settings_guards_fastapi.py b/tests/security/test_followup_and_settings_guards_fastapi.py
index d23dae2a38..23c5298918 100644
--- a/tests/security/test_followup_and_settings_guards_fastapi.py
+++ b/tests/security/test_followup_and_settings_guards_fastapi.py
@@ -74,13 +74,16 @@ can never pass because the endpoint was never called at all.
from __future__ import annotations
+import asyncio
import itertools
+import threading
import uuid
-from contextlib import ExitStack
-from datetime import datetime, timezone
+from contextlib import ExitStack, contextmanager
+from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
+import httpx
import pytest
from local_deep_research.constants import ResearchStatus
@@ -534,7 +537,7 @@ def _discovery_probe(client, api_key_setting):
patch(f"{PROVIDERS}.discover_providers", return_value=discovered)
)
response = client.post(
- AVAILABLE_MODELS_PATH,
+ f"{AVAILABLE_MODELS_PATH}?force_refresh=true",
headers={"X-CSRFToken": _csrf(client)},
)
return response, list_models
@@ -641,6 +644,403 @@ class TestCrossProviderCredentialLeak:
assert list_models.call_args.args[0] == CANARY_CREDENTIAL
+def _provider_cache_rows(username):
+ """Fresh SQL snapshots of every column, including IDs and timestamps."""
+ from sqlalchemy import select
+
+ from local_deep_research.database.models.providers import ProviderModel
+
+ with get_user_db_session(username, password=USER_PW) as session:
+ return [
+ dict(row)
+ for row in session.execute(
+ select(*ProviderModel.__table__.columns).order_by(
+ ProviderModel.id
+ )
+ ).mappings()
+ ]
+
+
+def _seed_provider_cache(username, *, expired=False):
+ from local_deep_research.database.models.providers import ProviderModel
+
+ with get_user_db_session(username, password=USER_PW) as session:
+ session.add(
+ ProviderModel(
+ provider="OPENAI",
+ model_key="cached-model",
+ model_label="Cached model",
+ model_metadata={"retained": ["all", "columns"]},
+ last_updated=datetime.now(timezone.utc)
+ - timedelta(hours=25 if expired else 1),
+ )
+ )
+ session.commit()
+
+
+@contextmanager
+def _observe_provider_cache_sql(*, fail_reads=False):
+ """Observe real SQL, optionally fail the actual cache SELECT boundary."""
+ from sqlalchemy import event
+ from sqlalchemy.engine import Engine
+ from sqlalchemy.exc import OperationalError
+
+ observed = SimpleNamespace(reads=[], writes=[])
+
+ def before_execute(_conn, _cursor, statement, parameters, _ctx, _many):
+ sql = statement.lstrip().lower()
+ if "provider_models" not in sql:
+ return
+ if sql.startswith("select"):
+ observed.reads.append(statement)
+ if fail_reads:
+ raise OperationalError(
+ statement,
+ parameters,
+ RuntimeError("private-cache-diagnostic-must-not-escape"),
+ )
+ elif sql.startswith(("insert", "update", "delete", "replace")):
+ observed.writes.append(statement)
+
+ event.listen(Engine, "before_cursor_execute", before_execute)
+ try:
+ yield observed
+ finally:
+ event.remove(Engine, "before_cursor_execute", before_execute)
+
+
+def model_cache_client(live_app):
+ """Keep auth, CSRF and storage real; replace only discovery dependencies.
+
+ Policy behavior has separate route-boundary tests. This fixture isolates
+ the cache-method contract with a known public provider, so a cold GET
+ cannot pass just because an unrelated policy refusal stopped the route.
+ """
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ client, username = _new_user(live_app, "models_cache")
+ token = _csrf(client)
+ assert token
+ list_models = MagicMock(
+ return_value=[{"value": "fresh-model", "label": "Fresh model"}]
+ )
+ provider = SimpleNamespace(
+ api_key_setting="llm.openai.api_key",
+ url_setting=None,
+ list_models_for_api=list_models,
+ )
+ policy_context = EgressContext(
+ scope=EgressScope.PUBLIC_ONLY,
+ primary_engine="wikipedia",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ with (
+ patch(
+ f"{SETTINGS_ROUTER}._resolve_model_discovery_policy",
+ return_value=(
+ policy_context,
+ {"policy.egress_scope": "public_only"},
+ ),
+ ) as policy,
+ patch(
+ f"{PROVIDERS}.get_discovered_provider_options",
+ return_value=[{"value": "OPENAI", "label": "OpenAI"}],
+ ) as options,
+ patch(
+ f"{PROVIDERS}.discover_providers",
+ return_value={
+ "OPENAI": SimpleNamespace(
+ provider_class=provider, provider_name="OpenAI"
+ )
+ },
+ ) as discovery,
+ patch(
+ f"{SETTINGS_ROUTER}._get_setting_from_session",
+ return_value="cache-test-key",
+ ) as credentials,
+ ):
+ # Store the key the stubbed read returns. Since main's #6578 the cache
+ # write re-reads each provider's stored key/URL settings and skips a
+ # provider whose inputs changed while discovery ran, so a stub that
+ # disagreed with the stored (default empty) key made every POST look
+ # superseded and left the cache unwritten.
+ _set_setting(
+ username, provider.api_key_setting, credentials.return_value
+ )
+ yield SimpleNamespace(
+ client=client,
+ username=username,
+ token=token,
+ policy=policy,
+ options=options,
+ discovery=discovery,
+ credentials=credentials,
+ list_models=list_models,
+ )
+
+
+class TestModelCacheMethodContract:
+ """GET is observational; both cache-populating POST modes require CSRF."""
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "forced", [False, True], ids=["ordinary", "forced"]
+ )
+ async def test_cancelled_authenticated_post_preserves_encrypted_cache(
+ self, model_cache_client, monkeypatch, forced
+ ):
+ from local_deep_research.database import thread_local_session
+
+ probe = model_cache_client
+ _seed_provider_cache(probe.username, expired=True)
+ before = _provider_cache_rows(probe.username)
+ started = threading.Event()
+ release = threading.Event()
+ finished = threading.Event()
+ owner = set()
+ original_cleanup = thread_local_session.cleanup_current_thread
+
+ def cleanup():
+ try:
+ return original_cleanup()
+ finally:
+ if threading.get_ident() in owner:
+ finished.set()
+
+ def list_models(*_args):
+ owner.add(threading.get_ident())
+ started.set()
+ assert release.wait(10), "test did not release the provider"
+ return [{"value": "fresh-model", "label": "Fresh model"}]
+
+ monkeypatch.setattr(
+ thread_local_session, "cleanup_current_thread", cleanup
+ )
+ probe.list_models.side_effect = list_models
+ transport = httpx.ASGITransport(app=probe.client.app)
+ with _observe_provider_cache_sql() as sql:
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ # TestClient may use httpx2; share its standard CookieJar.
+ cookies=probe.client.cookies.jar,
+ ) as client:
+ request = asyncio.create_task(
+ client.post(
+ AVAILABLE_MODELS_PATH,
+ params={"force_refresh": str(forced).lower()},
+ headers={"X-CSRFToken": probe.token},
+ )
+ )
+ try:
+ provider_started = await asyncio.to_thread(started.wait, 10)
+ if not provider_started and request.done():
+ response = await request
+ pytest.fail(
+ "discovery returned before reaching the provider: "
+ f"{response.status_code} {response.text[:200]}"
+ )
+ assert provider_started, (
+ "authenticated CSRF-protected discovery did not start"
+ )
+ request.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await request
+ finally:
+ release.set()
+ if not request.done():
+ request.cancel()
+ await asyncio.gather(request, return_exceptions=True)
+ if owner:
+ assert await asyncio.to_thread(finished.wait, 10), (
+ "discovery worker did not clean up"
+ )
+ assert owner and threading.get_ident() not in owner
+ probe.list_models.assert_called_once_with("cache-test-key", None)
+ assert sql.writes == []
+ assert _provider_cache_rows(probe.username) == before
+
+ @pytest.mark.parametrize("state", ["cold", "warm", "expired", "filtered"])
+ def test_get_never_discovers_or_rewrites_cache(
+ self, model_cache_client, state
+ ):
+ probe = model_cache_client
+ if state != "cold":
+ _seed_provider_cache(probe.username, expired=state == "expired")
+ if state == "filtered":
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ probe.policy.return_value = (
+ EgressContext(
+ scope=EgressScope.PRIVATE_ONLY,
+ primary_engine="library",
+ require_local_llm=True,
+ require_local_embeddings=True,
+ ),
+ {"policy.egress_scope": "private_only"},
+ )
+ before = _provider_cache_rows(probe.username)
+ with _observe_provider_cache_sql() as sql:
+ response = probe.client.get(AVAILABLE_MODELS_PATH)
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert set(body) == {
+ "providers",
+ "provider_options",
+ "benchmark_provider_options",
+ }
+ if state == "warm":
+ assert body["providers"]["openai_models"] == [
+ {
+ "value": "cached-model",
+ "label": "Cached model",
+ "provider": "OPENAI",
+ }
+ ]
+ else:
+ assert body["providers"] == {}
+ if state == "filtered":
+ assert body["provider_options"][0]["disabled"] is True
+ assert sql.reads, "The real cache SELECT must run"
+ assert sql.writes == []
+ assert _provider_cache_rows(probe.username) == before
+ probe.discovery.assert_not_called()
+ probe.credentials.assert_not_called()
+ probe.list_models.assert_not_called()
+
+ def test_get_cache_query_error_cannot_fall_through_to_discovery(
+ self, model_cache_client
+ ):
+ probe = model_cache_client
+ _seed_provider_cache(probe.username)
+ before = _provider_cache_rows(probe.username)
+ with _observe_provider_cache_sql(fail_reads=True) as sql:
+ response = probe.client.get(AVAILABLE_MODELS_PATH)
+ assert sql.reads, "The failure must be injected into an actual SELECT"
+ assert response.status_code == 500, response.text
+ assert response.json() == {
+ "status": "error",
+ "message": "Failed to retrieve available models",
+ }
+ assert "private-cache-diagnostic" not in response.text
+ assert sql.writes == []
+ assert _provider_cache_rows(probe.username) == before
+ probe.discovery.assert_not_called()
+ probe.credentials.assert_not_called()
+ probe.list_models.assert_not_called()
+
+ @pytest.mark.parametrize("state", ["cold", "warm", "expired"])
+ def test_ordinary_post_is_cache_first(self, model_cache_client, state):
+ probe = model_cache_client
+ if state != "cold":
+ _seed_provider_cache(probe.username, expired=state == "expired")
+ before = _provider_cache_rows(probe.username)
+ with _observe_provider_cache_sql() as sql:
+ response = probe.client.post(
+ AVAILABLE_MODELS_PATH, headers={"X-CSRFToken": probe.token}
+ )
+ assert response.status_code == 200, response.text
+ expected = "cached-model" if state == "warm" else "fresh-model"
+ assert [
+ m["value"] for m in response.json()["providers"]["openai_models"]
+ ] == [expected]
+ after = _provider_cache_rows(probe.username)
+ if state == "warm":
+ assert after == before
+ assert sql.writes == []
+ probe.discovery.assert_not_called()
+ probe.credentials.assert_not_called()
+ probe.list_models.assert_not_called()
+ else:
+ assert after != before
+ assert [row["model_key"] for row in after] == ["fresh-model"]
+ assert sql.writes
+ probe.discovery.assert_called_once()
+ probe.credentials.assert_called_once_with(
+ "llm.openai.api_key", probe.username, ""
+ )
+ probe.list_models.assert_called_once_with("cache-test-key", None)
+
+ def test_forced_post_bypasses_a_fresh_cache(self, model_cache_client):
+ probe = model_cache_client
+ _seed_provider_cache(probe.username)
+ before = _provider_cache_rows(probe.username)
+ with _observe_provider_cache_sql() as sql:
+ response = probe.client.post(
+ f"{AVAILABLE_MODELS_PATH}?force_refresh=true",
+ headers={"X-CSRFToken": probe.token},
+ )
+ assert response.status_code == 200, response.text
+ assert [
+ m["value"] for m in response.json()["providers"]["openai_models"]
+ ] == ["fresh-model"]
+ after = _provider_cache_rows(probe.username)
+ assert after != before
+ assert [row["model_key"] for row in after] == ["fresh-model"]
+ assert sql.writes
+ probe.discovery.assert_called_once()
+ probe.credentials.assert_called_once_with(
+ "llm.openai.api_key", probe.username, ""
+ )
+ probe.list_models.assert_called_once_with("cache-test-key", None)
+
+ @pytest.mark.parametrize(
+ "forced", [False, True], ids=["ordinary", "forced"]
+ )
+ @pytest.mark.parametrize(
+ "token", [None, "wrong-session-token"], ids=["missing", "bad"]
+ )
+ def test_post_without_csrf_cannot_read_or_mutate_cache(
+ self, model_cache_client, forced, token
+ ):
+ probe = model_cache_client
+ _seed_provider_cache(probe.username)
+ before = _provider_cache_rows(probe.username)
+ url = AVAILABLE_MODELS_PATH + ("?force_refresh=true" if forced else "")
+ headers = {} if token is None else {"X-CSRFToken": token}
+ with _observe_provider_cache_sql() as sql:
+ response = probe.client.post(url, headers=headers)
+ assert response.status_code == 403, response.text
+ assert response.headers.get("X-LDR-CSRF-Rejected") == "1"
+ assert sql.reads == sql.writes == []
+ assert _provider_cache_rows(probe.username) == before
+ probe.policy.assert_not_called()
+ probe.options.assert_not_called()
+ probe.discovery.assert_not_called()
+ probe.credentials.assert_not_called()
+ probe.list_models.assert_not_called()
+
+ @pytest.mark.parametrize("warm", [False, True], ids=["cold", "warm"])
+ def test_legacy_forced_get_refuses_before_any_cache_work(
+ self, model_cache_client, warm
+ ):
+ probe = model_cache_client
+ if warm:
+ _seed_provider_cache(probe.username)
+ before = _provider_cache_rows(probe.username)
+ with _observe_provider_cache_sql() as sql:
+ response = probe.client.get(
+ f"{AVAILABLE_MODELS_PATH}?force_refresh=true"
+ )
+ assert response.status_code == 405, response.text
+ assert response.headers["Allow"] == "POST"
+ assert sql.reads == sql.writes == []
+ assert _provider_cache_rows(probe.username) == before
+ probe.policy.assert_not_called()
+ probe.options.assert_not_called()
+ probe.discovery.assert_not_called()
+ probe.credentials.assert_not_called()
+ probe.list_models.assert_not_called()
+
+
# ===========================================================================
# COVERAGE AREA 3 -- queued-submission attribution
# ===========================================================================
diff --git a/tests/security/test_settings_egress_and_secrets_fastapi.py b/tests/security/test_settings_egress_and_secrets_fastapi.py
index 24117026f6..81ceaef24f 100644
--- a/tests/security/test_settings_egress_and_secrets_fastapi.py
+++ b/tests/security/test_settings_egress_and_secrets_fastapi.py
@@ -8,7 +8,7 @@ survived in ``src/`` but lost their direct assertions. This file is the
committed regression evidence for those four areas.
COVERAGE AREA 1 -- model-discovery egress policy on
-``GET /settings/api/available-models``
+``POST /settings/api/available-models?force_refresh=true``
(6 deleted tests). This route reads STORED PROVIDER CREDENTIALS and contacts
provider model-listing endpoints, so ``_resolve_model_discovery_policy``
and ``_model_discovery_provider_allowed`` (both in
@@ -372,13 +372,15 @@ def _discovery_probe(client, ollama_url, resolver=None):
with ExitStack() as stack:
for manager in managers:
stack.enter_context(manager)
- response = client.post("/settings/api/available-models")
+ response = client.post(
+ "/settings/api/available-models?force_refresh=true"
+ )
return response, credential_reads, list_models
@pytest.mark.timeout(180)
class TestModelDiscoveryEgressPolicy:
- """``GET /settings/api/available-models`` resolves the egress scope BEFORE
+ """Model reads and discovery resolve the egress scope BEFORE
it reads the model cache or contacts a provider, refuses providers outside
the resolved scope, and fails closed when the scope cannot be resolved."""
diff --git a/tests/test_config_env_var_contracts.py b/tests/test_config_env_var_contracts.py
index 376bec9e65..7149491761 100644
--- a/tests/test_config_env_var_contracts.py
+++ b/tests/test_config_env_var_contracts.py
@@ -714,7 +714,10 @@ def test_data_dir_settings_api_reports_the_variable_that_moves_the_directory():
# is a historical inventory, not a reimplementation of any logic.
_APP_CONFIG_PORTED = {
"SECRET_KEY": "SECRET_KEY = _load_secret_key()",
- "SESSION_COOKIE_SAMESITE": 'same_site="strict"',
+ # #7133 deliberately changes the ported cookie policy to Lax after the
+ # forced-refresh GET path becomes CSRF-protected POST. Runtime cookie
+ # behavior is checked in test_session_cookie_behavior.py.
+ "SESSION_COOKIE_SAMESITE": 'same_site="lax"',
"SESSION_COOKIE_SECURE": "class SecureCookieMiddleware",
"PERMANENT_SESSION_LIFETIME": "security.session_remember_me_days",
"MAX_CONTENT_LENGTH": "class BodySizeLimitMiddleware",
diff --git a/tests/ui_tests/chat/test_chat_url_q_param.js b/tests/ui_tests/chat/test_chat_url_q_param.js
index 5866cba599..ac5782e467 100644
--- a/tests/ui_tests/chat/test_chat_url_q_param.js
+++ b/tests/ui_tests/chat/test_chat_url_q_param.js
@@ -1,23 +1,27 @@
/**
- * E2E Tests for Chat Mode `?q=` URL Auto-Send
+ * E2E Tests for the chat page's `?q=` pre-fill and main-page message POST
*
- * The init code at chat.js reads `?q=` from the URL and
- * auto-sends the message after the session has been created. This is
- * the integration seam used by research.js, which redirects to
- *
- * /chat/<session_id>?q=<query>
- *
- * after the home page creates a fresh chat session. Note: the
- * `sessionId` guard on chat.js means `?q=` is only consumed when
- * the URL also includes a session id in its path (which is how the
- * production redirect builds it) — visiting bare `/chat/?q=...`
- * without a session id is a no-op for new users.
+ * The session cookie is SameSite=Lax, so a link from another site opens
+ * the chat page signed in, and that link chooses the URL. chat.js therefore
+ * never sends a URL parameter by itself: `?q=` only pre-fills the composer
+ * of a chat without messages, and the user has to press Send. The server
+ * also drops `q` from links the browser marks as cross-site; page.goto() is
+ * a browser-initiated navigation, so it keeps `q` here. Chat mode on the
+ * main page (research.js) creates the session and posts its first message
+ * before opening the clean chat URL. The chat page hydrates saved messages;
+ * it never restores a startup query from browser storage.
*
* Contract verified here:
- * - Visiting /chat/<session_id>?q=<query> auto-sends the query
- * - The query appears as a user message bubble
- * - The URL is cleaned via replaceState (?q= is removed)
+ * - Main page chat mode: one submit opens /chat/<session_id> (no `?q=`)
+ * and sends the query exactly once, also across a reload
+ * - Visiting /chat/<session_id>?q=<query> for a session without messages
+ * sends nothing; it pre-fills the composer without focusing it, cleans
+ * the URL, and one press of Send posts the query
+ * - Visiting /chat/?q=<query> opens a new draft, never the most recent
+ * conversation
* - Empty ?q= is a no-op
+ * - A legacy query left in the same tab by another account is discarded
+ * without being read, displayed or sent
*
* No LLM required — we stop at the user-side bubble.
*
@@ -51,8 +55,8 @@ async function snap(page, name) {
} catch (_) {}
}
-// Create a chat session via API and return its id. Mirrors the
-// production redirect path from research.js.
+// Create a chat session via API and return its id, the way research.js
+// creates one before it opens the chat page.
async function createSessionViaApi(page) {
await page.goto(`${BASE_URL}/chat/`, {
waitUntil: 'domcontentloaded',
@@ -110,21 +114,49 @@ async function run() {
try {
await auth.ensureAuthenticated();
- // Test 1: ?q= triggers auto-send and the query appears in the chat
- console.log('Test 1: /chat/<session>/?q=<query> auto-sends the query');
+ // Every chat message POST the page makes, across navigations.
+ const messagePosts = [];
+ const messagePostPages = [];
+ page.on('request', (request) => {
+ if (request.method() === 'POST'
+ && /\/api\/chat\/sessions\/[^/]+\/messages$/.test(new URL(request.url()).pathname)) {
+ messagePosts.push(request.url());
+ messagePostPages.push(page.url());
+ }
+ });
+
+ // Test 1: the main page accepts the message before opening chat.
+ console.log('Test 1: main-page chat mode sends its query once, without ?q=');
try {
- const sessionId = await createSessionViaApi(page);
- const probe = `qparam probe ${Date.now()}`;
- const target = `${BASE_URL}/chat/${sessionId}?q=${encodeURIComponent(probe)}`;
- await page.goto(target, {
+ const probe = `direct-post probe ${Date.now()}`;
+ const postsBefore = messagePosts.length;
+ await page.goto(`${BASE_URL}/`, {
waitUntil: 'domcontentloaded',
timeout: TIMEOUTS.navigation,
});
- await page.waitForSelector('.ldr-chat-container', {
- timeout: TIMEOUTS.selector,
- });
+ await page.waitForSelector('#query', { timeout: TIMEOUTS.selector });
+ await page.evaluate((query) => {
+ document.querySelector('.ldr-mode-option[data-mode="chat"]').click();
+ document.getElementById('query').value = query;
+ }, probe);
+ const mode = await page.$eval(
+ 'input[name="research_mode"]:checked',
+ (el) => el.value
+ );
+ if (mode !== 'chat') throw new Error(`Chat mode not selected: ${mode}`);
+
+ await Promise.all([
+ page.waitForNavigation({
+ waitUntil: 'domcontentloaded',
+ timeout: TIMEOUTS.navigation,
+ }),
+ page.evaluate(() => document.getElementById('start-research-btn').click()),
+ ]);
+ const landed = new URL(page.url());
+ if (!/^\/chat\/[^/]+$/.test(landed.pathname) || landed.search || landed.hash) {
+ throw new Error(`Expected /chat/<session_id> without a query, got ${page.url()}`);
+ }
- // Wait for the user bubble with our probe
await page.waitForFunction(
(needle) => {
const nodes = document.querySelectorAll(
@@ -137,49 +169,164 @@ async function run() {
{ timeout: TIMEOUTS.selector },
probe
);
+ await page
+ .waitForNetworkIdle({ idleTime: 500, timeout: TIMEOUTS.element })
+ .catch(() => {});
+ if (messagePosts.length - postsBefore !== 1) {
+ throw new Error(
+ `Expected one message POST, got ${messagePosts.length - postsBefore}`
+ );
+ }
+ if (new URL(messagePostPages[postsBefore]).pathname !== '/') {
+ throw new Error('The first message was sent after leaving the main page');
+ }
+ const leftover = await page.evaluate(
+ () => sessionStorage.getItem('pendingChatQuery')
+ );
+ if (leftover !== null) {
+ throw new Error('A startup query remained in browser storage');
+ }
- // Welcome should have disappeared
- const welcomeHidden = await page.$eval('#chat-welcome', (el) => {
- return !el || getComputedStyle(el).display === 'none';
- });
- if (!welcomeHidden) throw new Error('Welcome screen still visible');
-
+ // A reload must not send the query again.
+ await page.reload({ waitUntil: 'domcontentloaded', timeout: TIMEOUTS.navigation });
+ await page.waitForFunction(
+ () => document.getElementById('chat-input')?.dataset.initComplete === 'true',
+ { timeout: TIMEOUTS.selector }
+ );
+ await page
+ .waitForNetworkIdle({ idleTime: 500, timeout: TIMEOUTS.element })
+ .catch(() => {});
+ if (messagePosts.length - postsBefore !== 1) {
+ throw new Error('Reloading the chat page sent the query again');
+ }
console.log('PASSED');
passed++;
} catch (e) {
console.log(`FAILED: ${e.message}`);
- await snap(page, 'autosend');
+ await snap(page, 'direct_post');
failed++;
}
- // Test 2: URL is cleaned — ?q= removed via replaceState (chat.js)
- console.log('Test 2: ?q= is stripped from URL after auto-send');
+ // Test 2: ?q= in the URL only pre-fills the composer
+ console.log('Test 2: /chat/<session>?q=<query> pre-fills without sending');
try {
const sessionId = await createSessionViaApi(page);
- const probe = `qparam clean probe ${Date.now()}`;
+ const probe = `qparam probe ${Date.now()}`;
const target = `${BASE_URL}/chat/${sessionId}?q=${encodeURIComponent(probe)}`;
+ const postsBefore = messagePosts.length;
await page.goto(target, {
waitUntil: 'domcontentloaded',
timeout: TIMEOUTS.navigation,
});
- // The replaceState fires synchronously in the init handler.
await page.waitForFunction(
- () => !window.location.search.includes('q='),
+ () => document.getElementById('chat-input')?.dataset.initComplete === 'true',
+ { timeout: TIMEOUTS.selector }
+ );
+ await page
+ .waitForNetworkIdle({ idleTime: 500, timeout: TIMEOUTS.element })
+ .catch(() => {});
+
+ const state = await page.evaluate(() => ({
+ composer: document.getElementById('chat-input').value,
+ focused: document.activeElement === document.getElementById('chat-input'),
+ sendDisabled: document.getElementById('send-btn').disabled,
+ userBubbles: document.querySelectorAll('.ldr-chat-message-user').length,
+ search: window.location.search,
+ }));
+ if (messagePosts.length !== postsBefore) {
+ throw new Error('Opening a ?q= link sent a chat message');
+ }
+ if (state.userBubbles !== 0) {
+ throw new Error(`Expected 0 user bubbles, got ${state.userBubbles}`);
+ }
+ if (state.composer !== probe) {
+ throw new Error(`Composer not pre-filled: ${JSON.stringify(state.composer)}`);
+ }
+ // Text from a URL must not sit in a focused box one Enter away.
+ if (state.focused) throw new Error('The pre-filled composer took focus');
+ if (state.sendDisabled) throw new Error('Send stayed disabled after the pre-fill');
+ if (state.search.includes('q=')) throw new Error(`URL still has q=: ${page.url()}`);
+
+ // One press of Send posts the pre-filled query.
+ await Promise.all([
+ page.waitForRequest(
+ (request) => request.method() === 'POST'
+ && new URL(request.url()).pathname
+ === `/api/chat/sessions/${sessionId}/messages`,
+ { timeout: TIMEOUTS.selector }
+ ),
+ page.click('#send-btn'),
+ ]);
+ await page.waitForFunction(
+ (needle) => {
+ const nodes = document.querySelectorAll(
+ '.ldr-chat-message-user .ldr-chat-message-text'
+ );
+ return Array.from(nodes).some((n) =>
+ (n.textContent || '').includes(needle)
+ );
+ },
+ { timeout: TIMEOUTS.selector },
+ probe
+ );
+ if (messagePosts.length - postsBefore !== 1) {
+ throw new Error(
+ `Expected one message POST after Send, got ${messagePosts.length - postsBefore}`
+ );
+ }
+ console.log('PASSED');
+ passed++;
+ } catch (e) {
+ console.log(`FAILED: ${e.message}`);
+ await snap(page, 'prefill');
+ failed++;
+ }
+
+ // Test 2b: a bare /chat/?q= opens a new draft. Tests 1 and 2 left this
+ // user with chats, and the most recent one must not receive the text.
+ console.log('Test 2b: /chat/?q=<query> opens a new draft, not the latest chat');
+ try {
+ const probe = `new draft probe ${Date.now()}`;
+ const postsBefore = messagePosts.length;
+ await page.goto(`${BASE_URL}/chat/?q=${encodeURIComponent(probe)}`, {
+ waitUntil: 'domcontentloaded',
+ timeout: TIMEOUTS.navigation,
+ });
+ await page.waitForFunction(
+ () => document.getElementById('chat-input')?.dataset.initComplete === 'true',
{ timeout: TIMEOUTS.selector }
);
- const url = page.url();
- if (url.includes('q=')) throw new Error(`URL still has q=: ${url}`);
+ await page
+ .waitForNetworkIdle({ idleTime: 500, timeout: TIMEOUTS.element })
+ .catch(() => {});
+ const state = await page.evaluate(() => ({
+ composer: document.getElementById('chat-input').value,
+ focused: document.activeElement === document.getElementById('chat-input'),
+ bubbles: document.querySelectorAll('.ldr-chat-message').length,
+ path: window.location.pathname + window.location.search,
+ }));
+ if (messagePosts.length !== postsBefore) {
+ throw new Error('Opening a ?q= link sent a chat message');
+ }
+ if (state.path !== '/chat/') {
+ throw new Error(`Expected a new draft at /chat/, got ${state.path}`);
+ }
+ if (state.bubbles !== 0) {
+ throw new Error(`A restored conversation is showing (${state.bubbles} messages)`);
+ }
+ if (state.composer !== probe) {
+ throw new Error(`Composer not pre-filled: ${JSON.stringify(state.composer)}`);
+ }
+ if (state.focused) throw new Error('The pre-filled composer took focus');
console.log('PASSED');
passed++;
} catch (e) {
console.log(`FAILED: ${e.message}`);
- await snap(page, 'cleaned');
+ await snap(page, 'new_draft');
failed++;
}
- // Test 3: Empty ?q= does NOT trigger a send — the guard at
- // chat.js is `if (initialQuery && sessionId && !isProcessing)`.
- // An empty string is falsy so handleSend should not fire.
+ // Test 3: Empty ?q= changes nothing: chat.js ignores a falsy query.
console.log('Test 3: Empty ?q= leaves chat state unchanged');
try {
const sessionId = await createSessionViaApi(page);
@@ -215,6 +362,120 @@ async function run() {
await snap(page, 'empty_q');
failed++;
}
+
+ console.log('Test 4: switching accounts discards a legacy startup query without reading it');
+ try {
+ // Register B first, then A, so the boundary under test is an
+ // actual A logout followed by B login in this very same tab.
+ const suffix = `${Date.now()}_${process.pid}`;
+ const userA = `chat_legacy_a_${suffix}`;
+ const userB = `chat_legacy_b_${suffix}`;
+ const password = 'T3st!ChatPrivacy#2026';
+ await auth.logout();
+ await auth.register(userB, password);
+ await auth.logout();
+ await auth.register(userA, password);
+ if (auth.getPage() !== page) {
+ throw new Error('Authentication replaced the tab used for the storage regression');
+ }
+ const owner = await page.$eval('.ldr-user-info', el => el.textContent.trim());
+ if (owner !== userA) throw new Error('The source account was not authenticated');
+
+ const sessionId = await createSessionViaApi(page);
+ const ownerRead = await page.evaluate(async (id) => {
+ const response = await fetch(`/api/chat/sessions/${encodeURIComponent(id)}`);
+ const data = await response.json();
+ return { status: response.status, id: data.session?.id };
+ }, sessionId);
+ if (ownerRead.status !== 200 || ownerRead.id !== sessionId) {
+ throw new Error('The source account could not read its own real chat session');
+ }
+
+ // Model an interrupted navigation from an older revision. This
+ // synthetic marker must survive auth, but must never become B's
+ // draft even though B cannot hydrate A's session.
+ const privateQuery = `legacy account A query ${suffix}`;
+ const postsBefore = messagePosts.length;
+ await page.evaluate(({ id, query }) => {
+ sessionStorage.setItem('pendingChatQuery', JSON.stringify({ sessionId: id, query }));
+ }, { id: sessionId, query: privateQuery });
+ await auth.logout();
+ await auth.login(userB, password);
+ if (auth.getPage() !== page) throw new Error('The account switch did not keep the same tab');
+ const replacement = await page.$eval('.ldr-user-info', el => el.textContent.trim());
+ if (replacement !== userB) throw new Error('The replacement account was not authenticated');
+
+ const foreignRead = await page.evaluate(async (id) => {
+ const response = await fetch(`/api/chat/sessions/${encodeURIComponent(id)}`);
+ const data = await response.json();
+ return { status: response.status, success: data.success };
+ }, sessionId);
+ if (foreignRead.status !== 404 || foreignRead.success !== false) {
+ throw new Error('The replacement account could access the source account chat');
+ }
+ const legacyStillPresent = await page.evaluate(
+ () => Object.keys(sessionStorage).includes('pendingChatQuery')
+ );
+ if (!legacyStillPresent) {
+ throw new Error('The legacy-state premise disappeared before chat initialization');
+ }
+
+ // Observe actual production access without substituting its
+ // return value: an old get-and-restore implementation still
+ // reads the real marker and fails the privacy assertions below.
+ await page.evaluateOnNewDocument(() => {
+ window.__chatLegacyStorageAccess = { reads: 0, removals: 0 };
+ const read = globalThis.Storage.prototype.getItem;
+ const remove = globalThis.Storage.prototype.removeItem;
+ globalThis.Storage.prototype.getItem = function(key) {
+ if (this === window.sessionStorage && key === 'pendingChatQuery') {
+ window.__chatLegacyStorageAccess.reads++;
+ }
+ return read.call(this, key);
+ };
+ globalThis.Storage.prototype.removeItem = function(key) {
+ if (this === window.sessionStorage && key === 'pendingChatQuery') {
+ window.__chatLegacyStorageAccess.removals++;
+ }
+ return remove.call(this, key);
+ };
+ });
+ await page.goto(`${BASE_URL}/chat/${encodeURIComponent(sessionId)}`, {
+ waitUntil: 'domcontentloaded',
+ timeout: TIMEOUTS.navigation,
+ });
+ await page.waitForFunction(
+ () => document.getElementById('chat-input')?.dataset.initComplete === 'true',
+ { timeout: TIMEOUTS.selector }
+ );
+ const state = await page.evaluate((marker) => ({
+ composer: document.getElementById('chat-input').value,
+ markerVisible: document.body.textContent.includes(marker)
+ || document.title.includes(marker),
+ hasLegacyKey: Object.keys(sessionStorage).includes('pendingChatQuery'),
+ reads: window.__chatLegacyStorageAccess.reads,
+ removals: window.__chatLegacyStorageAccess.removals,
+ path: window.location.pathname + window.location.search + window.location.hash,
+ }), privateQuery);
+ if (state.composer !== '' || state.markerVisible) {
+ throw new Error('The source account query was displayed to the replacement account');
+ }
+ if (messagePosts.length !== postsBefore) {
+ throw new Error('Switching accounts or opening the unavailable chat sent a message');
+ }
+ if (state.hasLegacyKey || state.reads !== 0 || state.removals < 1) {
+ throw new Error('The legacy query was not removed without reading its value');
+ }
+ if (state.path !== `/chat/${encodeURIComponent(sessionId)}`) {
+ throw new Error('The source account query affected the replacement account URL');
+ }
+ console.log('PASSED');
+ passed++;
+ } catch (e) {
+ console.log(`FAILED: ${e.message}`);
+ await snap(page, 'account_switch');
+ failed++;
+ }
} catch (e) {
console.log(`Test suite error: ${e.message}`);
failed++;
diff --git a/tests/ui_tests/run_all_tests.js b/tests/ui_tests/run_all_tests.js
index 40d8d7faa6..68060574eb 100644
--- a/tests/ui_tests/run_all_tests.js
+++ b/tests/ui_tests/run_all_tests.js
@@ -563,7 +563,7 @@ const tests = [
name: 'Download & CSRF Flow CI Tests',
file: 'test_download_and_csrf_flows_ci.js',
shard: 'api-crud',
- description: 'Tests CSRF middleware rejects/accepts real mutations (JSON + multipart) and a binary download (PDF) delivers correct Content-Length/Content-Disposition/bytes; also session cookie flags and logout invalidation. No LLM needed.'
+ description: 'Tests CSRF middleware rejects/accepts real mutations (JSON + multipart) and a binary download (PDF) delivers correct Content-Length/Content-Disposition/bytes; also session cookie flags, external-link login preservation, external chat links with ?q= sending and pre-filling nothing, and logout invalidation. No LLM needed.'
},
// =====================================================================
@@ -661,7 +661,7 @@ const tests = [
name: 'Chat URL ?q= Param Test',
file: 'chat/test_chat_url_q_param.js',
shard: 'chat-core',
- description: 'Tests /chat?q=... pre-fills the input'
+ description: 'Tests /chat?q=... only pre-fills an unfocused new or empty chat and main-page chat mode sends its query once'
},
{
name: 'Chat Page Navigation Test',
diff --git a/tests/ui_tests/test_download_and_csrf_flows_ci.js b/tests/ui_tests/test_download_and_csrf_flows_ci.js
index b898f0675d..9f837320b8 100644
--- a/tests/ui_tests/test_download_and_csrf_flows_ci.js
+++ b/tests/ui_tests/test_download_and_csrf_flows_ci.js
@@ -62,6 +62,7 @@
* Prerequisites: Web server on http://127.0.0.1:5000 (override BASE_URL).
*/
+const { randomUUID } = require('node:crypto');
const puppeteer = require('puppeteer');
const AuthHelper = require('./auth_helper');
const { getPuppeteerLaunchOptions } = require('./puppeteer_config');
@@ -405,13 +406,13 @@ async function run() {
// ---------------------------------------------------------------
// Test 6: session cookie flags, per the actual SessionMiddleware
// config in fastapi_app.py (session_cookie="session",
- // same_site="strict"). Secure is added dynamically by
+ // same_site="lax"). Secure is added dynamically by
// SecureCookieMiddleware ONLY over an actually-HTTPS connection
// (marking Secure over plain HTTP would make the browser drop the
// cookie) — this suite talks to BASE_URL over plain HTTP, so
// Secure is correctly expected to be absent here.
// ---------------------------------------------------------------
- console.log('Test 6: session cookie carries HttpOnly + SameSite=Strict');
+ console.log('Test 6: session cookie carries HttpOnly + SameSite=Lax');
try {
const cookies = await page.cookies();
const sessionCookie = cookies.find((c) => c.name === 'session');
@@ -419,9 +420,9 @@ async function run() {
if (sessionCookie.httpOnly !== true) {
throw new Error(`Expected httpOnly=true, got ${sessionCookie.httpOnly}`);
}
- if (String(sessionCookie.sameSite).toLowerCase() !== 'strict') {
+ if (String(sessionCookie.sameSite).toLowerCase() !== 'lax') {
throw new Error(
- `Expected sameSite=Strict (same_site="strict" in fastapi_app.py's ` +
+ `Expected sameSite=Lax (same_site="lax" in fastapi_app.py's ` +
`SessionMiddleware config), got ${sessionCookie.sameSite}`
);
}
@@ -441,6 +442,138 @@ async function run() {
failed++;
}
+ // External navigation must carry the same authenticated session.
+ // Intercept the referring site locally: no DNS/server dependency and
+ // no request leaves the browser for this deliberately different site.
+ console.log('Test 6b: external link preserves authentication');
+ const navigationPage = await browser.newPage();
+ try {
+ const direct = await navigationPage.goto(`${BASE_URL}/`, {
+ waitUntil: 'domcontentloaded',
+ timeout: TIMEOUTS.navigation,
+ });
+ const checkAuth = () => navigationPage.evaluate(async () => {
+ const response = await fetch('/auth/check');
+ return { status: response.status, data: await response.json() };
+ });
+ const before = await checkAuth();
+ if (direct.status() !== 200 || before.status !== 200) {
+ throw new Error('Direct-navigation authentication control failed');
+ }
+
+ const sourceUrl = 'http://ldr-external-navigation.test/';
+ const target = `${BASE_URL}/`.replaceAll('&', '&amp;').replaceAll('"', '&quot;');
+ await navigationPage.setRequestInterception(true);
+ navigationPage.on('request', request => {
+ if (request.url() === sourceUrl) {
+ request.respond({
+ status: 200,
+ contentType: 'text/html',
+ body: `<a id="open-ldr" href="${target}">Open LDR</a>`,
+ });
+ } else {
+ request.continue();
+ }
+ });
+ await navigationPage.goto(sourceUrl, { waitUntil: 'domcontentloaded' });
+ await Promise.all([
+ navigationPage.waitForNavigation({
+ waitUntil: 'domcontentloaded',
+ timeout: TIMEOUTS.navigation,
+ }),
+ navigationPage.click('#open-ldr'),
+ ]);
+ const after = await checkAuth();
+ if (new URL(navigationPage.url()).pathname !== '/' || after.status !== 200
+ || after.data.username !== before.data.username) {
+ throw new Error('Following an external link lost the authenticated session');
+ }
+ console.log('PASSED');
+ passed++;
+ } catch (e) {
+ console.log(`FAILED: ${e.message}`);
+ failed++;
+ } finally {
+ await navigationPage.close();
+ }
+
+ // Such a link reaches any page signed in and chooses its URL, so no
+ // page-load script may turn URL parameters into a state-changing
+ // request, and the link must not even pre-fill the chat box: the
+ // server redirects a cross-site `?q=` away (303) before the page
+ // renders. The unknown-session link covers users who already have
+ // chats; its failed restore used to create a session for the linked
+ // query and start a research run.
+ console.log('Test 6c: external chat links with ?q= send and pre-fill nothing');
+ const chatLinkPage = await browser.newPage();
+ try {
+ const sourceUrl = 'http://ldr-external-navigation.test/chat-links';
+ const probe = `external link probe ${Date.now()}`;
+ const links = [
+ ['bare', `${BASE_URL}/chat/?q=${encodeURIComponent(probe)}`],
+ ['unknown-session', `${BASE_URL}/chat/${randomUUID()}?q=${encodeURIComponent(probe)}`],
+ ];
+ const escapeAttribute = (value) => value.replaceAll('&', '&amp;').replaceAll('"', '&quot;');
+ const chatWrites = [];
+ await chatLinkPage.setRequestInterception(true);
+ chatLinkPage.on('request', request => {
+ if (request.url() === sourceUrl) {
+ request.respond({
+ status: 200,
+ contentType: 'text/html',
+ body: links.map(([name, href]) => (
+ `<a id="open-${name}" href="${escapeAttribute(href)}">${name}</a>`
+ )).join(''),
+ });
+ return;
+ }
+ const { pathname } = new URL(request.url());
+ if (request.method() !== 'GET' && pathname.startsWith('/api/chat/')) {
+ chatWrites.push(`${request.method()} ${pathname}`);
+ }
+ request.continue();
+ });
+ for (const [name] of links) {
+ await chatLinkPage.goto(sourceUrl, { waitUntil: 'domcontentloaded' });
+ const [response] = await Promise.all([
+ chatLinkPage.waitForNavigation({
+ waitUntil: 'domcontentloaded',
+ timeout: TIMEOUTS.navigation,
+ }),
+ chatLinkPage.click(`#open-${name}`),
+ ]);
+ const landed = new URL(chatLinkPage.url());
+ if (!landed.pathname.startsWith('/chat/')) {
+ throw new Error(`The ${name} link did not open the chat page signed in: ${chatLinkPage.url()}`);
+ }
+ const hops = response ? response.request().redirectChain() : [];
+ if (!hops.some((hop) => hop.response()?.status() === 303)) {
+ throw new Error(`The server did not redirect the ${name} link's q away`);
+ }
+ await chatLinkPage.waitForFunction(
+ () => document.getElementById('chat-input')?.dataset.initComplete === 'true',
+ { timeout: TIMEOUTS.selector },
+ );
+ await chatLinkPage
+ .waitForNetworkIdle({ idleTime: 500, timeout: TIMEOUTS.selector })
+ .catch(() => {});
+ if (chatWrites.length > 0) {
+ throw new Error(`The ${name} link sent ${chatWrites.join(', ')}`);
+ }
+ const composer = await chatLinkPage.$eval('#chat-input', (el) => el.value);
+ if (composer !== '') {
+ throw new Error(`The ${name} link pre-filled the composer: ${JSON.stringify(composer)}`);
+ }
+ }
+ console.log('PASSED');
+ passed++;
+ } catch (e) {
+ console.log(`FAILED: ${e.message}`);
+ failed++;
+ } finally {
+ await chatLinkPage.close();
+ }
+
// ---------------------------------------------------------------
// Test 7: logout actually invalidates access to an authenticated
// page (require_auth's 401 -> 302 /auth/login redirect for HTML
diff --git a/tests/web/routers/test_chat_page_login_redirect.py b/tests/web/routers/test_chat_page_login_redirect.py
index 20f8356f13..bdac1dcf83 100644
--- a/tests/web/routers/test_chat_page_login_redirect.py
+++ b/tests/web/routers/test_chat_page_login_redirect.py
@@ -16,11 +16,13 @@ in ``web/fastapi_app.py::_register_exception_handlers``. These tests fence
the parts of that contract the chat page depends on, from the outside:
through the real route table and the real handler.
-Why the query string matters HERE specifically: ``static/js/components/
-chat.js`` reads ``?q=`` off the chat URL and pre-fills the composer with
-it, so ``/chat/?q=<question>`` is a shareable "ask this" link. Losing the
-query on the login bounce turns that link into a blank chat box for any
-recipient who is not already signed in.
+The bounce keeps the whole query string, as main did. For the chat page
+that includes ``q``, which ``static/js/components/chat.js`` pre-fills into
+the composer; the login page, not this bounce, drops it from ``next``
+(``web/routers/auth.py::_drop_chat_query``), so a recipient of a
+``/chat/?q=<question>`` link who is not signed in reaches an empty chat box
+after logging in. That is covered by
+``tests/web/test_redirect_and_url_generation.py::TestLoginNextDropsTheChatQuery``.
"""
from urllib.parse import parse_qs, unquote, urlparse
@@ -51,12 +53,16 @@ def test_anonymous_chat_page_redirects_to_login_carrying_the_path():
def test_anonymous_chat_page_redirect_preserves_the_q_query_string():
- """``/chat/?q=<question>`` must survive the login bounce.
-
- chat.js reads ``?q=`` in its routed-query bootstrap and calls
- handleSend(), so the query is not merely pre-filled -- it is
- auto-submitted as a research run. Dropping it stranded a signed-out user
- who followed a shared link on an empty chat box with the question gone.
+ """The login bounce keeps ``/chat/?q=<question>`` whole.
+
+ The bounce copies the requested URL, query included, into ``next``.
+ Dropping a chat ``q`` is the login page's job: after login the browser
+ follows this app's own redirect, so the login page removes ``q`` from a
+ chat ``next`` (tests/web/test_redirect_and_url_generation.py::
+ TestLoginNextDropsTheChatQuery). (This request sends no
+ ``Sec-Fetch-Site`` header. When that header marks a link as coming from
+ another origin, the chat route drops ``q`` before this bounce:
+ tests/chat/test_chat_page_routes.py.)
Was a strict xfail: the handler built ``next`` from ``request.url.path``,
truncating the query. main used Werkzeug's ``request.url`` (full URL).
diff --git a/tests/web/routers/test_model_discovery_cancellation.py b/tests/web/routers/test_model_discovery_cancellation.py
index f2d44d29cd..0d255d85cb 100644
--- a/tests/web/routers/test_model_discovery_cancellation.py
+++ b/tests/web/routers/test_model_discovery_cancellation.py
@@ -1,9 +1,13 @@
-"""Canceled HTTP discovery must drain its worker without starting more work."""
+"""Canceled POST discovery must drain its worker without starting more work.
+
+The isolated app exercises worker ownership and cancellation. Real-session
+GET/POST/CSRF contracts are covered by test_followup_and_settings_guards_fastapi.
+"""
import asyncio
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
import threading
from types import SimpleNamespace
@@ -22,6 +26,7 @@ from local_deep_research.web.dependencies.threadpool import (
prepare_router_for_worker_cleanup,
run_db_sync,
)
+from local_deep_research.web.dependencies import threadpool
from local_deep_research.web.routers import settings
@@ -39,6 +44,7 @@ def discovery_http(tmp_path, monkeypatch):
provider="SAVED",
model_key="saved-model",
model_label="Previously cached model",
+ model_metadata={"retained": ["cached", "metadata"]},
last_updated=datetime.now(UTC),
)
)
@@ -109,9 +115,27 @@ def _observe_cleanup(monkeypatch, owner):
@pytest.mark.asyncio
@pytest.mark.parametrize("provider_error", [False, True])
@pytest.mark.parametrize("include_second", [False, True])
[email protected]("force_refresh", [False, True])
async def test_cancellation_stops_later_providers_and_preserves_cache(
- discovery_http, monkeypatch, provider_error, include_second
+ discovery_http, monkeypatch, provider_error, include_second, force_refresh
):
+ if not force_refresh:
+ # Ordinary POST reaches discovery only when the cache is stale.
+ with discovery_http.sessions() as session:
+ session.query(ProviderModel).one().last_updated = datetime.now(
+ UTC
+ ) - timedelta(hours=25)
+ session.commit()
+ with discovery_http.sessions() as session:
+ cached = session.query(ProviderModel).one()
+ saved_row = (
+ cached.id,
+ cached.provider,
+ cached.model_key,
+ cached.model_label,
+ cached.model_metadata,
+ cached.last_updated,
+ )
started = threading.Event()
release = threading.Event()
owner = set()
@@ -141,10 +165,14 @@ async def test_cancellation_stops_later_providers_and_preserves_cache(
async with httpx.AsyncClient(
transport=transport, base_url="http://test"
) as client:
- # A full refresh is a POST without a target; GET with
- # ?force_refresh=true answers 405 before any discovery work.
+ # A POST discovers on a stale cache, or always with
+ # force_refresh=true; GET with ?force_refresh=true answers 405
+ # before any discovery work.
request = asyncio.create_task(
- client.post("/settings/api/available-models")
+ client.post(
+ "/settings/api/available-models",
+ params={"force_refresh": str(force_refresh).lower()},
+ )
)
try:
assert await asyncio.to_thread(started.wait, 10)
@@ -162,11 +190,17 @@ async def test_cancellation_stops_later_providers_and_preserves_cache(
assert owner and threading.get_ident() not in owner
assert calls == ["first"]
- assert discovery_http.cache_access == []
+ assert len(discovery_http.cache_access) == (0 if force_refresh else 1)
with discovery_http.sessions() as session:
- assert [
- row.model_key for row in session.query(ProviderModel).all()
- ] == ["saved-model"]
+ cached = session.query(ProviderModel).one()
+ assert (
+ cached.id,
+ cached.provider,
+ cached.model_key,
+ cached.model_label,
+ cached.model_metadata,
+ cached.last_updated,
+ ) == saved_row
@pytest.mark.asyncio
@@ -192,7 +226,9 @@ async def test_uncancelled_discovery_fetches_and_persists_all_models(
async with httpx.AsyncClient(
transport=transport, base_url="http://test"
) as client:
- response = await client.post("/settings/api/available-models")
+ response = await client.post(
+ "/settings/api/available-models?force_refresh=true"
+ )
assert response.status_code == 200
assert set(response.json()["providers"]) == {
@@ -213,11 +249,10 @@ async def test_uncancelled_discovery_fetches_and_persists_all_models(
@pytest.mark.asyncio
-async def test_slow_discovery_leaves_the_default_executor_free(
+async def test_slow_discovery_leaves_auth_and_cached_get_available(
discovery_http, monkeypatch
):
- """Every authenticated request checks its database on the default
- executor, so a provider stuck in discovery must not hold that executor."""
+ """A provider stuck in discovery must not block auth or cached GETs."""
started = threading.Event()
release = threading.Event()
workers = []
@@ -237,27 +272,46 @@ async def test_slow_discovery_leaves_the_default_executor_free(
asyncio.get_running_loop().set_default_executor(
ThreadPoolExecutor(max_workers=1)
)
- transport = httpx.ASGITransport(app=discovery_http.app)
- async with httpx.AsyncClient(
- transport=transport, base_url="http://test"
- ) as client:
- request = asyncio.create_task(
- client.post("/settings/api/available-models")
+ # Saturate the dedicated discovery pool with one blocked POST.
+ with ThreadPoolExecutor(
+ max_workers=1, thread_name_prefix="ldr-model-discovery"
+ ) as executor:
+ monkeypatch.setattr(
+ threadpool, "_get_model_discovery_executor", lambda: executor
)
- try:
- for _ in range(1000):
- if started.is_set():
- break
- await asyncio.sleep(0.01)
- assert started.is_set(), "discovery did not reach the provider"
- # Stands in for DatabaseMiddleware's ensure_user_database call.
- ready = await asyncio.wait_for(
- run_db_sync(lambda: "auth-ready"), timeout=5
+ transport = httpx.ASGITransport(app=discovery_http.app)
+ async with httpx.AsyncClient(
+ transport=transport, base_url="http://test"
+ ) as client:
+ request = asyncio.create_task(
+ client.post("/settings/api/available-models?force_refresh=true")
)
- assert ready == "auth-ready"
- finally:
- release.set()
- response = await request
+ try:
+ for _ in range(1000):
+ if started.is_set():
+ break
+ await asyncio.sleep(0.01)
+ assert started.is_set(), "discovery did not reach the provider"
+ # Stands in for DatabaseMiddleware's ensure_user_database call.
+ ready = await asyncio.wait_for(
+ run_db_sync(lambda: "auth-ready"), timeout=5
+ )
+ assert ready == "auth-ready"
+ cached = await asyncio.wait_for(
+ client.get("/settings/api/available-models"), timeout=5
+ )
+ assert cached.status_code == 200
+ assert cached.json()["providers"]["saved_models"] == [
+ {
+ "value": "saved-model",
+ "label": "Previously cached model",
+ "provider": "SAVED",
+ }
+ ]
+ assert not release.is_set()
+ finally:
+ release.set()
+ response = await request
assert response.status_code == 200
assert workers and workers[0].startswith("ldr-model-discovery"), workers
diff --git a/tests/web/routers/test_model_refresh_concurrency.py b/tests/web/routers/test_model_refresh_concurrency.py
index eb3dfe75cd..9d56805aeb 100644
--- a/tests/web/routers/test_model_refresh_concurrency.py
+++ b/tests/web/routers/test_model_refresh_concurrency.py
@@ -115,12 +115,17 @@ def model_catalog(tmp_path, monkeypatch, request):
yield db
def refresh(full=False):
+ # The full refresh is POST ?force_refresh=true. A POST without a
+ # query is cache-first and would return the fresh rows seeded above
+ # without discovering anything.
request = Request(
{
"type": "http",
"method": "POST",
"path": "/settings/api/available-models",
- "query_string": b"" if full else b"refresh_provider=qwen",
+ "query_string": (
+ b"force_refresh=true" if full else b"refresh_provider=qwen"
+ ),
"headers": [],
}
)
diff --git a/tests/web/routers/test_settings_routes_deep_coverage2_port.py b/tests/web/routers/test_settings_routes_deep_coverage2_port.py
index 401b9d7c6f..c152f1a444 100644
--- a/tests/web/routers/test_settings_routes_deep_coverage2_port.py
+++ b/tests/web/routers/test_settings_routes_deep_coverage2_port.py
@@ -792,6 +792,7 @@ def _call_available_models():
request = _fake_request()
request.method = "POST"
+ request.query_params = {"force_refresh": "true"}
return asyncio.run(api_get_available_models(request, username="testuser"))
diff --git a/tests/web/routers/test_settings_routes_gaps_coverage_port.py b/tests/web/routers/test_settings_routes_gaps_coverage_port.py
index e13e9a2a83..6a1e6e46bf 100644
--- a/tests/web/routers/test_settings_routes_gaps_coverage_port.py
+++ b/tests/web/routers/test_settings_routes_gaps_coverage_port.py
@@ -652,7 +652,7 @@ class TestApiTestNotificationUrl:
@contextmanager
def _models_env(discovered_options, discovered_providers=None, extra=()):
- """Common patch set for ``GET /settings/api/available-models``."""
+ """Common patch set for cached reads and POST model discovery."""
@contextmanager
def _fake_session(*a, **kw):
@@ -763,13 +763,13 @@ class TestApiGetAvailableModels:
]
def test_force_refresh_bypasses_cache(self, client):
- """A ``POST`` still carrying the legacy ``force_refresh=true`` (and
- no target) skips the cache and fetches live.
+ """POST with an explicit refresh flag (and no target) skips the
+ cache and fetches live.
The original asserted only ``200`` + ``"providers" in body``, which
stays green with the query-param parsing deleted. The cached-vs-fresh
model identity is added so the assertion actually depends on the
- force-refresh branch being taken.
+ POST refresh branch being taken.
"""
data = self._cache_vs_fresh(client, "?force_refresh=true")
@@ -794,12 +794,21 @@ class TestApiGetAvailableModels:
"fresh-model"
]
- def test_post_without_target_is_a_full_refresh(self, client):
- """A ``POST`` with no ``refresh_provider`` re-discovers every
- provider, bypassing the cache like ``POST ?force_refresh=true``."""
+ def test_post_without_a_refresh_query_reuses_the_cache(self, client):
+ """A ``POST`` with neither ``force_refresh=true`` nor
+ ``refresh_provider`` is cache-first: it returns the fresh cached rows
+ and discovers only on a cache miss.
+
+ This test once asserted the opposite: when only refreshes were
+ POSTs, a bare ``POST`` was the full refresh. Every model loader now
+ POSTs (a ``GET`` reads only the cache and never discovers, so a cold
+ cache would leave the dropdowns empty), so the full refresh is
+ ``POST ?force_refresh=true`` and a bare ``POST`` must not bypass a
+ fresh cache on every page load.
+ """
data = self._cache_vs_fresh(client, "", post=True)
assert [m["value"] for m in data["providers"]["ollama_models"]] == [
- "fresh-model"
+ "cached-only-model"
]
@pytest.mark.parametrize(
@@ -840,14 +849,14 @@ class TestApiGetAvailableModels:
"?refresh_provider=LMSTUDIO",
"?refresh_provider=LMSTUDIO&force_refresh=true",
],
- ids=["targeted", "legacy-force-flag-does-not-widen"],
+ ids=["targeted", "force-flag-does-not-widen"],
)
def test_refresh_provider_fetches_only_the_target(self, client, query):
"""A targeted refresh must not touch any other provider's
upstream: only the named provider's ``list_models_for_api`` runs,
- and its rows merge with (not replace) the cached catalog. The
- legacy ``force_refresh=true`` flag is ignored on a POST, so it
- cannot widen a targeted refresh into a full one."""
+ and its rows merge with (not replace) the cached catalog. A target
+ takes precedence over ``force_refresh=true``, so the flag cannot
+ widen a targeted refresh into a full one."""
from local_deep_research.security.egress.policy import (
EgressContext,
EgressScope,
@@ -1529,7 +1538,9 @@ class TestApiGetAvailableModels:
discovered,
extra=[patch(f"{S}._get_setting_from_session", return_value=None)],
):
- resp = client.post("/settings/api/available-models")
+ resp = client.post(
+ "/settings/api/available-models?force_refresh=true"
+ )
assert resp.status_code == 200
values = [opt["value"] for opt in resp.json()["provider_options"]]
@@ -1586,7 +1597,9 @@ class TestApiGetAvailableModels:
patch(f"{S}._get_setting_from_session", return_value=""),
],
):
- resp = client.post("/settings/api/available-models")
+ resp = client.post(
+ "/settings/api/available-models?force_refresh=true"
+ )
assert resp.status_code == 200, resp.text[:400]
return resp.json()["providers"]
@@ -1752,7 +1765,9 @@ class TestApiGetAvailableModelsEgressPolicy:
),
):
# When models are refreshed.
- response = client.post("/settings/api/available-models")
+ response = client.post(
+ "/settings/api/available-models?force_refresh=true"
+ )
# Then the provider is never actually called and no models are
# returned, but the option is still surfaced in the dropdown marked as
diff --git a/tests/web/test_auth_session_lifecycle.py b/tests/web/test_auth_session_lifecycle.py
index fa01e24250..166b8367be 100644
--- a/tests/web/test_auth_session_lifecycle.py
+++ b/tests/web/test_auth_session_lifecycle.py
@@ -58,7 +58,7 @@ whose absence is not observable from the cookie's own attributes:
DELIBERATELY NOT DUPLICATED (surveyed, already covered)
-------------------------------------------------------
-``SameSite=strict`` / ``HttpOnly`` on the session cookie, and the
+``SameSite=lax`` / ``HttpOnly`` on the session cookie, and the
remember-me ``Max-Age`` in both directions:
``tests/web/test_session_cookie_behavior.py``,
``tests/web/test_remember_me_and_json_body_cap.py``.
diff --git a/tests/web/test_js_fetch_parity.py b/tests/web/test_js_fetch_parity.py
index b9a2d81848..88d8ac1cf7 100644
--- a/tests/web/test_js_fetch_parity.py
+++ b/tests/web/test_js_fetch_parity.py
@@ -371,14 +371,15 @@ def local_url_constants(text: str) -> dict[str, str]:
#: Every function the codebase uses to reach the backend. ``safeFetch*`` are
#: defined in ``security/safe-fetch.js``; ``fetchWithErrorHandling`` and
-#: ``postJSON`` in ``services/api.js``. All forward to ``fetch(url, options)``
-#: unchanged, except ``postJSON``, which hard-codes POST + JSON.
+#: ``postJSON`` in ``services/api.js``. ``postChat`` in research.js uses the
+#: auth-context-fenced CSRF helper. Both post helpers hard-code POST + JSON.
FETCH_FNS = (
"safeFetchWithAuth",
"safeFetchJson",
"fetchWithErrorHandling",
"safeFetch",
"postJSON",
+ "postChat",
"fetch",
)
@@ -410,8 +411,8 @@ class FetchCall:
def method_of(fn: str, options_src: str) -> str:
"""The HTTP verb a call site sends, or ``"?"`` when not statically known."""
- if fn == "postJSON":
- return "POST" # api.js hard-codes method: 'POST'
+ if fn in {"postJSON", "postChat"}:
+ return "POST" # Both helpers hard-code method: 'POST'.
match = re.search(r"(?<![\w$])method\s*:\s*['\"](\w+)['\"]", options_src)
if match:
return match.group(1).upper()
@@ -997,7 +998,13 @@ LIVE_CASES = (
bad={"rating": "up"},
),
LiveCase(
- js_ref="components/chat.js:2717",
+ # Located by its URL expression, like the research.js case above:
+ # chat.js keeps growing above this call (the ?q= pre-fill rules
+ # moved it from line 2631), and the line is not what is modelled.
+ js_ref=_unique_js_ref(
+ "components/chat.js",
+ "`/api/chat/sessions/${encodeURIComponent(sessionIdAtRequest)}`",
+ ),
method="PATCH",
url=f"/api/chat/sessions/{NOPE_UUID}",
good={"title": "t"},
diff --git a/tests/web/test_redirect_and_url_generation.py b/tests/web/test_redirect_and_url_generation.py
index 5e17480af8..7c43e988f8 100644
--- a/tests/web/test_redirect_and_url_generation.py
+++ b/tests/web/test_redirect_and_url_generation.py
@@ -30,7 +30,9 @@ the routes are all still *enumerable*:
(``web/routers/auth.py``:284). It is filtered by
``URLValidator.get_safe_redirect_path`` plus a belt-and-braces
scheme/netloc check. Exercised end-to-end through a real login here,
- not as a unit test of the validator.
+ not as a unit test of the validator. A chat-page target also loses
+ its ``q`` there and in the form the login page renders
+ (``TestLoginNextDropsTheChatQuery``).
Deliberately NOT re-covered (already fenced elsewhere):
@@ -46,9 +48,11 @@ while every real navigation to that link costs a 307 round trip.
"""
import ast
+import html
+import re
import uuid
from pathlib import Path
-from urllib.parse import parse_qs, unquote, urlsplit
+from urllib.parse import parse_qs, quote, unquote, urlsplit
import pytest
from fastapi.testclient import TestClient
@@ -605,6 +609,158 @@ class TestOpenRedirectOnLoginNext:
assert location == "/history?a=1"
+_FORM_ACTION = re.compile(r'<form method="post" action="([^"]*)"')
+
+
+def _login_form_action(page) -> str:
+ """The rendered login form's action, HTML entities decoded."""
+ actions = [html.unescape(raw) for raw in _FORM_ACTION.findall(page.text)]
+ login = [a for a in actions if urlsplit(a).path == "/auth/login"]
+ assert len(login) == 1, f"expected one login form, found {actions}"
+ return login[0]
+
+
+def _login_form_next(page) -> str | None:
+ """The ``next`` the rendered login form posts back, if any."""
+ values = parse_qs(urlsplit(_login_form_action(page)).query).get("next")
+ return values[0] if values else None
+
+
+def _linked_login_page(client: TestClient, next_value: str):
+ """GET the login page through a link that another site wrote.
+
+ ``next`` is percent-encoded here rather than through the client's
+ ``params``, so the request is what such a link's ``href`` sends.
+ """
+ return client.get(
+ "/auth/login?next=" + quote(next_value, safe=""),
+ headers={"Sec-Fetch-Site": "cross-site"},
+ )
+
+
+# id: (the next= another site's link carries, the next the login form
+# posts back, the Location after login)
+_CHAT_NEXT = {
+ "q-only": ("/chat/?q=linked+text", "/chat/", "/chat/"),
+ "q-and-mode": (
+ "/chat/?q=linked+text&mode=quick",
+ "/chat/?mode=quick",
+ "/chat/?mode=quick",
+ ),
+ "session-and-fragment": (
+ "/chat/some-session?mode=quick&q=linked#top",
+ "/chat/some-session?mode=quick#top",
+ "/chat/some-session?mode=quick#top",
+ ),
+ # The router answers /chat with a 307 to /chat/ that keeps the query.
+ "no-trailing-slash": ("/chat?q=linked", "/chat", "/chat"),
+ # The server decodes %63 before routing; URLSearchParams decodes %71.
+ "percent-encoded": ("/%63hat/?%71=linked", "/%63hat/", "/%63hat/"),
+ "absolute-same-origin": (
+ "http://testserver/chat/?q=linked",
+ "http://testserver/chat/",
+ "/chat/",
+ ),
+}
+
+
+class TestLoginNextDropsTheChatQuery:
+ """A link from another site can open ``/auth/login?next=/chat/?q=...``.
+
+ chat.js pre-fills the chat box from ``?q=``. The chat route drops a
+ ``q`` when ``Sec-Fetch-Site`` says another origin started the
+ navigation, but after the login POST the browser follows this app's
+ own redirect, so the chat page loads as a same-origin navigation. The
+ login page therefore drops ``q`` from a chat target, in the form it
+ renders and in the redirect after login, and keeps the rest of
+ ``next``. Each case writes the ``next=`` link out directly.
+ """
+
+ @pytest.mark.parametrize(
+ ("next_value", "form_next"),
+ [
+ pytest.param(link, form, id=name)
+ for name, (link, form, _) in _CHAT_NEXT.items()
+ ],
+ )
+ def test_login_form_posts_the_chat_target_back_without_q(
+ self, anon, next_value, form_next
+ ):
+ page = _linked_login_page(anon, next_value)
+
+ assert page.status_code == 200, page.text[:300]
+ assert _login_form_next(page) == form_next
+
+ @pytest.mark.parametrize(
+ ("next_value", "location"),
+ [
+ pytest.param(link, location, id=name)
+ for name, (link, _, location) in _CHAT_NEXT.items()
+ ],
+ )
+ def test_login_redirect_leaves_q_off_the_chat_target(
+ self, account, next_value, location
+ ):
+ """The POST drops it as well, since ``next`` can reach the POST
+ without passing through this page's form (the 401 bounce, a login
+ form rendered before this change)."""
+ client, username = account
+
+ response = _login_with_next(client, username, next_value)
+
+ assert response.status_code == 302, response.text[:300]
+ assert response.headers["location"] == location
+
+ def test_linked_login_round_trip_opens_the_chat_without_q(self, account):
+ """The browser's whole path: the link, the form it renders, and
+ the credentials posted to that form's action."""
+ _, username = account
+ client = _make_client()
+ page = _linked_login_page(client, "/chat/?q=linked+text&mode=quick")
+ assert page.status_code == 200, page.text[:300]
+ action = _login_form_action(page)
+
+ ip = _unique_ip()
+ response = client.post(
+ action,
+ data={
+ "username": username,
+ "password": PASSWORD,
+ "csrf_token": _csrf(client, ip),
+ },
+ headers={"X-Forwarded-For": ip},
+ )
+
+ assert response.status_code == 302, response.text[:300]
+ assert response.headers["location"] == "/chat/?mode=quick"
+
+ @pytest.mark.parametrize(
+ "next_value",
+ ["/library/search/?q=a%20b", "/history?q=linked", "/chatroom?q=linked"],
+ )
+ def test_other_targets_keep_q_in_the_login_form(self, anon, next_value):
+ """Control: only a chat target loses ``q``."""
+ page = _linked_login_page(anon, next_value)
+
+ assert page.status_code == 200, page.text[:300]
+ assert _login_form_next(page) == next_value
+
+ @pytest.mark.parametrize(
+ "next_value", ["/history?q=linked", "/chatroom?q=linked"]
+ )
+ def test_other_targets_keep_q_in_the_login_redirect(
+ self, account, next_value
+ ):
+ """Control for the POST side (``/library/search/?q=`` is in
+ ``test_benign_local_next_survives_login_intact``)."""
+ client, username = account
+
+ response = _login_with_next(client, username, next_value)
+
+ assert response.status_code == 302, response.text[:300]
+ assert response.headers["location"] == next_value
+
+
# ---------------------------------------------------------------------------
# 4. URL generation: url_for output must be exact, not slash-approximate
# ---------------------------------------------------------------------------
diff --git a/tests/web/test_route_table_parity.py b/tests/web/test_route_table_parity.py
index 80c9b75c0e..b2b8a567a0 100644
--- a/tests/web/test_route_table_parity.py
+++ b/tests/web/test_route_table_parity.py
@@ -192,9 +192,10 @@ EXPECTED_ADDED = [
("DELETE", "/settings/api/{}"),
("GET", "/settings/api/{}"),
("PUT", "/settings/api/{}"),
- # A model refresh (``?refresh_provider=`` for one provider, else every
- # provider) calls providers with the user's stored keys and rewrites
- # their cached rows, so it moved from GET ``?force_refresh=true`` to a
+ # Model discovery calls providers with the user's stored keys and
+ # rewrites their cached rows (on a cache miss, for every provider with
+ # ``?force_refresh=true``, for one with ``?refresh_provider=``), so it
+ # moved from GET (``?force_refresh=true`` included) to a
# CSRF-protected POST. Ordinary GET reads remain available.
("POST", "/settings/api/available-models"),
# FastAPI-side counterpart of the bulk re-index GET -> POST move
@@ -1543,9 +1544,10 @@ def _where(views) -> str:
# sides spelled out — and an entry whose two sides stop diverging, or
# start diverging differently, fails too.
EXPECTED_METHOD_SET_DIVERGENCES = {
- # GET remains a read, while POST performs a model refresh (targeted by
- # ``?refresh_provider=``, else full). A GET carrying ``refresh_provider``
- # or ``force_refresh=true`` returns 405.
+ # GET remains a cache-only read, while POST discovers on a cache miss,
+ # replaces the whole model cache with ``?force_refresh=true`` and
+ # refreshes one provider with ``?refresh_provider=``. A GET carrying
+ # ``refresh_provider`` or ``force_refresh=true`` returns 405 (#6465).
"/settings/api/available-models": ({"GET"}, {"GET", "POST"}),
# The bulk re-index trigger; see the paired entries in
# EXPECTED_REMOVED / EXPECTED_ADDED for why the verb changed. Stated
@@ -1683,8 +1685,15 @@ EXPECTED_STATUS_CODES_GAINED = {
# A GET carrying ``refresh_provider`` or ``force_refresh=true`` would
# call providers with the stored keys and rewrite cached models without
# a CSRF check (``force_refresh=true`` deleted every cached row). It now
- # fails with 405 and directs clients to POST.
+ # fails with 405 and directs clients to POST (#6465).
("GET", "/settings/api/available-models"): [405],
+ # SameSite=Lax lets a link from another site open the chat page signed
+ # in. When Sec-Fetch-Site says another origin started the navigation, a
+ # `?q=` is redirected away (303, same page without it) before auth runs,
+ # so the link cannot pre-fill the chat box. Runtime coverage:
+ # tests/chat/test_chat_page_routes.py. chat.py:_drop_foreign_chat_query.
+ ("GET", "/chat/"): [303],
+ ("GET", "/chat/{}"): [303],
# Offsets above 10,000 are rejected before reaching the database. Flask
# attempted the query (and could raise on values outside SQLite's integer
# range); ordinary offsets and non-integer fallback behavior are retained.
diff --git a/tests/web/test_security_headers_matrix.py b/tests/web/test_security_headers_matrix.py
index 6550608065..384dd8018e 100644
--- a/tests/web/test_security_headers_matrix.py
+++ b/tests/web/test_security_headers_matrix.py
@@ -587,7 +587,7 @@ class TestCookieSurface:
assert cookie.startswith("session="), cookie
attrs = [part.strip().lower() for part in cookie.split(";")[1:]]
assert "httponly" in attrs, cookie
- assert "samesite=strict" in attrs, cookie
+ assert "samesite=lax" in attrs, cookie
assert "path=/" in attrs, cookie
assert not any(a.startswith("domain=") for a in attrs), (
f"session cookie carries a Domain attribute, widening it to "
@@ -660,7 +660,7 @@ class TestCookieSurface:
)
kwargs = entries[0].kwargs
assert kwargs.get("session_cookie") == "session", kwargs
- assert kwargs.get("same_site") == "strict", kwargs
+ assert kwargs.get("same_site") == "lax", kwargs
assert kwargs.get("https_only") is False, (
"https_only=True would make SessionMiddleware stamp Secure on "
"every session cookie, including over plain HTTP, where "
diff --git a/tests/web/test_session_cookie_behavior.py b/tests/web/test_session_cookie_behavior.py
index c03a406bfa..da88d491ad 100644
--- a/tests/web/test_session_cookie_behavior.py
+++ b/tests/web/test_session_cookie_behavior.py
@@ -9,8 +9,8 @@ TestClient:
stored _remember_me=False in the session);
- login WITH "remember me" keeps the ~30-day Max-Age SessionMiddleware
is configured with;
-- every session Set-Cookie carries SameSite=strict and HttpOnly
- (fastapi_app configures same_site="strict"), and the attribute
+- every session Set-Cookie carries SameSite=lax and HttpOnly
+ (fastapi_app configures same_site="lax"), and the attribute
stripping for non-remember-me logins must not drop them;
- SecureCookieMiddleware appends the Secure flag iff the request scheme
is https (exercised through the real middleware stack by flipping the
@@ -149,7 +149,7 @@ def test_login_without_remember_me_keeps_other_cookie_attributes(
cookie = _session_set_cookies(resp)[0]
assert _cookie_attr(cookie, "path") == "/", cookie
assert _cookie_attr(cookie, "httponly") is not None, cookie
- assert (_cookie_attr(cookie, "samesite") or "").lower() == "strict", cookie
+ assert (_cookie_attr(cookie, "samesite") or "").lower() == "lax", cookie
# And the cookie still carries a non-empty signed value.
assert len(cookie.split(";")[0].partition("=")[2]) > 0, cookie
@@ -174,7 +174,7 @@ def test_login_with_remember_me_issues_30_day_persistent_cookie(
assert int(max_age) == THIRTY_DAYS_SECONDS, cookie
# Persistence must not come at the cost of the hardening attributes.
assert _cookie_attr(cookie, "httponly") is not None, cookie
- assert (_cookie_attr(cookie, "samesite") or "").lower() == "strict", cookie
+ assert (_cookie_attr(cookie, "samesite") or "").lower() == "lax", cookie
# ---------------------------------------------------------------------------
@@ -182,9 +182,9 @@ def test_login_with_remember_me_issues_30_day_persistent_cookie(
# ---------------------------------------------------------------------------
-def test_unauthenticated_session_cookie_is_strict_and_httponly(app):
+def test_unauthenticated_session_cookie_is_lax_and_httponly(app):
"""Even the pre-login session cookie (created when the CSRF token is
- stamped on GET /auth/login) must be SameSite=strict + HttpOnly."""
+ stamped on GET /auth/login) must be SameSite=lax + HttpOnly."""
client = _fresh_client(app)
resp = client.get("/auth/login")
assert resp.status_code == 200
@@ -193,7 +193,7 @@ def test_unauthenticated_session_cookie_is_strict_and_httponly(app):
assert cookies, "GET /auth/login set no session cookie"
cookie = cookies[0]
assert _cookie_attr(cookie, "httponly") is not None, cookie
- assert (_cookie_attr(cookie, "samesite") or "").lower() == "strict", cookie
+ assert (_cookie_attr(cookie, "samesite") or "").lower() == "lax", cookie
# ---------------------------------------------------------------------------
diff --git a/tests/web/test_session_cookie_semantics.py b/tests/web/test_session_cookie_semantics.py
index 7537be2748..42026c498b 100644
--- a/tests/web/test_session_cookie_semantics.py
+++ b/tests/web/test_session_cookie_semantics.py
@@ -388,7 +388,7 @@ def test_session_survives_a_redirect_chain(app):
Every other session test in the suite uses ``follow_redirects=False``,
so nothing pins that the cookie actually rides through the bounce that
- real login performs. SameSite=strict is safe for a same-site redirect;
+ real login performs. SameSite=Lax permits this same-site redirect;
a stricter value, or a Path that did not cover the target, would strand
the session on the hop.
"""