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: recover stale CSRF tokens within the same login (#6789)

LearningCircuit7395c2b813be
diff --git a/changelog.d/+session-bound-csrf-recovery.bugfix.md b/changelog.d/+session-bound-csrf-recovery.bugfix.md
new file mode 100644
index 0000000000..dbb98b9cc3
--- /dev/null
+++ b/changelog.d/+session-bound-csrf-recovery.bugfix.md
@@ -0,0 +1 @@
+Recover stale CSRF tokens once for replayable API writes sent through the shared API helpers within the same login session. Send expired sessions to login, reject such writes when the login has been replaced, and preserve cancellation and timeouts.
diff --git a/src/local_deep_research/web/dependencies/csrf.py b/src/local_deep_research/web/dependencies/csrf.py
index 219df8bead..f5201debd7 100644
--- a/src/local_deep_research/web/dependencies/csrf.py
+++ b/src/local_deep_research/web/dependencies/csrf.py
@@ -114,6 +114,7 @@ library over hand-rolled security code, a reasonable default instinct):
in both directions, JSON and multipart).
"""
+import hashlib
import secrets
from fastapi import Request
@@ -136,6 +137,24 @@ def generate_csrf_token(request: Request) -> str:
return token
+def get_auth_context(session) -> str | None:
+ """Fingerprint a login for retry fencing, without exposing its session ID.
+
+ This value grants no authority. CSRF validation and authentication still
+ apply independently; the fingerprint only detects a different login.
+ """
+ session_id = session.get("session_id")
+ if (
+ not session.get("username")
+ or not isinstance(session_id, str)
+ or not session_id
+ ):
+ return None
+ return hashlib.sha256(
+ f"ldr-csrf-context:{session_id}".encode("utf-8")
+ ).hexdigest()
+
+
def _tokens_match(session_token: object, provided_token: object) -> bool:
"""Compare usable string tokens without letting malformed state raise."""
if not isinstance(session_token, str) or not isinstance(
@@ -271,9 +290,32 @@ class CSRFMiddleware:
await self.app(scope, receive, send)
return
- session = scope.get("session", {})
+ session = scope.get("session") or {}
session_token = session.get("_csrf_token") if session else None
+ # Read headers before token validation: a replacement login may not
+ # have rendered a page (and minted its CSRF token) yet.
+ headers = {
+ k.decode("latin-1").lower(): v.decode("latin-1")
+ for k, v in scope.get("headers", [])
+ }
+ # Bind opt-in writes to the login rendered into their page, including
+ # a change between CSRF refresh and retry. This header grants no auth.
+ expected_context = headers.get("x-ldr-auth-context")
+ if expected_context is not None:
+ context = get_auth_context(session)
+ if not _tokens_match(context, expected_context):
+ response = JSONResponse(
+ {
+ "error": "Your sign-in changed. Reload this page before trying again."
+ if context
+ else "Authentication required"
+ },
+ status_code=409 if context else 401,
+ )
+ await response(scope, receive, send)
+ return
+
# Fail closed: an unsafe request MUST carry a session-bound CSRF
# token. Endpoints legitimately reachable without one (login,
# register, csrf-token fetch, password-strength check) are in
@@ -291,15 +333,11 @@ class CSRFMiddleware:
response = JSONResponse(
{"error": "CSRF token missing: fetch /auth/csrf-token first"},
status_code=403,
+ headers={"X-LDR-CSRF-Rejected": "1"},
)
await response(scope, receive, send)
return
- # Read the X-CSRFToken header (case-insensitive).
- headers = {
- k.decode("latin-1").lower(): v.decode("latin-1")
- for k, v in scope.get("headers", [])
- }
provided = headers.get("x-csrftoken") or headers.get("x-csrf-token")
# Only buffer the body when we actually need to read the
@@ -388,7 +426,9 @@ class CSRFMiddleware:
bool(provided),
)
response = JSONResponse(
- {"error": "CSRF token missing or invalid"}, status_code=403
+ {"error": "CSRF token missing or invalid"},
+ status_code=403,
+ headers={"X-LDR-CSRF-Rejected": "1"},
)
await response(scope, receive, send)
return
diff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.py
index 54fcf0d316..805e22c6c4 100644
--- a/src/local_deep_research/web/routers/auth.py
+++ b/src/local_deep_research/web/routers/auth.py
@@ -49,10 +49,27 @@ router = APIRouter(prefix="/auth", tags=["auth"])
@router.get("/csrf-token")
def get_csrf_token(request: Request):
"""Get CSRF token for API requests."""
- from ..dependencies.csrf import generate_csrf_token
-
+ from ..dependencies.csrf import generate_csrf_token, get_auth_context
+
+ context = get_auth_context(request.session)
+ expected_context = request.headers.get("X-LDR-Auth-Context")
+ if expected_context is not None and expected_context != context:
+ # A recovery fetch is tied to the page's original login. Ordinary
+ # anonymous token fetches (login/register forms) remain supported.
+ return JSONResponse(
+ {
+ "error": "Your sign-in changed. Reload this page before trying again."
+ if context
+ else "Authentication required"
+ },
+ status_code=409 if context else 401,
+ headers={"Cache-Control": "no-store"},
+ )
token = generate_csrf_token(request)
- return {"csrf_token": token}
+ return JSONResponse(
+ {"csrf_token": token, "auth_context": context},
+ headers={"Cache-Control": "no-store"},
+ )
def _rollback_partial_session(request: Request, username: str) -> None:
diff --git a/src/local_deep_research/web/static/js/security/safe-fetch.js b/src/local_deep_research/web/static/js/security/safe-fetch.js
index 342cbaa5be..8974a88f47 100644
--- a/src/local_deep_research/web/static/js/security/safe-fetch.js
+++ b/src/local_deep_research/web/static/js/security/safe-fetch.js
@@ -16,11 +16,11 @@ async function safeFetch(url, options = {}) {
/**
* Auth-aware variant of safeFetch for our own API endpoints.
*
- * Identical to safeFetch, except that a 401 from an internal URL (an expired
- * session) navigates to the login page instead of returning the Response, so
- * callers that inspect response.status don't each have to special-case
- * re-authentication. On the redirect path it returns a never-resolving Promise
- * (the page is navigating away), matching fetchWithErrorHandling's behavior.
+ * Recovers an explicitly rejected CSRF check once for eligible writes within
+ * the page's original login. A 401 from an internal URL navigates to login,
+ * so callers that inspect response.status share the same re-authentication
+ * behavior. That redirect returns a never-resolving Promise (the page is
+ * navigating away), matching fetchWithErrorHandling's behavior.
*
* The "which 401s redirect" decision and the login-URL construction are reused
* from api.js (window.api) so there is a single definition shared with
@@ -29,7 +29,9 @@ async function safeFetch(url, options = {}) {
* Do NOT use on /auth/* endpoints — those handle their own 401 states.
*/
async function safeFetchWithAuth(url, options = {}) {
- const response = await safeFetch(url, options);
+ const response = typeof window.api?.fetchWithCsrfRecovery === 'function'
+ ? await window.api.fetchWithCsrfRecovery(url, options, safeFetch)
+ : await safeFetch(url, options);
if (response.status === 401 && window.api.shouldRedirectToLoginOn401(url)) {
window.api.redirectToLogin();
return new Promise(() => {}); // never resolves; page is navigating away
diff --git a/src/local_deep_research/web/static/js/services/api.js b/src/local_deep_research/web/static/js/services/api.js
index 6b8b680834..99e0e2f709 100644
--- a/src/local_deep_research/web/static/js/services/api.js
+++ b/src/local_deep_research/web/static/js/services/api.js
@@ -19,6 +19,71 @@ function getCsrfToken() {
return metaTag ? metaTag.getAttribute('content') : '';
}
+/** Read the non-authenticating fingerprint of the login that rendered this page. */
+function getAuthContext() {
+ const value = document.querySelector('meta[name="auth-context"]')?.getAttribute('content');
+ return typeof value === 'string' && /^[a-f0-9]{64}$/.test(value) ? value : null;
+}
+
+/** Retry only a rejected CSRF check, once, within the page's original login. */
+async function fetchWithCsrfRecovery(url, options = {}, send = fetch) {
+ const method = (options.method || 'GET').toUpperCase();
+ const repeatableBody = options.body == null || typeof options.body === 'string';
+ let internal = false;
+ if (typeof url === 'string' && url.startsWith('/') && typeof window !== 'undefined' && window.location?.href) {
+ const target = new URL(url, window.location.href);
+ internal = target.origin === new URL(window.location.href).origin
+ && !target.pathname.startsWith('/auth/')
+ && !window.location.pathname.startsWith('/auth/');
+ }
+ const eligible = internal && ['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)
+ && repeatableBody && options.credentials !== 'omit';
+ const context = eligible ? getAuthContext() : null;
+ // Snapshot the headers before sending. Do not mutate a caller's Headers
+ // instance or let later changes replace the original request's context.
+ let initialOptions = options;
+ if (context) {
+ const headers = new globalThis.Headers(options.headers);
+ headers.set('X-LDR-Auth-Context', context);
+ initialOptions = { ...options, headers };
+ }
+ const response = await send(url, initialOptions);
+ if (!context || response.status !== 403 || response.redirected
+ || response.headers?.get('X-LDR-CSRF-Rejected') !== '1') {
+ return response;
+ }
+
+ // The marker is emitted only by middleware before a handler is entered.
+ // Streams/uploads are never replayed, nor are ordinary application 403s.
+ options.signal?.throwIfAborted();
+ const refresh = await send('/auth/csrf-token', {
+ method: 'GET', credentials: 'same-origin', cache: 'no-store', redirect: 'error',
+ headers: { 'X-LDR-Auth-Context': context }, signal: options.signal
+ });
+ options.signal?.throwIfAborted();
+ if (getAuthContext() !== context) {
+ throw new Error('Your sign-in changed. Reload this page before trying again.');
+ }
+ // The endpoint returns 401/409 if the login expired or was replaced. Let
+ // the existing auth/error handling surface it; no original write is sent.
+ if (!refresh.ok) return refresh;
+ const fresh = await refresh.json();
+ options.signal?.throwIfAborted();
+ if (typeof fresh?.auth_context !== 'string' || typeof fresh?.csrf_token !== 'string' || !fresh.csrf_token) {
+ return response;
+ }
+ if (fresh.auth_context !== context || getAuthContext() !== context) {
+ throw new Error('Your sign-in changed. Reload this page before trying again.');
+ }
+ document.querySelector('meta[name="csrf-token"]')?.setAttribute('content', fresh.csrf_token);
+ const headers = new globalThis.Headers(initialOptions.headers);
+ headers.delete('X-CSRF-Token');
+ headers.set('X-CSRFToken', fresh.csrf_token);
+ // A direct send (not recursion) caps the entire operation at one retry.
+ // Reuse the original signal so refresh does not reset its timeout.
+ return send(url, { ...initialOptions, headers });
+}
+
/**
* Get the full URL for an API endpoint
* @param {string} path - The API path (without leading slash)
@@ -107,7 +172,7 @@ async function fetchWithErrorHandling(url, options = {}) {
try {
const csrfToken = getCsrfToken();
- const response = await fetch(url, {
+ const response = await fetchWithCsrfRecovery(url, {
...fetchOptions,
signal: controller.signal,
headers: {
@@ -349,6 +414,7 @@ if (typeof module !== 'undefined' && module.exports) {
module.exports = {
getCsrfToken,
fetchWithErrorHandling,
+ fetchWithCsrfRecovery,
shouldRedirectToLoginOn401,
redirectToLogin,
getApiUrl,
@@ -397,6 +463,7 @@ if (typeof window !== 'undefined') {
getApiUrl,
getCsrfToken,
fetchWithErrorHandling,
+ fetchWithCsrfRecovery,
// Exposed so the direct-safeFetch call sites (library/settings/etc.)
// can adopt the same 401->login behavior without duplicating the logic.
shouldRedirectToLoginOn401,
diff --git a/src/local_deep_research/web/template_config.py b/src/local_deep_research/web/template_config.py
index 5ea99cfcce..6ae7750a8d 100644
--- a/src/local_deep_research/web/template_config.py
+++ b/src/local_deep_research/web/template_config.py
@@ -46,6 +46,9 @@ class _LDRTemplates(Jinja2Templates):
# Inject session so templates can do {{ session.username }}.
# Every base template reads session.username for the top bar.
context.setdefault("session", session)
+ from .dependencies.csrf import get_auth_context
+
+ context["auth_context"] = get_auth_context(session)
# Inject CSRF token if not already present
if "csrf_token" not in context:
diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.html
index cd3d998718..af36a3d09e 100644
--- a/src/local_deep_research/web/templates/base.html
+++ b/src/local_deep_research/web/templates/base.html
@@ -4,6 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="{{ csrf_token() }}">
+ <meta name="auth-context" content="{{ auth_context|default('', true) }}">
<meta name="user-id" content="{{ session.username|default('anonymous', true) }}">
<title>{% block title %}Deep Research System{% endblock %}</title>
<link rel="icon" type="image/png" href="/static/favicon.png">
diff --git a/tests/js/components/settings-submit-runtime.test.js b/tests/js/components/settings-submit-runtime.test.js
index 7586f7f58d..dcda33d637 100644
--- a/tests/js/components/settings-submit-runtime.test.js
+++ b/tests/js/components/settings-submit-runtime.test.js
@@ -662,8 +662,8 @@ it('limits partial bulk-save errors to owned keys and preserves the newer spinne
{ key: 'app.extra', error: 'Current extra rejection' },
],
}, 400));
- await flushPromises();
- expect(fetchMock).toHaveBeenCalledTimes(2);
+ // Wait for the queued request, independent of API wrapper microtasks.
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
expect(field.item.querySelector('.ldr-settings-error-message')).toBeNull();
expect(window.ui.showMessage).toHaveBeenLastCalledWith(
'Error saving settings: Validation errors — app.extra: Current extra rejection',
diff --git a/tests/js/services/csrf-recovery.test.js b/tests/js/services/csrf-recovery.test.js
new file mode 100644
index 0000000000..2a55dc1a15
--- /dev/null
+++ b/tests/js/services/csrf-recovery.test.js
@@ -0,0 +1,170 @@
+import '@js/config/urls.js';
+import '@js/services/api.js';
+import '@js/security/url-validator.js';
+import '@js/security/safe-fetch.js';
+
+const context = 'a'.repeat(64);
+const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), {
+ status, headers: { 'Content-Type': 'application/json', ...headers }
+});
+const rejected = () => json({ error: 'CSRF token missing or invalid' }, 403, { 'X-LDR-CSRF-Rejected': '1' });
+const refreshed = (authContext = context) => json({ csrf_token: 'fresh-token', auth_context: authContext });
+const token = () => document.querySelector('meta[name="csrf-token"]').content;
+
+describe('session-bound CSRF recovery', () => {
+ const originalLocation = window.location;
+ const originalFetch = globalThis.fetch;
+
+ beforeEach(() => {
+ delete window.location;
+ window.location = { href: 'http://localhost/settings', pathname: '/settings', search: '', hash: '' };
+ document.head.replaceChildren();
+ for (const [name, content] of [['csrf-token', 'stale-token'], ['auth-context', context]]) {
+ const meta = document.createElement('meta');
+ meta.name = name;
+ meta.content = content;
+ document.head.append(meta);
+ }
+ globalThis.fetch = vi.fn();
+ });
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ window.location = originalLocation;
+ document.head.replaceChildren();
+ vi.useRealTimers();
+ });
+
+ it('refreshes and retries a rejected JSON write exactly once with the same body', async () => {
+ fetch.mockResolvedValueOnce(rejected()).mockResolvedValueOnce(refreshed()).mockResolvedValueOnce(json({ saved: true }));
+ const body = JSON.stringify({ value: 'keep this exact payload' });
+ await expect(window.api.fetchWithErrorHandling('/settings/api/save', { method: 'POST', body })).resolves.toEqual({ saved: true });
+ expect(fetch).toHaveBeenCalledTimes(3);
+ expect(fetch.mock.calls.map(([url]) => url)).toEqual(['/settings/api/save', '/auth/csrf-token', '/settings/api/save']);
+ expect(fetch.mock.calls[1][1]).toMatchObject({ cache: 'no-store', credentials: 'same-origin', redirect: 'error' });
+ const replay = fetch.mock.calls[2][1];
+ expect(replay.body).toBe(body);
+ expect(new globalThis.Headers(replay.headers).get('X-CSRFToken')).toBe('fresh-token');
+ expect(new globalThis.Headers(replay.headers).get('X-LDR-Auth-Context')).toBe(context);
+ expect(replay.signal).toBe(fetch.mock.calls[0][1].signal);
+ expect(token()).toBe('fresh-token');
+ });
+
+ it('supports auth-aware raw responses and replaces either spelling of a caller token', async () => {
+ fetch.mockResolvedValueOnce(rejected()).mockResolvedValueOnce(refreshed()).mockResolvedValueOnce(json({ deleted: true }));
+ const options = { method: 'DELETE', headers: new globalThis.Headers({ 'X-CSRF-Token': 'old-override', 'X-Trace': 'keep', 'x-ldr-auth-context': 'caller-value' }) };
+ const response = await window.safeFetchWithAuth('/library/api/item/1', options);
+ expect(await response.json()).toEqual({ deleted: true });
+ const sent = new globalThis.Headers(fetch.mock.calls[2][1].headers);
+ expect(sent.get('X-CSRFToken')).toBe('fresh-token');
+ expect(sent.has('X-CSRF-Token')).toBe(false);
+ expect(sent.get('X-Trace')).toBe('keep');
+ expect(new globalThis.Headers(fetch.mock.calls[0][1].headers).get('X-LDR-Auth-Context')).toBe(context);
+ expect(sent.get('X-LDR-Auth-Context')).toBe(context);
+ expect(options.headers.get('X-CSRF-Token')).toBe('old-override');
+ expect(options.headers.get('X-LDR-Auth-Context')).toBe('caller-value');
+ });
+
+ it.each([
+ ['/api/save', { method: 'POST', body: '{}' }, json({ error: 'Permission denied' }, 403)],
+ ['/api/save', { method: 'POST', body: '{}' }, json({ error: 'failed' }, 500)],
+ ['/api/save', { method: 'GET' }, rejected()],
+ ['https://outside.example/save', { method: 'POST', body: '{}' }, rejected()],
+ ['//outside.example/save', { method: 'POST', body: '{}' }, rejected()],
+ ['/\\outside.example/save', { method: 'POST', body: '{}' }, rejected()],
+ ['/\t/outside.example/save', { method: 'POST', body: '{}' }, rejected()],
+ ['/auth/login', { method: 'POST', body: '{}' }, rejected()],
+ ['/api/save', { method: 'POST', body: new FormData() }, rejected()],
+ ['/api/save', { method: 'POST', body: '{}', credentials: 'omit' }, rejected()],
+ ])('does not retry an ineligible request or unrelated error (%s)', async (url, options, response) => {
+ fetch.mockResolvedValueOnce(response);
+ await expect(window.api.fetchWithErrorHandling(url, options)).rejects.toThrow();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(token()).toBe('stale-token');
+ });
+
+ it('does not retry after a transport failure with an unknown write outcome', async () => {
+ fetch.mockRejectedValueOnce(new TypeError('Failed to fetch'));
+ await expect(window.api.postJSON('/api/save', {})).rejects.toThrow('Failed to fetch');
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not retry a CSRF rejection reached through a redirect', async () => {
+ const response = rejected();
+ Object.defineProperty(response, 'redirected', { value: true });
+ fetch.mockResolvedValueOnce(response);
+ await expect(window.api.postJSON('/api/save', {})).rejects.toThrow('CSRF');
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not recover without a rendered authenticated context', async () => {
+ document.querySelector('meta[name="auth-context"]').remove();
+ fetch.mockResolvedValueOnce(rejected());
+ await expect(window.api.postJSON('/api/save', {})).rejects.toThrow('CSRF');
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('never retries after another login replaced the original one', async () => {
+ fetch.mockResolvedValueOnce(rejected()).mockResolvedValueOnce(refreshed('b'.repeat(64)));
+ await expect(window.api.postJSON('/api/save', {})).rejects.toThrow(/sign-in.*changed/i);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(token()).toBe('stale-token');
+ });
+
+ it('does not replay if the page context changes while refreshing', async () => {
+ fetch.mockResolvedValueOnce(rejected()).mockImplementationOnce(async () => {
+ document.querySelector('meta[name="auth-context"]').content = 'b'.repeat(64);
+ return refreshed();
+ });
+ await expect(window.api.postJSON('/api/save', {})).rejects.toThrow(/sign-in.*changed/i);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(token()).toBe('stale-token');
+ });
+
+ it('sends an expired session to login without replaying its write', async () => {
+ fetch.mockResolvedValueOnce(rejected()).mockResolvedValueOnce(json({ error: 'Authentication required' }, 401));
+ const onRejected = vi.fn();
+ window.api.postJSON('/api/save', {}).catch(onRejected);
+ await vi.waitFor(() => expect(window.location.href).toBe('/auth/login?next=%2Fsettings'));
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(onRejected).not.toHaveBeenCalled();
+ });
+
+ it('stops after the second CSRF rejection', async () => {
+ fetch.mockResolvedValueOnce(rejected()).mockResolvedValueOnce(refreshed()).mockResolvedValueOnce(rejected());
+ await expect(window.api.postJSON('/api/save', {})).rejects.toThrow('CSRF');
+ expect(fetch).toHaveBeenCalledTimes(3);
+ });
+
+ it.each([json({ error: 'refresh failed' }, 503), json({ csrf_token: 'fresh-token' }), json({ auth_context: context })])(
+ 'does not replay when refresh fails or is malformed', async response => {
+ fetch.mockResolvedValueOnce(rejected()).mockResolvedValueOnce(response);
+ await expect(window.api.postJSON('/api/save', {})).rejects.toThrow();
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(token()).toBe('stale-token');
+ }
+ );
+
+ it('honors cancellation during refresh and never sends the write again', async () => {
+ const controller = new AbortController();
+ fetch.mockResolvedValueOnce(rejected()).mockImplementationOnce(async (_url, options) => {
+ controller.abort();
+ options.signal.throwIfAborted();
+ });
+ await expect(window.api.fetchWithErrorHandling('/api/save', {
+ method: 'POST', body: '{}', signal: controller.signal
+ })).rejects.toMatchObject({ name: 'AbortError' });
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps the original timeout across refresh', async () => {
+ vi.useFakeTimers();
+ fetch.mockResolvedValueOnce(rejected()).mockImplementationOnce((_url, options) => new Promise((_resolve, reject) => {
+ options.signal.addEventListener('abort', () => reject(new globalThis.DOMException('aborted', 'AbortError')), { once: true });
+ }));
+ const request = window.api.fetchWithErrorHandling('/api/save', { method: 'POST', body: '{}', timeout: 100 });
+ const assertion = expect(request).rejects.toThrow('Request timed out');
+ await vi.advanceTimersByTimeAsync(100);
+ await assertion;
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/tests/web/test_csrf_recovery.py b/tests/web/test_csrf_recovery.py
new file mode 100644
index 0000000000..d2c400293d
--- /dev/null
+++ b/tests/web/test_csrf_recovery.py
@@ -0,0 +1,202 @@
+"""A CSRF retry is distinguishable from an application error and session-bound."""
+
+import pytest
+
+from fastapi import FastAPI, Request
+from fastapi.responses import JSONResponse
+from fastapi.testclient import TestClient
+from starlette.middleware.sessions import SessionMiddleware
+
+from local_deep_research.web.dependencies.csrf import CSRFMiddleware
+from local_deep_research.web.routers.auth import get_csrf_token
+
+
+# Use the real application to cover its template injection and unconditional
+# session-revocation check before the token endpoint (not just the light stack).
+from tests.web.test_auth_session_lifecycle import (
+ _client as _lifecycle_client,
+ _login,
+ _register,
+ _session_payload,
+ live_app as _lifecycle_app,
+)
+
+live_app = _lifecycle_app
+
+
+def _client():
+ app = FastAPI()
+ calls = []
+
+ @app.get("/seed/{owner}")
+ def seed(request: Request, owner: str, mint_csrf: bool = True):
+ request.session.clear()
+ request.session.update(username="alice", session_id=owner)
+ return get_csrf_token(request) if mint_csrf else {"ok": True}
+
+ app.get("/auth/csrf-token")(get_csrf_token)
+
+ @app.post("/mutate")
+ def mutate():
+ calls.append("mutate")
+ return {"ok": True}
+
+ @app.post("/forbidden")
+ def forbidden():
+ calls.append("forbidden")
+ return JSONResponse({"error": "Permission denied"}, status_code=403)
+
+ app.add_middleware(CSRFMiddleware)
+ app.add_middleware(SessionMiddleware, secret_key="csrf-recovery-test")
+ return TestClient(app), calls
+
+
+def test_csrf_rejection_marker_means_handler_did_not_run():
+ client, calls = _client()
+ missing = client.post("/mutate")
+ assert missing.status_code == 403
+ assert missing.headers.get("X-LDR-CSRF-Rejected") == "1"
+ token = client.get("/seed/owner-a").json()["csrf_token"]
+ invalid = client.post("/mutate", headers={"X-CSRFToken": "stale"})
+ assert invalid.status_code == 403
+ assert invalid.headers.get("X-LDR-CSRF-Rejected") == "1"
+ assert calls == []
+ assert (
+ client.post("/mutate", headers={"X-CSRFToken": token}).status_code
+ == 200
+ )
+ assert calls == ["mutate"]
+ forbidden = client.post("/forbidden", headers={"X-CSRFToken": token})
+ assert forbidden.status_code == 403
+ assert "X-LDR-CSRF-Rejected" not in forbidden.headers
+ assert calls == ["mutate", "forbidden"]
+
+
+def test_refresh_context_identifies_the_login_without_exposing_its_id():
+ client, _ = _client()
+ anonymous = client.get("/auth/csrf-token")
+ assert anonymous.headers.get("Cache-Control") == "no-store"
+ assert anonymous.json()["auth_context"] is None
+ first = client.get("/seed/private-session-a").json()
+ assert (
+ first["auth_context"]
+ and "private-session-a" not in first["auth_context"]
+ )
+ assert first["auth_context"] != first["csrf_token"]
+ assert client.get("/auth/csrf-token").json() == first
+ second = client.get("/seed/private-session-b").json()
+ assert second["auth_context"] != first["auth_context"]
+
+
+def test_changed_login_cannot_receive_a_replayed_write_even_with_its_csrf_token():
+ client, calls = _client()
+ old = client.get("/seed/owner-a").json()
+ current = client.get("/seed/owner-b").json()
+ response = client.post(
+ "/mutate",
+ headers={
+ "X-CSRFToken": current["csrf_token"],
+ "X-LDR-Auth-Context": old["auth_context"],
+ },
+ )
+ assert response.status_code == 409
+ assert "X-LDR-CSRF-Rejected" not in response.headers
+ assert calls == []
+ accepted = client.post(
+ "/mutate",
+ headers={
+ "X-CSRFToken": current["csrf_token"],
+ "X-LDR-Auth-Context": current["auth_context"],
+ },
+ )
+ assert accepted.status_code == 200
+ assert calls == ["mutate"]
+
+
+def test_replaced_login_is_rejected_even_before_it_has_a_csrf_token():
+ client, calls = _client()
+ old = client.get("/seed/owner-a").json()
+ # Login clears the old token; a new page normally mints the next one.
+ client.get("/seed/owner-b", params={"mint_csrf": "false"})
+ response = client.post(
+ "/mutate",
+ headers={
+ "X-CSRFToken": old["csrf_token"],
+ "X-LDR-Auth-Context": old["auth_context"],
+ },
+ )
+ assert response.status_code == 409
+ assert "sign-in changed" in response.json()["error"]
+ assert "X-LDR-CSRF-Rejected" not in response.headers
+ assert calls == []
+
+
[email protected]("anonymous_token", [False, True])
+def test_bound_write_requires_login_after_the_cookie_is_cleared(
+ anonymous_token,
+):
+ client, calls = _client()
+ old = client.get("/seed/owner-a").json()
+ client.cookies.clear()
+ if anonymous_token:
+ client.get("/auth/csrf-token")
+ response = client.post(
+ "/mutate", headers={"X-LDR-Auth-Context": old["auth_context"]}
+ )
+ assert response.status_code == 401
+ assert "X-LDR-CSRF-Rejected" not in response.headers
+ assert calls == []
+
+
+def test_recovery_fetch_rejects_anonymous_or_replaced_login_without_minting_token():
+ client, _ = _client()
+ anonymous = client.get(
+ "/auth/csrf-token", headers={"X-LDR-Auth-Context": "old"}
+ )
+ assert anonymous.status_code == 401
+ assert anonymous.headers["Cache-Control"] == "no-store"
+ assert "csrf_token" not in anonymous.json()
+ old = client.get("/seed/owner-a").json()
+ current = client.get("/seed/owner-b").json()
+ changed = client.get(
+ "/auth/csrf-token", headers={"X-LDR-Auth-Context": old["auth_context"]}
+ )
+ assert changed.status_code == 409
+ assert "csrf_token" not in changed.json()
+ accepted = client.get(
+ "/auth/csrf-token",
+ headers={"X-LDR-Auth-Context": current["auth_context"]},
+ )
+ assert accepted.status_code == 200
+ assert accepted.json() == current
+
+
[email protected]_session_check
+def test_real_page_and_refresh_share_a_context_that_expires_with_the_login(
+ live_app,
+):
+ import re
+ import uuid
+ from local_deep_research.web.auth.session_manager import session_manager
+
+ client = _lifecycle_client(live_app)
+ username = "csrf_context_" + uuid.uuid4().hex[:8]
+ assert _register(client, username).status_code == 302
+ identity = client.get("/auth/csrf-token").json()
+ page = client.get("/settings/")
+ assert page.status_code == 200
+ rendered = re.search(
+ r'<meta name="auth-context" content="([a-f0-9]+)">', page.text
+ )
+ assert rendered and rendered.group(1) == identity["auth_context"]
+ session_id = _session_payload(client)["session_id"]
+ session_manager.destroy_session(session_id)
+ expired = client.get(
+ "/auth/csrf-token",
+ headers={"X-LDR-Auth-Context": identity["auth_context"]},
+ )
+ assert expired.status_code == 401
+ assert "csrf_token" not in expired.json()
+ assert _login(client, username).status_code == 302
+ replacement = client.get("/auth/csrf-token").json()
+ assert replacement["auth_context"] != identity["auth_context"]