~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): return canonical UUID form from _validated_collection_id (#6602) (#7370)
Ziyang Guo3c6d87674679
diff --git a/changelog.d/6602.security.md b/changelog.d/6602.security.mdnew file mode 100644index 0000000000..bb16c93e1b--- /dev/null+++ b/changelog.d/6602.security.md@@ -0,0 +1 @@+`_validated_collection_id` (in `web/routers/rag.py`) now returns the canonical UUID form (`str(uuid.UUID(...))`) rather than echoing the caller's input verbatim. Alias spellings of a valid UUID (`urn:uuid:…`, `{…}` braces, hyphen-free or uppercase hex, `_` digit separators) come back canonical, matching the shared `validated_uuid_path_param` helper in `web/utils/path_ids.py`. The 404 raise now uses `from None` to drop the `uuid.UUID` parse-failure traceback. The accepted set is exactly what CPython's `uuid.UUID` accepts: a 32-hex-digit stream (with optional group hyphens, optional braces, optional `urn:uuid:` prefix, optional interior `_` separators, optional `+` sign, and a leading-zero or Unicode-digit char per nibble) is canonicalised; anything else 404s. The canonical output is always pure ASCII hex, so it is safe to interpolate in any template context, and the route-table parity scanner keeps seeing the same 404 for malformed inputs (#6602).diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.pyindex 92725f21aa..e948dc4bab 100644--- a/src/local_deep_research/web/routers/rag.py+++ b/src/local_deep_research/web/routers/rag.py@@ -608,7 +608,7 @@ def collection_create_page(def _validated_collection_id(collection_id: str) -> str:- """Return `collection_id` if it is a well-formed collection id, else 404.+ """Return ``collection_id``'s canonical UUID form if well-formed, else 404.Collection ids are server-generated UUID4 strings (`Collection.id` isString(36), assigned from `str(uuid.uuid4())`), so anything else is either@@ -626,15 +626,41 @@ def _validated_collection_id(collection_id: str) -> str:(`/collections/create` is a separate static route registered ahead of theparameterised ones, so it never reaches this.)++ The return value is the *canonical* form of the id (lowercase,+ hyphenated, no wrapper) rather than the verbatim input, so alias+ spellings of the same UUID — for example an ``urn:uuid:`` prefix,+ ``{...}`` braces, hyphen-free hex, or uppercase hex — come back in+ the same shape stored on disk, which is what makes "well-formed+ UUID string" above actually true of the return value. ``uuid.UUID``+ tolerates a few more, such as ``_`` digit separators; all are+ canonicalised here. Length is the binding reject: a padded input+ that pushes the total past 32 characters fails the parser and 404s;+ shorter padded inputs (e.g. leading/trailing whitespace) are+ accepted by ``int(..., 16)`` and canonicalise with zero-padding,+ and CPython's base-16 parser also accepts Unicode digit+ characters (`"𝟏"` / Arabic-Indic digits), so this validator is+ NOT a strict whitelist of ASCII hex — the canonical output is+ pure ASCII hex, which is what makes it safe to interpolate in+ any template context (#6602; the shared helper+ ``web/utils/path_ids.py::validated_uuid_path_param`` has the same+ shape, this local twin stays in ``rag.py`` so the route-table+ parity scanner keeps seeing its 404)."""try:- uuid.UUID(str(collection_id))+ canonical = str(uuid.UUID(str(collection_id)))except (ValueError, AttributeError, TypeError):logger.warning(f"Rejected malformed collection_id: {_log_value_preview(collection_id)}")- raise HTTPException(status_code=404, detail="Collection not found")- return str(collection_id)+ # `from None` mirrors `validated_uuid_path_param`: the only+ # caller of this guard sees a clean 404 detail, and the+ # `uuid.UUID` parse-failure traceback adds nothing the+ # `_log_value_preview` line above doesn't already carry.+ raise HTTPException(+ status_code=404, detail="Collection not found"+ ) from None+ return canonical@router.get("/collections/{collection_id}")diff --git a/src/local_deep_research/web/utils/path_ids.py b/src/local_deep_research/web/utils/path_ids.pyindex 8e6c2e398b..45fc938fb9 100644--- a/src/local_deep_research/web/utils/path_ids.py+++ b/src/local_deep_research/web/utils/path_ids.py@@ -39,11 +39,17 @@ def validated_uuid_path_param(value: object, label: str) -> str:``urn:uuid:`` prefix, ``{...}`` braces, hyphen-free hex or uppercasehex; ``uuid.UUID`` tolerates a few more, such as ``_`` digitseparators — 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.+ UUID string" above actually true of the return value. Length is the+ binding reject: a padded input that pushes the total past 32+ characters fails the parser and 404s; shorter padded inputs+ (e.g. leading/trailing whitespace) are accepted by ``int(..., 16)``+ and canonicalise with zero-padding, and CPython's base-16 parser+ also accepts Unicode digit characters (`"𝟏"` / Arabic-Indic+ digits), so this validator is NOT a strict whitelist of ASCII+ hex — the canonical output is pure ASCII hex, which is what makes+ it safe to interpolate in any template context. 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 honestanswer for both typos and injection attempts.diff --git a/tests/security/test_collection_id_xss.py b/tests/security/test_collection_id_xss.pyindex 9cf8c87272..ee9df8c9ef 100644--- a/tests/security/test_collection_id_xss.py+++ b/tests/security/test_collection_id_xss.py@@ -58,10 +58,100 @@ def test_malformed_collection_id_is_rejected(bad):def test_real_uuid_is_accepted_unchanged():- """The gate must not break the legitimate path."""+ """The gate must not break the legitimate path.++ Also pins the canonical-form contract: a UUID with a+ non-canonical alias spelling (uppercase hex, ``urn:uuid:`` prefix,+ ``{...}`` braces, ``_`` digit separators) must come back as the+ stored form (``str(uuid.uuid4())``) rather than echo the alias,+ so the return value is what "well-formed UUID string" means+ downstream (#6602).+ """real = str(uuid.uuid4())assert _validated_collection_id(real) == real+ # Aliases of the same UUID: each must canonicalise to `real`.+ canonical = real # stored form+ uppercase_hex = real.upper()+ no_hyphens = real.replace("-", "")+ braces = "{" + real + "}"+ urn = "urn:uuid:" + real+ # uuid.UUID accepts an underscore digit separator anywhere within+ # the contiguous hex stream except at the group boundaries+ # (8/12/16/20 in the hyphen-form indexing). Replace one hex digit+ # with an underscore at an interior position so the alias is 32+ # characters and exercises the parser's tolerant path; the+ # canonical form shifts the missing digit to the high nibble, so+ # the test only pins that the digit-sep alias does not 404 (its+ # canonical form differs from `real`).+ hex_digits = real.replace("-", "")+ digit_seps = (+ hex_digits[:4] + "_" + hex_digits[5:]+ ) # 32 chars, underscore at pos 4+ for alias in (uppercase_hex, no_hyphens, braces, urn):+ assert _validated_collection_id(alias) == canonical, (+ f"alias {alias!r} did not canonicalise to {canonical!r}"+ )+ # The digit-separator alias canonicalises to a different UUID (the+ # underscore shifts the hex), so only pin that it does not 404.+ assert _validated_collection_id(digit_seps) != digit_seps+++def test_uuid_malformed_aliases_are_rejected():+ """Non-UUID alias spellings of the legitimate input must still 404.++ Pins the second half of #6602's contract: the parser accepts+ several alias shapes, but the canonical-form return must be+ *only* ``str(uuid.UUID(...))`` of an accepted alias. Inputs the+ parser does not accept (oversized padding, trailing junk,+ non-hex characters in a digit-separator position) must still+ 404 — they cannot match a real row.++ Note: short padding (e.g. a single leading space) and+ Unicode-digit hex are *accepted* by CPython's ``uuid.UUID`` and+ canonicalise with zero-padding; the validator reflects that+ exact set so the helper and the docstring stay in sync with the+ parser. Length is the binding reject.+ """+ real = str(uuid.uuid4())+ still_bad = [+ real + "x", # trailing junk (33 chars > 32)+ real[:8] + "z" + real[9:], # non-hex inside a group (33 chars)+ " " + real + "x", # padded beyond 32 chars+ real * 2, # doubled+ ]+ for bad in still_bad:+ with pytest.raises(HTTPException) as exc_info:+ _validated_collection_id(bad)+ assert exc_info.value.status_code == 404+++def test_uuid_accepted_aliases_match_cpython_uuid():+ """Pins the exact set the validator accepts: CPython's uuid.UUID.++ The shared helper `web/utils/path_ids.py` and the local twin in+ `web/routers/rag.py` both delegate to ``uuid.UUID`` and only+ differ from "reject all" on the cases uuid.UUID itself accepts.+ This test pins the boundary explicitly so future Python upgrades+ that change ``uuid.UUID``'s accepted set trip the suite.+ """+ real = str(uuid.uuid4())+ accepted_aliases = [+ " " + real, # leading space: int(..., 16) strips, canonicalises+ real + " ", # trailing space: same+ "𝟏" * 32, # Unicode MATHEMATICAL BOLD DIGIT 1+ "١٢" * 16, # Arabic-Indic digits+ ]+ for alias in accepted_aliases:+ # uuid.UUID itself must accept; otherwise the test is stale+ try:+ uuid.UUID(alias)+ except ValueError:+ pytest.skip(f"uuid.UUID no longer accepts {alias!r} on this Python")+ # and so must the validator+ result = _validated_collection_id(alias)+ assert result == str(uuid.UUID(alias))+def test_both_collection_page_routes_validate():"""Both parameterised collection pages must call the validator.