~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): fence the notes and chunks page routes with UUID shape validation (#6433)
LearningCircuitd1957b9a37b2
diff --git a/changelog.d/6433.security.md b/changelog.d/6433.security.mdnew file mode 100644index 0000000000..ca860ba7c7--- /dev/null+++ b/changelog.d/6433.security.md@@ -0,0 +1 @@+The notes detail page and the document chunks page now validate their path-parameter ids as UUIDs at the route boundary, following the same pattern `_validated_collection_id` established for the collection pages. The notes page previously rendered any single-segment string into the template context, relying solely on that one template's escaping; a malformed id now returns a 404 before any template sees it, and the chunks page skips its DB roundtrip for malformed ids. The validator also canonicalises the id it returns, so alias spellings of a valid UUID (an `urn:uuid:` prefix, `{...}` braces, hyphen-free hex, uppercase hex) resolve the same as their canonical form instead of being rendered verbatim. Well-formed UUIDs -- the only form ids are ever stored or generated in -- render exactly as before.diff --git a/src/local_deep_research/web/routers/notes.py b/src/local_deep_research/web/routers/notes.pyindex 2848590957..b5f827ce35 100644--- a/src/local_deep_research/web/routers/notes.py+++ b/src/local_deep_research/web/routers/notes.py@@ -640,6 +640,9 @@ def note_detail_page(username: Annotated[str, Depends(require_auth)],):"""Render the note detail page."""+ from ..utils.path_ids import validated_uuid_path_param++ note_id = validated_uuid_path_param(note_id, "Note")return templates.TemplateResponse(request=request,name="pages/note_detail.html",diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.pyindex 78b4e08ffc..705c930539 100644--- a/src/local_deep_research/web/routers/rag.py+++ b/src/local_deep_research/web/routers/rag.py@@ -502,9 +502,12 @@ def view_document_chunks(username: Annotated[str, Depends(require_auth)],):"""View all chunks for a document across all collections."""+ from ..utils.path_ids import validated_uuid_path_paramfrom ...database.session_context import get_user_db_sessionfrom ...database.models.library import DocumentChunk+ document_id = validated_uuid_path_param(document_id, "Document")+with get_user_db_session(username) as db_session:# Get document infodocument = db_session.query(Document).filter_by(id=document_id).first()diff --git a/src/local_deep_research/web/utils/path_ids.py b/src/local_deep_research/web/utils/path_ids.pynew file mode 100644index 0000000000..8e6c2e398b--- /dev/null+++ b/src/local_deep_research/web/utils/path_ids.py@@ -0,0 +1,59 @@+"""UUID shape validation for parameterized page-route ids.++Page routes that interpolate a path parameter into templates validate+the id's *shape* at the boundary: collection/note/document ids are+server-generated UUID4 strings (``String(36)`` columns assigned from+``str(uuid.uuid4())``), so anything else is a typo or an injection+attempt. Shape validation is strictly more robust than fixing any one+template's escaping — it holds for every interpolation context,+including inline-JS handlers where HTML-escaping is not sufficient.++Same pattern as ``_validated_collection_id`` (the stored-reflection XSS+fix for the collection pages), but that helper is not reused here: it+stays a local twin in ``rag.py`` so the route-table parity scanner+(which only follows same-module dependency closures) still sees its+404 for the collection routes. This shared helper is for page-route+fences outside ``rag.py`` instead. Not every page route is fenced yet:+``GET /chat/{session_id}`` and ``GET+/library/document/{document_id}/txt`` still pass their raw path+parameter (``session_id``, ``document_id``) into template contexts.+``GET /library/document/{document_id}`` is unfenced too, but does not+pass the raw id into its template — it looks the document up first and+passes the object instead (``context={"request": request, "document":+document}``, library.py). No known live vulnerability at the two+raw-id sites (autoescaped attribute contexts) — they are the same+hardening tier and remain to be fenced.+"""++import uuid++from fastapi import HTTPException+from loguru import logger+++def validated_uuid_path_param(value: object, label: str) -> str:+ """Return *value*'s canonical UUID form if well-formed, else 404.++ Returns ``str(uuid.UUID(str(value)))`` rather than echoing *value*+ back verbatim, so alias spellings of the same UUID — for example an+ ``urn:uuid:`` prefix, ``{...}`` braces, hyphen-free hex or uppercase+ hex; ``uuid.UUID`` tolerates a few more, such as ``_`` digit+ separators — come back canonical, which is what makes "well-formed+ UUID string" above actually true of the return value. Whitespace is+ not stripped: a padded 32-digit id fails the parser's length check+ and is rejected. Ids as stored are already ``str(uuid.uuid4())`` (lowercase,+ hyphenated, no wrapper), so canonicalising a real id is a no-op+ round-trip.++ A malformed id cannot match a real row, so 404 is the honest+ answer for both typos and injection attempts.+ """+ try:+ canonical = str(uuid.UUID(str(value)))+ except (ValueError, AttributeError, TypeError):+ value_preview = repr(value)[:100]+ logger.warning("Rejected malformed {}: {}", label, value_preview)+ raise HTTPException(+ status_code=404, detail=f"{label} not found"+ ) from None+ return canonicaldiff --git a/tests/research_library/routes/test_rag_routes_coverage_main_port.py b/tests/research_library/routes/test_rag_routes_coverage_main_port.pyindex b8fba34717..a5325fde2b 100644--- a/tests/research_library/routes/test_rag_routes_coverage_main_port.py+++ b/tests/research_library/routes/test_rag_routes_coverage_main_port.py@@ -115,6 +115,8 @@ _THREAD_LOCAL = "local_deep_research.database.thread_local_session"# rejection of a malformed one is already covered by# tests/security/test_collection_id_xss.py and is not re-ported here._COLL_UUID = str(uuid.UUID(int=0x5EC0))+#: A well-formed document id (page routes fence non-UUID shapes).+_DOC_UUID = str(uuid.UUID(int=0xD0C))# ---------------------------------------------------------------------------@@ -445,22 +447,56 @@ class TestPageRoutes:)with _route_env(db_session=db_session):+ # UUID-shaped but unknown: the shape fence must not preempt+ # the route's own html 404 branch this contract pins.resp = view_document_chunks(- _fake_request(), "doc-123", username="testuser"+ _fake_request(), _DOC_UUID, username="testuser")assert resp.status_code == 404+ def test_view_document_chunks_malformed_id_skips_db_query(self):+ """A malformed document_id must 404 at the shape fence, never+ reaching ``db_session.query`` -- the "skips its DB roundtrip"+ half of changelog.d/6433.security.md.++ Unlike ``test_view_document_chunks_not_found`` above (a+ UUID-shaped but unknown id, which reaches the route's own+ missing-row branch and returns a response),+ ``validated_uuid_path_param`` raises ``HTTPException`` directly+ with no ``try`` around it in the route body, so calling the+ route function outside FastAPI's exception-handling layer+ surfaces the exception rather than a response. This is exactly+ what would stop being true if the fence call were moved after+ the query: ``db_session.query`` would then be called before+ the malformed id was ever rejected, and this assertion would+ fail.+ """+ from fastapi import HTTPException++ from local_deep_research.web.routers.rag import view_document_chunks++ db_session = _make_db_session()++ with _route_env(db_session=db_session):+ with pytest.raises(HTTPException) as exc_info:+ view_document_chunks(+ _fake_request(), "doc-123", username="testuser"+ )++ assert exc_info.value.status_code == 404+ db_session.query.assert_not_called()+def test_view_document_chunks_found(self):from local_deep_research.web.routers.rag import view_document_chunksmock_doc = Mock()- mock_doc.id = "doc-123"+ mock_doc.id = _DOC_UUIDmock_doc.title = "Test Doc"mock_chunk = Mock()mock_chunk.id = "chunk-1"- mock_chunk.source_id = "doc-123"+ mock_chunk.source_id = _DOC_UUIDmock_chunk.collection_name = "collection_coll-1"mock_chunk.chunk_index = 0mock_chunk.chunk_text = "Hello world"@@ -493,7 +529,7 @@ class TestPageRoutes:with _route_env(db_session=db_session) as env:resp = view_document_chunks(- _fake_request(), "doc-123", username="testuser"+ _fake_request(), _DOC_UUID, username="testuser")assert resp.status_code == 200diff --git a/tests/research_library/routes/test_rag_routes_deep_main_port.py b/tests/research_library/routes/test_rag_routes_deep_main_port.pyindex eed2dea61a..5b950d9d93 100644--- a/tests/research_library/routes/test_rag_routes_deep_main_port.py+++ b/tests/research_library/routes/test_rag_routes_deep_main_port.py@@ -69,6 +69,7 @@ guard is deleted -- verified by reading each successor's assertions):import asyncioimport json+import uuidfrom contextlib import contextmanagerfrom types import SimpleNamespacefrom unittest.mock import ANY, MagicMock, Mock, patch@@ -1216,8 +1217,12 @@ class TestViewDocumentChunks:f"{_DB_CTX}.get_user_db_session",side_effect=_session_ctx(db_session),):+ # UUID-shaped but unknown: the shape fence must not+ # preempt the html 404 branch this contract pins.resp = view_document_chunks(- _fake_request(), "999", username="testuser"+ _fake_request(),+ str(uuid.uuid4()),+ username="testuser",)assert resp.status_code == 404diff --git a/tests/security/test_page_route_uuid_fences.py b/tests/security/test_page_route_uuid_fences.pynew file mode 100644index 0000000000..cb66c32a43--- /dev/null+++ b/tests/security/test_page_route_uuid_fences.py@@ -0,0 +1,121 @@+"""UUID shape fences on parameterized page routes.++``_validated_collection_id`` (rag.py) established the pattern: page+routes that interpolate a path parameter into templates must validate+the id's *shape* at the boundary, because collection/note/document ids+are server-generated UUID4 strings — anything else is a typo or an+injection attempt, and shape validation is strictly more robust than+fixing any one template context (it covers inline-JS interpolation,+``onclick`` handlers, and anything added later).++This change fences two page routes:++* ``GET /notes/{note_id}`` renders the page for *any* string — the raw+ id reaches the template context (``window.noteId = ...``), currently+ contained only by ``| tojson`` escaping in that one template.+* ``GET /library/document/{document_id}/chunks`` queries before any+ shape check — malformed ids already 404 via the missing-row path,+ but only after a needless DB roundtrip and without the boundary+ guarantee the collection fix documents.++The fence does not close the class: other page routes still pass a+raw path parameter into template contexts unfenced —+``GET /chat/{session_id}`` and the library document pages+``GET /library/document/{document_id}`` and+``GET /library/document/{document_id}/txt``. None is a known live+vulnerability (autoescaped attribute contexts, the same containment+tier the fenced routes are triaged at); they remain to be fenced.++These tests pin the fence: malformed ids (including script-payload+shapes) get a 404 from both page routes, while well-formed UUIDs keep+rendering exactly as before — and the source-inspection test below+fails if either fence call is silently reverted.+"""++import inspect+from uuid import uuid4++from local_deep_research.web.routers import notes, rag++_HOSTILE_ID = 'x"><img src=x onerror=alert(1)>'+++def test_note_page_rejects_malformed_note_id(authenticated_client):+ """The notes page must not render for a non-UUID note id.++ Pre-fence the route rendered any string into the template context+ and relied on the one template's ``| tojson`` escaping. The+ boundary fence makes that hold for every future context.+ """+ response = authenticated_client.get(f"/notes/{_HOSTILE_ID}")++ assert response.status_code == 404, (+ "note page rendered for a malformed note_id; the id reached the "+ "template context relying only on per-template escaping"+ )+++def test_note_page_renders_for_well_formed_uuid(authenticated_client):+ """A UUID-shaped id keeps rendering the page as before."""+ response = authenticated_client.get(f"/notes/{uuid4()}")++ assert response.status_code == 200, response.text[:200]+++def test_document_chunks_page_rejects_malformed_document_id(+ authenticated_client,+):+ """The chunks page must 404 malformed ids AT THE FENCE, not via the+ route's own missing-row branch.++ A bare status-code check cannot tell the two apart, and both are+ green today: the missing-row branch also answers 404, with body+ ``"Document not found"`` (``rag.py``:+ ``return HTMLResponse("Document not found", status_code=404)``).+ If the fence call were ever moved after the DB query, this test+ would stay green on status code alone while silently losing the+ "skips its DB roundtrip" guarantee.++ The fence's 404 is different: ``validated_uuid_path_param`` raises+ ``HTTPException(404, ...)``, which never reaches the client as+ written -- Starlette dispatches by exact status code first, so+ ``fastapi_app.py``'s ``@app.exception_handler(404)`` wins over+ FastAPI's default ``HTTPException`` handler and, for a browser+ (non-API) request, answers ``HTMLResponse("Not found",+ status_code=404)``. Asserting the exact body pins which branch+ answered.+ """+ response = authenticated_client.get(+ f"/library/document/{_HOSTILE_ID}/chunks"+ )++ assert response.status_code == 404+ assert response.text == "Not found", (+ "chunks page 404 did not come from the shape fence -- got body "+ f"{response.text[:100]!r}. The route's own missing-row branch "+ 'answers 404 too, with a different body ("Document not found"), '+ "so a fence moved after the DB query would still pass a bare "+ "status-code check."+ )+++def test_fenced_page_routes_call_the_uuid_validator():+ """The fence call itself must survive a silent revert.++ A status-code probe cannot catch deletion of the chunks-page+ fence: the route's own missing-row branch 404s a malformed id too,+ so the HTTP-level tests above stay green with the fence gone.+ Inspecting the route source — the idiom+ test_both_collection_page_routes_validate uses for the collection+ pages (tests/security/test_collection_id_xss.py) — fails the+ moment either call site disappears.+ """+ for fn, param in (+ (rag.view_document_chunks, "document_id"),+ (notes.note_detail_page, "note_id"),+ ):+ src = inspect.getsource(fn)+ assert f"validated_uuid_path_param({param}" in src, (+ f"{fn.__name__} no longer fences {param} with "+ "validated_uuid_path_param"+ )diff --git a/tests/security/test_path_ids_uuid_validation.py b/tests/security/test_path_ids_uuid_validation.pynew file mode 100644index 0000000000..b7ae9eb8c8--- /dev/null+++ b/tests/security/test_path_ids_uuid_validation.py@@ -0,0 +1,86 @@+"""Direct unit tests for ``validated_uuid_path_param`` (web/utils/path_ids.py).++Mirrors ``tests/security/test_collection_id_xss.py:50-60``, the direct+unit test for ``_validated_collection_id`` -- the sibling helper this+one's docstring is modelled on. ``test_page_route_uuid_fences.py``+already exercises this function indirectly through the two page routes+over HTTP; these tests drive it directly, including the property that+distinguishes it from a bare shape check: the return value is the+*canonical* form of the UUID, not an echo of whatever alias spelling+was submitted (path_ids.py: ``canonical = str(uuid.UUID(str(value)))``).+"""++import uuid++import pytest+from fastapi import HTTPException++from local_deep_research.web.utils.path_ids import validated_uuid_path_param++_CANON = "00000000-0000-0000-0000-000000000000"+_HEX32 = "0" * 32++# Malformed / hostile shapes: none of these is a well-formed UUID under+# any spelling, so every one must 404 -- whatever the payload.+REJECTED_VALUES = [+ "<script>alert(1)</script>",+ "1';alert(document.cookie);var x='",+ '1";alert(1);var y="',+ "../../etc/passwd",+ "1 OR 1=1",+ "",+ "not-a-uuid",+ 7,+ None,+ # ``uuid.UUID`` strips only braces and hyphens before its 32-character+ # length guard, so padding a full 32-digit hex string leaves 33+ # characters and is rejected -- ``int(hex, 16)`` would tolerate the+ # whitespace, but it never runs. (Whitespace plus 31 hex digits does+ # parse, as a *different* value, so it is not an alias of this one.)+ (" " + _HEX32),+ (_HEX32 + "\n"),+]++[email protected]("bad", REJECTED_VALUES, ids=lambda v: repr(v)[:40])+def test_malformed_value_is_rejected(bad):+ """Every non-UUID shape 404s, carrying the fence's own status code."""+ with pytest.raises(HTTPException) as exc_info:+ validated_uuid_path_param(bad, "Note")+ assert exc_info.value.status_code == 404+++# Alias spellings of the SAME UUID value: must be accepted, and the+# return value must be that UUID's canonical form -- not the alias+# verbatim. (Pre-tidy, ``validated_uuid_path_param`` returned+# ``str(value)``, so every one of these reached the template exactly+# as submitted; see gate report R5.)+ALIAS_VALUES = [+ ("urn_uuid_prefix", "urn:uuid:" + _CANON),+ ("braces", "{" + _CANON + "}"),+ ("hyphen_free_hex", _HEX32),+ ("sixteen_kb_hyphens_plus_hex", "-" * 16384 + _HEX32),+ ("unicode_digits_arabic_indic", "٠" * 32),+ ("uppercase_hex", "A" * 32),+]+++ "value", [v for _, v in ALIAS_VALUES], ids=[n for n, _ in ALIAS_VALUES]+)+def test_alias_shape_is_accepted_and_canonicalised(value):+ result = validated_uuid_path_param(value, "Note")+ # Same UUID value as the alias input...+ assert uuid.UUID(result) == uuid.UUID(str(value))+ # ...returned in canonical form: idempotent under re-parsing, so it+ # is not just "a" valid spelling but *the* canonical one.+ assert result == str(uuid.UUID(result))+++def test_real_uuid4_round_trips_unchanged():+ """Stored ids are already ``str(uuid.uuid4())``: canonicalising a+ real id must be a no-op, or every existing note/document link+ breaks.+ """+ real = str(uuid.uuid4())+ assert validated_uuid_path_param(real, "Note") == realdiff --git a/tests/ui_tests/playwright/tests/notes/notes-editing.spec.js b/tests/ui_tests/playwright/tests/notes/notes-editing.spec.jsindex 5ca38ec3b9..fe1094f39f 100644--- a/tests/ui_tests/playwright/tests/notes/notes-editing.spec.js+++ b/tests/ui_tests/playwright/tests/notes/notes-editing.spec.js@@ -124,8 +124,10 @@ test.describe('Not-found state', () => {test('an unknown note id shows the not-found panel', async ({ page }, testInfo) => {const detail = new NoteDetailPage(page);// Navigate raw — the goto() helper asserts the content wrapper is- // visible, which won't happen for a missing note.- await page.goto(`/notes/does-not-exist-${salt()}`);+ // visible, which won't happen for a missing note. The id must be+ // UUID-shaped: the page route 404s malformed ids before rendering+ // the shell, and only the client-side fetch drives this panel.+ await page.goto(`/notes/${require('node:crypto').randomUUID()}`);await expect(detail.notFound).toBeVisible({ timeout: 10000 });await capture(page, 'note-not-found', testInfo);});