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(csrf): guard the state-changing index-all GET in the middleware (#6439)

LearningCircuit820a875a8a86
diff --git a/changelog.d/6439.breaking.md b/changelog.d/6439.breaking.md
new file mode 100644
index 0000000000..e274ca6c3a
--- /dev/null
+++ b/changelog.d/6439.breaking.md
@@ -0,0 +1 @@
+**`/library/api/rag/index-all` and `/library/api/collections/<id>/index` are now `POST`-only.** Both endpoints start an indexing run — the bulk library re-index and the per-collection re-index, respectively — and stream progress over SSE. A `GET` to either path now answers 405 instead of starting the run. Fetch-based clients must send the `X-CSRFToken` header on both, exactly as for any other POST.
diff --git a/changelog.d/6439.security.md b/changelog.d/6439.security.md
new file mode 100644
index 0000000000..7df6eda4b0
--- /dev/null
+++ b/changelog.d/6439.security.md
@@ -0,0 +1 @@
+The library's bulk "index all" trigger (`/library/api/rag/index-all`, which runs the embedding/index pipeline over every document in a collection and streams progress over SSE) and the per-collection indexing trigger (`/library/api/collections/<id>/index`, the same pipeline and SSE progress stream scoped to one collection) are now POST instead of GET. Both mutate, so they belong on a mutating verb: the CSRF middleware keys enforcement on the method alone, so both routes are now covered by the same rule as every other mutation, and same-site markup that can only issue a GET — a link, an `<img>`/`<script>` src, an iframe — can no longer start a re-index of a signed-in user's whole library or of an individual collection. Fetch-based clients must send the `X-CSRFToken` header, exactly as they already do for any other POST. The GET no longer routes on either endpoint.
diff --git a/docs/library-and-rag.md b/docs/library-and-rag.md
index 0dea95dd99..9edecfb1d0 100644
--- a/docs/library-and-rag.md
+++ b/docs/library-and-rag.md
@@ -275,7 +275,7 @@ Uses OpenAI's embedding API.
| `/library/api/rag/settings` | GET | Get RAG configuration |
| `/library/api/rag/configure` | POST | Update RAG settings |
| `/library/api/rag/info` | GET | Get index statistics |
-| `/library/api/collections/<id>/index` | GET | Start indexing (SSE) |
+| `/library/api/collections/<id>/index` | POST | Start indexing (SSE) |
---
diff --git a/src/local_deep_research/web/dependencies/csrf.py b/src/local_deep_research/web/dependencies/csrf.py
index 89d39e7166..219df8bead 100644
--- a/src/local_deep_research/web/dependencies/csrf.py
+++ b/src/local_deep_research/web/dependencies/csrf.py
@@ -170,6 +170,15 @@ def validate_csrf_token(request: Request, token: str) -> bool:
# Methods that mutate state and require CSRF validation.
+#
+# Enforcement is keyed on the METHOD and nothing else, so a route that
+# mutates state has to be declared on one of these verbs to be covered.
+# That is deliberate: the method arrives in its own ASGI scope key and
+# has exactly one spelling, whereas a per-path allowlist has to agree
+# with the router about how a path is written, and disagreeing fails
+# OPEN (the middleware misses, the router still matches, the handler
+# runs). Keep state-changing routes on an unsafe verb rather than
+# re-introducing a path allowlist to cover a mutating GET.
_UNSAFE_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
# Routes that bootstrap auth or are token-authenticated and so cannot
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index e1a2b7a6c7..903591a547 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -1163,12 +1163,25 @@ async def remove_document(
return handle_api_error(f"removing document {text_doc_id}", e)
[email protected]("/api/rag/index-all")
[email protected]("/api/rag/index-all")
def index_all(
request: Request,
username: Annotated[str, Depends(require_auth)],
):
- """Index all documents in a collection with Server-Sent Events progress."""
+ """Index all documents in a collection with Server-Sent Events progress.
+
+ POST, not GET, because it mutates: it resolves the caller's collection,
+ writes embedding metadata, and runs the embedding/index pipeline over
+ every document in it (``?force_reindex=true`` discards and rebuilds
+ vectors that already exist). CSRFMiddleware keys enforcement on the
+ method, so declaring it here is what puts it behind the token check —
+ a GET would be outside the middleware entirely and startable from
+ same-site markup riding the victim's session cookie. Progress still
+ streams as Server-Sent Events; the caller is a fetch client, which can
+ send both the X-CSRFToken header and a POST, so nothing about the
+ streaming response changes. Query parameters (``collection_id``,
+ ``force_reindex``) are unchanged.
+ """
from ...database.session_context import get_user_db_session
from ...database.library_init import get_default_library_id
from ...utilities.db_utils import get_settings_manager
@@ -3196,13 +3209,25 @@ def _query_documents_to_index(db_session, collection_id, force_reindex):
return query.all()
[email protected]("/api/collections/{collection_id}/index")
[email protected]("/api/collections/{collection_id}/index")
def index_collection(
request: Request,
collection_id,
username: Annotated[str, Depends(require_auth)],
):
- """Index all documents in a collection with Server-Sent Events progress."""
+ """Index all documents in a collection with Server-Sent Events progress.
+
+ POST, not GET, because it mutates — same reasoning as index-all:
+ it writes embedding metadata and runs the embedding/index pipeline
+ over every document in the collection (``?force_reindex=true``
+ discards and rebuilds vectors that already exist), and
+ CSRFMiddleware keys enforcement on the method, so the verb is what
+ puts it behind the token check. A GET would sit outside the
+ middleware entirely and be startable from same-site markup riding
+ the victim's session cookie. Nothing in the shipped frontend called
+ it — the history page's Index button POSTs COLLECTION_INDEX_START.
+ Progress still streams as SSE; a fetch client can send both a POST
+ and the header. Query parameters are unchanged."""
from ...database.session_context import get_user_db_session
from ...database.session_passwords import session_password_store
diff --git a/src/local_deep_research/web/static/js/config/urls.js b/src/local_deep_research/web/static/js/config/urls.js
index 7f5ba6857b..fd0b0dbfec 100644
--- a/src/local_deep_research/web/static/js/config/urls.js
+++ b/src/local_deep_research/web/static/js/config/urls.js
@@ -120,12 +120,10 @@ if (typeof URLS !== 'undefined') {
COLLECTION_DETAILS: '/library/api/collections/{id}',
COLLECTION_DOCUMENTS: '/library/api/collections/{id}/documents',
COLLECTION_UPLOAD: '/library/api/collections/{id}/upload',
- COLLECTION_INDEX: '/library/api/collections/{id}/index',
COLLECTION_INDEX_START: '/library/api/collections/{id}/index/start',
COLLECTION_INDEX_STATUS: '/library/api/collections/{id}/index/status',
// RAG management
- RAG_INDEX_ALL: '/library/api/rag/index-all',
RAG_DOCUMENTS: '/library/api/rag/documents',
// Config
diff --git a/tests/research_library/routes/test_rag_routes_gaps_main_port.py b/tests/research_library/routes/test_rag_routes_gaps_main_port.py
index 8945d93ccc..0bb9d5e4c1 100644
--- a/tests/research_library/routes/test_rag_routes_gaps_main_port.py
+++ b/tests/research_library/routes/test_rag_routes_gaps_main_port.py
@@ -8,8 +8,8 @@ files do not reach:
* ``GET /library/api/rag/settings`` (``get_current_settings``)
* ``POST /library/api/rag/configure`` (``configure_rag``)
-* ``GET /library/api/collections/{id}/index`` (``index_collection``, SSE)
-* ``GET /library/api/rag/index-all`` (``index_all``, SSE)
+* ``POST /library/api/collections/{id}/index`` (``index_collection``, SSE)
+* ``POST /library/api/rag/index-all`` (``index_all``, SSE)
* the crash-window / status-classification invariants shared by those two
SSE routes and ``_background_index_worker``
* the RAG-service close-on-exit guarantee
@@ -769,7 +769,7 @@ class TestConfigureRag:
class TestIndexCollection:
"""Ported from ``origin/main:.../test_rag_routes_gaps_coverage.py``
- ``::TestIndexCollection`` -- ``GET /library/api/collections/{id}/index``.
+ ``::TestIndexCollection`` -- ``POST /library/api/collections/{id}/index``.
The Flask route streamed via ``stream_with_context``; the branch
returns a ``StreamingResponse`` around the same ``generate()``. The
diff --git a/tests/research_library/test_library_pipeline_contracts.py b/tests/research_library/test_library_pipeline_contracts.py
index 4a98ab91b2..8fda7f4fd6 100644
--- a/tests/research_library/test_library_pipeline_contracts.py
+++ b/tests/research_library/test_library_pipeline_contracts.py
@@ -22,10 +22,12 @@ Deliberately NOT repeated here:
* The RAG index lifecycle against a real FAISS store --
``tests/research_library/test_document_full_lifecycle.py``.
-Two known-and-filed defects are load-bearing context but are not
+One known-and-filed defect is load-bearing context but is not
re-asserted: ``POST /library/api/collections/{id}/index/start`` accepting
-a nonexistent collection (#5828) and ``GET /library/api/rag/index-all``
-being state-changing without CSRF (#5830).
+a nonexistent collection (#5828). The bulk re-index trigger is no longer
+one of them -- it is a POST, so the CSRF middleware challenges it like
+any other mutation (pinned by
+``tests/security/test_csrf_coverage.py``).
Every assertion is paired with a control that proves this harness can
observe the opposite outcome through the identical path -- the deleted
diff --git a/tests/security/test_auth_dependencies_fastapi.py b/tests/security/test_auth_dependencies_fastapi.py
index 5112ceeeac..67bca678bc 100644
--- a/tests/security/test_auth_dependencies_fastapi.py
+++ b/tests/security/test_auth_dependencies_fastapi.py
@@ -293,7 +293,7 @@ SELF_ENFORCING_ROUTES: dict[tuple[str, str], str] = {
_STATIC_ALLOWLIST = {**PUBLIC_ROUTES, **SELF_ENFORCING_ROUTES}
# Floors for the vacuity guards below. Set well under today's numbers (317
-# route-method pairs: 182 GET, 135 mutating, 13 unauthenticated) so ordinary
+# route-method pairs: 180 GET, 137 mutating, 13 unauthenticated) so ordinary
# churn does not trip them, but high enough that a broken enumeration — the
# failure mode that would make every assertion in this file pass trivially —
# cannot slip through.
diff --git a/tests/security/test_csrf_coverage.py b/tests/security/test_csrf_coverage.py
index 47515c2867..3b08f1f654 100644
--- a/tests/security/test_csrf_coverage.py
+++ b/tests/security/test_csrf_coverage.py
@@ -25,8 +25,11 @@ the ``/ws`` prefix constraint; ``tests/security/test_csrf_protection.py`` /
* token ROTATION across the real login / logout / register transitions;
* real full-stack probes of the three body shapes the middleware treats
differently (JSON, multipart, urlencoded form-field fallback);
-* the method-shaped hole: a GET route that mutates is outside
- ``_UNSAFE_METHODS`` and therefore outside the middleware entirely;
+* the method-shaped hole: a mutating route parked on a verb outside
+ ``_UNSAFE_METHODS`` sits outside the middleware entirely, and a
+ per-path allowlist cannot pull it back in — the middleware and the
+ router do not agree on how a path is spelled — so the only fix is the
+ verb, pinned here against the real route table;
* an independent static audit of every ``<form method=post>`` and every
state-changing ``fetch`` in the shipped frontend.
@@ -47,7 +50,6 @@ from contextlib import contextmanager
from pathlib import Path
import pytest
-
from local_deep_research.web.dependencies import csrf as csrf_mod
from local_deep_research.web.dependencies.csrf import (
CSRFMiddleware,
@@ -626,50 +628,162 @@ def test_logout_is_csrf_protected_end_to_end(authenticated_client):
# A5. The method-shaped hole: a mutating route on a "safe" verb
# ---------------------------------------------------------------------------
-_GET_MUTATION_DEFECT = (
- "LIVE DEFECT: GET /library/api/rag/index-all is state-changing — it "
- "resolves the caller's collection, reads rag.indexing_* settings and "
- "runs the embedding/index pipeline over every document in the "
- "collection (?force_reindex=true re-embeds documents that are already "
- "indexed). CSRFMiddleware only guards _UNSAFE_METHODS "
- "{POST,PUT,PATCH,DELETE}, so this route is outside the middleware "
- "entirely: no token is required and none is checked. CONSEQUENCE: an "
- "attacker page that gets the victim's browser to issue a same-site GET "
- "(a link, an <img>/<script> src, an iframe) triggers an unbounded "
- "re-index of the victim's whole library — LLM/embedding cost and CPU "
- "burn, and with force_reindex it discards and rebuilds existing "
- "vectors. Cross-SITE exploitation is currently blunted by the "
- "SameSite=strict session cookie, which is a browser-side mitigation, "
- "not the app-side control the middleware is supposed to be. FIX: make "
- "the trigger a POST (SSE over POST via fetch+ReadableStream, which the "
- "frontend already does elsewhere), or keep the GET and add an explicit "
- "validate_csrf_token(request, request.headers['X-CSRFToken']) gate in "
- "the handler before any indexing work starts."
+
+ "path",
+ [
+ "/library/api/rag/index-all",
+ "/library/api/collections/123/index",
+ ],
)
+def test_mutating_routes_are_not_reachable_on_an_unguarded_verb(
+ authenticated_client,
+ path,
+):
+ """A state-changing route must not sit on a verb the middleware skips.
+
+ ``CSRFMiddleware`` challenges ``_UNSAFE_METHODS`` and nothing else, so
+ a route that mutates state from a GET is outside the check entirely.
+ An allowlist of state-changing GET paths does NOT close that: the
+ middleware compares ``scope["path"]`` as a string while the router
+ matches it with a ``$``-anchored regex, and the two disagree — uvicorn
+ percent-decodes the target into ``scope["path"]``, so
+ ``/library/api/rag/index-all%0A`` arrives with a trailing newline that
+ Python's ``$`` still matches but a set-membership test does not. The
+ allowlist misses, the router dispatches, the handler runs: fail-open.
+ The verb is the only spelling-proof key, so ``index-all`` is a POST.
+
+ CONTROL: the same path on its real verb IS challenged. This pins
+ that the route exists and enforces CSRF, so a route shipped
+ CSRF-exempt cannot satisfy it.
+ """
+ client = authenticated_client
+
+ with _no_token(client):
+ challenged = client.post(path)
+ assert _csrf_refused(challenged), (
+ f"CONTROL FAILED — POST {path} was not "
+ "challenged for CSRF, so the route is either gone or unguarded and "
+ f"the assertion below proves nothing: {challenged.status_code} "
+ f"{challenged.text[:200]}"
+ )
+
+ stale = client.get(path + "?force_reindex=true")
+ assert stale.status_code == 405, (
+ f"GET {path} still routes. A mutating route on "
+ "a verb the middleware skips is reachable from same-site markup "
+ "(a link, an <img>/<script> src, an iframe) riding the victim's "
+ f"session cookie: {stale.status_code} {stale.text[:200]}"
+ )
[email protected](strict=True, reason=_GET_MUTATION_DEFECT)
-def test_mutating_routes_are_not_reachable_on_an_unguarded_verb():
- """A state-changing route must not sit on a verb the middleware skips."""
- control = drive(
+def test_index_all_post_without_a_token_is_refused():
+ """The bulk re-index trigger is challenged like any other mutation."""
+ outcome = drive(
"POST",
- "/library/api/rag/index-document",
+ "/library/api/rag/index-all",
session={"username": "victim"},
)
- assert control.is_csrf_rejection, (
- "CONTROL FAILED — the POST sibling in the same router was not "
- f"challenged either, so the assertion below is vacuous: {control!r}"
+ assert outcome.is_csrf_rejection, (
+ "POST /library/api/rag/index-all was not challenged for CSRF: "
+ f"{outcome!r}"
)
- mutating = drive(
- "GET",
- "/library/api/rag/index-all",
+
+def test_collection_index_post_without_a_token_is_refused():
+ """The per-collection trigger is challenged like any other mutation."""
+ outcome = drive(
+ "POST",
+ "/library/api/collections/123/index",
session={"username": "victim"},
)
- assert not mutating.reached, (
- "GET /library/api/rag/index-all reached the handler with no CSRF "
- f"token: {mutating!r}"
+ assert outcome.is_csrf_rejection, (
+ "POST /library/api/collections/123/index was not challenged for "
+ f"CSRF: {outcome!r}"
+ )
+
+
+def test_collection_index_post_with_a_valid_token_passes_the_middleware():
+ """CONTROL for the refusal above — a valid token passes the middleware.
+
+ ``drive()`` wires the middleware around a sentinel with no router, so
+ this pins the middleware's pass-through, not the collection-index
+ handler.
+ """
+ token = "a" * 64
+ outcome = drive(
+ "POST",
+ "/library/api/collections/123/index",
+ session={"username": "victim", "_csrf_token": token},
+ headers={"X-CSRFToken": token},
)
+ assert outcome.reached, (
+ "CONTROL FAILED — the tokened POST was refused too, so the "
+ f"rejection above proves nothing: {outcome!r}"
+ )
+
+
+def test_index_all_post_with_a_valid_token_passes_the_middleware():
+ """CONTROL for the refusal above — a valid token passes the middleware.
+
+ ``drive()`` wires the middleware around a sentinel with no router, so
+ this pins the middleware's pass-through, not the index-all handler. A
+ fetch-based SSE client sends X-CSRFToken like it does for every other
+ POST, and must still get through the middleware.
+ """
+ token = "a" * 64
+ outcome = drive(
+ "POST",
+ "/library/api/rag/index-all",
+ session={"username": "victim", "_csrf_token": token},
+ headers={"X-CSRFToken": token},
+ )
+ assert outcome.reached, (
+ "CONTROL FAILED — the same request WITH a valid token was refused "
+ f"too, so the rejection above proves nothing: {outcome!r}"
+ )
+
+
+def test_the_challenge_does_not_depend_on_how_the_path_is_spelled():
+ """No path spelling can move a mutation outside the middleware.
+
+ This is the property a per-path allowlist cannot provide and the verb
+ can. Each spelling below either reaches the router or does not; what
+ matters is that the middleware challenges it either way, so the
+ middleware can never be the component that lets one through. The
+ percent-decoded trailing newline is the one that defeated an exact
+ path match; the sub-path prefixes are the same failure under a
+ ``root_path`` deployment.
+
+ CONTROL: the identical spellings on a method the middleware skips are
+ NOT refused, so "everything is refused" cannot satisfy this.
+ """
+ base = "/library/api/rag/index-all"
+ spellings = [
+ base,
+ base + "\n", # uvicorn's unquote() of a trailing %0A
+ base + "\r",
+ base + "/",
+ base + " ",
+ base + "%0A", # literal, if something upstream did not decode it
+ "/ldr" + base, # root_path sub-path deployment
+ ]
+
+ for path in spellings:
+ outcome = drive("POST", path, session={"username": "victim"})
+ assert outcome.is_csrf_rejection, (
+ f"a tokenless POST spelled {path!r} was not challenged — the "
+ f"middleware's enforcement key is path-sensitive again: "
+ f"{outcome!r}"
+ )
+
+ for path in spellings:
+ outcome = drive("GET", path, session={"username": "victim"})
+ assert outcome.reached, (
+ "CONTROL FAILED — a GET at {!r} was refused as well, so the "
+ "refusals above are not evidence that the METHOD is what "
+ "decides: {!r}".format(path, outcome)
+ )
# ---------------------------------------------------------------------------
diff --git a/tests/security/test_realtime_channel_isolation.py b/tests/security/test_realtime_channel_isolation.py
index 7bd16185f7..9f9025ac2e 100644
--- a/tests/security/test_realtime_channel_isolation.py
+++ b/tests/security/test_realtime_channel_isolation.py
@@ -725,8 +725,8 @@ def test_captured_cookie_cannot_open_a_new_socket_after_logout(app, two_users):
# here rather than silently dropping out of the sweep.
_STREAM_ROUTES = [
("GET", "/api/research/{rid}/logs/export"),
- ("GET", "/library/api/rag/index-all"),
- ("GET", "/library/api/collections/{cid}/index"),
+ ("POST", "/library/api/rag/index-all"),
+ ("POST", "/library/api/collections/{cid}/index"),
("POST", "/library/api/download-all-text"),
("POST", "/library/api/download-bulk"),
]
@@ -914,7 +914,7 @@ def test_user_b_cannot_read_the_contents_of_user_as_collection_sse(
path = f"/library/api/collections/{cid}/index"
- a_resp = user_a.client.get(path)
+ a_resp = user_a.client.post(path)
assert a_resp.status_code == 200, a_resp.status_code
a_frames = [
json.loads(chunk.split("data: ", 1)[1])
@@ -927,7 +927,7 @@ def test_user_b_cannot_read_the_contents_of_user_as_collection_sse(
f"below proves nothing: {a_frames!r}"
)
- b_resp = user_b.client.get(path)
+ b_resp = user_b.client.post(path)
assert b_resp.status_code == 200, b_resp.status_code
b_frames = [
json.loads(chunk.split("data: ", 1)[1])
diff --git a/tests/ui_tests/run_all_tests.js b/tests/ui_tests/run_all_tests.js
index ff57351cec..7c30c6254e 100644
--- a/tests/ui_tests/run_all_tests.js
+++ b/tests/ui_tests/run_all_tests.js
@@ -276,7 +276,7 @@ const tests = [
'the rewritten transports (python-socketio ASGI at /ws, Starlette SSE) ' +
'rather than just asserting DOM/route structure. Socket.IO handshake ' +
'auth (accept authenticated, reject unauthenticated), SSE streaming ' +
- 'contract on GET /library/api/rag/index-all (headers + multi-chunk ' +
+ 'contract on POST /library/api/rag/index-all (headers + multi-chunk ' +
'delivery + parsed events), and console-error-free load of the pages ' +
'that depend on these subsystems.'
},
diff --git a/tests/ui_tests/test_streaming_realtime_ci.js b/tests/ui_tests/test_streaming_realtime_ci.js
index 01c8a4d218..7cd77e0806 100644
--- a/tests/ui_tests/test_streaming_realtime_ci.js
+++ b/tests/ui_tests/test_streaming_realtime_ci.js
@@ -24,7 +24,7 @@
* with no username — see the code comment there for the security
* rationale: accepting it would leak roomless broadcasts, e.g.
* parallel_search_started, to anyone).
- * 2. A real SSE endpoint (GET /library/api/rag/index-all, StreamingResponse
+ * 2. A real SSE endpoint (POST /library/api/rag/index-all, StreamingResponse
* + media_type="text/event-stream") delivers its body to the browser
* as multiple discrete chunks over chunked transfer-encoding, carrying
* the anti-buffering headers the frontend depends on, and that the
@@ -38,9 +38,9 @@
*
* Endpoint choice for (2): /library/api/rag/index-all was picked over the
* other three SSE endpoints in the codebase (POST /library/api/download-all-text,
- * POST /library/api/download-research/<id>, GET /library/api/collections/<id>/index)
- * because it is a plain GET, needs no request body/seed data, needs no LLM,
- * and — critically — every freshly authenticated user already has an empty
+ * POST /library/api/download-research/<id>, POST /library/api/collections/<id>/index)
+ * because it needs no request body/seed data, needs no LLM, and —
+ * critically — every freshly authenticated user already has an empty
* default "Library" collection (ensure_default_library_collection() runs at
* login), so the generator's "no documents to index" branch fires in well
* under a second while still emitting >1 real SSE event over the wire
@@ -215,8 +215,27 @@ async function testSseEndpointStreams(page) {
await page.goto(`${BASE_URL}/`, { waitUntil: 'domcontentloaded', timeout: 30000 });
}
- const result = await page.evaluate(async () => {
- const resp = await fetch('/library/api/rag/index-all', { credentials: 'same-origin' });
+ // The route mutates (it runs the embedding/index pipeline), so it is a
+ // POST and CSRFMiddleware challenges it like any other mutation. Same
+ // token source the shipped frontend uses: the csrf-token meta tag
+ // base.html renders on every page (see getCsrf() in
+ // test_download_and_csrf_flows_ci.js).
+ const csrfToken = await page.evaluate(() => {
+ const m = document.querySelector('meta[name="csrf-token"]');
+ return m ? m.content : '';
+ });
+ if (!csrfToken) {
+ fail('SSE endpoint: no csrf-token meta tag on the authenticated page');
+ await captureOnFailure(page, SCREENSHOT_PREFIX, 'sse_endpoint', false);
+ return;
+ }
+
+ const result = await page.evaluate(async (csrf) => {
+ const resp = await fetch('/library/api/rag/index-all', {
+ method: 'POST',
+ credentials: 'same-origin',
+ headers: { 'X-CSRFToken': csrf },
+ });
const headers = {};
for (const [k, v] of resp.headers.entries()) headers[k] = v;
@@ -256,7 +275,7 @@ async function testSseEndpointStreams(page) {
}
return { status: resp.status, ok: resp.ok, headers, chunkReads, events };
- });
+ }, csrfToken);
// --- Contract assertions ---
if (result.status === 200) {
@@ -356,7 +375,7 @@ async function main() {
await testAuthenticatedSocketConnects(authedPage);
await testUnauthenticatedSocketRejected(browser);
- section('SSE — GET /library/api/rag/index-all streams to the browser');
+ section('SSE — POST /library/api/rag/index-all streams to the browser');
await testSseEndpointStreams(authedPage);
section('No console errors on realtime-dependent authenticated pages');
diff --git a/tests/web/routers/test_all_endpoints.py b/tests/web/routers/test_all_endpoints.py
index 9e82917a79..8465edf24e 100644
--- a/tests/web/routers/test_all_endpoints.py
+++ b/tests/web/routers/test_all_endpoints.py
@@ -58,19 +58,23 @@ SKIP_PATHS = {
"/docs/oauth2-redirect",
"/openapi.json",
"/api/docs",
- # These three GET endpoints call get_rag_service(), which eagerly builds
+ # These two GET endpoints call get_rag_service(), which eagerly builds
# LibraryRAGService and loads the ~400MB sentence-transformers embedding
- # model — even /stats and /info, which only read metadata (verified with
- # a per-endpoint fresh-process probe: exactly these three pull the ML
+ # model — even though /stats and /info only read metadata (verified with
+ # a per-endpoint fresh-process probe: exactly these pull the ML
# stack; the other rag GETs do not). Under the whole-suite `-n auto` run,
# each xdist worker that hits one loads the model into its own process;
# several loading concurrently OOM-kill the CI runner, and the OOM-killer
# takes out unrelated workers (observed as "worker gwN crashed" on trivial
- # endpoints like / and /favicon.ico, plus a journal-warm 503 race). All
- # three are covered by dedicated tests in tests/research_library/routes/.
+ # endpoints like / and /favicon.ico, plus a journal-warm 503 race). Both
+ # are covered by dedicated tests in tests/research_library/routes/.
# (That a GET /stats spins up a 400MB model is a minor product
# inefficiency worth a separate lazy-load follow-up.)
- "/library/api/rag/index-all",
+ #
+ # The bulk re-index trigger shared this hazard and used to be listed
+ # here too; it is a POST now, so this GET-only enumerator never reaches
+ # it. Its entry lives in test_full_surface_smoke.py's
+ # MUTATING_DENY_LIST instead.
"/library/api/rag/info",
"/library/api/rag/stats",
# Still skipped, but for a different and much smaller reason than before,
diff --git a/tests/web/routers/test_full_surface_smoke.py b/tests/web/routers/test_full_surface_smoke.py
index 56250368d6..491844d678 100644
--- a/tests/web/routers/test_full_surface_smoke.py
+++ b/tests/web/routers/test_full_surface_smoke.py
@@ -131,11 +131,6 @@ STREAMING_CONTENT_TYPE_EXEMPT = {
# ----------------------------------------------------------------------------
-# Parameterized GET routes excluded from the sweep. Same reasoning as
-# test_all_endpoints.py's SKIP_PATHS for /library/api/rag/index-all et al.
-# (see the full postmortem comment there) — this is the one *parameterized*
-# GET route with the identical hazard, so it needs its own entry here rather
-# than landing in that file's (non-parameterized-only) skip list.
# Mutating routes whose correct, intended response is a >=500 status,
# because the underlying feature is deliberately not implemented — not
# because a domain exception got swallowed. Same convention as
@@ -159,17 +154,17 @@ KNOWN_5XX = {
# ----------------------------------------------------------------------------
-GET_DENY_LIST = {
- ("GET", "/library/api/collections/{collection_id}/index"): (
- "calls get_rag_service() unconditionally, before any check that "
- "collection_id refers to a real collection — eagerly loads the "
- "~400MB sentence-transformers embedding model on every hit, the "
- "exact hazard test_all_endpoints.py's SKIP_PATHS documents for "
- "the sibling /rag/index-all, /info, /stats GETs (those are "
- "non-parameterized so they landed in that file's skip list "
- "instead)."
- ),
-}
+# Parameterized GET routes excluded from the sweep. Same reasoning as
+# test_all_endpoints.py's SKIP_PATHS for /library/api/rag/info et al. (see
+# the full postmortem comment there). Currently empty: the one
+# parameterized GET route that used to need its own entry here,
+# /library/api/collections/{collection_id}/index, is now a POST and is
+# covered by MUTATING_DENY_LIST instead (see its entry there — "moved here
+# with the verb change"). Kept as a placeholder for the next parameterized
+# GET route with the same hazard, so it lands here rather than in that
+# file's (non-parameterized-only) skip list.
+# ----------------------------------------------------------------------------
+GET_DENY_LIST = {}
# ----------------------------------------------------------------------------
@@ -235,6 +230,22 @@ MUTATING_DENY_LIST = {
"thread before ever checking whether collection_id refers to a "
"real collection."
),
+ ("POST", "/library/api/collections/{collection_id}/index"): (
+ "the parameterized sibling of /rag/index-all: same embedding/"
+ "index pipeline (force_reindex rebuilds vectors), so it both "
+ "starts real work and eagerly loads the embedding model. Was a "
+ "GET with the same hazard — moved here with the verb change."
+ ),
+ ("POST", "/library/api/rag/index-all"): (
+ "calls get_rag_service() before any validation, which eagerly "
+ "loads the ~400MB sentence-transformers embedding model — the "
+ "same OOM hazard test_all_endpoints.py's SKIP_PATHS documents "
+ "for the sibling /rag/info and /rag/stats GETs — and with no "
+ "collection_id in the URL it resolves the caller's default "
+ "library and runs the real bulk embedding pipeline over it. It "
+ "also always answers text/event-stream, so it could not meet "
+ "this sweep's application/json contract either."
+ ),
("POST", "/library/api/zotero/sync"): (
"spawns a real threading.Thread that calls the live Zotero API "
"when Zotero is configured for the user. Today a fresh "
diff --git a/tests/web/routers/test_router_sibling_consistency.py b/tests/web/routers/test_router_sibling_consistency.py
index 6f84b529bd..7b480312da 100644
--- a/tests/web/routers/test_router_sibling_consistency.py
+++ b/tests/web/routers/test_router_sibling_consistency.py
@@ -151,8 +151,8 @@ def _references_name_anywhere(node: ast.AST, name: str) -> bool:
# 1. Auth uniformity on state-changing routes
# ===========================================================================
#
-# Survey (live dependant-tree walk over all 135 POST/PUT/PATCH/DELETE
-# routes across all 18 routers): 128 declare `username: str =
+# Survey (live dependant-tree walk over all 137 POST/PUT/PATCH/DELETE
+# routes across all 18 routers): 130 declare `username: str =
# Depends(require_auth)` as a DIRECT dependency. The remaining 7 split into
# two verified, narrow families:
#
@@ -319,12 +319,12 @@ def test_every_mutating_route_requires_auth_or_is_allowlisted():
def test_direct_require_auth_dependencies_use_uniform_param_name():
- """Of the 135 mutating routes, every one that declares require_auth
- DIRECTLY (128 of them, verified) names the injected value `username` --
+ """Of the 137 mutating routes, every one that declares require_auth
+ DIRECTLY (130 of them, verified) names the injected value `username` --
not `user`, `current_user`, or any other spelling. This is the
"auth declared differently in one router than the other nineteen"
shape: a route that authenticates via a same-purpose dependency named
- or typed differently from its 128 siblings is exactly the kind of
+ or typed differently from its 130 siblings is exactly the kind of
drift per-file review misses."""
exceptions = {**PUBLIC_MUTATING_ROUTES, **INDIRECT_AUTH_VIA_STRONGER_GATE}
violations = []
diff --git a/tests/web/routers/test_sse_response_headers.py b/tests/web/routers/test_sse_response_headers.py
index e5a252dca5..a56a8c6c3d 100644
--- a/tests/web/routers/test_sse_response_headers.py
+++ b/tests/web/routers/test_sse_response_headers.py
@@ -15,9 +15,11 @@ SSE endpoints:
via ``fetch('/library/api/download-all-text')`` in library.html and
download_manager.html); fixed alongside this test to mirror
``download_bulk``,
-* ``rag.py::index_all`` — did NOT set them (frontend calls it via
- ``RAG_INDEX_ALL`` in urls.js from the history page's index-all button);
- fixed alongside this test to mirror ``index_collection``.
+* ``rag.py::index_all`` — did NOT set them (read by a fetch-based
+ SSE client; the ``RAG_INDEX_ALL`` constant in urls.js has no caller in
+ the shipped frontend, whose Index All button POSTs
+ ``COLLECTION_INDEX_START`` instead); fixed alongside this test to
+ mirror ``index_collection``.
The HTTP tests drive the real routers through Starlette's TestClient with
``require_auth`` overridden and only true boundaries mocked (DB sessions,
@@ -183,21 +185,27 @@ def rag_client(monkeypatch):
@pytest.mark.timeout(30)
def test_index_collection_sse_sets_anti_buffering_headers(rag_client):
- """Existing-behavior fence: GET /library/api/collections/{id}/index
+ """Existing-behavior fence: POST /library/api/collections/{id}/index
sets Cache-Control no-cache + X-Accel-Buffering no (plus
no-transform); dropping them would re-break collection indexing
progress behind nginx."""
- resp = rag_client.get("/library/api/collections/coll-missing/index")
+ resp = rag_client.post("/library/api/collections/coll-missing/index")
_assert_anti_buffering(resp)
assert "Collection not found" in resp.text
@pytest.mark.timeout(30)
def test_index_all_sse_sets_anti_buffering_headers(rag_client):
- """GET /library/api/rag/index-all streams bulk-index progress to the
- history page; the audit found it sent NO anti-buffering headers
- (fixed alongside this test to mirror index_collection)."""
- resp = rag_client.get(
+ """POST /library/api/rag/index-all streams bulk-index progress; the
+ audit found it sent NO anti-buffering headers (fixed alongside this
+ test to mirror index_collection).
+
+ POST because the route mutates — it is the verb, not a path
+ allowlist, that puts it behind CSRFMiddleware. The handler reads
+ ``collection_id``/``force_reindex`` from the query string either
+ way, and this fixture's app has no CSRF middleware.
+ """
+ resp = rag_client.post(
"/library/api/rag/index-all", params={"collection_id": "coll-missing"}
)
_assert_anti_buffering(resp)
diff --git a/tests/web/test_content_negotiation_census.py b/tests/web/test_content_negotiation_census.py
index fa00471687..93a94885de 100644
--- a/tests/web/test_content_negotiation_census.py
+++ b/tests/web/test_content_negotiation_census.py
@@ -66,7 +66,7 @@ handler. Four things fell out that no other suite covers:
already had.
Two census results are *clean*, and are pinned here so they stay clean:
-the 401 axis over all 182 GET routes (every ``/api/``-shaped path answers
+the 401 axis over all 180 GET routes (every ``/api/``-shaped path answers
a browser with JSON, every browser-shaped path answers with a redirect or
HTML, with four reviewed exceptions), and the "``return`` a JSONResponse
error instead of ``raise``" class, which bypasses the handlers entirely
diff --git a/tests/web/test_route_table_parity.py b/tests/web/test_route_table_parity.py
index 3df57b01ed..23445c80c0 100644
--- a/tests/web/test_route_table_parity.py
+++ b/tests/web/test_route_table_parity.py
@@ -160,6 +160,26 @@ EXPECTED_REMOVED = [
("DELETE", "/settings/api/{:path}"),
("GET", "/settings/api/{:path}"),
("PUT", "/settings/api/{:path}"),
+ # The library's bulk re-index trigger moved from GET to POST. It runs
+ # the embedding/index pipeline over every document in the collection
+ # (`?force_reindex=true` discards and rebuilds vectors that already
+ # exist), so it is a mutation and belongs on a verb CSRFMiddleware
+ # guards — enforcement there is keyed on the method, and a per-path
+ # allowlist cannot stand in for it (the middleware compares
+ # `scope["path"]` as a string, the router matches a `$`-anchored
+ # regex, and uvicorn's percent-decode makes those two disagree). Same
+ # path, same handler, same query parameters, same SSE response; the
+ # GET now 405s. No shipped frontend called it — urls.js's
+ # RAG_INDEX_ALL has no caller and the history page's Index All button
+ # POSTs COLLECTION_INDEX_START — and fetch-based SSE clients send the
+ # token as they already do for every other POST. Paired with the
+ # ("POST", ...) entry in EXPECTED_ADDED and the method-set entry in
+ # EXPECTED_METHOD_SET_DIVERGENCES.
+ ("GET", "/library/api/rag/index-all"),
+ # Same verb move for the parameterized sibling: the per-collection
+ # re-index trigger. Nothing in the repo sent the GET either — the
+ # history page's Index button POSTs COLLECTION_INDEX_START.
+ ("GET", "/library/api/collections/{}/index"),
]
EXPECTED_ADDED = [
@@ -170,6 +190,11 @@ EXPECTED_ADDED = [
("DELETE", "/settings/api/{}"),
("GET", "/settings/api/{}"),
("PUT", "/settings/api/{}"),
+ # FastAPI-side counterpart of the bulk re-index GET -> POST move
+ # recorded in EXPECTED_REMOVED above.
+ ("POST", "/library/api/rag/index-all"),
+ # ...and of the per-collection sibling right below it.
+ ("POST", "/library/api/collections/{}/index"),
]
@@ -1505,8 +1530,29 @@ def _where(views) -> str:
# fails too (so the tables cannot rot into permanent suppression).
# ---------------------------------------------------------------------------
+# {normalised path: (Flask method set, FastAPI method set)}. A path both
+# tables serve on a DIFFERENT set of verbs fails
+# `test_method_sets_match_per_path` unless it is listed here with both
+# sides spelled out — and an entry whose two sides stop diverging, or
+# start diverging differently, fails too.
+EXPECTED_METHOD_SET_DIVERGENCES = {
+ # The bulk re-index trigger; see the paired entries in
+ # EXPECTED_REMOVED / EXPECTED_ADDED for why the verb changed. Stated
+ # here as well because a verb move is exactly the "silent 405 for
+ # every client still sending the old method" this test exists to
+ # surface, and it should be reviewed as a method change rather than
+ # read as two unrelated diff lines. Nothing in the repo sent the GET.
+ "/library/api/rag/index-all": ({"GET"}, {"POST"}),
+ # The per-collection sibling; same reasoning as above. Nothing in
+ # the repo sent the GET.
+ "/library/api/collections/{}/index": (
+ {"DELETE", "GET"},
+ {"DELETE", "POST"},
+ ),
+}
+
# (METHOD, normalised path, slot index, Flask converter, FastAPI annotation).
-# The whole comparison is 141 parameter slots across 309 shared routes, of
+# The whole comparison is 141 parameter slots across 308 shared routes, of
# which 8 are Flask `<int:...>` — every one of those 8 is annotated `int` on
# the FastAPI side, so the int-widening failure mode this check exists for
# does not occur anywhere. One slot diverges textually:
@@ -1693,9 +1739,9 @@ EXPECTED_ERROR_KEY_DROPPED = [
# Anti-vacuity floors. A parity check that resolves nothing passes
# trivially, so every behavioural test asserts a lower bound on how much it
# actually compared. These are set just under the counts measured when the
-# tables above were reviewed (309 shared routes, 141 parameter slots of
-# which 8 int, 295 auth-gated routes, 306 routes with status codes on both
-# sides, 192 routes whose Flask side emits an `error` key, 10 rules
+# tables above were reviewed (308 shared routes, 141 parameter slots of
+# which 8 int, 294 auth-gated routes, 305 routes with status codes on both
+# sides, 191 routes whose Flask side emits an `error` key, 10 rules
# declared with a trailing slash). If an extraction breaks and starts
# yielding an empty or shrunken table, these fail loudly instead of the
# comparison silently succeeding against nothing.
@@ -1728,6 +1774,12 @@ class TestRouteBehaviourParityAgainstFlaskSnapshot:
own property so the failure message names the path and both method
sets instead of showing two unrelated-looking diff lines, and so
the dimension is visibly covered rather than covered by accident.
+
+ A deliberate verb move is recorded in
+ EXPECTED_METHOD_SET_DIVERGENCES, with both method sets written
+ out, on the same contract as every other table here: an
+ unreviewed divergence fails, and so does an entry that no longer
+ diverges (or diverges differently).
"""
flask_index, fastapi_index, _ = _matched_views()
@@ -1753,14 +1805,26 @@ class TestRouteBehaviourParityAgainstFlaskSnapshot:
for path in shared
if flask_methods[path] != fastapi_methods[path]
]
- assert not mismatches, (
+ reviewed = {
+ path
+ for path, flask, fastapi in mismatches
+ if EXPECTED_METHOD_SET_DIVERGENCES.get(path)
+ == (set(flask), set(fastapi))
+ }
+ unexpected = [m for m in mismatches if m[0] not in reviewed]
+ stale = sorted(set(EXPECTED_METHOD_SET_DIVERGENCES) - reviewed)
+
+ assert not unexpected and not stale, (
"these paths serve a different set of HTTP methods than Flask "
- "did. A method Flask accepted and FastAPI does not is a 405 "
- "for any client still sending it:\n"
+ "did, and it was NOT reviewed. A method Flask accepted and "
+ "FastAPI does not is a 405 for any client still sending it:\n"
+ "\n".join(
f" {path}: Flask {flask} -> FastAPI {fastapi}"
- for path, flask, fastapi in mismatches
+ for path, flask, fastapi in unexpected
)
+ + "\n\nEXPECTED_METHOD_SET_DIVERGENCES entries whose two "
+ "method sets no longer diverge as recorded — prune or "
+ f"re-review these:\n{stale}"
)
def test_path_converter_types_match(self):