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.

feat(notes-api): log rejected validation requests for audit trail (#5497)

LearningCircuitb7e0ac4a049a
diff --git a/changelog.d/5486.security.md b/changelog.d/5486.security.md
new file mode 100644
index 0000000000..8fa1956326
--- /dev/null
+++ b/changelog.d/5486.security.md
@@ -0,0 +1 @@
+Notes API now emits a `logger.warning` audit line when a request is rejected for a non-boolean `is_collapsed`/`force_reindex`/`create_note`, a non-finite `min_similarity`, or a stale `note_id`, giving operators visibility into probing of the tightened input contract (rejected values are logged type-tagged and truncated).
diff --git a/src/local_deep_research/web/routers/notes.py b/src/local_deep_research/web/routers/notes.py
index b152532e30..abe3f17a8b 100644
--- a/src/local_deep_research/web/routers/notes.py
+++ b/src/local_deep_research/web/routers/notes.py
@@ -23,6 +23,7 @@ Notes on the port:
import asyncio
import json
import math
+import reprlib
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
@@ -89,6 +90,49 @@ def _clamp_text_query(value, name, max_len=MAX_SEARCH_LEN):
return value
+# Bounded repr for an untrusted value going into an audit-log line. A naive
+# ``repr(value)[:100]`` slices AFTER building the full repr — for a value
+# that came out of ``_notes_json_body`` (up to the 100 MB notes JSON body
+# cap, see ``_MAX_JSON_BODY_BYTES`` above) that means materializing a second
+# ~100 MB+ string (more if it's escape-heavy, since ``repr`` expands each
+# control char to ``\xNN``) just to throw all but 100 chars away. Same
+# problem for a huge list/dict: ``repr()`` walks and stringifies every
+# element before any truncation happens.
+#
+# ``reprlib.Repr`` avoids this: its container/string methods slice or
+# ``itertools.islice`` BEFORE recursing/stringifying (see
+# ``reprlib.Repr.repr_str`` / ``repr_list`` / ``repr_dict`` in the stdlib),
+# so cost is bounded by the limits below regardless of the input's real
+# size. ``maxlevel`` also caps recursion depth for a deeply nested dict.
+_log_value_repr = reprlib.Repr(
+ maxlevel=4,
+ maxtuple=10,
+ maxlist=10,
+ maxdict=10,
+ maxset=10,
+ maxfrozenset=10,
+ maxstring=100,
+ maxlong=100,
+ maxother=100,
+)
+
+
+def _log_value_preview(value: Any) -> str:
+ """Bounded, ``logger.warning``-safe preview of an untrusted JSON value.
+
+ Use in place of ``repr(value)[:100]`` at any audit-log site whose value
+ comes from request input (query params, and especially JSON bodies,
+ which this router allows up to ~100 MB). See ``_log_value_repr`` above
+ for why plain ``repr()[:100]`` is unsafe here.
+
+ The final ``[:100]`` is a cheap backstop, not the primary defense — the
+ limits on ``_log_value_repr`` already keep the *work* bounded; this just
+ keeps the *output* bounded too (e.g. a container's per-element reprs can
+ still sum past 100 chars before ellipsis is added).
+ """
+ return _log_value_repr.repr(value)[:100]
+
+
# Rate limits for AI-heavy endpoints. Split into two buckets so cheap
# FAISS / local-embedding lookups (semantic search, similar notes,
# suggested links, related research) don't drain the same budget as
@@ -542,6 +586,12 @@ def semantic_search_notes(
status_code=400,
)
if not math.isfinite(min_similarity_raw):
+ logger.warning(
+ "notes_api validation reject: min_similarity={!r} (non-finite) "
+ "(user={!r})",
+ min_similarity_raw,
+ username,
+ )
return JSONResponse(
{"success": False, "error": "Invalid limit or min_similarity"},
status_code=400,
@@ -994,6 +1044,13 @@ def patch_note_research(
if "is_collapsed" in data and not isinstance(
data["is_collapsed"], bool
):
+ logger.warning(
+ "notes_api validation reject: is_collapsed={} (type={}) "
+ "(user={!r})",
+ _log_value_preview(data["is_collapsed"]),
+ type(data["is_collapsed"]).__name__,
+ username,
+ )
return JSONResponse(
{
"success": False,
@@ -1739,6 +1796,13 @@ def index_note_to_collection(
# Omitted: defaults to False (do not force-reindex).
force_reindex = data.get("force_reindex", False)
if not isinstance(force_reindex, bool):
+ logger.warning(
+ "notes_api validation reject: force_reindex={} (type={}) "
+ "(user={!r})",
+ _log_value_preview(force_reindex),
+ type(force_reindex).__name__,
+ username,
+ )
return JSONResponse(
{
"success": False,
@@ -2180,6 +2244,12 @@ def similar_passages(
text = text.strip()[:MAX_PASSAGE_LEN]
if not NoteService(username).note_exists(note_id):
+ logger.warning(
+ "notes_api validation reject: similar-passages note_id={} "
+ "not found (user={!r})",
+ _log_value_preview(note_id),
+ username,
+ )
return JSONResponse(
{"success": False, "error": "Note not found"}, status_code=404
)
@@ -2586,6 +2656,13 @@ def synthesize_notes(
# Omitted: defaults to True (persist synthesis as a new note).
create_note = data.get("create_note", True)
if not isinstance(create_note, bool):
+ logger.warning(
+ "notes_api validation reject: create_note={} (type={}) "
+ "(user={!r})",
+ _log_value_preview(create_note),
+ type(create_note).__name__,
+ username,
+ )
return JSONResponse(
{
"success": False,
diff --git a/tests/notes/test_notes_router_fastapi.py b/tests/notes/test_notes_router_fastapi.py
index a50a47e169..523758ae3a 100644
--- a/tests/notes/test_notes_router_fastapi.py
+++ b/tests/notes/test_notes_router_fastapi.py
@@ -157,6 +157,20 @@ def _rand_id():
return uuid.uuid4().hex
+def _validation_warnings(cap):
+ """Audit-log lines from the notes router's validation-reject warnings.
+
+ The router logs through loguru, not stdlib logging, so a bare ``caplog``
+ sees nothing here -- the ``loguru_caplog_full`` fixture (tests/conftest.py)
+ bridges loguru into caplog via a PropagateHandler.
+ """
+ return [
+ line
+ for line in cap.text.splitlines()
+ if "notes_api validation reject" in line
+ ]
+
+
# ---------------------------------------------------------------------------
# 1. Auth-gating — a representative sample across endpoint groups
# ---------------------------------------------------------------------------
@@ -373,16 +387,23 @@ class TestValidation:
assert r.status_code == 400
assert r.json()["success"] is False
- def test_index_non_bool_force_reindex_400(self, client):
+ def test_index_non_bool_force_reindex_400(self, client, loguru_caplog_full):
# Validated before the note_exists/RAG-service work — a nonexistent
# note id still hits the 400, not a 404.
- r = client.post(
- f"/notes/api/notes/{_rand_id()}/index",
- json={"collection_id": _rand_id(), "force_reindex": "yes"},
- headers={"X-CSRFToken": _csrf(client)},
- )
+ with loguru_caplog_full.at_level("WARNING"):
+ r = client.post(
+ f"/notes/api/notes/{_rand_id()}/index",
+ json={"collection_id": _rand_id(), "force_reindex": "yes"},
+ headers={"X-CSRFToken": _csrf(client)},
+ )
assert r.status_code == 400
assert r.json()["error"] == "force_reindex must be a boolean"
+ # The reject is audit-logged (visibility into probing of the
+ # tightened input contract) with the rejected value type-tagged.
+ msgs = _validation_warnings(loguru_caplog_full)
+ assert msgs, "expected a validation-reject audit line"
+ assert "force_reindex" in msgs[0]
+ assert "type=str" in msgs[0]
@pytest.mark.skip(
reason=(
@@ -527,16 +548,23 @@ class TestResearchAndDocuments:
assert r.status_code == 400
assert r.json()["error"] == "research_id is required"
- def test_patch_research_non_bool_is_collapsed_400(self, client):
+ def test_patch_research_non_bool_is_collapsed_400(
+ self, client, loguru_caplog_full
+ ):
# Validated before service.update_note_research is called — a
# nonexistent note/research pair still hits the 400, not a 404.
- r = client.patch(
- f"/notes/api/notes/{_rand_id()}/research/{_rand_id()}",
- json={"is_collapsed": "yes"},
- headers={"X-CSRFToken": _csrf(client)},
- )
+ with loguru_caplog_full.at_level("WARNING"):
+ r = client.patch(
+ f"/notes/api/notes/{_rand_id()}/research/{_rand_id()}",
+ json={"is_collapsed": "yes"},
+ headers={"X-CSRFToken": _csrf(client)},
+ )
assert r.status_code == 400
assert r.json()["error"] == "is_collapsed must be a boolean"
+ msgs = _validation_warnings(loguru_caplog_full)
+ assert msgs, "expected a validation-reject audit line"
+ assert "is_collapsed" in msgs[0]
+ assert "type=str" in msgs[0]
def test_get_research_notes_unknown_research_404(self, client):
r = client.get(f"/notes/api/research/{_rand_id()}/notes")
@@ -758,14 +786,21 @@ class TestAIEndpoints:
assert r.json()["error"] == "Query is required"
@pytest.mark.parametrize("value", ["nan", "inf", "-inf"])
- def test_semantic_search_non_finite_min_similarity_400(self, client, value):
+ def test_semantic_search_non_finite_min_similarity_400(
+ self, client, value, loguru_caplog_full
+ ):
# NaN survives max()/min() unchanged, so a non-finite min_similarity
# needs its own math.isfinite() guard, checked before the AI call.
- r = client.get(
- f"/notes/api/notes/semantic-search?q=topic&min_similarity={value}"
- )
+ with loguru_caplog_full.at_level("WARNING"):
+ r = client.get(
+ f"/notes/api/notes/semantic-search?q=topic&min_similarity={value}"
+ )
assert r.status_code == 400
assert r.json()["error"] == "Invalid limit or min_similarity"
+ msgs = _validation_warnings(loguru_caplog_full)
+ assert msgs, "expected a validation-reject audit line"
+ assert "min_similarity" in msgs[0]
+ assert "non-finite" in msgs[0]
def test_similar_unknown_note_404(self, client):
# note_exists gate fires before any AI/embeddings call.
@@ -773,29 +808,43 @@ class TestAIEndpoints:
assert r.status_code == 404
assert r.json()["error"] == "Note not found"
- def test_similar_passages_unknown_note_404(self, client):
+ def test_similar_passages_unknown_note_404(
+ self, client, loguru_caplog_full
+ ):
# note_exists gate fires before any AI/embeddings call.
- r = client.post(
- f"/notes/api/notes/{_rand_id()}/similar-passages",
- json={"text": "some selected passage text"},
- headers={"X-CSRFToken": _csrf(client)},
- )
+ with loguru_caplog_full.at_level("WARNING"):
+ r = client.post(
+ f"/notes/api/notes/{_rand_id()}/similar-passages",
+ json={"text": "some selected passage text"},
+ headers={"X-CSRFToken": _csrf(client)},
+ )
assert r.status_code == 404
assert r.json()["error"] == "Note not found"
+ msgs = _validation_warnings(loguru_caplog_full)
+ assert msgs, "expected a validation-reject audit line"
+ assert "similar-passages" in msgs[0]
+ assert "note_id" in msgs[0]
- def test_synthesize_non_bool_create_note_400(self, client):
+ def test_synthesize_non_bool_create_note_400(
+ self, client, loguru_caplog_full
+ ):
# Validated before the AI service is invoked — no mock required.
- r = client.post(
- "/notes/api/notes/synthesize",
- json={
- "note_ids": [_rand_id(), _rand_id()],
- "synthesis_type": "merge",
- "create_note": "yes",
- },
- headers={"X-CSRFToken": _csrf(client)},
- )
+ with loguru_caplog_full.at_level("WARNING"):
+ r = client.post(
+ "/notes/api/notes/synthesize",
+ json={
+ "note_ids": [_rand_id(), _rand_id()],
+ "synthesis_type": "merge",
+ "create_note": "yes",
+ },
+ headers={"X-CSRFToken": _csrf(client)},
+ )
assert r.status_code == 400
assert r.json()["error"] == "create_note must be a boolean"
+ msgs = _validation_warnings(loguru_caplog_full)
+ assert msgs, "expected a validation-reject audit line"
+ assert "create_note" in msgs[0]
+ assert "type=str" in msgs[0]
# ------------------------------------------------------------------
# Omitted-default controls, ported from main's #5500.