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): recover unusable sessions and stale logout forms (#6965)

LearningCircuit011c32b1329f
diff --git a/changelog.d/+session-logout-recovery.bugfix.md b/changelog.d/+session-logout-recovery.bugfix.md
new file mode 100644
index 0000000000..e265f32d57
--- /dev/null
+++ b/changelog.d/+session-logout-recovery.bugfix.md
@@ -0,0 +1 @@
+Require sign-in again when an encrypted database session loses its credential, even while a shared connection remains open. This applies to the root page as well as protected routes, and the rejected session is also ended on the server and its live sockets disconnected. When the user's database cannot be reopened, the root page ends the session the same way before sending the browser to sign in. Clear expired or already-used bootstrap tokens from stale cookies so they cannot hide the missing credential. Desktop and mobile logout recover expired sessions and stale CSRF tokens without submitting logout against a replacement login.
diff --git a/src/local_deep_research/web/dependencies/auth.py b/src/local_deep_research/web/dependencies/auth.py
index 65f508a84e..d6b500b7d7 100644
--- a/src/local_deep_research/web/dependencies/auth.py
+++ b/src/local_deep_research/web/dependencies/auth.py
@@ -24,27 +24,29 @@ def get_session_username(request: Request) -> str | None:
def clear_session_if_unrecoverable(request: Request, username: str) -> bool:
- """Drop a stale session that has no way back to an open database.
+ """Drop a stale session that has no database recovery credential.
Ports ``cleanup_stale_sessions()``, which Flask ran as a before_request
handler on every request (``web/auth/session_cleanup.py`` on main, deleted
by this migration with no successor). Without it, a session whose password
has been evicted keeps a valid ``username`` cookie that 401s on every
protected route: the browser still believes it is logged in and nothing
- tells it otherwise. The root route clears the session on its own error path
- (``fastapi_app.py`` index()), so someone who navigates to "/" recovers —
- but an API or XHR client polling endpoints never does.
+ tells it otherwise. An API or XHR client polling endpoints would never
+ recover.
Only clears when recovery is genuinely impossible, matching the original:
a temp auth token or a stored session password means
``ensure_user_database()`` can still reopen the connection, so the session
is stale rather than dead and must be left alone.
- Unlike the Flask version this is not throttled. That throttle
- (``should_skip_session_cleanup()``) existed because a before_request hook
- ran on every request including static assets; here the check is reached
- only when authentication has already failed on a missing connection, which
- is rare.
+ This also runs when a server-side session is still valid and its shared
+ connection is open. Background work or another device can keep that
+ connection alive after this session loses its required credential.
+
+ When it clears the cookie it also destroys the matching server-side
+ session and disconnects that session's sockets
+ (``_revoke_server_session``), because the cleared browser can no longer
+ reach logout to do it.
Returns True if the session was cleared.
"""
@@ -66,14 +68,85 @@ def clear_session_if_unrecoverable(request: Request, username: str) -> bool:
return False
logger.info(
- "Clearing stale session for {} — no database connection and no "
- "recovery credential",
- username,
+ "Clearing stale session for {} — no recovery credential", username
)
+ if session_id:
+ _revoke_server_session(session_id, username)
request.session.clear()
return True
+def _revoke_server_session(session_id: str, username: str) -> None:
+ """Destroy the server-side session behind a cookie that is being cleared.
+
+ Clearing only the cookie would leave the ``session_manager`` record alive
+ for the rest of its idle timeout (up to ``session_remember_me_days``).
+ Once the cookie is gone the browser cannot reach logout, the path that
+ normally destroys it. A replayed copy of the cookie would keep renewing
+ that record, and checks that rely on ``validate_session`` alone (the
+ Socket.IO connect gate, ``has_active_sessions_for`` in the idle sweeper)
+ would keep treating the session as live. So destroy the record and
+ disconnect its sockets, the same per-session teardown logout performs.
+
+ Only this session is affected. The user's other sessions keep working.
+ A session id owned by a different user is left alone. Teardown is
+ best-effort so a failure here cannot turn the 401 into a 500.
+ """
+ try:
+ owner = session_manager.validate_session(session_id)
+ if owner is not None and owner != username:
+ return
+ if owner is not None:
+ session_manager.destroy_session(session_id)
+ from ..services.socketio_asgi import disconnect_session
+
+ disconnect_session(session_id)
+ except Exception as exc:
+ # Type name only: a rendered traceback would include session_id.
+ failure = type(exc).__name__
+ else:
+ return
+ logger.warning(
+ "Failed to revoke an unrecoverable server-side session: {}", failure
+ )
+
+
+def end_rejected_session(request: Request) -> None:
+ """Log out a browser whose session ``require_auth`` rejected but kept.
+
+ ``require_auth`` keeps the cookie on one 401 path on purpose: the user's
+ database is not connected, but ``clear_session_if_unrecoverable`` still
+ sees a way to recover (this session's stored password, a temp auth token,
+ or an unencrypted install). If the reopen then keeps failing (missing or
+ corrupt database file, a failed migration, the close/rekey window of a
+ password change), every request 401s with ``username`` still in the
+ cookie. ``/auth/login`` sends any cookie with a username back to ``/``,
+ so a page that redirects that 401 to the login page without clearing the
+ cookie loops between the two until the browser gives up.
+
+ Call this before redirecting such a 401 to the login page. It destroys
+ the server-side session, disconnects its sockets, drops this session's
+ stored password, and clears the cookie, so the browser lands on the
+ login form. Other sessions of the same user are not touched. Does
+ nothing when ``require_auth`` already cleared the session.
+ """
+ username = request.session.get("username")
+ if not username:
+ return
+ session_id = request.session.get("session_id")
+ if session_id:
+ _revoke_server_session(session_id, username)
+ try:
+ session_password_store.clear_session(username, session_id)
+ except Exception as exc:
+ # Type name only: a rendered traceback would include session_id.
+ logger.warning(
+ "Failed to drop a rejected session's stored password: {}",
+ type(exc).__name__,
+ )
+ request.session.clear()
+
+
def require_auth(request: Request) -> str:
"""Require authentication. Returns username or raises 401.
@@ -86,9 +159,9 @@ def require_auth(request: Request) -> str:
raise HTTPException(status_code=401, detail="Authentication required")
if not db_manager.is_user_connected(username):
- # Stale session with no recoverable credential: clear the cookie so the
- # client is sent back to login instead of 401-ing on every request
- # until someone happens to load "/".
+ # Stale session with no recoverable credential: clear the cookie (and
+ # revoke the server-side session) so the client is sent back to login
+ # instead of 401-ing on every request until someone loads "/".
clear_session_if_unrecoverable(request, username)
raise HTTPException(
status_code=401, detail="Database connection required"
@@ -128,7 +201,12 @@ def require_auth(request: Request) -> str:
def _server_session_valid(request: Request, username: str) -> bool:
- """Whether the cookie's ``session_id`` still resolves to ``username``.
+ """Whether the login still owns a usable authenticated session.
+
+ An open shared connection alone cannot make an encrypted database usable:
+ request handlers still need the session's in-memory credential. Require
+ re-authentication when it is gone, even if background work keeps the
+ connection open.
Split out of ``require_auth`` as a named seam rather than inlined, so a
test suite can relax the server-side-session gate without relaxing
@@ -144,9 +222,10 @@ def _server_session_valid(request: Request, username: str) -> bool:
"accept unconditionally" is exactly the pre-revocation contract.
"""
session_id = request.session.get("session_id")
- return bool(
+ valid_owner = bool(
session_id and session_manager.validate_session(session_id) == username
)
+ return valid_owner and not clear_session_if_unrecoverable(request, username)
def get_db_session_dep(
@@ -283,6 +362,12 @@ def ensure_user_database(request: Request) -> None:
session_password_store.store_session_password(
username, session_id, password
)
+ else:
+ # An expired/consumed marker is not a recovery credential.
+ # A concurrent response can retain this old cookie after
+ # another request consumed the token. Leaving it in place
+ # would bypass clear_session_if_unrecoverable indefinitely.
+ request.session.pop("temp_auth_token", None)
# Fast path: the connection is already open, so there is nothing left
# to do. Placed after the token block above rather than at the top of
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index a360af2272..6c0e8aa33f 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -1597,21 +1597,21 @@ def _enforce_session_revocation(session) -> None:
`require_auth` rejects a cookie whose `session_id` no longer resolves
to the claimed username, which is what makes logout actually revoke a
- session rather than merely ask the browser to forget it. But two GET
- routes deliberately bypass `require_auth` — `/` and `/auth/check` —
+ session rather than merely ask the browser to forget it. When this was
+ added, two GET routes bypassed `require_auth` — `/` and `/auth/check` —
because they must render/answer for anonymous visitors too, and both
read `request.session["username"]` directly. A sweep of all 110 GET
routes found exactly those two granting a revoked session strictly
more than an anonymous one: after logout, a replayed cookie still
rendered the authenticated index and still got `authenticated: true`,
- for the full remaining itsdangerous window. `/` additionally opens
- `get_user_db_session(username)` without a `session_id`, so the page
- renders with the user's real saved settings.
-
- Enforcing it here rather than patching those two handlers means the
- property holds for every route by construction — including any future
- handler that reads the session without going through `require_auth`,
- which is precisely how these two got missed. Same placement rationale
+ for the full remaining itsdangerous window. Both now call
+ `require_auth` themselves (catching its 401), which also applies the
+ per-session credential check this function does not perform.
+
+ Enforcing revocation here as well means the property holds for every
+ route by construction — including any future handler that reads the
+ session without going through `require_auth`, which is precisely how
+ these two got missed. Same placement rationale
as `_enforce_session_expiry`: clearing the dict makes a revoked
session indistinguishable from "never logged in" to everything
downstream, so no call site needs to know about revocation.
@@ -2536,8 +2536,28 @@ def _mount_all(app: FastAPI) -> None:
@app.get("/", include_in_schema=False)
def index(request: Request):
"""Root route - redirect to login if not authenticated."""
- username = request.session.get("username")
- if not username:
+ if not request.session.get("username"):
+ return RedirectResponse(url="/auth/login", status_code=302)
+
+ # Same gate as every protected route. Reading the username from the
+ # cookie alone would let a session that lost its own credential render
+ # the user's saved settings: without a session-scoped password,
+ # get_user_db_session falls back to a sibling session's password.
+ # require_auth rejects that session (and revokes it) instead.
+ from fastapi import HTTPException
+
+ from .dependencies.auth import end_rejected_session, require_auth
+
+ try:
+ username = require_auth(request)
+ except HTTPException as exc:
+ if exc.status_code != 401:
+ raise
+ # One require_auth 401 keeps the cookie (database not connected
+ # but still recoverable). /auth/login sends any cookie with a
+ # username back here, so redirecting without ending the session
+ # would loop. Every protected page's 401 funnels through here.
+ end_rejected_session(request)
return RedirectResponse(url="/auth/login", status_code=302)
from ..constants import get_available_strategies
@@ -2550,7 +2570,9 @@ def _mount_all(app: FastAPI) -> None:
settings = {}
try:
- with get_user_db_session(username) as db_session:
+ with get_user_db_session(
+ username, session_id=request.session.get("session_id")
+ ) as db_session:
if db_session:
sm = get_settings_manager(db_session, username)
# Operator-gated escape hatch (#5148 / 87537d9ec): the
diff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.py
index 27432a257c..bee7fdb178 100644
--- a/src/local_deep_research/web/routers/auth.py
+++ b/src/local_deep_research/web/routers/auth.py
@@ -3,10 +3,10 @@ Authentication routes for login, register, and logout.
Uses SQLCipher encrypted databases with browser password manager support.
"""
-from fastapi import APIRouter, Depends, Form, Query, Request
+from fastapi import APIRouter, Depends, Form, HTTPException, Query, Request
from fastapi.responses import JSONResponse, RedirectResponse
-from ..dependencies.auth import clear_session_if_unrecoverable, require_auth
+from ..dependencies.auth import require_auth
from ..dependencies.flash import flash
from ..dependencies.rate_limit import (
INTEGRITY_CHECK_RATE_LIMIT,
@@ -974,6 +974,8 @@ def logout(request: Request):
logger.info(f"User {username} logged out")
flash(request, "You have been logged out successfully", "info")
+ if "application/json" in request.headers.get("accept", ""):
+ return JSONResponse({"success": True})
return RedirectResponse(url="/auth/login", status_code=302)
@@ -982,26 +984,18 @@ def check_auth(request: Request):
"""
Check if user is authenticated (for AJAX requests).
- Deliberately NOT ``Depends(require_auth)``: this endpoint is polled by
- AJAX/XHR clients that need a machine-readable answer unconditionally.
- ``require_auth``'s 401 is converted to an HTML redirect for non-``/api/``
- requests without an ``Accept: application/json`` header by the global
- exception handler (``_is_api_request`` / ``handle_http_exception`` in
- ``fastapi_app.py``), and ``/auth/check`` doesn't live under ``/api/`` and
- can't rely on every caller sending that header. So the connectivity
- check that ``require_auth`` does is inlined here instead, to keep the
- raw-JSON response contract for every caller.
+ Catch the authentication failure locally so this endpoint always answers
+ JSON, including for callers without an Accept header. Share the actual
+ authentication checks with protected routes, including credential loss
+ while a shared database connection is still open.
"""
- username = request.session.get("username")
- if username and not db_manager.is_user_connected(username):
- # Stale session: same "no recoverable credential" cleanup
- # require_auth performs, but report it as unauthenticated rather
- # than raising (see docstring above for why this can't delegate).
- clear_session_if_unrecoverable(request, username)
- username = None
- if username:
- return {"authenticated": True, "username": username}
- return JSONResponse({"authenticated": False}, status_code=401)
+ try:
+ username = require_auth(request)
+ except HTTPException as exc:
+ if exc.status_code != 401:
+ raise
+ return JSONResponse({"authenticated": False}, status_code=401)
+ return {"authenticated": True, "username": username}
@router.get("/change-password")
diff --git a/src/local_deep_research/web/static/js/mobile-navigation.js b/src/local_deep_research/web/static/js/mobile-navigation.js
index 37381a64b4..fc4a08a7a3 100644
--- a/src/local_deep_research/web/static/js/mobile-navigation.js
+++ b/src/local_deep_research/web/static/js/mobile-navigation.js
@@ -576,7 +576,17 @@
handleLogout() {
const logoutForm = document.getElementById('logout-form');
if (logoutForm) {
- logoutForm.submit();
+ // requestSubmit() fires the submit event api.js handles.
+ // Browsers without it (Safari < 16) get the same event
+ // dispatched by hand; only if nothing handled it (api.js
+ // not loaded) does a plain POST go out.
+ if (typeof logoutForm.requestSubmit === 'function') {
+ logoutForm.requestSubmit();
+ } else if (logoutForm.dispatchEvent(
+ new Event('submit', { bubbles: true, cancelable: true })
+ )) {
+ logoutForm.submit();
+ }
}
}
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 99e0e2f709..bc97b74350 100644
--- a/src/local_deep_research/web/static/js/services/api.js
+++ b/src/local_deep_research/web/static/js/services/api.js
@@ -137,6 +137,73 @@ function redirectToLogin() {
window.location.href = `/auth/login?next=${next}`;
}
+/** Recover a stale logout form without applying it to a replacement login. */
+async function submitLogout(form) {
+ if (form.dataset.logoutPending === 'true') return;
+ form.dataset.logoutPending = 'true';
+ form.setAttribute('aria-busy', 'true');
+ // The control is a link (see base.html), so mark it busy rather than
+ // relying on `disabled`; logoutPending above already blocks re-entry.
+ const control = form.querySelector('.ldr-logout-btn');
+ if (control) control.setAttribute('aria-disabled', 'true');
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 30000);
+ const changed = 'Your sign-in changed. Reload this page before logging out.';
+
+ try {
+ const context = getAuthContext();
+ if (!context) throw new Error('Reload this page before logging out.');
+ const options = {
+ credentials: 'same-origin', cache: 'no-store', redirect: 'error',
+ signal: controller.signal,
+ headers: { 'Accept': 'application/json', 'X-LDR-Auth-Context': context }
+ };
+ const refresh = await fetch('/auth/csrf-token', { ...options, method: 'GET' });
+ if (getAuthContext() !== context || refresh.status === 409) throw new Error(changed);
+ if (refresh.status === 401) {
+ window.location.href = '/auth/login';
+ return;
+ }
+ if (!refresh.ok) throw new Error('Could not check your session. Please try logging out again.');
+ const fresh = await refresh.json();
+ if (getAuthContext() !== context || fresh.auth_context !== context) throw new Error(changed);
+ if (typeof fresh.csrf_token !== 'string' || !fresh.csrf_token) {
+ throw new Error('Could not refresh your session. Reload this page before logging out.');
+ }
+ // Not signal.throwIfAborted(): it needs Safari 15.4 / Chrome 100 /
+ // Firefox 97, and its absence would block logout on older browsers.
+ if (controller.signal.aborted) throw new window.DOMException('Aborted', 'AbortError');
+ const response = await fetch('/auth/logout', {
+ ...options, method: 'POST',
+ headers: { ...options.headers, 'X-CSRFToken': fresh.csrf_token }
+ });
+ if (getAuthContext() !== context || response.status === 409) throw new Error(changed);
+ if (response.status === 401) {
+ window.location.href = '/auth/login';
+ return;
+ }
+ if (!response.ok) throw new Error('Could not log out. Reload this page and try again.');
+ const result = await response.json();
+ if (getAuthContext() !== context) throw new Error(changed);
+ if (result.success !== true) throw new Error('Logout was not confirmed. Please try again.');
+ window.location.href = '/auth/login';
+ } catch (error) {
+ // A transport failure may happen after logout succeeded. Leave a
+ // retry to the user; its fresh session check handles that case.
+ const message = error.name === 'AbortError'
+ ? 'Logout timed out. Please try again.'
+ : error instanceof TypeError
+ ? 'Could not confirm logout. Please check your connection and try again.'
+ : error.message;
+ window.ui.showMessage(message, 'error', 10000);
+ } finally {
+ clearTimeout(timeout);
+ delete form.dataset.logoutPending;
+ form.removeAttribute('aria-busy');
+ if (control) control.removeAttribute('aria-disabled');
+ }
+}
+
/**
* Generic fetch with error handling and timeout support
* @param {string} url - The URL to fetch
@@ -441,6 +508,21 @@ if (typeof module !== 'undefined' && module.exports) {
// Make api available globally for browser usage
if (typeof window !== 'undefined') {
+ document.addEventListener('submit', async event => {
+ if (event.target.id !== 'logout-form') return;
+ event.preventDefault();
+ await submitLogout(event.target);
+ });
+ // The top-bar logout control is a link rather than a submit button
+ // (base.html), so page-wide submit-button selectors never match it.
+ document.addEventListener('click', async event => {
+ const control = event.target instanceof Element
+ ? event.target.closest('#logout-form .ldr-logout-btn')
+ : null;
+ if (!control) return;
+ event.preventDefault();
+ await submitLogout(control.closest('form'));
+ });
window.api = {
startResearch,
getResearchStatus,
diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.html
index c929d8bb49..2564b08093 100644
--- a/src/local_deep_research/web/templates/base.html
+++ b/src/local_deep_research/web/templates/base.html
@@ -199,7 +199,8 @@
</span>
<form action="{{ url_for('auth.logout') }}" method="POST" class="ldr-logout-form" id="logout-form" style="display: inline;">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
- <a href="#" class="ldr-logout-btn" onclick="event.preventDefault(); document.getElementById('logout-form').submit(); return false;">
+ {# A link, not a submit button: this sits before every page's own form, so page-wide button[type="submit"] selectors would otherwise find Logout first. services/api.js handles the click. #}
+ <a href="#" class="ldr-logout-btn">
<i aria-hidden="true" class="fas fa-sign-out-alt"></i> Logout
</a>
</form>
diff --git a/tests/infrastructure_tests/test_csrf_api.test.js b/tests/infrastructure_tests/test_csrf_api.test.js
index f1f278726a..bb8c1f434d 100644
--- a/tests/infrastructure_tests/test_csrf_api.test.js
+++ b/tests/infrastructure_tests/test_csrf_api.test.js
@@ -9,7 +9,9 @@
// --- Global mocks (set BEFORE require) ---
global.document = {
- querySelector: jest.fn()
+ querySelector: jest.fn(),
+ // api.js registers the shared logout handler when loaded in a browser.
+ addEventListener: jest.fn()
};
global.fetch = jest.fn();
diff --git a/tests/js/mobile-navigation.test.js b/tests/js/mobile-navigation.test.js
index 7c3dbfbe5c..c6382fff17 100644
--- a/tests/js/mobile-navigation.test.js
+++ b/tests/js/mobile-navigation.test.js
@@ -347,12 +347,36 @@ describe('MobileNavigation interactive lifecycle', () => {
expect(more.getAttribute('aria-expanded')).toBe('false');
});
+ it.each([
+ ['hands logout to the submit handler', true, 0],
+ ['falls back to a plain logout POST without a handler', false, 1],
+ ])('where requestSubmit is unavailable, %s', (_name, handled, posts) => {
+ document.body.innerHTML = '<form id="logout-form"></form>';
+ const form = document.getElementById('logout-form');
+ // Safari before 16 has no requestSubmit.
+ Object.defineProperty(form, 'requestSubmit', { value: undefined });
+ const submit = vi.spyOn(form, 'submit').mockImplementation(() => {});
+ const seen = [];
+ const listener = event => {
+ seen.push(event.type);
+ if (handled) event.preventDefault();
+ };
+ document.addEventListener('submit', listener);
+ try {
+ MobileNavigation.prototype.handleLogout.call({});
+ } finally {
+ document.removeEventListener('submit', listener);
+ }
+ expect(seen).toEqual(['submit']);
+ expect(submit).toHaveBeenCalledTimes(posts);
+ });
+
it('delegates tab, sheet, and logout actions through safe navigation', () => {
setInnerWidth(500);
document.body.innerHTML = '<form id="logout-form"></form>';
const submit = vi.spyOn(
document.getElementById('logout-form'),
- 'submit',
+ 'requestSubmit',
).mockImplementation(() => {});
nav = new MobileNavigation();
nav.init();
diff --git a/tests/js/services/logout-recovery.test.js b/tests/js/services/logout-recovery.test.js
new file mode 100644
index 0000000000..002bcf0ad3
--- /dev/null
+++ b/tests/js/services/logout-recovery.test.js
@@ -0,0 +1,180 @@
+import '@js/services/api.js';
+import baseTemplate from '../../../src/local_deep_research/web/templates/base.html?raw';
+
+const context = 'a'.repeat(64);
+const json = (body, status = 200) => new Response(JSON.stringify(body), {
+ status, headers: { 'Content-Type': 'application/json' }
+});
+const fresh = () => json({ csrf_token: 'fresh-token', auth_context: context });
+
+describe('logout recovery from an open page', () => {
+ const originalLocation = window.location;
+ const originalFetch = globalThis.fetch;
+ const originalUi = window.ui;
+
+ beforeEach(() => {
+ delete window.location;
+ window.location = { href: 'http://localhost/settings', pathname: '/settings', search: '', hash: '' };
+ document.head.replaceChildren();
+ for (const [name, content] of [['csrf-token', 'old-token'], ['auth-context', context]]) {
+ const meta = document.createElement('meta');
+ meta.name = name;
+ meta.content = content;
+ document.head.append(meta);
+ }
+ const formMarkup = baseTemplate.match(/<form\b[^>]+id="logout-form"[\s\S]*?<\/form>/)[0];
+ const parsed = new globalThis.DOMParser().parseFromString(formMarkup, 'text/html');
+ const form = parsed.getElementById('logout-form');
+ form.setAttribute('action', '/auth/logout');
+ form.querySelector('[name="csrf_token"]').value = 'old-token';
+ document.body.replaceChildren(document.importNode(form, true));
+ globalThis.fetch = vi.fn();
+ window.ui = { showMessage: vi.fn() };
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ window.location = originalLocation;
+ window.ui = originalUi;
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+ vi.useRealTimers();
+ });
+
+ const submit = () => document.getElementById('logout-form').requestSubmit();
+ const button = () => document.querySelector('.ldr-logout-btn');
+ const expectLogin = () => vi.waitFor(() => expect(window.location.href).toBe('/auth/login'));
+ const expectError = () => vi.waitFor(() => expect(window.ui.showMessage).toHaveBeenCalled());
+
+ it('keeps the top-bar logout control out of page-wide submit-button selectors', () => {
+ // base.html renders this form before every page's own content, so a
+ // page-wide button[type="submit"] lookup would find Logout first.
+ expect(button().tagName).toBe('A');
+ expect(document.querySelector('button[type="submit"], input[type="submit"]')).toBeNull();
+ expect(document.querySelector('button')).toBeNull();
+ });
+
+ it('desktop logout refreshes its stale form token and logs out the same session', async () => {
+ fetch.mockResolvedValueOnce(fresh()).mockResolvedValueOnce(json({ success: true }));
+ button().click();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ await expectLogin();
+ expect(fetch.mock.calls.map(([url]) => url)).toEqual(['/auth/csrf-token', '/auth/logout']);
+ const refresh = fetch.mock.calls[0][1];
+ const logout = fetch.mock.calls[1][1];
+ expect(refresh).toMatchObject({ method: 'GET', credentials: 'same-origin', cache: 'no-store', redirect: 'error' });
+ expect(logout).toMatchObject({ method: 'POST', credentials: 'same-origin', redirect: 'error' });
+ expect(new globalThis.Headers(refresh.headers).get('X-LDR-Auth-Context')).toBe(context);
+ expect(new globalThis.Headers(logout.headers).get('X-LDR-Auth-Context')).toBe(context);
+ expect(new globalThis.Headers(logout.headers).get('X-CSRFToken')).toBe('fresh-token');
+ expect(new globalThis.Headers(logout.headers).get('Accept')).toBe('application/json');
+ expect(logout.signal).toBe(refresh.signal);
+ });
+
+ it('goes to sign-in when the old session is already gone without another logout POST', async () => {
+ fetch.mockResolvedValueOnce(json({ error: 'Authentication required' }, 401));
+ submit();
+ await expectLogin();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['refresh', 'logout'])('refuses to log out a replacement login detected at %s', async phase => {
+ if (phase === 'logout') fetch.mockResolvedValueOnce(fresh());
+ fetch.mockResolvedValueOnce(json({ error: 'Your sign-in changed' }, 409));
+ submit();
+ await expectError();
+ expect(window.ui.showMessage.mock.calls[0][0]).toMatch(/sign-in changed.*reload/i);
+ expect(window.location.href).toBe('http://localhost/settings');
+ expect(fetch).toHaveBeenCalledTimes(phase === 'refresh' ? 1 : 2);
+ });
+
+ it('rejects a mismatched context in a token response', async () => {
+ fetch.mockResolvedValueOnce(json({ csrf_token: 'new-login-token', auth_context: 'b'.repeat(64) }));
+ submit();
+ await expectError();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not send logout without a rendered login context', async () => {
+ document.querySelector('meta[name="auth-context"]').remove();
+ submit();
+ await expectError();
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('suppresses repeated clicks while logout is pending', async () => {
+ let resolveRefresh;
+ fetch.mockImplementationOnce(() => new Promise(resolve => { resolveRefresh = resolve; }))
+ .mockResolvedValueOnce(json({ success: true }));
+ submit();
+ submit();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(button().getAttribute('aria-disabled')).toBe('true');
+ resolveRefresh(fresh());
+ await expectLogin();
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+
+ it('reports a failed logout without replaying an uncertain outcome', async () => {
+ fetch.mockResolvedValueOnce(fresh()).mockRejectedValueOnce(new TypeError('Failed to fetch'));
+ submit();
+ await expectError();
+ expect(button().hasAttribute('aria-disabled')).toBe(false);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(window.location.href).toBe('http://localhost/settings');
+ });
+
+ it('keeps CSRF rejection visible without a retry loop', async () => {
+ fetch.mockResolvedValueOnce(fresh()).mockResolvedValueOnce(json({ error: 'CSRF rejected' }, 403));
+ submit();
+ await expectError();
+ expect(button().hasAttribute('aria-disabled')).toBe(false);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+
+ it('bounds a stalled recovery request and restores the logout control', async () => {
+ vi.useFakeTimers();
+ fetch.mockImplementation((_url, options) => new Promise((_resolve, reject) => {
+ options.signal.addEventListener('abort', () => reject(new globalThis.DOMException('aborted', 'AbortError')));
+ }));
+ submit();
+ await vi.advanceTimersByTimeAsync(30000);
+ expect(window.ui.showMessage.mock.calls[0][0]).toMatch(/timed out/i);
+ expect(button().hasAttribute('aria-disabled')).toBe(false);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('logs out where AbortSignal.throwIfAborted is unavailable (older Safari/Chrome)', async () => {
+ const original = Object.getOwnPropertyDescriptor(globalThis.AbortSignal.prototype, 'throwIfAborted');
+ Object.defineProperty(globalThis.AbortSignal.prototype, 'throwIfAborted', { value: undefined, configurable: true });
+ try {
+ expect(new AbortController().signal.throwIfAborted).toBeUndefined();
+ fetch.mockResolvedValueOnce(fresh()).mockResolvedValueOnce(json({ success: true }));
+ submit();
+ await expectLogin();
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(window.ui.showMessage).not.toHaveBeenCalled();
+ } finally {
+ if (original) Object.defineProperty(globalThis.AbortSignal.prototype, 'throwIfAborted', original);
+ else delete globalThis.AbortSignal.prototype.throwIfAborted;
+ }
+ });
+
+ it('does not send the logout POST once the deadline passed during the token refresh', async () => {
+ vi.useFakeTimers();
+ const original = Object.getOwnPropertyDescriptor(globalThis.AbortSignal.prototype, 'throwIfAborted');
+ Object.defineProperty(globalThis.AbortSignal.prototype, 'throwIfAborted', { value: undefined, configurable: true });
+ try {
+ const slow = fresh();
+ slow.json = () => new Promise(resolve => setTimeout(() => resolve({ csrf_token: 'fresh-token', auth_context: context }), 31000));
+ fetch.mockResolvedValueOnce(slow).mockResolvedValueOnce(json({ success: true }));
+ submit();
+ await vi.advanceTimersByTimeAsync(31000);
+ expect(window.ui.showMessage.mock.calls[0][0]).toMatch(/timed out/i);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ } finally {
+ if (original) Object.defineProperty(globalThis.AbortSignal.prototype, 'throwIfAborted', original);
+ else delete globalThis.AbortSignal.prototype.throwIfAborted;
+ }
+ });
+});
diff --git a/tests/security/test_auth_attack_scenarios.py b/tests/security/test_auth_attack_scenarios.py
index 4f0f03ead5..d90d614768 100644
--- a/tests/security/test_auth_attack_scenarios.py
+++ b/tests/security/test_auth_attack_scenarios.py
@@ -363,10 +363,9 @@ def _assert_refused_by_the_session_gate(
Two probes, because the two routes are guarded by different things
and a regression can take out either one:
- * ``/auth/check`` deliberately does NOT use ``require_auth`` (it must
- answer for anonymous callers too), so the ONLY thing that can
- refuse a revoked cookie there is
- ``fastapi_app._enforce_session_revocation``.
+ * ``/auth/check`` must answer anonymous callers with JSON, so it calls
+ ``require_auth`` itself and converts the 401. A revoked cookie is
+ refused there first by ``fastapi_app._enforce_session_revocation``.
* ``/auth/integrity-check`` does use ``require_auth``, and reaches
the encrypted database.
diff --git a/tests/security/test_auth_credential_lifetime_fastapi.py b/tests/security/test_auth_credential_lifetime_fastapi.py
index 2cb928264a..3735e73ca9 100644
--- a/tests/security/test_auth_credential_lifetime_fastapi.py
+++ b/tests/security/test_auth_credential_lifetime_fastapi.py
@@ -60,8 +60,8 @@ from local_deep_research.web.dependencies import auth as auth_dep
# bare-username route tests keep working. The HTTP tests below exist to prove
# a revoked session IS rejected, so the shim must never be able to relax what
# is under test. (It patches ``require_auth``'s helper, which ``/`` and
-# ``/auth/check`` do not use — but this suite's whole point is that the gate
-# is real, so it must not run against a relaxed one by accident either.)
+# ``/auth/check`` also reach by calling ``require_auth`` in their bodies, so
+# the gate must be real here.)
pytestmark = pytest.mark.real_session_check
@@ -812,9 +812,8 @@ class TestRevokedCookieOnRequireAuthFreeRoutes:
assert resp.status_code == 302, (
"GET / rendered for a cookie whose server-side session was "
- "destroyed at logout — and it opens get_user_db_session() "
- "without a session_id, so the page comes back with the user's "
- "real saved settings"
+ "destroyed at logout — and the page would come back with the "
+ "user's real saved settings"
)
assert resp.headers.get("location", "").startswith("/auth/login")
diff --git a/tests/security/test_auth_dependencies_fastapi.py b/tests/security/test_auth_dependencies_fastapi.py
index 7c4b059cde..6058bf973a 100644
--- a/tests/security/test_auth_dependencies_fastapi.py
+++ b/tests/security/test_auth_dependencies_fastapi.py
@@ -274,18 +274,18 @@ PUBLIC_ROUTES: dict[tuple[str, str], str] = {
# BEHAVIOURAL sweep, which proves the hand-rolled rejection actually happens.
SELF_ENFORCING_ROUTES: dict[tuple[str, str], str] = {
("GET", "/"): (
- "index() reads the session itself and returns "
- "RedirectResponse('/auth/login') when there is no username or the "
- "user's database cannot be opened (fastapi_app.py). Cannot use "
- "require_auth because it also clears an unrecoverable session on "
- "that path."
+ "index() redirects an anonymous caller to /auth/login itself, then "
+ "calls require_auth(request) in its body and turns its 401 into the "
+ "same redirect, first ending any session require_auth left in place "
+ "(fastapi_app.py). Not a Depends(require_auth): the "
+ "global handler would answer that 401 differently from the redirect "
+ "this page has always returned."
),
("GET", "/auth/check"): (
- "the AJAX 'am I logged in?' probe. Deliberately does NOT delegate to "
- "require_auth: its docstring explains that require_auth's 401 would "
- "be rewritten into an HTML login redirect by the global exception "
- "handler for this non-/api/ path, breaking every XHR caller. It "
- "inlines the same username + is_user_connected check and answers "
+ "the AJAX 'am I logged in?' probe. Not a Depends(require_auth): the "
+ "global exception handler would rewrite that 401 into an HTML login "
+ "redirect for this non-/api/ path, breaking every XHR caller. It "
+ "calls require_auth(request) in its body and answers its 401 as "
"JSON 401 {'authenticated': false} instead."
),
}
diff --git a/tests/security/test_research_password_gate_fastapi.py b/tests/security/test_research_password_gate_fastapi.py
index 02a82a7afe..9357a1f383 100644
--- a/tests/security/test_research_password_gate_fastapi.py
+++ b/tests/security/test_research_password_gate_fastapi.py
@@ -24,23 +24,23 @@ on either route ("session has expired" had zero hits in the suite).
HOW THE EXPIRED STATE IS PRODUCED HERE
--------------------------------------
-Nothing is patched at or above the guard: ``resolve_user_password`` and
-``get_user_password`` run for real. The store entry the caller's session
-resolves through is genuinely deleted, exactly as the 24h TTL would delete
-it. Only the boundary BELOW the guard — ``start_research_process``, the
-thread-spawning entry point — is replaced, so the guard decides for real
-while no research thread is ever created.
+``resolve_user_password`` and ``get_user_password`` run for real. The store
+entry the caller's session resolves through is genuinely deleted, either
+before authentication or immediately before the route resolves its password.
+The latter simulates eviction after authentication has already succeeded:
+a wrapper controls the timing, then calls the real resolver. Both the shared
+authentication gate and the route's later credential check must reject the
+request. The thread-spawning entry point is replaced so no research runs.
The caller keeps a *second*, live session (a different browser/device), for
a mechanical reason that also makes the assertion stronger:
``get_user_db_session(username)`` is called by both handlers before the
guard and falls back to ``get_any_session_password(username)``, so with no
-password anywhere for that user the request is refused one layer earlier
-(``require_auth``/``clear_session_if_unrecoverable``) and never reaches the
-guard at all. Keeping a live sibling session means the database opens
-normally and the ONLY thing missing is the credential the guard itself
-looks up — which additionally proves the guard is keyed to the calling
-SESSION, not merely to the username.
+password anywhere for that user the database cannot be opened. Keeping a
+live sibling session preserves the database while testing that neither
+authentication layer accepts that sibling's credential on this session's
+behalf. An already-expired session is now refused by ``require_auth``;
+eviction during the request must still be refused by the route's own guard.
Each refusal test issues the identical request from the live sibling client
FIRST and requires a 200 from it. That rules out the vacuity trap: a 4xx
@@ -265,6 +265,20 @@ def _expire_session_password(username, session_id):
assert session_id not in _stored_session_ids(username)
+def _observe_password_resolution(target, username, session_id, expire_late):
+ """Optionally evict just before the real route-level credential lookup."""
+ from local_deep_research.web.auth.password_utils import (
+ resolve_user_password,
+ )
+
+ def resolve(request_username):
+ if expire_late:
+ _expire_session_password(username, session_id)
+ return resolve_user_password(request_username)
+
+ return patch(target, side_effect=resolve)
+
+
def _configure_model(username, password=CALLER_PW):
"""Set ``llm.model`` in the user's settings database.
@@ -365,7 +379,10 @@ class TestStartResearchPasswordGate:
assert spawn.call_args.kwargs["user_password"] == CALLER_PW
assert _run_record_counts(username)["history"] == 1
- def test_expired_session_is_refused_and_starts_no_research(self, live_app):
+ @pytest.mark.parametrize("expire_late", [False, True])
+ def test_expired_session_is_refused_and_starts_no_research(
+ self, live_app, expire_late
+ ):
"""Encrypted DB + this session's password gone -> 401, nothing started.
A second user is logged in and live throughout, and the caller's own
@@ -390,10 +407,19 @@ class TestStartResearchPasswordGate:
)
assert spawn.called
- _expire_session_password(username, session_id)
+ if not expire_late:
+ _expire_session_password(username, session_id)
before = _run_record_counts(username)
- with patch(self.SPAWN_TARGET) as spawn:
+ with (
+ patch(self.SPAWN_TARGET) as spawn,
+ _observe_password_resolution(
+ "local_deep_research.web.routers.research.resolve_user_password",
+ username,
+ session_id,
+ expire_late,
+ ) as resolver,
+ ):
spawn.return_value = MagicMock(ident=4242)
resp = _post_json(client, START_RESEARCH_PATH, START_RESEARCH_BODY)
@@ -404,8 +430,13 @@ class TestStartResearchPasswordGate:
f"{resp.status_code}: {resp.text[:400]}"
)
body = resp.json()
- assert body["status"] == "error"
- assert "log out" in body["message"].lower()
+ if expire_late:
+ resolver.assert_called_once_with(username)
+ assert body["status"] == "error"
+ assert "log out" in body["message"].lower()
+ else:
+ resolver.assert_not_called()
+ assert body == {"detail": "Authentication required"}
spawn.assert_not_called()
assert _run_record_counts(username) == before, (
@@ -503,7 +534,10 @@ class TestFollowupStartPasswordGate:
# +1: the seeded parent, +1: the follow-up run just started.
assert _run_record_counts(username)["history"] == 2
- def test_expired_session_is_refused_and_starts_no_research(self, live_app):
+ @pytest.mark.parametrize("expire_late", [False, True])
+ def test_expired_session_is_refused_and_starts_no_research(
+ self, live_app, expire_late
+ ):
"""Encrypted DB + this session's password gone -> 401, nothing started."""
_decoy_client, _decoy_user, _decoy_sid = _new_user(
live_app, "fup_decoy", OTHER_PW
@@ -523,10 +557,19 @@ class TestFollowupStartPasswordGate:
)
assert spawn.called
- _expire_session_password(username, session_id)
+ if not expire_late:
+ _expire_session_password(username, session_id)
before = _run_record_counts(username)
- with patch(self.SPAWN_TARGET) as spawn:
+ with (
+ patch(self.SPAWN_TARGET) as spawn,
+ _observe_password_resolution(
+ "local_deep_research.web.routers.followup.resolve_user_password",
+ username,
+ session_id,
+ expire_late,
+ ) as resolver,
+ ):
spawn.return_value = MagicMock(ident=4243)
resp = _post_json(
client, FOLLOWUP_START_PATH, _followup_body(parent_id)
@@ -538,8 +581,13 @@ class TestFollowupStartPasswordGate:
f"{resp.status_code}: {resp.text[:400]}"
)
body = resp.json()
- assert body["success"] is False
- assert "log out" in body["error"].lower()
+ if expire_late:
+ resolver.assert_called_once_with(username)
+ assert body["success"] is False
+ assert "log out" in body["error"].lower()
+ else:
+ resolver.assert_not_called()
+ assert body == {"detail": "Authentication required"}
spawn.assert_not_called()
assert _run_record_counts(username) == before, (
diff --git a/tests/web/dependencies/test_session_revocation.py b/tests/web/dependencies/test_session_revocation.py
index a89ed13acf..6f5205eb93 100644
--- a/tests/web/dependencies/test_session_revocation.py
+++ b/tests/web/dependencies/test_session_revocation.py
@@ -70,6 +70,13 @@ class _FakeSessionManager:
def connected_db(monkeypatch):
"""The user's database is open — the state a later login produces."""
monkeypatch.setattr(auth_dep, "db_manager", _FakeDBManager(connected=True))
+ # Keep the credential usable so every rejection below is caused by the
+ # owner/revocation check, rather than by missing database credentials.
+ monkeypatch.setattr(
+ auth_dep.session_password_store,
+ "get_session_password",
+ lambda _username, _session_id: "test-password",
+ )
return
diff --git a/tests/web/dependencies/test_stale_session_cleanup.py b/tests/web/dependencies/test_stale_session_cleanup.py
index 8c442588eb..0caf7d398f 100644
--- a/tests/web/dependencies/test_stale_session_cleanup.py
+++ b/tests/web/dependencies/test_stale_session_cleanup.py
@@ -5,8 +5,9 @@ Regression guard for a behaviour lost in the Flask->FastAPI migration. Flask ran
(``web/auth/session_cleanup.py``); that module was deleted with no successor, so
``require_auth`` began raising 401 without ever clearing the cookie. The browser
kept believing it was logged in and every protected route 401'd indefinitely.
-Only the root route cleared the session (``fastapi_app.py`` index()), so a user
-recovered by navigating to "/" while an API or XHR client never did.
+At the time only the root route cleared the session (``fastapi_app.py``
+index()), so a user recovered by navigating to "/" while an API or XHR client
+never did.
The clearing is deliberately conditional: a temp auth token or a stored session
password means ``ensure_user_database()`` can still reopen the connection, so
@@ -53,13 +54,23 @@ class _FakeSessionManager:
reason and prove nothing about credential recovery.
"""
+ def __init__(self):
+ self.destroyed = []
+
def validate_session(self, session_id):
- return "alice" if session_id == "s1" else None
+ if session_id in self.destroyed:
+ return None
+ return {"s1": "alice", "s-bob": "bob"}.get(session_id)
+
+ def destroy_session(self, session_id):
+ self.destroyed.append(session_id)
@pytest.fixture(autouse=True)
def _live_server_session(monkeypatch):
- monkeypatch.setattr(auth_dep, "session_manager", _FakeSessionManager())
+ sessions = _FakeSessionManager()
+ monkeypatch.setattr(auth_dep, "session_manager", sessions)
+ return sessions
@pytest.fixture
@@ -86,6 +97,66 @@ def test_unrecoverable_session_is_cleared(disconnected):
)
+def test_unrecoverable_session_is_revoked_server_side(
+ disconnected, _live_server_session, monkeypatch
+):
+ """Clearing the cookie must also end the server-side session.
+
+ Once the cookie is gone the browser cannot reach logout, so without this
+ the record would stay valid for its whole idle timeout and its sockets
+ would stay connected.
+ """
+ from local_deep_research.web.services import socketio_asgi
+
+ disconnected_sockets = []
+ monkeypatch.setattr(
+ socketio_asgi, "disconnect_session", disconnected_sockets.append
+ )
+ request = _FakeRequest({"username": "alice", "session_id": "s1"})
+
+ with pytest.raises(HTTPException):
+ auth_dep.require_auth(request)
+
+ assert _live_server_session.destroyed == ["s1"]
+ assert disconnected_sockets == ["s1"]
+
+
+def test_revocation_never_touches_another_users_session(
+ disconnected, _live_server_session, monkeypatch
+):
+ from local_deep_research.web.services import socketio_asgi
+
+ disconnected_sockets = []
+ monkeypatch.setattr(
+ socketio_asgi, "disconnect_session", disconnected_sockets.append
+ )
+ request = _FakeRequest({"username": "alice", "session_id": "s-bob"})
+
+ assert auth_dep.clear_session_if_unrecoverable(request, "alice") is True
+
+ assert request.session == {}
+ assert _live_server_session.destroyed == []
+ assert disconnected_sockets == []
+
+
+def test_revocation_failure_still_returns_401(disconnected, monkeypatch):
+ """Teardown is best-effort: it must not turn the 401 into a 500."""
+
+ def _explode(_session_id):
+ raise RuntimeError("socket layer down")
+
+ from local_deep_research.web.services import socketio_asgi
+
+ monkeypatch.setattr(socketio_asgi, "disconnect_session", _explode)
+ request = _FakeRequest({"username": "alice", "session_id": "s1"})
+
+ with pytest.raises(HTTPException) as exc:
+ auth_dep.require_auth(request)
+
+ assert exc.value.status_code == 401
+ assert request.session == {}
+
+
def test_session_with_stored_password_is_kept(monkeypatch):
"""ensure_user_database() can still recover this one — do not log them out."""
monkeypatch.setattr(auth_dep, "db_manager", _FakeDBManager(connected=False))
@@ -103,7 +174,9 @@ def test_session_with_stored_password_is_kept(monkeypatch):
)
-def test_session_with_temp_auth_token_is_kept(disconnected):
+def test_session_with_temp_auth_token_is_kept(
+ disconnected, _live_server_session
+):
"""The post-login bootstrap token opens the DB on the next request."""
request = _FakeRequest(
{"username": "alice", "session_id": "s1", "temp_auth_token": "tok"}
@@ -116,6 +189,7 @@ def test_session_with_temp_auth_token_is_kept(disconnected):
"cleared a session holding a live temp auth token, which "
"ensure_user_database() would have consumed to open the database"
)
+ assert _live_server_session.destroyed == []
def test_unencrypted_database_session_is_kept(monkeypatch):
diff --git a/tests/web/routers/test_auth_disconnected_db_gate.py b/tests/web/routers/test_auth_disconnected_db_gate.py
index 174aa5feaf..080622dc60 100644
--- a/tests/web/routers/test_auth_disconnected_db_gate.py
+++ b/tests/web/routers/test_auth_disconnected_db_gate.py
@@ -19,7 +19,8 @@ sibling and ``integrity_check``. ``check_auth`` keeps its bespoke raw-JSON
response contract on purpose -- it must never redirect a non-``/api/``,
non-JSON-``Accept`` caller the way ``Depends(require_auth)``'s 401 does
(see ``_is_api_request`` / ``handle_http_exception`` in
-``fastapi_app.py``) -- but now inlines the same connectivity check.
+``fastapi_app.py``) -- so it calls ``require_auth`` directly and converts
+its 401 into the JSON answer.
A fresh client logs in from scratch inside EVERY test (rather than once in
a shared fixture) because ``tests/conftest.py``'s autouse
diff --git a/tests/web/test_auth_session_lifecycle.py b/tests/web/test_auth_session_lifecycle.py
index 06f9c43877..8d92e3153e 100644
--- a/tests/web/test_auth_session_lifecycle.py
+++ b/tests/web/test_auth_session_lifecycle.py
@@ -234,10 +234,12 @@ def _session_payload(client) -> dict:
def _assert_authenticated(client, username, why):
"""Positive control: this client is fully logged in as ``username``.
- Probes both gates: ``/auth/check`` (no ``require_auth`` — guarded only
- by ``_enforce_session_revocation`` / ``_enforce_session_expiry``) and
- ``/auth/integrity-check`` (a real ``Depends(require_auth)`` route that
- opens the user's encrypted database and echoes the username back).
+ Probes both gates: ``/auth/check`` (calls ``require_auth`` itself and
+ turns its 401 into a JSON answer, behind the
+ ``_enforce_session_revocation`` / ``_enforce_session_expiry``
+ middleware checks) and ``/auth/integrity-check`` (a real
+ ``Depends(require_auth)`` route that opens the user's encrypted database
+ and echoes the username back).
"""
check = client.get("/auth/check")
assert check.status_code == 200, (
diff --git a/tests/web/test_unusable_database_session.py b/tests/web/test_unusable_database_session.py
new file mode 100644
index 0000000000..28dc8ee2fe
--- /dev/null
+++ b/tests/web/test_unusable_database_session.py
@@ -0,0 +1,268 @@
+"""A live connection must not hide missing web-session credentials."""
+
+import uuid
+
+import pytest
+
+from local_deep_research.database.encrypted_db import db_manager
+from local_deep_research.database.session_passwords import (
+ session_password_store,
+)
+from tests.web.test_auth_session_lifecycle import (
+ _client,
+ _login,
+ _register,
+ _session_payload,
+ live_app as _lifecycle_app,
+)
+
+live_app = _lifecycle_app
+pytestmark = pytest.mark.real_session_check
+
+
[email protected]("path", ["/auth/check", "/settings/api"])
[email protected]("other_device", [False, True])
+ "stale_bootstrap", [False, True], ids=["current_cookie", "stale_bootstrap"]
+)
+def test_missing_credential_requires_login_even_with_an_open_database(
+ live_app, path, other_device, stale_bootstrap
+):
+ if not db_manager.has_encryption:
+ pytest.skip("Requires SQLCipher")
+ client = _client(live_app)
+ username = "missing_credential_" + uuid.uuid4().hex[:8]
+ assert _register(client, username).status_code == 302
+ bootstrap_cookies = type(client.cookies)(client.cookies)
+ assert client.get(path).status_code == 200
+ sibling = _client(live_app) if other_device else None
+ if sibling:
+ assert _login(sibling, username).status_code == 302
+ assert sibling.get("/auth/check").status_code == 200
+ if stale_bootstrap:
+ # A concurrent response can retain the initial cookie after another
+ # request has already consumed its one-time bootstrap credential.
+ client.cookies = bootstrap_cookies
+ assert _session_payload(client).get("temp_auth_token")
+ session_password_store.clear_session(
+ username, _session_payload(client)["session_id"]
+ )
+ assert db_manager.is_user_connected(username)
+
+ response = client.get(path, headers={"Accept": "application/json"})
+
+ assert response.status_code == 401
+ assert "username" not in _session_payload(client)
+ assert client.get("/auth/check").status_code == 401
+ if sibling:
+ assert sibling.get("/auth/check").status_code == 200
+
+
+def test_consumed_bootstrap_cookie_keeps_a_usable_session(live_app):
+ client = _client(live_app)
+ username = "consumed_bootstrap_" + uuid.uuid4().hex[:8]
+ assert _register(client, username).status_code == 302
+ bootstrap_cookies = type(client.cookies)(client.cookies)
+ session_id = _session_payload(client)["session_id"]
+ assert client.get("/auth/check").status_code == 200
+ client.cookies = bootstrap_cookies
+
+ response = client.get("/settings/api")
+
+ assert response.status_code == 200
+ assert _session_payload(client)["session_id"] == session_id
+ assert "temp_auth_token" not in _session_payload(client)
+
+
[email protected]("lose_credential", [False, True])
+def test_json_logout_requires_csrf_and_recovers_missing_credentials(
+ live_app, lose_credential
+):
+ client = _client(live_app)
+ username = "logout_recovery_" + uuid.uuid4().hex[:8]
+ assert _register(client, username).status_code == 302
+ identity = client.get("/auth/csrf-token").json()
+ headers = {
+ "Accept": "application/json",
+ "X-LDR-Auth-Context": identity["auth_context"],
+ }
+ assert client.post("/auth/logout", headers=headers).status_code == 403
+ assert client.get("/auth/check").status_code == 200
+ if lose_credential:
+ session_password_store.clear_all_for_user(username)
+ assert db_manager.is_user_connected(username)
+ refreshed = client.get("/auth/csrf-token", headers=headers)
+ assert refreshed.status_code == 200
+ headers["X-CSRFToken"] = refreshed.json()["csrf_token"]
+
+ response = client.post("/auth/logout", headers=headers)
+
+ assert response.status_code == 200
+ assert response.json() == {"success": True}
+ assert client.get("/auth/check").status_code == 401
+
+
+def test_old_page_cannot_log_out_a_replacement_login(live_app):
+ client = _client(live_app)
+ username = "replaced_logout_" + uuid.uuid4().hex[:8]
+ assert _register(client, username).status_code == 302
+ original = client.get("/auth/csrf-token").json()
+ assert _login(client, username).status_code == 302
+ replacement = client.get("/auth/csrf-token").json()
+ assert replacement["auth_context"] != original["auth_context"]
+
+ rejected = client.post(
+ "/auth/logout",
+ headers={
+ "Accept": "application/json",
+ "X-CSRFToken": replacement["csrf_token"],
+ "X-LDR-Auth-Context": original["auth_context"],
+ },
+ )
+
+ assert rejected.status_code == 409
+ assert client.get("/auth/check").json() == {
+ "authenticated": True,
+ "username": username,
+ }
+
+
[email protected]("other_device", [False, True])
+def test_rejecting_a_session_without_its_credential_revokes_it_server_side(
+ live_app, monkeypatch, other_device
+):
+ """Clearing only the cookie would strand the server-side session.
+
+ Once the cookie is gone the browser cannot reach logout, so the record
+ would stay valid for its whole idle timeout, and a replayed copy of the
+ cookie would keep renewing it. The rejection must destroy the record and
+ disconnect that session's sockets, and must leave other sessions alone.
+ """
+ if not db_manager.has_encryption:
+ pytest.skip("Requires SQLCipher")
+ from local_deep_research.web.auth.session_manager import session_manager
+ from local_deep_research.web.services import socketio_asgi
+
+ disconnected = []
+ monkeypatch.setattr(
+ socketio_asgi, "disconnect_session", disconnected.append
+ )
+ client = _client(live_app)
+ username = "revoked_credential_" + uuid.uuid4().hex[:8]
+ assert _register(client, username).status_code == 302
+ assert client.get("/auth/check").status_code == 200
+ session_id = _session_payload(client)["session_id"]
+ sibling = _client(live_app) if other_device else None
+ if sibling:
+ assert _login(sibling, username).status_code == 302
+ sibling_id = _session_payload(sibling)["session_id"]
+ captured = type(client.cookies)(client.cookies)
+ session_password_store.clear_session(username, session_id)
+ assert session_manager.validate_session(session_id) == username
+
+ assert client.get("/auth/check").status_code == 401
+
+ assert session_manager.validate_session(session_id) is None, (
+ "the rejected session's server-side record is still live"
+ )
+ assert disconnected == [session_id]
+ client.cookies = captured
+ assert client.get("/auth/check").status_code == 401
+ if sibling:
+ assert session_manager.validate_session(sibling_id) == username
+ assert sibling.get("/auth/check").status_code == 200
+
+
[email protected]("other_device", [False, True])
+def test_root_page_requires_this_sessions_own_credential(
+ live_app, other_device
+):
+ """``/`` reads the user's settings, so it needs the same gate.
+
+ Without a session-scoped password, ``get_user_db_session`` falls back to
+ any other live session's password, so the page would render this
+ session's view of the user's saved settings from a sibling's credential.
+ """
+ if not db_manager.has_encryption:
+ pytest.skip("Requires SQLCipher")
+ client = _client(live_app)
+ username = "root_credential_" + uuid.uuid4().hex[:8]
+ assert _register(client, username).status_code == 302
+ assert client.get("/", follow_redirects=False).status_code == 200
+ sibling = _client(live_app) if other_device else None
+ if sibling:
+ assert _login(sibling, username).status_code == 302
+ session_password_store.clear_session(
+ username, _session_payload(client)["session_id"]
+ )
+ assert db_manager.is_user_connected(username)
+
+ response = client.get("/", follow_redirects=False)
+
+ assert response.status_code == 302
+ assert response.headers["location"] == "/auth/login"
+ assert "username" not in _session_payload(client)
+ if sibling:
+ assert sibling.get("/", follow_redirects=False).status_code == 200
+
+
[email protected]("start", ["/", "/settings/"])
+def test_unreopenable_database_signs_out_instead_of_looping(
+ live_app, monkeypatch, start
+):
+ """A 401 that keeps the cookie must not loop ``/`` <-> ``/auth/login``.
+
+ When the database is closed and will not reopen while this session still
+ holds its own password, ``require_auth`` answers 401 and leaves the
+ cookie in place (the session still looks recoverable). ``/auth/login``
+ sends any cookie with a username back to ``/``, so ``/`` has to end the
+ session before redirecting, or the browser bounces until it gives up.
+ Every protected page's HTML 401 funnels through that same pair.
+ """
+ from local_deep_research.web.auth.session_manager import session_manager
+ from local_deep_research.web.services import socketio_asgi
+
+ disconnected = []
+ monkeypatch.setattr(
+ socketio_asgi, "disconnect_session", disconnected.append
+ )
+ client = _client(live_app)
+ username = "unreopenable_" + uuid.uuid4().hex[:8]
+ assert _register(client, username).status_code == 302
+ assert client.get("/", follow_redirects=False).status_code == 200
+ session_id = _session_payload(client)["session_id"]
+ assert session_password_store.get_session_password(username, session_id)
+ sibling = _client(live_app)
+ assert _login(sibling, username).status_code == 302
+ sibling_id = _session_payload(sibling)["session_id"]
+
+ # The database file is gone, corrupt, or failing migration: every reopen
+ # fails while this session's stored password is still present.
+ db_manager.close_user_database(username)
+ monkeypatch.setattr(
+ db_manager, "open_user_database", lambda *args, **kwargs: None
+ )
+ assert not db_manager.is_user_connected(username)
+
+ location = start
+ hops = []
+ response = None
+ for _ in range(6):
+ response = client.get(location, follow_redirects=False)
+ hops.append((location, response.status_code))
+ if response.status_code != 302:
+ break
+ location = response.headers["location"]
+
+ assert response is not None and response.status_code == 200, hops
+ assert location.split("?")[0] == "/auth/login", hops
+ assert "username" not in _session_payload(client)
+ assert session_manager.validate_session(session_id) is None
+ assert disconnected == [session_id]
+ assert (
+ session_password_store.get_session_password(username, session_id)
+ is None
+ )
+ # Only this browser is signed out.
+ assert session_manager.validate_session(sibling_id) == username
+ assert session_password_store.get_session_password(username, sibling_id)